android-fragments 我正在使用片段创建Android Note应用程序,但我无法科普www.example.com中出现的错误NoteFragment.java

ylamdve6  于 2022-11-13  发布在  Android
关注(0)|答案(1)|浏览(115)

注解片段.java

public class NoteFragment extends Fragment {

    private ListView noteListView;
    private Note note;
    List <Note> notes = new ArrayList<Note>();
    private Button add;
    private NoteAdapter noteAdapter;
    private String title = "title";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_note, container, false);
        noteListView = (ListView) view.findViewById(R.id.noteListView);

        initWidgets();
        loadFromDBtoMemory();
        setNoteAdapter();

        return view;
    }

    private void initWidgets() {
        noteListView = getActivity().findViewById(R.id.noteListView);
        add = getActivity().findViewById(R.id.add_fragment);
    }

    private void loadFromDBtoMemory() {
        SQLiteManager sqLiteManager = new SQLiteManager(getActivity());
        sqLiteManager.populateNoteListArray("");
    }

    private void setNoteAdapter() {

        NoteAdapter noteAdapter = new NoteAdapter(getContext().getApplicationContext(), Note.nonDeletedNotes());
        noteListView.setAdapter(noteAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        setNoteAdapter();
    }

注意适配器.java

public class NoteAdapter extends ArrayAdapter<Note> {

    public NoteAdapter(Context context, List<Note> notes){
        super(context, 0,notes);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        Note note = getItem(position);
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.note_cell, parent, false);
        }

        TextView title = convertView.findViewById(R.id.cellTitle);
        TextView description = convertView.findViewById(R.id.cellDesc);
        TextView realTime = convertView.findViewById(R.id.realTime);
        ImageView smallImg = convertView.findViewById(R.id.smallImg);
        TextView impTextView = convertView.findViewById(R.id.ImpTextView);

        title.setText(note.getTitle());
        description.setText(note.getDescription());

        String formatedTime = DateFormat.getDateTimeInstance().format(note.getRealTime());
        realTime.setText(formatedTime);

        Uri uri = Uri.parse(note.getUri());
        smallImg.setImageURI(null);
        smallImg.setImageURI(uri);

        if (Objects.equals(note.getSelection(), "very important")) {
            impTextView.setText(note.getSelection());
            impTextView.setBackgroundColor(Color.rgb(255, 0, 0));
        }
        if (Objects.equals(note.getSelection(), "important")) {
            impTextView.setText(note.getSelection());
            impTextView.setBackgroundColor(Color.rgb(255, 255, 153));
        }
        if (Objects.equals(note.getSelection(), "not very important")) {
            impTextView.setText(note.getSelection());
            impTextView.setBackgroundColor(Color.rgb(240, 248, 255));
        }

        return convertView;
    }

}

添加片段.java

public class AddFragment extends Fragment {

    private EditText titleEditText, descEditText;
    private Note selectedNote;
    private ImageView newImg;
    private FloatingActionButton addImg;
    private ConstraintLayout imgContainer;
    private final int PICK_IMAGE_CODE = 123;
    private String tempUri = "empty";
    private String[] importancy = {"very important", "important", "not very important"};
    private Spinner spinner;
    private String selectedItem;
    private View view;
    private Button saveNote;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_add, container, false);
        SQLiteManager sqLiteManager = new SQLiteManager(getActivity());
        spinner = view.findViewById(R.id.importancy);

        titleEditText = view.findViewById(R.id.titleEditText);
        descEditText = view.findViewById(R.id.descriptionEditText);
        addImg = view.findViewById(R.id.addImg);
        imgContainer = view.findViewById(R.id.imgContainer);
        newImg = view.findViewById(R.id.newImg);
        spinner = view.findViewById(R.id.importancy);
        saveNote = view.findViewById(R.id.saveNote);

        saveNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                saveNote(view);
            }
        });

        ArrayAdapter<String> importancyAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, importancy);
        importancyAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(importancyAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                selectedItem = adapterView.getSelectedItem().toString();
                for (int u = 0; u < importancy.length; u++) {
                    if (importancy[i] == "very important")
                        view.setBackgroundColor(Color.rgb(255, 0, 0));
                    if (importancy[i] == "important")
                        view.setBackgroundColor(Color.rgb(255, 255, 153));
                    if (importancy[i] == "not very important")
                        view.setBackgroundColor(Color.rgb(240, 248, 255));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        return view;
}

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    public void saveNote(View view) {

        SQLiteManager sqLiteManager = new SQLiteManager(getActivity());

        String title = String.valueOf(titleEditText.getText());
        String desc = String.valueOf(descEditText.getText());
        long realTime = System.currentTimeMillis();
        String uri = String.valueOf(tempUri);
        String selection = String.valueOf(selectedItem);

        if(selectedNote == null){
            int id = Note.noteArrayList.size();
            Note newNote = new Note(id, title, desc, realTime, uri, selection);
            Note.noteArrayList.add(newNote);

            System.out.println(Note.noteArrayList);

            sqLiteManager.addNoteToDatabase(newNote);
            Toast.makeText(getActivity().getApplicationContext(), "Note saved", Toast.LENGTH_SHORT).show();
        }
        else {
            selectedNote.setTitle(title);
            selectedNote.setDescription(desc);
            selectedNote.setRealTime(realTime);
            selectedNote.setUri(uri);
            selectedNote.setSelection(selection);
            sqLiteManager.updateNoteInDB(selectedNote);
        }

    }

}

注解.java

public class Note {

    public static ArrayList<Note> noteArrayList = new ArrayList<>();
    public static String NOTE_EDIT_EXTRA = "noteEdit";

    private int id;
    private String title;
    private String description;
    private long realTime;
    private String uri = "empty";
    private String selection;
    private Date deleted;

    public Note(int id, String title, String description, long realTime, String uri, String selection, Date deleted) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.realTime = realTime;
        this.uri = uri;
        this.selection = selection;
        this.deleted = deleted;
    }

    public Note(int id, String title, String description, long realTime, String uri, String selection) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.realTime = realTime;
        this.uri = uri;
        this.selection = selection;
        deleted = null;
    }

    public static Note getNoteForID(int passedNoteID) {
        for(Note note : noteArrayList){
            if(note.getId() == passedNoteID){
                return note;
            }
        }
        return null;
    }

    public static ArrayList<Note> nonDeletedNotes(){

        ArrayList<Note> nonDeleted = new ArrayList<>();
        for(Note note : noteArrayList){
            if(note.getDeleted() == null){
                nonDeleted.add(note);
            }
        }
        return nonDeleted;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public long getRealTime() {return  realTime; }

    public void setRealTime(long realTime) {this.realTime = realTime;}

    public String getUri (){return uri;}

    public void setUri(String uri) {this.uri = uri;}

    public String getSelection(){return selection;}

    public void setSelection(String selection) {this.selection = selection;}

    public Date getDeleted() {
        return deleted;
    }

    public void setDeleted(Date deleted) {
        this.deleted = deleted;
    }

}

SQLiteManager.java

public class SQLiteManager extends SQLiteOpenHelper {

    private static SQLiteManager sqLiteManager;

    private static final String DATABASE_NAME = "NoteDB";
    private static final int DATABASE_VERSION = 3;
    private static final String TABLE_NAME = "Note";
    private static final String COUNTER = "Counter";

    private static final String ID_FIELD = "id";
    private static final String TITLE_FIELD = "title";
    private static final String DESC_FIELD = "desc";
    private static final String REAL_TIME = "realtime";
    private static final String IMAGE_URI = "uri";
    private static final String SELECTED_ITEM = "selection";
    private static final String DELETED_FIELD = "deleted";

    @SuppressLint("SimpleDateFormat")
    private static final DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");

    public SQLiteManager(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static SQLiteManager instanceOfDatabase(Context context) {
        if (sqLiteManager == null) {
            sqLiteManager = new SQLiteManager(context);
        }

        return sqLiteManager;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        StringBuilder sql;
        sql = new StringBuilder()
                .append(" CREATE TABLE ")
                .append(TABLE_NAME)
                .append("(")
                .append(COUNTER)
                .append(" INTEGER PRIMARY KEY AUTOINCREMENT, ")
                .append(ID_FIELD)
                .append(" INT, ")
                .append(TITLE_FIELD)
                .append(" TEXT, ")
                .append(DESC_FIELD)
                .append(" TEXT, ")
                .append(REAL_TIME)
                .append(" TEXT, ")
                .append(IMAGE_URI)
                .append(" TEXT, ")
                .append(SELECTED_ITEM)
                .append(" TEXT, ")
                .append(DELETED_FIELD)
                .append(" TEXT)");

        sqLiteDatabase.execSQL(sql.toString());
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        //if(newVersion ==2)
          sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME );
          onCreate(sqLiteDatabase);
        //sqLiteDatabase.execSQL("ALTER TABLE " + "Note" + " ADD COLUMN " +REAL_TIME + " TEXT");
    }

    public void addNoteToDatabase(Note note) {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(ID_FIELD, note.getId());
        contentValues.put(TITLE_FIELD, note.getTitle());
        contentValues.put(DESC_FIELD, note.getDescription());
        contentValues.put(REAL_TIME, String.valueOf(note.getRealTime()));
        contentValues.put(IMAGE_URI, note.getUri());
        contentValues.put(SELECTED_ITEM, note.getSelection());
        contentValues.put(DELETED_FIELD, getStringFromDate(note.getDeleted()));

        sqLiteDatabase.insert(TABLE_NAME, null, contentValues);

    }

    public void populateNoteListArray(String title_field) {
        SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
            String Selection = "title" + " like ?";
            Cursor result = sqLiteDatabase.query(TABLE_NAME, null, Selection, new String[]{"%" + title_field + "%"}, null, null, null);

                while (result.moveToNext()) {
                    int id = result.getInt(1);
                    String title = result.getString(2);
                    String desc = result.getString(3);
                    String time = result.getString(4);
                    long realtime = Long.parseLong(time);
                    String imgUri = result.getString(5);
                    String selection = result.getString(6);
                    String stringDeleted = result.getString(7);
                    Date deleted = getDatefromString(stringDeleted);
                    Note note = new Note(id, title, desc, realtime, imgUri, selection, deleted);
                    Note.noteArrayList.add(note);
                }

    }

    public void updateNoteInDB(Note note){
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(ID_FIELD, note.getId());
        contentValues.put(TITLE_FIELD, note.getTitle());
        contentValues.put(DESC_FIELD, note.getDescription());
        contentValues.put(SELECTED_ITEM, note.getSelection());
        contentValues.put(DELETED_FIELD, getStringFromDate(note.getDeleted()));

        sqLiteDatabase.update(TABLE_NAME, contentValues, ID_FIELD + " =?", new String[]{String.valueOf(note.getId())});
    }

    private String getStringFromDate(Date date) {
        if(date == null){
            return null;
        }
        return dateFormat.format(date);
    }

    private Date getDatefromString(String string){
        try
        {
            return dateFormat.parse(string);
        }
        catch (ParseException | NullPointerException e)
        {
            return null;
        }
    }

问题在于:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: andrii.sosnytskyi.nure.mynote_v2, PID: 16771
    java.lang.RuntimeException: Unable to start activity ComponentInfo{andrii.sosnytskyi.nure.mynote_v2/andrii.sosnytskyi.nure.mynote_v2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at andrii.sosnytskyi.nure.mynote_v2.NoteFragment.setNoteAdapter(NoteFragment.java:55)
        at andrii.sosnytskyi.nure.mynote_v2.NoteFragment.onCreateView(NoteFragment.java:37)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3138)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:502)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1334)
        at android.app.Activity.performStart(Activity.java:7029)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2741)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

请告诉我怎么修。

z31licg0

z31licg01#

根据堆栈跟踪,本方法中noteListView为null:

private void setNoteAdapter() {

    NoteAdapter noteAdapter = new NoteAdapter(getContext().getApplicationContext(), Note.nonDeletedNotes());
    noteListView.setAdapter(noteAdapter);
}

相关问题