首页 > 解决方案 > 对象的ArrayList不会添加对象

问题描述

我尝试在数组列表 journalList 中添加 journalNote 对象,但它们不会被插入。我想使用这个数组列表在另一个活动中使用相应的数据绘制条形图。

My array list is in this fragment:


public class MyJournalFragment extends Fragment {

    public MyJournalFragment() {
        // Required empty public constructor
    }


    private FloatingActionButton floatingActionButton;
    Button btnShowGraph;
    private Intent intent;
    public static final int REQUEST_CODE = 200;

    public static final int REQUEST_CODE_EDIT = 300;

    public static final String EDIT_JNOTE = "editJNote";

    public int poz;

    private ListView listView;
    List<JournalNote> notesList = new ArrayList<JournalNote>();

    //Ce era in onCreate ~= onCreateView
    //nu E setOnContentView pt fragmente, ai alte metode
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my_journal, container, false);

        //in activity la seminar era pus in onCreate, dupa startActivity
        listView = (ListView) view.findViewById(R.id.listView);
        //set the adapter, etc

      //  FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.floatingActionButton);
        floatingActionButton = (FloatingActionButton) view.findViewById(R.id.floatingActionButton);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {

         //de ce punem intentul in onClickView?
            //Aici punem intentul si start activity
         //this is what runs when you click the button
            @Override
            public void onClick(View view) {

                intent = new Intent(getActivity().getApplicationContext(), Add_Journal_Note_Activity.class);
                Serializable data = intent.getSerializableExtra(Add_Journal_Note_Activity.ADD_JNOTE);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

//在这里我创建新的数组列表并启动条形图活动 //当我在调试器模式下使用它时,我的新列表有 0 个元素,而我的旧列表有很多对象,因为我手动插入了它们 //BarChart Tip Notita btnShowGraph = (按钮) view.findViewById(R.id.buttonShowGraph); btnShowGraph.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ArrayList journalList = new ArrayList(); for (JournalNote journalNote : notesList) journalList.add(journalNote);

                Intent intent1 = new Intent( getActivity().getApplicationContext() , BarChart_Journal_Activity.class);
                intent1.putExtra("journalList",journalList);
                startActivity(intent1);
            }
        });

        //Modifica notita
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                poz = position;
                intent = new Intent(getActivity().getApplicationContext(), Add_Journal_Note_Activity.class);
                intent.putExtra(EDIT_JNOTE, notesList.get(position));
                startActivityForResult(intent, REQUEST_CODE_EDIT);
            }
        });

        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {

                final JournalNote notes = notesList.get(position);

                final JournalAdapter adapter = (JournalAdapter) listView.getAdapter();

                AlertDialog dialog = new AlertDialog.Builder(getActivity())
                        .setTitle("Confirmare stergere")
                        .setMessage("Sigur doriti stergerea?")
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(getActivity(), "Nu s-a sters nimic!",
                                        Toast.LENGTH_LONG).show();
                                dialogInterface.cancel();
                            }
                        }).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                notesList.remove(notes);
                                adapter.notifyDataSetChanged();
                                Toast.makeText(getActivity(), "S-a sters filmul: "+notes.toString(),
                                        Toast.LENGTH_LONG).show();
                                dialogInterface.cancel();
                            }
                        }).create();

                dialog.show();

                return true;
            }
        });

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
            JournalNote notes = (JournalNote) data.getSerializableExtra(Add_Journal_Note_Activity.ADD_JNOTE);

            if (notes != null) {

                notesList.add(notes);


                JournalAdapter adapter = new JournalAdapter(getActivity(), R.layout.journal_listview,
                        notesList, getLayoutInflater()){
                    @NonNull
                    @Override
                    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                        View view = super.getView(position, convertView, parent);

                        JournalNote notes =  notesList.get(position);
                        System.out.println(notes.getCurNote().toString());
                        TextView tvMessage = view.findViewById(R.id.mesaj);
                        if(notes.getCurNote().toString() == "LECTURE" )
                            tvMessage.setTextColor(Color.GREEN);
                        else
                            System.out.println(notes.getCurNote().toString());
                          if(notes.getCurNote().toString()== "LAB")
                            tvMessage.setTextColor(Color.BLUE);
                       else
                              System.out.println(notes.getCurNote().toString());
                        if(notes.getCurNote().toString() == "OTHERS")
                            tvMessage.setTextColor(Color.RED);

                        return view;

                    }
                };

                listView.setAdapter(adapter);
            }
        }
        else
        if (requestCode == REQUEST_CODE_EDIT && resultCode == Activity.RESULT_OK && data != null) {
            JournalNote notes = (JournalNote) data.getSerializableExtra(ADD_JNOTE);
            {
                if (notes!=null)
                {
                    notesList.get(poz).setTitle(notes.getTitle());
                    notesList.get(poz).setData(notes.getData());
                    notesList.get(poz).setMessage(notes.getMessage());
                    notesList.get(poz).setNotetype(notes.getNotetype());
                    notesList.get(poz).setCurNote(notes.getCurNote());

                    JournalAdapter adapter = new JournalAdapter(getActivity(), R.layout.journal_listview,
                            notesList, getLayoutInflater()){
                        @NonNull
                        @Override
                        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            View view = super.getView(position, convertView, parent);

                            JournalNote notes =  notesList.get(position);

                            TextView tvMessage = view.findViewById(R.id.mesaj);
                            if(notes.getCurNote().toString() == "LECTURE" )
                                tvMessage.setTextColor(Color.GREEN);
                         else if(notes.getCurNote().toString()== "LAB")
                                tvMessage.setTextColor(Color.BLUE);
                         else
                         if(notes.getCurNote().toString() == "OTHERS")
                             tvMessage.setTextColor(Color.RED);

                            return view;
                        }
                    };
                    listView.setAdapter(adapter);
                }
            }
        }
    }
}

BArcchart Activity:
public class BarChart_Journal_Activity extends AppCompatActivity {

    List<JournalNote> journalList;
    LinearLayout layout;
    Map<String, Integer> source;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bar_chart_journal);

        Intent intent = getIntent();

        journalList = (ArrayList<JournalNote>) intent.getSerializableExtra("jounalList");

        source = getSource(journalList);

        layout = findViewById(R.id.layoutBar);
        layout.addView(new BarChartView(getApplicationContext(), source));
        }

        private Map<String, Integer> getSource( List<JournalNote> notes)
        {
            if(notes == null || notes.isEmpty())
                return new HashMap<>();
            else{
                Map<String,Integer> results = new HashMap<>();
                for(JournalNote journalNote: notes)
                    if(results.containsKey(journalNote.getNotetype()))
                        results.put(journalNote.getNotetype().toString(),  results.get(journalNote.getNotetype())+1);

                    else { results.put(journalNote.getNotetype().toString(),1);}


                return results;
            }

        }

}

更新:这是我的 JournalNote 类:

package ro.ase.proiect_draft;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;



public class JournalNote implements Serializable {

    private String id;
    private String title;
    private Date data;
    private String message;
    private NoteType notetype;
    private CurricularNote curNote;

    public JournalNote(String title, Date data, String message, NoteType notetype, CurricularNote curNote) {
        id = UUID.randomUUID().toString();
        this.title = title;
        this.data = data;
        this.message = message;
        this.notetype = notetype;
        this.curNote = curNote;
    }


    public String getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

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

    public Date getData() {
        return data;
    }

    public void setData(Date data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public NoteType getNotetype() {
        return notetype;
    }

    public void setNotetype(NoteType notetype) {
        this.notetype = notetype;
    }

    public CurricularNote getCurNote() {
        return curNote;
    }

    public void setCurNote(CurricularNote curNote) {
        this.curNote = curNote;
    }

    @Override
    public String toString() {
        return "JournalNote{" +
                "title='" + title + '\'' +
                ", data=" + data +
                ", message='" + message + '\'' +
                ", notetype=" + notetype +
                ", curNote=" + curNote +
                '}';
    }

    public enum NoteType {FAVORITE, IMPORTANT, REMINDMELATER}

    public enum CurricularNote {LECTURE, LAB, OTHERS}
}

标签: javaandroidfragmentbar-chart

解决方案


当您启动 Barchart Activity 时,您的新列表有 0 个元素,因为您intent以错误的形式传递列表。首先,在JournalNote类中实现Parcelable而不是Serializable. 所以,你最终的 JournalNote 类应该是这样的。

import android.os.Parcel;
import android.os.Parcelable;

import java.util.Date;
import java.util.UUID;

public class JournalNote implements Parcelable {

    private String id;
    private String title;
    private Date data;
    private String message;
    private NoteType notetype;
    private CurricularNote curNote;

    public JournalNote(String title, Date data, String message, NoteType notetype, CurricularNote curNote) {
        id = UUID.randomUUID().toString();
        this.title = title;
        this.data = data;
        this.message = message;
        this.notetype = notetype;
        this.curNote = curNote;
    }


    protected JournalNote(Parcel in) {
        id = in.readString();
        title = in.readString();
        message = in.readString();
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(title);
        dest.writeString(message);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public static final Creator<JournalNote> CREATOR = new Creator<JournalNote>() {
        @Override
        public JournalNote createFromParcel(Parcel in) {
            return new JournalNote(in);
        }

        @Override
        public JournalNote[] newArray(int size) {
            return new JournalNote[size];
        }
    };

    public String getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

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

    public Date getData() {
        return data;
    }

    public void setData(Date data) {
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public NoteType getNotetype() {
        return notetype;
    }

    public void setNotetype(NoteType notetype) {
        this.notetype = notetype;
    }

    public CurricularNote getCurNote() {
        return curNote;
    }

    public void setCurNote(CurricularNote curNote) {
        this.curNote = curNote;
    }

    @Override
    public String toString() {
        return "JournalNote{" +
                "title='" + title + '\'' +
                ", data=" + data +
                ", message='" + message + '\'' +
                ", notetype=" + notetype +
                ", curNote=" + curNote +
                '}';
    }

    public enum NoteType {FAVORITE, IMPORTANT, REMINDMELATER}

    public enum CurricularNote {LECTURE, LAB, OTHERS}
}

然后在通过意图传递完整列表的同时,编写如下代码,

Intent intent1 = new Intent( getActivity().getApplicationContext() , BarChart_Journal_Activity.class);
                intent1.putParcelableArrayList("journalList",journalList);
                startActivity(intent1);

通过在 JournalNote 类中实现 parcelable,您可以将完整列表从一个 Activity 传递到另一个 Activity。


推荐阅读