简体   繁体   中英

ArrayList to another activity and display in a ListView

I am trying to create an arrayList in one of the activity and pass it in another activity, and display it in the Listview . The first intent code in the first activity is inside onOptionItemSelected method

else if(id == R.id.History)
    {  
Intent i=new Intent(this,History.class);
 i.putExtra("name",al);
 startActivity(i);

this is the other activity code

protected void onCreate(Bundle savedInstanceState)    
{

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ArrayList<String> str= (ArrayList<String>)getIntent().getParcelableExtra("name");

ListView lv=(ListView)findViewById(R.id.list);
 ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                    this,
                    android.R.layout.simple_list_item_1,
                     str);
            lv.setAdapter(arrayAdapter);

This is how I am adding to the array list in the first activity, ArrayList is defined globally, n is a variable that is running the index. it is defined as 0 at first, then incremeneted by 2 before addToStringList method is called

public void addToStringList(){

    EditText et=(EditText)findViewById(R.id.abcd);
    EditText et1=(EditText)findViewById(R.id.abc);
    String eam1=et.getText().toString();
    String eam2=et1.getText().toString();
    al1.add(n-2,eam1);
    al1.add(n-1,eam2);
}

Whenever I am clicking the overflow item button "Caused by: java.lang.NullPointerException: " is shown and nothing is getting displayed. I don't know where I am going wrong

Take a look at this post Intent.putExtra List it should help. You need to use the intent.putStringArrayListExtra() method instead it appears, if you still get a null object make sure the list you are passing is not a null object.

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