In my android app, I have one Activity and more java class which is not an activity.
So there is a get method in this other java class, which returns an Object. This method starts a new thread to gets the data and attaches it with the object
Now I am calling this get method in my Activity to get that object. I am doing something like this –
mNewsList = new ArrayList<NewsContentManager.NewsPojo>();
mNewsList = manager.getNewsList();
and the method is this -
public ArrayList<NewsPojo> getNewsList() {
Log.v("TAG", ""+newsList);
if(newsList == null)
{
Thread t = new Thread(){
public void run(){
Log.v("TAG", "Inside run");
np1 = new NewsPojo();
np1.setTitle("A");
np1.setDescription("dhghfdklsa");
np2 = new NewsPojo();
np2.setTitle("B");
np2.setDescription("dhghfdklsa");
np3 = new NewsPojo();
np3.setTitle("c");
np3.setDescription("dhghfdklsa");
newsList = new ArrayList<NewsPojo>();
Log.v("in run",""+newsList);
newsList.add(np1);
newsList.add(np2);
newsList.add(np3);
Log.v("in run",""+newsList.size());
setNewsList(newsList);
handler.sendEmptyMessage(0);
}// end of run
};// end of thread
t.start();
}//end of if
return newsList;
}
But I am getting nullPointer Exception in my Activity.
If I remove Thread from this method then it works correctly.
What should I do ?
Thanks
Additionally to my comment to your question.
First, try to avoid using Threads in such a way. Use AsyncTask instead.
On it’s preExecute show some dialog to the user, that you are loading a list, on it’s doInBackground put your logic that will return new list, and in postExecute just dismiss the dialog and proceed.