coder
coder

Reputation: 13248

Adding items to listview from bundle in fragment

Scenario:

First user login and goes to mainactivity which contains a homefragment which opens by default. Now from here the user goes to new activity where I add some text to edit text and clicks add button which gets back the user back to home fragment which is in mainactivity.

Now my problem is how do I add this text to my listview.

As by default the home fragment loads for the first time it dosen't contain any bundle.

First when my Main Activity Loads this what triggers:

public class HomeFragment extends Fragment  {
    ListView lv;
    public HomeFragment(){}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    return rootView;
  }

}

After loading the home fragment It has a list view where I need to add some data to it. Now I go to new activity by clicking a menu option.

Here I add some text to the edittext and pass that data through intent back to mainactivity as shown below:

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

Lastly I'm getting the value using intent as shown below:

String AddedTask ;
     if (intent.hasExtra("NewTask")) {
                 AddedTask = this.getIntent().getExtras().getString("NewTask");
                 Log.d("Task Added:",AddedTask);
                 Bundle bundle = new Bundle();
                 bundle.putString("Task Added", AddedTask);
                 HomeFragment fragobj = new HomeFragment();
                 fragobj.setArguments(bundle);
    }

Now my question is I have a listview in homefragment so how do I add this value to the listview I'm trying to use this way but logcat is showing me the null exception as when my mainactivity loads the home fragment loads first and I dont get any value from intent:

public class HomeFragment extends Fragment  {
    ListView lv;
    public HomeFragment(){}
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        lv = (ListView)rootView.findViewById(R.id.tasklist);
        Bundle b = getActivity().getIntent().getExtras();
        if (b != null) {
            ArrayList<String> list = new ArrayList<String>();
            ArrayAdapter<String> Listadapter;
            String ItemName = getArguments().getString("Task Added");  
            list.add(ItemName);
            Listadapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
            lv.setAdapter(Listadapter);
            Listadapter.notifyDataSetChanged();

        }
        return rootView;
  }

}

Can anyone help me out with this ?

Upvotes: 3

Views: 792

Answers (2)

JafarKhQ
JafarKhQ

Reputation: 8734

1- From HomeFragment/MainActivity start you 2nd Activity AddTaskActivity using

startActivityForResult(addTaskIntent, CODE_ADD_TASK);

2- Now in your AddTaskActivity change btnaddlist callback to

@Override
public void onClick(View v) {
     EditText edit = (EditText) findViewById(R.id.tskname);
     Intent i = new Intent();
     String TaskName = edit.getText().toString();
     i.putExtra("NewTask", TaskName);
     setResult(RESULT_OK, i);
     finish();
}

3- In your MainActivity override the method onActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == CODE_ADD_TASK) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            String taskName = data.getStringExtra("NewTask");
            // send this data to your Fragment and add it to the list
        }
    }
}

Upvotes: 2

vishalk
vishalk

Reputation: 659

You can add check for first time loading, like following.

String ItemName = getArguments().getString("Task Added", "");  
if(ItemName != "") {
    list.add(ItemName);
}

So it won't crash.

Upvotes: -1

Related Questions