Android:如何获取从数据库中获取的CustomListView项的id?

时间:2015-07-09 17:38:46

标签: android android-listview

大家好我正在寻找这个问题的解决方案,因为8天仍然无法找到任何解决方案,我使用的所有实现都给了我一个空指针异常。

嗯,这是问题,我正在创建一个应用程序,我允许用户能够对列表视图中的特定项目发表评论,按钮点击用户将被重定向到包含评论的评论页面与那篇文章有关。

所以为此我需要我的按钮才能获得该帖子的ID我可以编写关于该id如何查询数据库并显示特定于该帖子的注释的逻辑

以下是与此项目相关的文件;

FeedListAdapter

public class FeedListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<FeedItem> feedItems;
    private ListView lv;
    private FeedItem fi;

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
        this.activity = activity;
        this.feedItems = feedItems;
    }

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

    @Override
    public Object getItem(int location) {
        return feedItems.get(location);
    }

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

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

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.feed_item, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();

        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView timestamp = (TextView) convertView
                .findViewById(R.id.timestamp);
        TextView statusMsg = (TextView) convertView
                .findViewById(R.id.txtStatusMsg);
        TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
        NetworkImageView profilePic = (NetworkImageView) convertView
                .findViewById(R.id.profilePic);
        FeedImageView feedImageView = (FeedImageView) convertView
                .findViewById(R.id.feedImage1);

        final FeedItem item = feedItems.get(position);
        Button ops= (Button) convertView.findViewById(R.id.ops);
        name.setText(item.getName());
        ops.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myIntent = new Intent(activity,  Post.class);

                activity.startActivity(myIntent);




            }
        });
        // Converting timestamp into x ago format
        CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
                Long.parseLong(item.getTimeStamp()),
                System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
        timestamp.setText(timeAgo);


        // Chcek for empty status message
        if (!TextUtils.isEmpty(item.getStatus())) {
            statusMsg.setText(item.getStatus());
            statusMsg.setVisibility(View.VISIBLE);
        } else {
            // status is empty, remove from view
            statusMsg.setVisibility(View.GONE);
        }

        // Checking for null feed url
        if (item.getUrl() != null) {
            url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
                    + item.getUrl() + "</a> "));

            // Making url clickable
            url.setMovementMethod(LinkMovementMethod.getInstance());
            url.setVisibility(View.VISIBLE);
        } else {
            // url is null, remove from the view
            url.setVisibility(View.GONE);
        }

        // user profile pic
        profilePic.setImageUrl(item.getProfilePic(), imageLoader);

        // Feed image
        if (item.getImge() != null) {
            feedImageView.setImageUrl(item.getImge(), imageLoader);
            feedImageView.setVisibility(View.VISIBLE);
            feedImageView
                    .setResponseObserver(new FeedImageView.ResponseObserver() {
                        @Override
                        public void onError() {
                        }

                        @Override
                        public void onSuccess() {
                        }
                    });
        } else {
            feedImageView.setVisibility(View.GONE);
        }

        return convertView;
    }
    public void setMyList(List myListOfObjects) {
        this.feedItems = myListOfObjects;
        this.notifyDataSetChanged();
    }
}

FeedItem

public class FeedItem {
    private int id;
    private String name, status, image, profilePic, timeStamp, url;
    private Button but;
    public FeedItem() {
    }

    public FeedItem(int id, String name, String image, String status,
                    String profilePic, String timeStamp, String url, Button but) {
        super();
        this.id = id;
        this.name = name;
        this.image = image;
        this.status = status;
        this.profilePic = profilePic;
        this.timeStamp = timeStamp;
        this.url = url;
        this.but= but;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImge() {
        return image;
    }

    public void setImge(String image) {
        this.image = image;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getProfilePic() {
        return profilePic;
    }

    public void setProfilePic(String profilePic) {
        this.profilePic = profilePic;
    }

    public String getTimeStamp() {
        return timeStamp;
    }

    public void setTimeStamp(String timeStamp) {
        this.timeStamp = timeStamp;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

}

FragmentOne

public class FragmentOne extends BaseActivity {
    private static final String TAG = FragmentOne.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://fomains.esy.es/android_app_api/json.php";
    public  int pid;
    private Button b1;
    public CursorAdapter me;
    public ArrayAdapter my;
    int global_position =0;
    FeedListAdapter feedi;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLayoutInflater().inflate(R.layout.fragment_layout_one, frameLayout);

        mDrawerList.setItemChecked(position, true);
        setTitle(listArray[position]);

        listView = (ListView) findViewById(R.id.list);
        b1 = (Button) findViewById(R.id.button);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                global_position=position;
                Toast.makeText(getApplicationContext(),""+global_position,Toast.LENGTH_LONG).show();

            }
        });


        // These two lines not needed,
        // just to get the look of facebook (changing background color & hiding the icon)
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF6600")));
        getActionBar().setIcon(
                new ColorDrawable(getResources().getColor(android.R.color.transparent)));

        // We first check for cached request
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(URL_FEED);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    if (response != null) {
                        parseJsonFeed(response);
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }
         b1.setOnClickListener(new View.OnClickListener(){
             @Override
             public void onClick(View v) {
                 Intent myIntent = new Intent(FragmentOne.this, Post.class);

                 FragmentOne.this.startActivity(myIntent);
             }
         });
        listView.invalidateViews();
    }

    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = feedArray.length()-1 ; i >=0 ; i--) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);


                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));
                 pid = feedObj.getInt("id");

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));


                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);

            }

            listView.invalidateViews();
            // notify data changes to list adapater

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

以上是我从数据库获取数据并使用自定义列表适配器显示数据的代码

所以你们可以帮助我解决这个问题

1 个答案:

答案 0 :(得分:0)

你没有使用viewholder模式,我建议你使用ViewHolder模式,你可以使用如下,

class ViewHolder {
    TextView name;
    TextView timestamp;
    TextView statusmsg;
    TextView url;
    FeedImageView feedImageView;
    NetworkImageView profilePic;
    Button ops;
}

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

    final ViewHolder viewHolder;

    if (convertView == null) {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        viewHolder = new ViewHolder();
        viewHolder.name = (TextView) convertView.findViewById(R.id.name);
        viewHolder.timestamp = (TextView) convertView
            .findViewById(R.id.timestamp);
        viewHolder.statusMsg = (TextView) convertView
            .findViewById(R.id.txtStatusMsg);
        viewHolder.url = (TextView) convertView.findViewById(R.id.txtUrl);
        viewHolder.profilePic = (NetworkImageView) convertView
            .findViewById(R.id.profilePic);
        viewHolder.feedImageView = (FeedImageView) convertView
            .findViewById(R.id.feedImage1);
        viewHolder.ops = (Button) convertView.findViewById(R.id.ops);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = convertView.getTag();
        viewHolder.ops.setTag(null);
    }
    viewHolder.ops.setTag(/*give the id whatever u want to*/);
    /* follow other part of code as it is */
}

在按钮操作的单击方法中,您可以获取相同的标记并使用它来查询数据库。

希望它有助于欢呼!!