Android列表视图当前位置无法正常工作

时间:2014-06-25 17:46:58

标签: android android-listview

我从数据库中获取数据并将其推送到ListView以查看所有数据。

在我的ListView中,我还有一个带有文字“Like”的TextView。现在,当我单击相同的文本时,它将更改为“Liked”,并且我正在更新我在数据库中的状态。

现在我的问题是,当我点击“赞”文字时,文字会变为“喜欢”,并且会在数据库中更新。但是当我滚动列表视图时,我可以注意到其他列表'喜欢的文字也被改为喜欢。我不确定出了什么问题。

我一直试图解决这个问题很多天但没有成功。

这是我的适配器代码。在底部,您可以看到我的onClickListener for textview

package com.mytestapp.myapp;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ForumAdapter extends ArrayAdapter<DiscussionList> {
    private static List<DiscussionList> items = null;

    public ForumAdapter(Context context, List<DiscussionList> items) {
        super(context, R.layout.custom_list, items);
        this.items = items;
    }

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

    public static DiscussionList getModelPosition(int position) {
        return items.get(position);
    }

    public void refill(List<DiscussionList> items) {
        items.clear();
        items.addAll(items);
        notifyDataSetChanged();
    }

    public static class ViewHolder {
        WebView mywebviewholder;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        View v = convertView;

        if (v == null) {
            LayoutInflater li = LayoutInflater.from(getContext());
            v = li.inflate(R.layout.custom_list, null);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        DiscussionList app = items.get(position);

        if (app != null) {
            TextView titleText = (TextView) v.findViewById(R.id.dscTitle);
            TextView categoryText = (TextView) v.findViewById(R.id.dscCategory);
            TextView descriptionText = (TextView) v
                    .findViewById(R.id.dscDescription);
            TextView timeText = (TextView) v.findViewById(R.id.dscTime);
            TextView idText = (TextView) v.findViewById(R.id.dscDiscId);
            final TextView likeText = (TextView) v.findViewById(R.id.likeText1);
            String like_Status = app.getLikeStatus();

            titleText.setText(app.getTitle());
            categoryText.setText(app.getCategory());
            descriptionText.setText(app.getDescription());
            timeText.setText(app.getTime());
            idText.setText(app.getDiscId());
            if (like_Status == "null") {
                likeText.setText("Like");
            } else {
                likeText.setText("Liked");
            }

            final String dId = app.getDiscId();

            // onClick for image button inside list view

            likeText.setTag(new Integer(position));
            likeText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    final Integer myposition = (Integer) view.getTag();
                    // Toast.makeText(getContext(), "" + dId,
                    // Toast.LENGTH_SHORT)
                    // .show();
                    likeText.setText("Liked");
                    MainActivity val = new MainActivity();
                    val.updateLikeTable(dId);
                }

            });

        }

        return v;
    }
}

这也是我的MainActivity.java文件,我更新数据库中的喜欢

package com.mytestapp.myapp;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity implements FetchDataListener {
    public static String strTitle = "0", strCategory = "0",
            strDescription = "0", strTime = "0", strDid = "0";
    Collegemate_DB db = new Collegemate_DB(this);
    int likeStatus = 1;
    private ProgressDialog dialog;
    public static String usId=null;
    ImageButton imgButton;
    List<DiscussionList> items = new ArrayList<DiscussionList>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_forum_topics);
        usId = db.getCurrentuserId();
        initView();

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        /*
         * On click listener to get values from DiscussionList class and send it
         * to another activity when clicking on the list item
         */

        ListView forumList = getListView();
        forumList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // Get position of the clicked list item from adapter

                String dTitle, dCategory, dDescription, dTime, dDid;

                DiscussionList accessVar = ForumAdapter
                        .getModelPosition(position);
                dTitle = accessVar.getTitle();
                dCategory = accessVar.getCategory();
                dDescription = accessVar.getDescription();
                dTime = accessVar.getTime();
                dDid = accessVar.getDiscId();

                /*
                 * Storing the forum values in string and passing it to another
                 * activity
                 */

                String values[] = { dTitle, dCategory, dDescription, dTime,
                        dDid };
                Intent i = new Intent(MainActivity.this, ForumFullView.class);
                i.putExtra("sendData", values);
                startActivity(i);
            }
        });
    }

    private void initView() {
        // show progress dialog
        Log.i("j","Inside Init");
        dialog = ProgressDialog.show(this, "", "Loading...");

        String url = "http://example.com/mypath/listData.php?currentUser_id="
                + usId;
        Log.i("Fetch Url : ", url);
        FetchDataTask task = new FetchDataTask(this);
        task.execute(url);
    }

    @Override
    public void onFetchComplete(List<DiscussionList> data) {
        // dismiss the progress dialog
        if (dialog != null)
            dialog.dismiss();
        // create new adapter
        ListView forumList = getListView();
        // set the adapter to list
        ForumAdapter adapter = new ForumAdapter(this, data);
        if (forumList.getAdapter() == null) {
            //final ForumAdapter adapter = new ForumAdapter(this, data);
            forumList.setAdapter(adapter);
        } else {
            ((ForumAdapter) forumList.getAdapter()).refill(items);
        }
        // setListAdapter(adapter);
    }

    @Override
    public void onFetchFailure(String msg) {
        // dismiss the progress dialog
        if (dialog != null)
            dialog.dismiss();
        // show failure message
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    public void updateLikeTable(String dId,List<DiscussionList> items) {
        try {
            String likeUrl = "http://example.com/mypath/createlike.php?discId="
                    + dId + "&userId=" + usId + "&like_status=" + likeStatus;
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(likeUrl));
            client.execute(request);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

感谢任何帮助。

提前致谢

1 个答案:

答案 0 :(得分:1)

您遇到的问题是ListView窗口小部件可以回收其视图。一旦视图离开屏幕滚动,它就会进入垃圾堆,这样当新视图滚动到位时可以重复使用,而不是要求从头开始充气。该回收的视图是convertView方法中的getView()参数。首次填充ListView时,convertView将始终为空,因为垃圾堆中没有任何内容,因此您不得不强制新视图,但后续调用可能会有该参数为非空。

这样做的实际结果是,当点击的视图被设置为&#34;喜欢&#34;得到回收,TextView仍然存在,并且仍然填充了#34;喜欢&#34;而不是推定的默认值&#34;喜欢&#34;。因此,如果您点击一个视图,然后向下滚动以使其离开屏幕,它会回来并导致您看到的错误。

您可能想要解决此问题的方法是每次根据数据库中的内容在likeText内设置getView()的文本。如果帖子已被喜欢,请将其设置为&#34; Liked&#34;,如果没有,请将其设置为&#34; Like&#34;。它应该只是一行,假设您可以轻松访问您的DiscussionList对象是否喜欢该帖子。

P.S。作为旁注,在Android中,硬编码的字符串通常不受欢迎,因此您可能希望移动您的&#34;喜欢&#34;字符串到资源文件中。除非您计划进行翻译,否则它确实是必要的,但它仍然是良好的做法。