简体   繁体   中英

Sending and receiving arraylist from one activity to another

I am trying to send an ArrayList from NoteActivity to MainActivity.

ArrayList<String> data = new ArrayList<String>();

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

  final FloatingActionButton button = 
     (FloatingActionButton)findViewById(R.id.save_button);

  button.setOnClickListener(new View.OnClickListener() 
   {

     @Override
     public void onClick(View v) 
     {
       SaveData();
     }
   });
}

public void SaveData()
{
   FileOutputStream outputStream;

   try 
   {
     EditText editText = findViewById(R.id.textView3);

     final String str = editText.getText().toString();

     String content = findViewById(R.id.textView).toString();
     Log.d("Test","inside try block");

     outputStream = openFileOutput(str, Context.MODE_PRIVATE);
     outputStream.write(content.getBytes());

     Toast.makeText(getApplicationContext(),"Note 
     saved",Toast.LENGTH_SHORT).show();

     Log.d("Test","save done");

     final String str1 = editText.getText().toString();
     data.add(str1);

     SendData();
   }
   catch (FileNotFoundException e)
   {
       e.printStackTrace();
   }
   catch (IOException e)
   {
       e.printStackTrace();
   }
}

   public void SendData()
   {
      EditText editText = findViewById(R.id.textView3);

      Log.d("Check","str:"+data);
      Intent intent = new Intent(NotePad.this,MainActivity.class);
      intent.putExtra(EXTRA_MESSAGE, data);
      startActivity(intent);
   }
}

My Main Activity

public class MainActivity extends AppCompatActivity 
{
   private RecyclerView recyclerView;
   private RecyclerView.Adapter mAdapter;
   private RecyclerView.LayoutManager layoutManager;
   ArrayList<String> notes = new ArrayList<String>();




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


      Intent intent = getIntent();
      notes = intent.getStringArrayListExtra(NotePad.EXTRA_MESSAGE);

      Log.d("Check","title added: "+notes);


      final FloatingActionButton button = 
       (FloatingActionButton)findViewById(R.id.add_notebutton);


      button.setOnClickListener(new View.OnClickListener() 
      {

         @Override
         public void onClick(View v) 
         {
             Intent intent = new Intent(MainActivity.this,NotePad.class);
             startActivity(intent);
         }
      });

      recyclerView = (RecyclerView)findViewById(R.id.recycle_list);


      layoutManager = new LinearLayoutManager(this);
      recyclerView.setLayoutManager(layoutManager);
      mAdapter = new MyAdapter(notes);
      recyclerView.setAdapter(mAdapter);

   }

}

my Adapter code

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> 
{

  ArrayList<String> Notes_list = new ArrayList<String>();

   public MyAdapter(ArrayList<String> notes)
   {
      Notes_list = notes;
   }

   @NonNull
   @Override
     public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int 
     viewType) 
   {
     LayoutInflater inflater = LayoutInflater.from(parent.getContext());
      View view = inflater.inflate(R.layout.list_items,parent,false);
      return new MyViewHolder(view);
   }

   @Override
   public void onBindViewHolder(@NonNull MyViewHolder holder, int position) 
   {

       holder.mTextView.setText(Notes_list.get(position));
   }

   @Override
   public int getItemCount()  
   {
      return Notes_list.size();
   }

   public class MyViewHolder extends RecyclerView.ViewHolder 
   {
       TextView mTextView;
       public MyViewHolder(@NonNull View itemView)
       {
          super(itemView);
          mTextView = (TextView) itemView.findViewById(R.id.view_holder);
       }
   }
}

I dont receive any data in my notes (arrayList). When I run the code

The app instantly crashes with a null pointer exception.

Error: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference at com.example.quicknote.MyAdapter.getItemCount(MyAdapter.java:39)

Try this:-

Intent intent = new Intent(NotePad.this,MainActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("EXTRA_MESSAGE", data);
intent.putExtras(bundle);

//in MainActivity.class
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
ArrayList<String> data=(ArrayList<String>)bundle.getSerializable("EXTRA_MESSAGE");

You are trying to pass ArrayList and you read data from intent with getStringArrayListExtra method. You have to put data like this:

intent.putStringArrayListExtra(EXTRA_MESSAGE, data);

Edit : Check if intent has key:

if (intent.hasExtra(NotePad.EXTRA_MESSAGE)) {
    notes = intent.getStringArrayListExtra(NotePad.EXTRA_MESSAGE);
}

Note : If this is just a playground it is OK. But if you trying to build something then your architecture is wrong. It is not a good idea to pass same array every time between two activity. You can use startActivityForResult method and get new note onActivityResult method of MainActivity.

The best way given in android document to send the arraylist or any custom object from one activity to another to Try the light weight process for this in android

Read the full overview about it https://developer.android.com/reference/android/os/Parcelable

hope it will help for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM