1

Here is my code :

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 Code :

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;
    }

}

            }

price list 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>

And Finally main 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>

I'm not an expert in custom layout but i'm getting an error in parsing the JSON Array into the custom listview. Of course my main goal is to fill the custom listview with the JSON array but i don't have any clue how to do it and non of question asked before have helped me. Can anyone help me right here? Here all the info, the program is stopping at the JSon catch exception and giving me the toastBox : Couldn't connect to the internet. any suggestion? :)

7
  • your internet connection is not available.. Commented Jun 22, 2013 at 5:35
  • i don't think that's the problem, because im working on a localhost on the emulator.. Commented Jun 22, 2013 at 5:43
  • just see your exception. it clearly say that couldn't connect to the internet.. Commented Jun 22, 2013 at 5:45
  • in the code below : } 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(); } Is for the JSON parsing part which is giving me the error and not the connection one. Commented Jun 22, 2013 at 5:47
  • then put your logcat here. Commented Jun 22, 2013 at 5:48

1 Answer 1

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;
    }


}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.