0

I am trying to call fragment method from main activity.But my app is crashing

This is my code:

    public class MainActivity extends FragmentActivity implements 
    ActionBar.TabListener,ConversationFragment.OnGetFromUserClickListener {
         ConversationFragment frgObj;
         Hashtable<String, ArrayList<Message>> table = new Hashtable<String, ArrayList<Message>>();

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            addMessageToFragment("test");
    }

public void addMessageToFragment(String message) {
    Log.w("Step 1",message);
    table.put("tolgay", new ArrayList<Message>());
    table.get("tolgay").add(new Message("asda", "asda"));
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    frgObj=ConversationFragment.newInstance(table.get("tolgay"));
    fragmentTransaction.replace(R.id.container, frgObj,"ConversationFragment");
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
    getSupportFragmentManager().executePendingTransactions();
    frgObj.addMessageToList("asd");

}
}

What is wrong with this code ? I want to load fragment with some data in oncreate method.How can I fix it ?

Here logcat:http://goo.gl/id4UmY

Tolgay Toklar
  • 4,151
  • 8
  • 43
  • 73

2 Answers2

0

Your NPE is on this row:

 table.get("tolgay").add(new Message("asda", "asda"));

Since table is non-null by initialization, the only possibility for a NPE here is that table.get("tolgay") returns null. The hashtable doesn't contain a message with such key. Use put() to insert new keys in case one didn't exist.

Also consider using HashMap instead of Hashtable. In UI code like this running in a single thread you don't need the synchronization provided by Hashtable.

laalto
  • 150,114
  • 66
  • 286
  • 303
0

My suggestions would be to simply create your fragment instance, add Bundle and then use the setArguments() methods to set it on the fragment. Just make sure the data you are setting is not null.

Then while in your fragment (could be inside onAttach or onCreate or onActivityCreated method, just use this:

Bundle bundle = this.getArguments(); 

Then retrieve the data that you added before.

I hope this helps you!

Eenvincible
  • 5,641
  • 2
  • 27
  • 46
  • I can't do it because I am passing arraylist. – Tolgay Toklar Aug 19 '14 at 14:20
  • You cannot pass an array to a bundle? http://stackoverflow.com/questions/5299532/passing-arrays-using-bundle-in-android or you might have to use a different approach if you cannot modify the data structure to use primities; http://stackoverflow.com/questions/1441871/passing-data-of-a-non-primitive-type-between-activities-in-android – Eenvincible Aug 19 '14 at 14:22