arraylist对象不会添加对象

62o28rlo  于 2021-06-26  发布在  Java
关注(0)|答案(1)|浏览(323)

我尝试在数组列表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);
            }
        });

//在这里,我创建新的数组列表并启动“条形图”活动//;btnshowgraph.setonclicklistener(new view.onclicklistener(){@override public void onclick(view 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}
}
8hhllhi2

8hhllhi21#

当您启动条形图活动时,您的新列表有0个元素,因为您正在传入列表 intent 以错误的形式。首先,在 JournalNote 类实现 Parcelable 而不是 Serializable . 所以,你的最后一堂课应该是这样的。

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传递完整列表的同时,编写如下代码,

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

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

相关问题