listview没有从asynctask刷新

时间:2014-03-17 13:26:22

标签: android listview android-asynctask

嘿所有我试图从asyncktask更新自定义列表视图我有2个不同的layuots 1我的主要,另一个是1行。 我还有4个主要的活动,一个adaptar类,一个asyncktask,以及一个对象的Entry。 我注意到一些奇怪的事情,当我在onpost方法上使用断点时一切正常,它加载我的列表,但如果我不工作thx alow

public class connect_Async_Task extends AsyncTask<String,ArrayList<Entry>,ArrayList<Entry>> {
    private Activity mContext;
    private ProgressDialog progressDialog ;
    custom_list adapter;
    ArrayList<Entry> EntryArray=new ArrayList<Entry>();
    connect_Async_Task(Activity context,custom_list adapter1)
    {
        mContext=context;
        adapter=adapter1;
    }
    //ProgressDialog dialog = new ProgressDialog(getParent(),R.style.progressdialog);
    // The variable is moved here, we only need it here while displaying the
    // progress dialog.
    TextView txtView;
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setMessage("Loading preview...");
        if(progressDialog != null) progressDialog.show();
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                connect_Async_Task.this.cancel(true);
            }
        });
    }
    @Override
    protected ArrayList<Entry> doInBackground(String... uri) {
        android.os.Debug.waitForDebugger();
        HttpClient httpclient = new DefaultHttpClient();
        // Prepare a request object
        HttpGet httpget = new HttpGet(uri[0]);
        // Execute the request
        HttpResponse response;
        String result;
        result = null;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release
            if (entity != null) {
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                result = convertStreamToString(instream);
                // now you have the string representation of the HTML request
                instream.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONArray json_Array;

        try {
            json_Array = new JSONArray(result);
            for (int i = 0; i < json_Array.length(); i++) {
                JSONObject json_data = json_Array.getJSONObject(i);
                Integer jsonIDs = json_data.getInt("ID");
                String jsonNames = json_data.getString("Name");
                //String jsonImage =  json_data.getString("Image");
                String jsonCategory = json_data.getString("Category");
                String jsonIngredients = json_data.getString("Ingredients");
                String jsonPrice = json_data.getString("Price");
                Entry k=new Entry(jsonIDs,jsonNames,jsonCategory,jsonIngredients,jsonPrice);
                EntryArray.add(i,k);                    
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return EntryArray;
    }
    @Override
    protected void onPostExecute(ArrayList<Entry> EntryArray) {
        this.progressDialog.dismiss();
        adapter.upDateEntries(EntryArray);
    }
}

和主要活动

public class MainActivity extends ActionBarActivity  {

ListView list;
custom_list madapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    list=(ListView)findViewById(R.id.listView);
    madapter=new custom_list(this);
    list.setAdapter(madapter);

    connect_Async_Task conn = new connect_Async_Task(this,madapter);
    conn.execute("string that return jason array");     
}

编辑 - 适配器:

package com.example.app;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class custom_list extends BaseAdapter {

private Context mContext;

private LayoutInflater mLayoutInflater;

private ArrayList<Entry> mEntries = new ArrayList<Entry>();

public custom_list(Context context) {
    mContext = context;
    mLayoutInflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);        
}

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

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

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

@Override
public View getView(int position, View convertView,
                    ViewGroup parent) {
    RelativeLayout itemView;
    if (convertView == null) {
        itemView = (RelativeLayout) mLayoutInflater.inflate(
                R.layout.fragment_custom, parent, false);
    } else {
        itemView = (RelativeLayout) convertView;
    }
    TextView titleText = (TextView)
            itemView.findViewById(R.id.listTitle);
    TextView descriptionText = (TextView)
            itemView.findViewById(R.id.listDescription);
    String title = mEntries.get(position).getJsonNames();
    titleText.setText(title);
    String description =
            mEntries.get(position).getJsonNames();
    if (description.trim().length() == 0) {
        description = "Sorry, no description for this image.";
    }
    descriptionText.setText(description);
    return itemView;
}

public void upDateEntries(ArrayList<Entry> entries) {
    mEntries.clear();
    mEntries.addAll(entries);
    notifyDataSetChanged();
}

}

1 个答案:

答案 0 :(得分:0)

我还不能发表评论。但是,您并不需要在ListView上再次设置适配器(AsyncTask的onPostExecute())。只需使用 notifyDataSetChanged()即可。

好吧,尝试删除 ListView k =(ListView)mContext.findViewById(R.id.listView); (及其对该方法的后续调用)并查看是否作品。

PS:看看Retrofit处理您的JSON请求。