Add items to listview from other activity

て烟熏妆下的殇ゞ 提交于 2019-12-26 12:23:27

问题


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 ?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/30072055/add-items-to-listview-from-other-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!