使用替换事务后,在片段中重新启动Asynctask

时间:2014-04-03 07:02:21

标签: android android-fragments android-listview fragment

我在我的片段中使用AsyncTask来加载Json的数据列表。单击每个列表项后,此列表片段将被包含详细信息的详细信息片段替换。然后在新片段(细节片段)中,用户按下后退按钮。然后再次列出片段开始 问题是Asynctask再次重新加载以获取列表项。我不想要这个。我想显示以前加载的列表。这是代码:

    public class MainList extends Fragment {
public MainList(){}

ArrayList<Country> countryList = new ArrayList<Country>();
Country country;
Button btnLoadMore;
ListView listView;
JSONParser jsonParser = new JSONParser();
public static String received_id;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
int current_page = 0;
int last_item;
int total_items = 32;
boolean continue_loading = true;
boolean loadingMore = false;
View footerView;
public ImageLoader_Json imageLoader;
int currentPosition = 0;
MyCustomAdapter dataAdapter = null;

private static String url_all_products_LoadMore = "http://www.hitel.ir/FarsiPlanet/Apps.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_RATE = "rate";
private static final String TAG_RATINGCOUNT = "ratingcount";
private static final String TAG_SHORT_DESCRIPTION = "short_description";



// products JSONArray
JSONArray products = null;
String Category;

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

    View rootView = inflater.inflate(R.layout.items_list, container, false);

    Category = getArguments().getString("category");

    footerView= ((LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_footer, null,false);
    listView = (ListView) rootView.findViewById(R.id.listView1);
    listView.addFooterView(footerView);
    imageLoader = new ImageLoader_Json(getActivity().getApplicationContext());
    displayListView();

    return rootView;
}

private void displayListView() {
    //create an ArrayAdaptar from the String Array
    dataAdapter = new MyCustomAdapter(getActivity(),
            R.layout.country_info, countryList);



    listView.setOnScrollListener(new OnScrollListener() {

        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub
        }

        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            int lastInScreen = firstVisibleItem + visibleItemCount;

            if((lastInScreen == totalItemCount) && !(loadingMore)){     

                new loadMoreListView().execute();
            } 
        }
    });

    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            final String pid = ((TextView) view.findViewById(R.id.pid)).getText().toString();
            Bundle data = new Bundle();
            data.putString(TAG_PID, pid);
            data.putString("TAG_Category", Category);
            Fragment fragment = new Details_Restaurant();
            FragmentManager fm = getFragmentManager();
            fragment.setArguments(data);
            fm.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack("f_02").commit();
        }
    });

    listView.setAdapter(dataAdapter);
    listView.setSelectionFromTop(currentPosition, 0); 
}

private class MyCustomAdapter extends ArrayAdapter<Country> {

    private ArrayList<Country> countryList;

    public MyCustomAdapter(Context context, int textViewResourceId, 
            ArrayList<Country> countryList) {
        super(context, textViewResourceId, countryList);
        this.countryList = new ArrayList<Country>();
        this.countryList.addAll(countryList);
    }

    private class ViewHolder {
        TextView code;
        TextView name;
        RatingBar rate;
        TextView ratingcount;
        TextView short_description;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));
        if (convertView == null) {

            LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.country_info, null);

            holder = new ViewHolder();
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.ratingcount = (TextView) convertView.findViewById(R.id.ratingCount);
            holder.short_description = (TextView) convertView.findViewById(R.id.short_description);
            holder.rate = (RatingBar) convertView.findViewById(R.id.ratingBar1);
            holder.code = (TextView) convertView.findViewById(R.id.pid);

            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final Country country = countryList.get(position);
        holder.name.setText(country.getName());
        holder.ratingcount.setText(country.getRatingCount());
        holder.short_description.setText(country.getShort_description());
        holder.rate.setRating(country.getRate());
        holder.code.setText(country.getCode());

        return convertView;
    }
}

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getActivity().getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}

class loadMoreListView extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        /*
        pDialog = new ProgressDialog(AllProductsActivity.this);
        pDialog.setMessage("درحال دريافت اطلاعات...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show(); */
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {

        String firts_item = Integer.toString(current_page*10);
        int success;
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("pid", firts_item));
            params.add(new BasicNameValuePair("category", Category));

            // getting product details by making HTTP request
            // Note that product details url will use GET request
            JSONObject json = jsonParser.makeHttpRequest(
                    url_all_products_LoadMore, "GET", params);

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    Float rate = (float) c.getInt(TAG_RATE);
                    String ratingcount = c.getString(TAG_RATINGCOUNT);
                    String short_description = c.getString(TAG_SHORT_DESCRIPTION);

                    country = new Country(id,name,rate,ratingcount,short_description,"","");
                    countryList.add(country);
                }
            }
            else{
                continue_loading = false;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
        current_page += 1;
        if (continue_loading) {
            currentPosition = listView.getFirstVisiblePosition();
            dataAdapter.notifyDataSetChanged();
            displayListView();
            loadingMore = false;

        } else {
            listView.removeFooterView(footerView);
        }

    }
}

}

2 个答案:

答案 0 :(得分:1)

在调用onScrollStateChanged和onScroll之前,你需要包含@Override

listView.setOnScrollListener(new OnScrollListener() {

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
    }

    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        int lastInScreen = firstVisibleItem + visibleItemCount;

        if((lastInScreen == totalItemCount) && !(loadingMore)){     

            new loadMoreListView().execute();
        } 
    }
});

答案 1 :(得分:0)

当您对片段执行replace()操作时,您将删除列表片段,因此在回击时,您将使用listfragment替换详细信息片段,该片段调用onCreateView()作为片段生命周期的一部分。

当asynctask的onPostExecute()结束时,我会尝试将静态booelan设置为true,因此下次调用列表片段的onCreateView()时,您将检查该标志的值,如果设置为true不会执行任务,只需使用旧的静态数据设置适配器。