【问题标题】:AsyncTask and JSON - AndroidAsyncTask 和 JSON - Android
【发布时间】:2014-09-25 21:41:22
【问题描述】:

我将 id 从 FirstFragment 传递给 SecondFragment。我需要将 POST 请求发送到 Web 服务以检索 JSON,我需要创建 SecondFragment 的内容。 SecondFragment 是具有自定义布局的 ListView。我正在使用我的自定义适配器类 (MyAdapter) 添加该布局。对于 JSON,我还有 AsyncTask 类 (GetCategoryTas) 问题是 SecondFragment 是在服务返回结果之前创建的。所以内容总是空白的。我该如何解决这个问题。

第一个片段:

@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    Bundle bundle = new Bundle();
    bundle.putString("id", menuList.get(position).getAlias());
    categoryPage = new FragmentCategoryPage();
    categoryPage.setArguments(bundle);
    transaction = manager.beginTransaction();
    transaction.replace(R.id.mainContainer, categoryPage, "CategoryPage");
    transaction.addToBackStack("CategoryPage");
    transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    transaction.commit();

}

第二个片段:

public class FragmentCategoryPage extends Fragment implements OnItemClickListener {

    private ListView lvCategory;
    private List<NameValuePair> pair;

    private ArrayList<ItemCategory> itemCatList = new ArrayList<ItemCategory>();
    private ItemCategory itemCat;

    private MyAdapter myAdapter;
    private Context context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);

        context = getActivity();

        String id = getArguments().getString("id");
        pair = new ArrayList<NameValuePair>();
        pair.add(new BasicNameValuePair("category", id));
        new GetCategoryTask().execute();

        lvCategory = (ListView) view.findViewById(R.id.lvCategory);

        myAdapter = new MyAdapter();
        lvCategory.setAdapter(myAdapter);
        lvCategory.setOnItemClickListener(this);

        return view;
    }

    // Creating own adapter for categories
    class MyAdapter extends BaseAdapter {

        @Override
        public View getView(final int pos, View convertView, ViewGroup parent) {
            View row = null;

            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.item_layout_category, parent, false);
            } else {
                row = convertView;
            }

            TextView tvCatTitle = (TextView) row.findViewById(R.id.tvCategoryTitle);
            TextView tvCatDate = (TextView) row.findViewById(R.id.tvCategoryDate);
            ImageView ivCatImage = (ImageView) row.findViewById(R.id.ivCategoryImage);

            return row;
        }

        @Override
        public int getCount() { return itemCatList.size(); }
        @Override
        public Object getItem(int pos) { return null; }
        @Override
        public long getItemId(int pos) { return 0; }
    }

    public class GetCategoryTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(Variables.URL_CATEGORY);
                httpPost.setEntity(new UrlEncodedFormEntity(pair));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                String data = EntityUtils.toString(httpEntity);

                int status = httpResponse.getStatusLine().getStatusCode();

                if (status == HttpStatus.SC_OK) {

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

                        JSONObject jRealObject = jArray.getJSONObject(i);

                        itemCat = new ItemCategory();
                        itemCat.setId(jRealObject.get("id").toString());
                        itemCat.setTitle(jRealObject.get("title").toString());
                        itemCat.setImage_name(jRealObject.get("image_name").toString());

                        itemCatList.add(itemCat);
                    }

                    return true;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            if(result == false) {
                Toast.makeText(context, Variables.ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

我该如何解决这个问题?

【问题讨论】:

    标签: android json android-fragments android-asynctask android-json


    【解决方案1】:

    您应该通过调用来刷新onPostExecute() 中的适配器;

    myAdapter.notifyDataSetChanged();
    

    【讨论】:

    • Ooooooooooooooooooooooooooooooo 伙计,非常感谢!!! :D 我整天都被 tihs sh*t 困住了 :) 再次感谢!
    【解决方案2】:

    我在您的代码中没有看到您已将列表视图与 itemCatList 连接。你应该在 onPostExecute 中对列表视图做任何你想做的事情,而不是在 onCreate 中,这样你就可以确定列表存在于那个点,因为 AsyncTask 在它自己的线程上运行 在 onPostExecute

     lv = (ListView) findViewById(R.id.your_list_view_id);
     List<String> your_array_list = new ArrayList<String>();
     ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
             this, 
             android.R.layout.simple_list_item_1,
             your_array_list );
    
     lv.setAdapter(arrayAdapter); 
    

    【讨论】:

    • 我有自定义布局的自定义适配器,我正在这样做:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 2021-09-27
    相关资源
    最近更新 更多