填充一个ListView与Parse.com Android的对象 [英] Populating a ListView with Objects from Parse.com Android

查看:122
本文介绍了填充一个ListView与Parse.com Android的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我在Parse.com数据库填充对象一个ListView,但我时遇到麻烦,因为ListView控件不直接接受对象。我试着通过我的对象循环和铸造他们为字符串,但是失败使字符串数组。我也试图呼吁对象的ToString,但没有运气无论是。

我的计划是遍历所有解析对象,然后将它们添加到ListView。然后该ListView的将被用于允许用户通过所有从Parse.com对象的搜索。从Parse.com对象应更换listview_array []数据....恩替换百威,Dubra等....

循环我没有创建检索对象的名称,价格,尺寸做的工作,但我不能把它变成ListView控件,因为我相信这是一个对象。

下面是我的code

 包com.alpha.dealtap;进口java.lang.reflect.Array中;
进口的java.util.List;
进口的java.util.ArrayList;
进口android.app.Activity;
进口android.content.Intent;
进口android.os.Bundle;
进口android.text.Editable;
进口android.text.TextWatcher;
进口android.util.Log;
进口android.view.View;
进口android.widget.ArrayAdapter;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.ListView;进口com.parse.FindCallback;
进口com.parse.Parse;
进口com.parse.ParseException;
进口com.parse.ParseObject;
进口com.parse.ParseQuery;公共类Search_Page延伸活动{    私人的ListView LV;
    私人的EditText等;
    公共字符串listview_array [] = {百威,Dubra,科罗娜,
            杰克丹尼,斯米尔诺夫,梯形光,自然冰};
    私人的ArrayList<串GT; array_sort =新的ArrayList<串GT;();
    公众的ArrayList<对象> _arrayList =新的ArrayList<对象>();
    INT长度限制:Textlength = 0;
    的parseObject dealsObject;
    INT N = 0;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.search_page);        Parse.initialize(这一点,vUz23Z6zdIL1jbxbVWeLpsSdu1ClTu3YiG30zTWY
                4BTyoq1QQKows8qVJV7lvU3ZokSRrLFyOCPzffwJ);        //使用这个Parsequery ......我可以抓住/从解析找到对象
        //列表...在这里,我抓起有Burnettes和价格的对象
        //它
        //最后我可能需要设置上,我会多少结果得到的限制
        //从循环....到目前为止,我认为它是有限的,缺省值为100
        ParseQuery查询=新ParseQuery(交易);        // query.whereEqualTo(品牌,Burnettes);
        query.findInBackground(新FindCallback(){            @覆盖
            公共无效完成(列表<&的parseObject GT;对象,ParseException的E){
                如果(E == NULL){
                    Log.d(品牌,取自+ objects.size()+品牌);
                    对于(的parseObject dealsObject:对象){
                        //使用dealsObject.get('COLUMNNAME')来访问
                        //将交易对象的属性                        对象品牌= dealsObject.get(品牌)的toString()。                        _arrayList.add(品牌);
                        listview_array = _arrayList;
                        //遇到问题把字符串到一个数组列表....不得不转换为ArrayList的,然后它会导致错误!
                        Log.d(大小,(字符串)dealsObject.get(大小));
                        Log.d(价格(字符串)dealsObject.get(价格));
                        Log.d(品牌,(字符串)dealsObject.get(品牌));
                        Ñ​​++;
                    }                }其他{
                    Log.d(品牌,错误:+ e.getMessage());
                }
            }
        });
        巴顿店=(按钮)findViewById(R.id.b1);
        按钮交易=(按钮)findViewById(R.id.b2);        LV =(ListView控件)findViewById(R.id.ListView01);
        等=(EditText上)findViewById(R.id.search_box);
        lv.setAdapter(新ArrayAdapter<对象>(这一点,
                android.R.layout.simple_list_item_1,listview_array));        et.addTextChangedListener(新TextWatcher(){
            公共无效afterTextChanged(编辑S){
                // TextWatcher接口的抽象方法。
            }            公共无效beforeTextChanged(CharSequence中,诠释开始,诠释计数,
                    INT后){
                // TextWatcher接口的抽象方法。
            }            公共无效之前onTextChanged(CharSequence中,诠释开始,诠释,
                    诠释计数){
                。=长度限制:Textlength et.getText()长();
                array_sort.clear();
                的for(int i = 0; I< listview_array.length;我++){
                    如果(长度限制:Textlength&下; = listview_array [I]。长度()){
                        如果(et.getText()
                                的ToString()
                                .equalsIgnoreCase(
                                        (字符串)listview_array [I] .subSequence(
                                                0,长度限制:Textlength))){
                            (listview_array [I])array_sort.add;
                        }
                    }
                }
                lv.setAdapter(新ArrayAdapter<串GT;(Search_Page.this,
                        android.R.layout.simple_list_item_1,array_sort));
            }
        });        store.setOnClickListener(新View.OnClickListener(){
            //当您使用OnClickListener ......你需要onClick的方法内
            //它            @覆盖
            公共无效的onClick(查看为arg0){
                // TODO自动生成方法存根
                startActivity(新意图(com.alpha.dealtap.STOREPAGE));
            }        });        deal.setOnClickListener(新View.OnClickListener(){
            //当您使用OnClickListener ......你需要onClick的方法内
            //它            @覆盖
            公共无效的onClick(查看为arg0){
                // TODO自动生成方法存根
                startActivity(新意图(com.alpha.dealtap.DEALPAGE));            }        });    }    保护无效onListItemClick(ListView中升,视图V,INT位置,长的id){        //奶酪等于为哪个项目被点击的位置...所以它
        //取决于所点击的项目
        字符串奶酪=TAPDEAL;
        尝试{
            类ourClass =的Class.forName(com.alpha.dealtap。+奶酪);
            意图ourIntent =新意图(Search_Page.this,ourClass);
            startActivity(ourIntent);
        }赶上(ClassNotFoundException的E){
            // TODO自动生成catch块
            e.printStackTrace();
        }    }    @覆盖
    保护无效的onPause(){        super.onPause();
    }


解决方案

您可以使用BaseAdapter类的自定义列表视图。这里是code表示。

 列表<&的parseObject GT;解析=新的ArrayList<&的parseObject GT;();公共类CustomChannelListAdapter延伸BaseAdapter {    私人上下文的背景下;    公共CustomChannelListAdapter(上下文的背景下){
        超();
        this.context =背景;
    }    @覆盖
    公众诠释的getCount(){
        如果(解析!= NULL){
            返回parse.size();
        }
        返回0;
    }    @覆盖
    公共频道的getItem(INT位置){
        // TODO自动生成方法存根
        返回parse.get(位置);
    }    @覆盖
    众长getItemId(INT位置){
        // TODO自动生成方法存根
        返回0;
    }    @覆盖
    公共查看getView(INT位置,查看convertView,父母的ViewGroup){        查看查看= convertView;
        TextView中丝毫不差= NULL;
        TextView的递减= NULL;
        TextView的nowPlaying = NULL;
        如果(查看== NULL){
            LayoutInflater吹气=((活动)上下文)
                    .getLayoutInflater();
            鉴于= inflater.inflate(R.layout.video_listrow,父母,假);        }其他{
            鉴于= convertView;
        }
        丝毫不差=(TextView中)view.findViewById(R.id.title);
        DESC =(TextView中)view.findViewById(R.id.Descp);        nowPlaying =(TextView中)view.findViewById(R.id.NowplayingId);
        如果(解析!= NULL){            如果(parse.get(位置).getName()!= NULL){
                tittle.setText(parse.get(位置).getName()
                        的ToString());
            }其他{
                tittle.setText(----------------------);
            }            如果(parse.get(位置).getDesc()!= NULL){
                desc.setText(parse.get(位置).getDesc()
                        的ToString());
            }其他{
                desc.setText(------------------------);
            }        }
        返回视图。
    }}

video_listrow.xml

 <?XML版本=1.0编码=UTF-8&GT?;
<的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =400dp
    机器人:layout_height =75dp
    机器人:背景=@绘制/ videolist_selector
    机器人:方向=横向
    机器人:paddingLeft =5DP
    机器人:paddingRight =5DP>
    <! - 标题之歌 - >    <的TextView
        机器人:ID =@ + ID /标题
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:paddingTop =5DP
        机器人:文字颜色=@色/橙色
        机器人:TEXTSIZE =18dip
        机器人:文字样式=大胆
        机器人:字体=SANS
          机器人:ellipsize =金字招牌
        机器人:freezesText =真
        机器人:marqueeRepeatLimit =marquee_forever
        机器人:paddingLeft =5dip
        机器人:scrollHorizo​​ntally =真
        机器人:单线=真
        机器人:文字=丝毫不差未找到/>    <! - 艺人名称 - >    <的TextView
        机器人:ID =@ + ID / Descp
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_below =@ ID /标题
        机器人:layout_marginTop =1dip
        机器人:layout_toRightOf =@ + ID /缩略图
        机器人:paddingTop =5DP
        机器人:文字颜色=@色/白
        机器人:TEXTSIZE =12dip
        机器人:文字样式=大胆
        机器人:字体=SANS
        机器人:ellipsize =金字招牌
        机器人:freezesText =真
        机器人:marqueeRepeatLimit =marquee_forever
        机器人:paddingLeft =5dip
        机器人:scrollHorizo​​ntally =真
        机器人:单线=真
        机器人:文字=说明未找到
       />    <! - Rightend时间 - >
    <! -
         <的TextView
        机器人:ID =@ + ID /时间
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentRight =真
        机器人:layout_alignTop =@ ID /标题
        机器人:重力=右
        机器人:文字=5:45
        机器人:layout_marginRight =5dip
        机器人:TEXTSIZE =10dip
        机器人:文字颜色=#10bcc9
        机器人:文字样式=大胆/>
     - >
    <! - Rightend箭 - >
    <! -
        < ImageView的机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:SRC =@绘制/箭头
        机器人:layout_alignParentRight =真
        机器人:layout_centerVertical =真/>
     - >    <的TextView
        机器人:ID =@ + ID / NowplayingId
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_alignParentBottom =真
        机器人:layout_alignParentRight =真
        机器人:layout_marginBottom =5DP
        机器人:layout_marginRight =4DP
        机器人:文字=现在打......
        机器人:文字颜色=@色/红
        机器人:TEXTSIZE =12dp/>< / RelativeLayout的>

在您的活动code

 的ListView videoList =(ListView控件)findviewByid(_);
   CustomChannelListAdapter channelAdapter =新CustomChannelListAdapter(PlasmaView.this);
                videoList.setAdapter(channelAdapter);

I'm trying to fill a ListView with objects from my database at Parse.com, but I'm am having trouble because the ListView does not accept objects directly. I've tried making an array of strings by looping through my objects and casting them as strings but that failed. I have also tried to call a .toString on the objects but no luck either.

My plan is to loop through all of the parse objects and then add them to the ListView. That ListView will then be used to allow the user to search through all of the objects from Parse.com. The objects from Parse.com should replace the listview_array[] data....ex replace "BudWeiser", "Dubra" etc....

The loop I did create to retrieve the Objects names, prices, size did work, but I could not place it into the listView since I believe it was an object.

Here's my code

package com.alpha.dealtap;

import java.lang.reflect.Array;
import java.util.List;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class Search_Page extends Activity {

    private ListView lv;
    private EditText et;
    public String listview_array[] = { "BudWeiser", "Dubra", "Corona",
            "Jack Daniels", "Smirnoff", "Keystone Light", "Natural Ice" };
    private ArrayList<String> array_sort = new ArrayList<String>();
    public ArrayList<Object> _arrayList = new ArrayList<Object>();
    int textlength = 0;
    ParseObject dealsObject;
    int n = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_page);

        Parse.initialize(this, "vUz23Z6zdIL1jbxbVWeLpsSdu1ClTu3YiG30zTWY",
                "4BTyoq1QQKows8qVJV7lvU3ZokSRrLFyOCPzffwJ");

        // Using this Parsequery...I can grab/locate the objects from the Parse
        // list...Here I grabbed the objects that have Burnettes and the price
        // of it
        // Eventually I may need to set a limit on how many results I will get
        // from the for loop....So far I think it is limited to 100 by default
        ParseQuery query = new ParseQuery("Deals");

        // query.whereEqualTo("Brand", "Burnettes");
        query.findInBackground(new FindCallback() {

            @Override
            public void done(List<ParseObject> objects, ParseException e) {
                if (e == null) {
                    Log.d("Brand", "Retrieved " + objects.size() + " Brands");
                    for (ParseObject dealsObject : objects) {
                        // use dealsObject.get('columnName') to access the
                        // properties of the Deals object

                        Object brands = dealsObject.get("Brand").toString();

                        _arrayList.add(brands);
                        listview_array = _arrayList;
                        //Having trouble putting strings into an array list....Have to cast as ArrayList and then it causes error!


                        Log.d("Size", (String) dealsObject.get("Size"));
                        Log.d("Price", (String) dealsObject.get("Price"));
                        Log.d("Brand", (String) dealsObject.get("Brand"));
                        n++;
                    }

                } else {
                    Log.d("Brand", "Error: " + e.getMessage());
                }
            }
        });




        Button store = (Button) findViewById(R.id.b1);
        Button deal = (Button) findViewById(R.id.b2);

        lv = (ListView) findViewById(R.id.ListView01);
        et = (EditText) findViewById(R.id.search_box);
        lv.setAdapter(new ArrayAdapter<Object>(this,
                android.R.layout.simple_list_item_1, listview_array));

        et.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                // Abstract Method of TextWatcher Interface.
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // Abstract Method of TextWatcher Interface.
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                textlength = et.getText().length();
                array_sort.clear();
                for (int i = 0; i < listview_array.length; i++) {
                    if (textlength <= listview_array[i].length()) {
                        if (et.getText()
                                .toString()
                                .equalsIgnoreCase(
                                        (String) listview_array[i].subSequence(
                                                0, textlength))) {
                            array_sort.add(listview_array[i]);
                        }
                    }
                }
                lv.setAdapter(new ArrayAdapter<String>(Search_Page.this,
                        android.R.layout.simple_list_item_1, array_sort));
            }
        });

        store.setOnClickListener(new View.OnClickListener() {
            // When you use OnClickListener...you need the onClick method inside
            // of it

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                startActivity(new Intent("com.alpha.dealtap.STOREPAGE"));
            }

        });

        deal.setOnClickListener(new View.OnClickListener() {
            // When you use OnClickListener...you need the onClick method inside
            // of it

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                startActivity(new Intent("com.alpha.dealtap.DEALPAGE"));

            }

        });

    }

    protected void onListItemClick(ListView l, View v, int position, long id) {

        // Cheese equals the position for which item that is clicked...so it
        // depends on which item that is clicked
        String cheese = "TAPDEAL";
        try {
            Class ourClass = Class.forName("com.alpha.dealtap." + cheese);
            Intent ourIntent = new Intent(Search_Page.this, ourClass);
            startActivity(ourIntent);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @Override
    protected void onPause() {

        super.onPause();
    }

解决方案

you can use BaseAdapter class for custom listview. here is the code for that.

List<ParseObject> parse = new ArrayList<ParseObject>();

public class CustomChannelListAdapter extends BaseAdapter {

    private Context context;

    public CustomChannelListAdapter(Context context) {
        super();
        this.context = context;
    }

    @Override
    public int getCount() {
        if (parse != null) {
            return parse.size();
        }
        return 0;
    }

    @Override
    public Channel getItem(int position) {
        // TODO Auto-generated method stub
        return parse.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

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

        View view = convertView;
        TextView tittle = null;
        TextView desc = null;
        TextView nowPlaying = null;
        if (view == null) {
            LayoutInflater inflater = ((Activity) context)
                    .getLayoutInflater();
            view = inflater.inflate(R.layout.video_listrow, parent, false);

        } else {
            view = convertView;
        }
        tittle = (TextView) view.findViewById(R.id.title);
        desc = (TextView) view.findViewById(R.id.Descp);

        nowPlaying = (TextView) view.findViewById(R.id.NowplayingId);
        if (parse!= null) {

            if (parse.get(position).getName() != null) {
                tittle.setText(parse.get(position).getName()
                        .toString());
            } else {
                tittle.setText("----------------------");
            }

            if (parse.get(position).getDesc() != null) {
                desc.setText(parse.get(position).getDesc()
                        .toString());
            } else {
                desc.setText("------------------------");
            }

        } 
        return view;
    }

}

video_listrow.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="400dp"
    android:layout_height="75dp"
    android:background="@drawable/videolist_selector"
    android:orientation="horizontal"
    android:paddingLeft="5dp"
    android:paddingRight="5dp" >


    <!-- Title Of Song -->

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:textColor="@color/orange"
        android:textSize="18dip"
        android:textStyle="bold"
        android:typeface="sans"
          android:ellipsize="marquee"
        android:freezesText="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:paddingLeft="5dip"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:text="Tittle Not Found " />

    <!-- Artist Name -->

    <TextView
        android:id="@+id/Descp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:paddingTop="5dp"
        android:textColor="@color/white"
        android:textSize="12dip"
        android:textStyle="bold"
        android:typeface="sans" 
        android:ellipsize="marquee"
        android:freezesText="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:paddingLeft="5dip"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:text="Description Not Found"
       />

    <!-- Rightend Duration -->
    <!--
         <TextView
        android:id="@+id/duration"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@id/title"
        android:gravity="right"
        android:text="5:45"
        android:layout_marginRight="5dip"
        android:textSize="10dip"
        android:textColor="#10bcc9"
        android:textStyle="bold"/>
    -->


    <!-- Rightend Arrow -->
    <!--
        <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/arrow"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"/>
    -->

    <TextView
        android:id="@+id/NowplayingId"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="4dp"
        android:text="Now playing..."
        android:textColor="@color/red"
        android:textSize="12dp" />

</RelativeLayout>

In your activity code

     ListView videoList = (ListView) findviewByid(_);
   CustomChannelListAdapter channelAdapter = new CustomChannelListAdapter(PlasmaView.this);
                videoList.setAdapter(channelAdapter);

这篇关于填充一个ListView与Parse.com Android的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆