ArrayList.add无法与AsyncTask一起使用

时间:2018-06-30 07:35:48

标签: android arrays json arraylist android-asynctask

我正在使用片段视图在我的Android应用程序中显示ListView。当我手动输入ArrayList时,它运行良好。但是现在我想将JSON数组添加到ArryList类中的AsyncTask并将该ArrayList添加到Adapter。

所以我得到了JSON数组并将其放入ArrayList。此过程在AsyncTask类中完成。

我在Fragment的AsyncTask方法中执行该onCreateView()类。然后,将ArrayList设置为Adapter。但是问题就在那里。

在执行AsyncTask类之后,完美获取我的JSON数组并添加到ArrayList中。但是,当我尝试将ArrayList添加到适配器时。然后我的ArryaList为空。

这是我的带有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)
    }
}

}

这是我的类别课程
这个用于创建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;
}
}

这是我的适配器类

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;
}
}

4 个答案:

答案 0 :(得分:0)

拥有数据后,您需要在适配器上调用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();

答案 1 :(得分:0)

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

答案 2 :(得分:0)

根据您的代码,我看到的是对Fragment OnCreateView()和AysncTask类的OnPostExecuation进行如下代码更改。

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;
}

在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)
    }

答案 3 :(得分:0)

已解决的问题 我这样更改我的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)
}

当我放置这部分时

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

lvCategory.setAdapter(categotyAdapter);
OnCreateView()应用程序中的

无法正常工作。所以我把它放在onPostExecute()中。然后,它完美地工作。谢谢大家