ArrayList.add not working with AsyncTask


ArrayList.add not working with AsyncTask



I'm using fragment view to show ListView in my Android Application. It is working perfectly when I manually enter ArrayList. But now I want to add JSON array to the ArryList in AsyncTask class and add that ArrayList to Adapter.


ListView


ArrayList


ArryList


AsyncTask


ArrayList



So I got JSON array and put It ArrayList. This process doing in the AsyncTask class.


ArrayList


AsyncTask



I execute that AsyncTask class in onCreateView() method in Fragment. Then I set ArrayList to Adapter. But problem is there..


AsyncTask


onCreateView()


ArrayList



After execute AsyncTask class get my JSON array perfectly and add to the ArrayList. But when I try to add my ArrayList to Adapter. Then my ArryaList empty.


AsyncTask


ArrayList


ArrayList


ArryaList



This my fragment class with AsyncTask Part


AsyncTask


public class FragmentCategory extends Fragment {

private ListView lvCategory;
private CategoryAdapter categotyAdapter;
private List<Category> mCategoryLst;

View view;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

view = inflater.inflate(R.layout.fragment_category , container, false);
lvCategory = (ListView) view.findViewById(R.id.listview_category);
mCategoryLst = new ArrayList<>();
/*mCategoryLst.add(new Category(1, "hghjj" ,null));
mCategoryLst.add(new Category(2,"Abcd", null));
mCategoryLst.add(new Category(3,"Aeec", null));*/
new FetchDataTask().execute();
if(mCategoryLst!=null && mCategoryLst.size()>0) {
categotyAdapter = new CategoryAdapter(getContext(), mCategoryLst);
}

lvCategory.setAdapter(categotyAdapter);
return view;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//new FetchDataTask().execute();

}
public class FetchDataTask extends AsyncTask<String,String,Void>
{
private ProgressDialog progressDialog = new ProgressDialog(getActivity());
private String mUrlCategory;
@Override
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
FetchDataTask.this.cancel(true);
}
});
}

@Override
protected Void doInBackground(String... strings) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
Uri bUri = Uri.parse(getString(R.string.url_category));
URL url;
try {
url = new URL(bUri.toString());
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();

if(inputStream==null)
{
return null;
}

reader = new BufferedReader(new InputStreamReader(inputStream));

String line;
while ((line = reader.readLine()) != null)
{
buffer.append(line + "n");
}

if(buffer.length() == 0)
{
return null;
}
mUrlCategory = buffer.toString();

}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (JSONException e) {
e.printStackTrace();
} */finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
try {
if (progressDialog.isShowing())
progressDialog.dismiss();
JSONArray jArray = new JSONArray(mUrlCategory);
for (int i = 0; i < jArray.length(); i++) {

JSONObject jObject = jArray.getJSONObject(i);

int id = Integer.parseInt(jObject.getString("id"));
String name = jObject.getString("categoryName");
String imageUrl = jObject.getString("iconPath");

mCategoryLst.add(new Category(id, name ,null));
}
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (Exception e)
}
}

}



This my Category class
This one using for create ArrayList


ArrayList


public class Category {

private int categoryId;
private String categoryName;
private String imgUrl;

public Category()
{

}

public Category(int id,String name, String img)
{
this.categoryId=id;
this.categoryName=name;
this.imgUrl=img;
}

//Gettert

public int getCategoryId() {
return categoryId;
}

public String getCategoryName() {
return categoryName;
}


public String getImgUrl() {
return imgUrl;
}

//Settert


public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}

public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}

public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}



This my Adapter class


public class CategoryAdapter extends BaseAdapter {

private Context mContext;
private List<Category> mCategoryList;

//Constructor


public CategoryAdapter(Context mContext, List<Category> mCategoryList) {
this.mContext = mContext;
this.mCategoryList = mCategoryList;
}

@Override
public int getCount() {
return mCategoryList.size();
}

@Override
public Object getItem(int position) {
return mCategoryList.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.item_category, null);
TextView tvCategoryName = (TextView) v.findViewById(R.id.category_name);
ImageView ivCategoryImg = (ImageView) v.findViewById(R.id.img_category);
//Set Value
tvCategoryName.setText(mCategoryList.get(position).getCategoryName());
//ivCategoryImg.setImageResource();
//Set ID
v.setTag(mCategoryList.get(position).getCategoryId());

return v;
}
}





add this line categotyAdapter = new CategoryAdapter(getContext(), mCategoryLst); lvCategory.setAdapter(categotyAdapter); in your onPostExecute method it will work
– Nilesh Rathod
Jun 30 at 7:37


categotyAdapter = new CategoryAdapter(getContext(), mCategoryLst); lvCategory.setAdapter(categotyAdapter);


onPostExecute





Even better Use categotyAdapter.notifyDataSetChanged(); after adding data in your mCategoryLst inside onPostExecute method of your FetchDataTask asynctask
– Nilesh Rathod
Jun 30 at 7:44


categotyAdapter.notifyDataSetChanged();


mCategoryLst


onPostExecute


FetchDataTask





@Nilesh Thank you.. It's working...
– Ayesh Ruwantha
Jun 30 at 8:49




4 Answers
4


categotyAdapter = new CategoryAdapter(getActivity(), mCategoryLst);
lvCategory.setAdapter(categotyAdapter);





While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Narendra Jadhav
Jun 30 at 11:08



as per your code, what i see, make changes like below code, for Fragment OnCreateView() and OnPostExecuation of AysncTask class.


public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

view = inflater.inflate(R.layout.fragment_category , container, false);
lvCategory = (ListView) view.findViewById(R.id.listview_category);
mCategoryLst = new ArrayList<>();
/*mCategoryLst.add(new Category(1, "hghjj" ,null));
mCategoryLst.add(new Category(2,"Abcd", null));
mCategoryLst.add(new Category(3,"Aeec", null));*/
new FetchDataTask().execute();

categotyAdapter = new CategoryAdapter(getContext(), mCategoryLst);
lvCategory.setAdapter(categotyAdapter);
return view;
}



And in OpPostExecution


protected void onPostExecute(Void aVoid) {
try {
if (progressDialog.isShowing())
progressDialog.dismiss();
JSONArray jArray = new JSONArray(mUrlCategory);
for (int i = 0; i < jArray.length(); i++) {

JSONObject jObject = jArray.getJSONObject(i);

int id = Integer.parseInt(jObject.getString("id"));
String name = jObject.getString("categoryName");
String imageUrl = jObject.getString("iconPath");

mCategoryLst.add(new Category(id, name ,null));
}
categotyAdapter.notifyDataSetChanged();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (Exception e)
}





This is not working for me. but thank you. Your answer was help to me solved this problem
– Ayesh Ruwantha
Jun 30 at 9:07



Problem Solved
I change my onPostExecute() method like this...


onPostExecute()


@Override
protected void onPostExecute(Void aVoid) {
try {
if (progressDialog.isShowing())
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(mUrlCategory);

Log.v("Response", jsonObject.toString());

JSONArray categoryArray = jsonObject.getJSONArray("itemcategory");
for (int i = 0; i < categoryArray.length(); i++) {

JSONObject jCategory = (JSONObject) categoryArray.get(i);

int id = Integer.parseInt(jCategory.getString("id"));
String name = jCategory.getString("categoryName");
String imageUrl = jCategory.getString("iconPath");

mCategoryLst.add(new Category(id, name, null));
}

if (mCategoryLst != null && mCategoryLst.size() > 0) {
categotyAdapter = new CategoryAdapter(getContext(), mCategoryLst);
}

lvCategory.setAdapter(categotyAdapter);
categotyAdapter.notifyDataSetChanged();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (Exception e)
}



When I put this part


if (mCategoryLst != null && mCategoryLst.size() > 0) {
categotyAdapter = new CategoryAdapter(getContext(), mCategoryLst);
}

lvCategory.setAdapter(categotyAdapter);



in OnCreateView() application not working. So I put It in onPostExecute(). Then It work perfectly. Thanks All


OnCreateView()


onPostExecute()



You need to call notifyDataSetChanged() on your adapter when you have the data:


notifyDataSetChanged()


for (int i = 0; i < jArray.length(); i++) {

JSONObject jObject = jArray.getJSONObject(i);

int id = Integer.parseInt(jObject.getString("id"));
String name = jObject.getString("categoryName");
String imageUrl = jObject.getString("iconPath");

mCategoryLst.add(new Category(id, name, null));
}
categotyAdapter.notifyDataSetChanged();






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Extract Id from Twitch Clip URL

Why are these constructs (using ++) undefined behavior in C?

I'm Still Waiting (Diana Ross song)