使用JsonArray进行自定义布局

时间:2013-06-22 05:33:54

标签: android android-listview arrays

这是我的代码:

public class Fragment1 extends SherlockFragment {
        ListView lista;
        ArrayList<String> items = new ArrayList<String>();
        private ArrayList<MyListAdapter> thelista = new ArrayList<MyListAdapter>();
        View rootView;
        ListView list;
        TextView title, price;
        MyListAdapter adapter;

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            // TODO Auto-generated method stub
            super.onCreateOptionsMenu(menu, inflater);
            MenuInflater blowup = this.getSherlockActivity()
                    .getSupportMenuInflater();
            blowup.inflate(R.menu.menuxml, menu);
            return;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.main, container, false);
            ActionBar ab = this.getSherlockActivity().getSupportActionBar();
            ab.setTitle("");
            title = (TextView) rootView.findViewById(R.id.title);
            price = (TextView) rootView.findViewById(R.id.details);

            list = (ListView) rootView.findViewById(R.id.list);
            SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(
                    this.getSherlockActivity(), R.array.phones_array,
                    android.R.layout.simple_spinner_dropdown_item);
            ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
            ab.setListNavigationCallbacks(mSpinnerAdapter, null);
            StrictMode.enableDefaults();
            getData();
            return rootView;

        }

        public void getData() {
            String result = "";
            InputStream isr = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httpost = new HttpPost(
                        "http://10.0.2.2/AndroidArabia/android3arabiya.php");
                HttpResponse resposne = httpclient.execute(httpost);
                HttpEntity entity = resposne.getEntity();
                isr = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "error in http connection" + e.toString());
                Toast.makeText(getSherlockActivity(),
                        "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                        .show();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        isr, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                isr.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting Result " + e.toString());
            }
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json = jArray.getJSONObject(i);
                    thelista.add(new MyListAdapter(json.getString("PhoneName"),
                            json.getString("PhonePrice")));
                }
                list.setAdapter((ListAdapter) thelista);

            } catch (Exception e) {
                Log.e("lag_tag", "ERROR PARSING DATA" + e.toString());
                Toast.makeText(getSherlockActivity(),
                        "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                        .show();
            }

MyListAdapter代码:

public class MyListAdapter extends BaseAdapter {

    private String[] data;
    private String[] data2;
    private Context context;



    public MyListAdapter(String string, String string2) {
        // TODO Auto-generated constructor stub
    }

    @Override
    public int getCount() {
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        return data[position];
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = LayoutInflater.from(context).inflate(R.layout.pricelist,
                parent, false);

        TextView text1 = (TextView) rowView.findViewById(R.id.title);
        TextView text2 = (TextView) rowView.findViewById(R.id.details);
        text1.setText(data[position]);
        text2.setText(data2[position]);
        return rowView;
    }

}

            }

价格表xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >


    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip"
        android:background="@drawable/image_bg"
        android:padding="3dip" >

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="50dip"
            android:layout_height="50dip" />
    </LinearLayout>


    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Smartphone Name"
        android:textColor="#040404"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="sans" />


    <TextView
        android:id="@+id/details"
        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:text="Smartphone Price"
        android:textColor="#343434"
        android:textSize="10dip" />




    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/rating" />

</RelativeLayout>

最后主要的xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp" >
    </ListView>

</LinearLayout>

我不是自定义布局的专家,但是在将JSON数组解析为自定义列表视图时遇到错误。当然,我的主要目标是使用JSON数组填充自定义列表视图,但我没有任何线索如何做到这一点,并且之前没有问过我帮助过。 有人可以帮我吗? 在这里所有的信息,程序停止在JSon捕获异常并给我toastBox:无法连接到互联网。有什么建议吗? :)

1 个答案:

答案 0 :(得分:1)

Fragment1.java


    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.app.ActionBar;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SpinnerAdapter;
    import android.widget.TextView;
    import android.widget.Toast;

    public class Fragment1 extends SherlockFragment {
            ArrayList<String> items = new ArrayList<String>();
            ArrayList<BeanClass> beanClass=new ArrayList<BeanClass>();
            View rootView;
            ListView list;
            TextView title, price;
            MyListAdapter adapter;

            @Override
            public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
                // TODO Auto-generated method stub
                super.onCreateOptionsMenu(menu, inflater);
                MenuInflater blowup = this.getSherlockActivity()
                        .getSupportMenuInflater();
                blowup.inflate(R.menu.menuxml, menu);
                return;
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                rootView = inflater.inflate(R.layout.main, container, false);
                ActionBar ab = this.getSherlockActivity().getSupportActionBar();
                ab.setTitle("");
                title = (TextView) rootView.findViewById(R.id.title);
                price = (TextView) rootView.findViewById(R.id.details);

                list = (ListView) rootView.findViewById(R.id.list);
                SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(
                        this.getSherlockActivity(), R.array.phones_array,
                        android.R.layout.simple_spinner_dropdown_item);
                ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
                ab.setListNavigationCallbacks(mSpinnerAdapter, null);
                StrictMode.enableDefaults();
                getData();
                return rootView;

            }

            public void getData() {
                String result = "";
                InputStream isr = null;
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httpost = new HttpPost(
                            "http://10.0.2.2/AndroidArabia/android3arabiya.php");
                    HttpResponse resposne = httpclient.execute(httpost);
                    HttpEntity entity = resposne.getEntity();
                    isr = entity.getContent();

                } catch (Exception e) {
                 /*   Log.e("log_tag", "error in http connection" + e.toString());
                    Toast.makeText(getSherlockActivity(),
                            "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                            .show();*/
                }
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            isr, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    isr.close();
                    result = sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Error converting Result " + e.toString());
                }
                try {
                    JSONArray jArray = new JSONArray(result);
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json = jArray.getJSONObject(i);
                    /*    thelista.add(new MyListAdapter(json.getString("PhoneName"),
                                json.getString("PhonePrice")));*/
                        beanClass.add(new BeanClass(json.getString("PhoneName"),
                                json.getString("PhonePrice"));
                    }
                    list.setAdapter(new MyListAdapter(Fragment1.this, beanClass));

                } catch (Exception e) {
                    Log.e("lag_tag", "ERROR PARSING DATA" + e.toString());
                    Toast.makeText(getSherlockActivity(),
                            "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                            .show();
                }


Your Adapter 



import java.util.ArrayList;

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

public class MyListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<BeanClass> beanClass=new ArrayList<BeanClass>();


    public MyListAdapter(Context context,ArrayList<BeanClass> beanClass) {
        // TODO Auto-generated constructor stub
        this.context=context;
        this.beanClass=beanClass;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = LayoutInflater.from(context).inflate(R.layout.pricelist,
                parent, false);

        TextView text1 = (TextView) rowView.findViewById(R.id.title);
        TextView text2 = (TextView) rowView.findViewById(R.id.details);
        text1.setText(beanClass.get(position).phoneName);
        text2.setText(beanClass.get(position).phonePrice);
        return rowView;
    }

}

            }


BeanClasss




public class BeanClass {

    String phoneName;
    String phonePrice;
    public String getPhoneName() {
        return phoneName;
    }
    public String getPhonePrice() {
        return phonePrice;
    }
    public void setPhoneName(String phoneName) {
        this.phoneName = phoneName;
    }
    public void setPhonePrice(String phonePrice) {
        this.phonePrice = phonePrice;
    }
    public BeanClass(String phoneName, String phonePrice) {
        super();
        this.phoneName = phoneName;
        this.phonePrice = phonePrice;
    }


}