Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

change single item listview android with asynctask

I'm learning how to change single item custom listview android with AsyncTask, I've followed this tutorial.

but it's seem not work in my listview.

this my code

private class ViewHolder {
    public ImageButton favorite;
    public TextView jmlh_favorite;
    protected int position;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    final ViewHolder holder;

    if (convertView == null) {
        vi = inflater.inflate(R.layout.laporan_list_item, null);
        holder = new ViewHolder();
        holder.jmlh_favorite = (TextView)vi.findViewById(R.id.jmlh_favorite);
        holder.favorite = (ImageButton)vi.findViewById(R.id.favorite);
        vi.setTag(holder);
    } else {
        holder = (ViewHolder) vi.getTag();
    }

    holder.favorite.setOnClickListener(new android.view.View.OnClickListener() {
        @Override
        public void onClick(View v) {
            holder.position = position;
            position_change=position;
            String varid_laporan = holder.id_laporan.getText().toString();
            String var_kat_favorite = holder.kat_favorite.getText().toString();
            url = "http://xxxx.com/android/upload_image/favorite_laporan.php?kat="+var_kat_favorite+"&id_laporan="+varid_laporan+"&uid="+URLEncoder.encode(uid);
            grabURL(url,position,holder); 
        } 
    });

    return vi;
}

public void grabURL(String url, int position,ViewHolder holder) {
    Log.v("Android Spinner JSON Data Activity", url);
    mTask = new GrabURL(position, holder).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
}

private class GrabURL extends AsyncTask<String, Void, String> {
    private static final int REGISTRATION_TIMEOUT = 3 * 1000;
    private static final int WAIT_TIMEOUT = 30 * 1000;
    private final HttpClient httpclient = new DefaultHttpClient();
    final HttpParams params = httpclient.getParams();
    HttpResponse response;
    private String content = null;
    private boolean error = false;
    private ProgressDialog dialog = new ProgressDialog(activity);

    private int mPosition;
    private ViewHolder mHolder;

    public GrabURL(int position, ViewHolder holder) {
        mPosition = position;
        mHolder = holder;
    }

    protected void onPreExecute() {
        dialog.setMessage("Getting your data... Please wait...");
    }

    protected String doInBackground(String... urls) {
        String URL = null;

        try {
            URL = urls[0];
            HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
            ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);

            HttpPost httpPost = new HttpPost(URL);
            response = httpclient.execute(httpPost);

            StatusLine statusLine = response.getStatusLine();

            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                content = out.toString();
            } else {
                //Closes the connection.
                Log.w("HTTP1:",statusLine.getReasonPhrase());
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            Log.w("HTTP2:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        } catch (IOException e) {
            Log.w("HTTP3:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        } catch (Exception e) {
            Log.w("HTTP4:",e );
            content = e.getMessage();
            error = true;
            cancel(true);
        }

        return content;
    }

    protected void onCancelled() {
        mTask.cancel(true);
        statusKoneksi();
    }

    protected void onPostExecute(String content) {
        if (error) {
            mTask.cancel(true);

            statusKoneksi();
        } else {
            displaylaporanList(content,mPosition,mHolder);
            mTask.cancel(true);
        }
    }
}

private void displaylaporanList(String response, int mPosition, ViewHolder mHolder){

    JSONObject json = null; 

    try {
        json = new JSONObject(response); 
        laporanListObj = json.getJSONArray(ContentLaporanActivity.TAG_FAVORITE_LAPORAN);
        int Jumlah_list_Data = laporanListObj.length();

        if (Jumlah_list_Data== 0) {
        } else {
            JSONObject c = laporanListObj.getJSONObject(0);
            String jumlah_favorite = c.getString(ContentLaporanActivity.TAG_BANYAK_FAVORITE_LAPORAN);
            String status_favorite = c.getString(ContentLaporanActivity.TAG_STATUS_FAVORITE);

            if (mHolder.position == mPosition) {
                mHolder.jmlh_favorite.setText(status_favorite);
            }
        }

        notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

void statusKoneksi(){
    Toast.makeText(activity, "gagal", Toast.LENGTH_SHORT).show();
}

and this part where I want to setText when result asynctask in method displaylaporanList(), but it's not set Text.

if (mHolder.position == mPosition) {
    mHolder.jmlh_favorite.setText(status_favorite);
}

How to update the text?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The logic issue with your code is the following: You shouldn't update ViewHolder outside of getView(). ViewHolder is just about making list performance better and shouldn't be used as reference to list items in any moment of time.

In your case, to fix the issue You should call holder.jmlh_favorite.setText(status_favorite) inside getView() (e.g. store position and text somewhere). From displaylaporanList() You just need to call notifyDataSetChanged() to notify the Adapter that the data has been changed and list items should be updated. Also, refer to this session from Google I/O for more details about ListViews.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...