0

I am making an app in which i want to show all previous Order Details to user in a ListView using Server from PHPMYADMIN.

Problem: Not getting ListView in Activity, getting blank activity instead of ListView

OrdersAdapter.java:

public class OrdersAdapter extends BaseAdapter {

    TextView tName,tId,tOid ;
    String MemberID,resultServer,strMemberID,strName,strOrderID;

    Activity activity;
    LayoutInflater inflater;
    ListView listView;


    public OrdersAdapter(Activity a) {
        // TODO Auto-generated constructor stub
        activity = a;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return 0;
        // TODO Auto-generated method stub

    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

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

        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            View vi = convertView;
            if (convertView == null)
                vi = inflater.inflate(R.layout.listrow_orders, null);  // listrow_cart

            // Permission StrictMode
            if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);


            tId = (TextView)activity.findViewById(R.id.txtTotalAmount);
            tName = (TextView)activity.findViewById(R.id.txtItemDetails);

            String url = "http://172.16.0.4/res/order_fetch.php";
            Intent intent= activity.getIntent();
            MemberID = intent.getStringExtra("MemberID");
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("sMemberID", MemberID));
            resultServer  = getHttpPost(url,params);

            strMemberID = "";
            strName = "";


            JSONObject c;
            try {
                c = new JSONObject(resultServer);
                strMemberID = c.getString("TotalAmount");               
                strName = c.getString("ItemDetails");

                if(!strMemberID.equals(""))
                    {                   
                        tName.setText(strName);
                        tId.setText(strMemberID);               
                    }
                    else
                    {               
                        tName.setText("-");
                        tId.setText("-");
                    }
                    } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }       

                }
            return vi;
        }       

                String getHttpPost(String url,List<NameValuePair> params) {
                StringBuilder str = new StringBuilder();
                HttpClient client = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    HttpResponse response = client.execute(httpPost);
                    StatusLine statusLine = response.getStatusLine();
                    int statusCode = statusLine.getStatusCode();
                    if (statusCode == 200) { // Status OK
                        HttpEntity entity = response.getEntity();
                        InputStream content = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            str.append(line);
                        }
                    } else {
                        Log.e("Log", "Failed to download result..");
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return str.toString();  
        }

}

OrdersActivity.java:

    public class OrdersActivity extends Activity 
{               
    ListView mLstView1;
    OrdersAdapter mViewOrdersAdpt;

    @SuppressLint("NewApi")
    @Override

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders);   

         mLstView1 = (ListView) findViewById(R.id.listView1);

            mViewOrdersAdpt = new OrdersAdapter(OrdersActivity.this);
            mLstView1.setAdapter(mViewOrdersAdpt);

            mLstView1.setOnItemClickListener(new OnItemClickListener() {

                 public void onItemClick(AdapterView<?> parent, View v,
                         final int position, long id) 
                 {       

                }
            }); 
    }
}

activity_orders.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff" >

    <include
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        layout="@layout/header_orders" />

<ListView 
    android:layout_width="match_parent" 
    android:id="@+id/listView1" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_below="@+id/header" 
    android:cacheColorHint="#00000000" 
    android:divider="#b5b5b5" 
    android:dividerHeight="1dp" 
    android:layout_alignParentBottom="true" />

</RelativeLayout>

listrow_orders.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="5dp"
    android:background="@drawable/btn_background"
    android:orientation="horizontal"
    android:padding="5dip" >

<TextView
    android:id="@+id/txtTotalAmount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:textColor="#a60704"
    android:text="TextView" />

<TextView
    android:id="@+id/txtItemDetails"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView3"
    android:layout_below="@+id/textView3"
    android:textColor="#a60704"
    android:text="Item Details Here" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtTotalAmount"
    android:layout_below="@+id/txtTotalAmount"
    android:layout_marginTop="17dp"
    android:text="Ordered Items:"
    android:textColor="#a60704"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="Total Amount"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="#a60704" />

</RelativeLayout>
Chulbul Pandey
  • 506
  • 1
  • 8
  • 20
  • 1
    Hi Chulbul ji, plz use [Asynctask](http://developer.android.com/reference/android/os/AsyncTask.html) for getting data from server instead of doing long task on UI Thread – ρяσѕρєя K May 22 '13 at 05:20
  • you are doing whole lot of operation in getView try doing in another thread – Iftikar Urrhman Khan May 22 '13 at 05:22
  • You have used 0 in your `getCount` method of the adapter. Change it to the total count of the item in the listview. – Oam May 22 '13 at 05:22
  • @Oam hello actually i am confuse what i should need to use there – Chulbul Pandey May 22 '13 at 05:24
  • You have to use the total number of items retrieving from the server. I think you are retrieving each item data on your `getView`. I suggest you fetch all the items before setting your adapter using `Asynctask` and finally set adapter to the listview. – Oam May 22 '13 at 05:29
  • @Oam yes buddy i agree with you, but if you don't mind can you show me how my above code look like finally, place your answer below and i will accept that one..thanks a lot – Chulbul Pandey May 22 '13 at 05:32
  • @Oam first of all you have given correct solution, therefore i want to give you what you deserve please post your answer – Chulbul Pandey May 22 '13 at 05:41
  • You are retrieving the item details individually from the server, by passing `MemberId`? You need to fetch it all the items as a whole and not individually, in that way your code works good. So that we can help a bit too. Please try changing the service to get all the items. – Oam May 22 '13 at 05:46

5 Answers5

1

It is good if you parse json inside Activity instead of BaseAdapter , getView() will be called multiple times so json will be parsed multiple times too

Inside Activity write json fetching code inside AsyncTask store data in ArrayList , if you have single ArrayList than use like follow else you need to pass multiple ArrayList to BaseAdapter constructor

onPostExecute use setAdapter();

Here, mArrayList is a ArrayList<String>

 OrdersAdapter ordersAdapter = new OrdersAdapter(MyAct.this,mArrayList);

Inside BaseAdapter

ArrayList<String> mMyList;

public OrdersAdapter(Activity a, ArrayList<String> mList) 
 {
   activity = a;
   mMyList = mList;
   inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 }

getCount method

public int getCount() {
   return mMyList.size();
}
Ronak Mehta
  • 5,971
  • 5
  • 42
  • 69
  • yeah buddy i agree with you, i also think i should parse json inside activity instead of BaseAdapter, could you please update your answer, and show me finally how my code should look like, for activity and adapter class, just place as you think, then i will do necessary changes – Chulbul Pandey May 22 '13 at 05:56
0

your adapter says it has no items as getCount() returns 0

pskink
  • 23,874
  • 6
  • 66
  • 77
0

Problem in your OrdersAdapter.java class you must need to override adapter getCount() method in proper way like

 public int getCount() {
        return SIZE_OF_ARRAYLIST;

    }

if you write return 0 then list will not display. So you need to return size of arrayList

Vivek Kumar Srivastava
  • 2,158
  • 1
  • 16
  • 23
0

Pass a Collection, lets say strings in constructor

public OrdersAdapter(Activity a, List stringsToShow) {
    // TODO Auto-generated constructor stub
    activity = a;
    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   this.stringsToShow = stringsToShow;
}

and then

public int getCount() {
    return stringsToShow.size();

}

And avoid doing so many things in getView().. Kamal karte ho Pande ji..

mn0102
  • 839
  • 1
  • 12
  • 25
0

Don't try to load data in getView() method because it is called by systems many times. You can check this two link to know better Yet another getView called multiple times and the second link custom listview adapter getView method being called multiple times, and in no coherent order So now what you have to do to overcome this problem. You load data from web so you can use asynctask that will be used to load the data and pass it in a class. Check this to know about asynctask http://developer.android.com/reference/android/os/AsyncTask.html From asynctask class you can pass this data in a class. This class holds the data and then you can use this data in main activity. It is best to parse json data in asynctask class. Actually you did not pass any data in your adapter class. That's why your listview did not show any data. Hope this will work.

Community
  • 1
  • 1
androidcodehunter
  • 21,567
  • 19
  • 47
  • 70