m0j1
m0j1

Reputation: 4267

ArrayList values gone after calling setAdapter

I have a android app which shows a gridview , there's two classes one is GridActivity and another is GridActivityAdapter. I read a json file in AsyncTask method and add json items to an ArrayList. the problem is that I need the data of this ArrayList in my adapter , before setting the adapter the size of this ArrayList is 3 but right after setting the adapter and when I log it in adapter constructor the size is 0 and all the values in my ArrayList is gone!
here's the code from my GridActivity

public class GridActivity extends Activity{
 public GridView gridView;
 public GridActivityAdaptor adaptorl
 public JsonObject[] jsonObjs;
 public ArrayList<String> urls = new ArrayList<String>();

 protected void onCreate(Bundle savedInstaceState){
 super.onCreate(savedInstanceState);
 setContentView(R.layout.grid_layout);

 new GetJson().execute();
 });
}

private class GetJson extends AsyncTask<Void,Void,Void>
{
 @Override
 protected Void doInBackground(Void... params){
 serviceHandler sh = new ServiceHandler();//handles all http connection parts
 String jsonStr = sh.makeServiceCall(jsonUrl;ServiceHandler.Get);//gets the json data
 if(jsonStr!=null)
 {
  try{
   JSONObject jsonObj = new JSONObject(jsonStr);
   JSONArray jsons = jsonObj.getJSONArray("items");
   jsonObjs = new JSONObject[jsons.length()];
   for(int i=0;i<jsons.length();i++)
   {
    jsonObjs = jsons.getJSONObject(i);
    urls.add(jsonObjs[i].getString("url"));
   }
  }
  catch(JSONException e){
   e.printStackTrace();
  }
 }
 return null;
}

@Override
protected void onPostExecute(Void result){
 super.onPostExecute(result);
 Log.d("appname","urls.size()" + urls.size()); //returns 3 here
 gridView.setAdapter(new GridActivityAdapter(GridActivity.this));
}
}
}

And this is the code of GridActivityAdapter :

public class GridActivityAdapter extends BaseAdapter{
 public GridActivity gridActivity;
 public GridActivity(Context c){
  gridActivity = new GridActivity();
  Log.d("appname","urls size: " + gridActivity.urls.size()); //returns 0
 }
 ...
 ...
 ...
 ...
}

the urls.size() return 3 when I log before setAdapter but right after it and in the constructor of the GridActivityAdapter the same log returns 0 and I can't use my ArrayList anymore.
I'll appreciate if someone can help me with this.

Upvotes: 1

Views: 120

Answers (1)

Rami
Rami

Reputation: 7929

try this:

in your adapter:

public GridActivity(Context c, ArrayList<String> urls){

  Log.d("appname","urls size: " + urls.size());
}

in your activity:

@Override
protected void onPostExecute(Void result){
 super.onPostExecute(result);
   Log.d("appname","urls.size()" + urls.size()); 
   gridView.setAdapter(new GridActivityAdapter(GridActivity.this, urls));
}

Upvotes: 1

Related Questions