Add items to listview from other activity

2019-09-23 14:16发布

scenario:

First mainactivity launches and from the menu option user launches second activity using intent and there he adds some text to edittext and get that edittext value using intent to the first activity and add that value to the listview.

FirstActivity:

public class MainActivity extends Activity {

    ListView lv;
    EditText et;
    String AddedTask ;
    ArrayList<Model> modelList;
    CustomAdapter adapter;

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

              Intent intent = getIntent();
                if (intent.hasExtra("NewTask")) {
                AddedTask = this.getIntent().getExtras().getString("NewTask");
                lv = (ListView) findViewById(R.id.listViewData);
                String name = AddedTask;
                Model md = new Model(name);
                modelList.add(md);
                adapter = new CustomAdapter(getApplicationContext(), modelList);
                lv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
          }



    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        case R.id.action_add_task:
            Intent i = new Intent(MainActivity.this, AddTask.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

}

Second Activity:

public class AddTask extends Activity {
Button addtask;
      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.add_task);

            // get action bar   
            ActionBar actionBar = getActionBar();

            // Enabling Up / Back navigation
            actionBar.setDisplayHomeAsUpEnabled(true);

            addtask = (Button) findViewById(R.id.btnaddlist);
            findViewById(R.id.btnaddlist).setOnClickListener(
                      new View.OnClickListener() {
                          public void onClick(View arg0) {
                              EditText edit = (EditText) findViewById(R.id.tskname);
                              Intent i = new Intent(AddTask.this,
                                      MainActivity.class);
                              //Bundle bundle = new Bundle();
                              String TaskName = edit.getText().toString();
                              //bundle.putString("NewTask", TaskName);
                              i.putExtra("NewTask", TaskName);
                              i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                              //i.putExtras(bundle);
                              startActivity(i);
                          }
                      });

          } 

        }

Now my problem is I'm able to add the data to the listview but each time I come back to mainactivity the previous data which was added is lost and updating the old data with my new data.

I have searched for many SO answers and most of them suggest to add adapter.notifyDataSetChanged(); which I have already tried and nothing worked.

I have done by checking the adapter is null or updating the data this way and getting null pointer exception:

if ( adapter== null )
{
   adapter = new CustomAdapter(getApplicationContext(), modelList);
  lv.setAdapter(adapter);
}

Can anyone say me how do I get this working ?

2条回答
对你真心纯属浪费
2楼-- · 2019-09-23 15:00

Don't use putextra and intent techniques. Follow below technique.

In main activity create sharedpref as follows:

public static final String SharedPref = "MyPreferences";

In activity 2 insert this code.

SharedPreferences settings=null;//declaration

settings=getSharedPreferences(SharedPref,0);//initialization

String TaskName= edit.getText().toString();
SharedPreferences.Editor editor = settings.edit();
editor.putString("NewTask", TaskName);
editor.commit();
finishfromchild(AddTask.this);

In main activity:

SharedPreferences settings=null;//declaration

In onCreate

//now initialise settings
settings=getSharedPreferences(SharedPref,0);//SharedPref is the foldername      
//of your sharedpreferences(you create it first)

//Now create onResume method
public void onResume()
{
 super.onResume();
            AddedTask=settings.getString("NewTask", "");
            lv = (ListView) findViewById(R.id.listViewData);
            String name = AddedTask;
            Model md = new Model(name);
            modelList.add(md);
            adapter = new CustomAdapter(getApplicationContext(), modelList);
            lv.setAdapter(adapter);
}

Hope this works. I did the same in my previous project.

查看更多
一夜七次
3楼-- · 2019-09-23 15:02
new View.OnClickListener() {
                      public void onClick(View arg0) {
                          EditText edit = (EditText) findViewById(R.id.tskname);
                          Intent i = new Intent(AddTask.this,
                                  MainActivity.class);
                          //Bundle bundle = new Bundle();
                          String TaskName = edit.getText().toString();
                          //bundle.putString("NewTask", TaskName);
                          i.putExtra("NewTask", TaskName);
                          i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                          //i.putExtras(bundle);
                          startActivity(i);
                      }
                  });

You are starting a new Activity each time you want to add an item.
Consider using

startActivityForResult()  

Link to Android Documentation

Even if startActivityForResult() is IMHO the best way to fix your problem, i'll give you a hint why it doesn't show your "old" data. You don't finish your first Activity when going to the Second. You could aswell just finish your second activity and your MainActivity would run into

onResume()

therefor check the Android lifecycle

查看更多
登录 后发表回答