Bumble Bee Bumble Bee - 4 months ago 39
JSON Question

Json parsing using Listview in Android using Ayntask

Hi there I want to get data from a table through API using following query

select * from Order as O where username=O.username;


my Asyntask code is :

protected String doInBackground(Void... params) {
String data = "";
//login doesnt exist
final String url = Data.server + "/Order.aspx";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username", mEmail));
UrlEncodedFormEntity uefa = null;
try {
uefa = new UrlEncodedFormEntity(param);
post.setEntity(uefa);
HttpResponse response;
response = client.execute(post);
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
} catch (IOException e) {
// TODO Auto-generated catch block
data = e.toString();
e.printStackTrace();
}
return data;
}

@Override
protected void onPostExecute(String success) {
mAuthTask = null;
showProgress(false);
if (success.contains("[{") && (success.length() > 5)) {
//start the profile activity if json is returned
LocalRegistryreg(success);
try {
JSONArray jarr = new JSONArray(res);
ArrayAdapter<jarr> adapter = new ArrayAdapter<jarr>(this,
android.R.layout.simple_list_item_1, items);

scourseslist.setAdapter(adapter);

for (int i = 0; i < jarr.length(); ++i) {
// Extract values from JSON row:
JSONObject jsonObject = jarr.getJSONObject(i);
String PID = jsonObject.has("PID ") ? jsonObject.getString("PID ") : "";
String PTitle = jsonObject.has("PTitle ") ? jsonObject.getString("PTitle ") : "";
String Quantity = jsonObject.has("Quantity ") ? jsonObject.getString("Quantity ") : "";
String Price = jsonObject.has("Price ") ? jsonObject.getString("Price ") : "";

}
} catch (JSONException e) {
e.printStackTrace();
}
finish();
//Utility.shoAlert(success,LoginActivity.this);
} else {
Utility.shoAlert(success, Order.this);
}
}


im storing return json in a string variable String data;and my data look like this DATA TABLE PICTURE
and the data is multi row. i want to show up all my data row using listview. i treied but i got error. so kindly provide a piece of code to show my data in listview? thanks in advanced

Answer
  1. You need to define a class to hold the data:
public class Order {
    private String pID;
    private String pTitle;
    private String quantity;
    private String price;

    public Order(String pID, String pTitle, String quantity, String price) {
        this.pID = pID;
        this.pTitle = pTitle;
        this.quantity = quantity;
        this.price = price;
    }

    public String getpID() {
        return pID;
    }

    public void setpID(String pID) {
        this.pID = pID;
    }

    public String getpTitle() {
        return pTitle;
    }

    public void setpTitle(String pTitle) {
        this.pTitle = pTitle;
    }

    public String getQuantity() {
        return quantity;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}
  1. you need to create a custom adapter class:
public class OrderAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<Order> orderList = new ArrayList<Order>();
    private static LayoutInflater inflater = null;

    public OrderAdapter(Activity activity, ArrayList<Order> orderList,
            Resources res) {

        this.activity = activity;
        this.orderList = orderList;
        // Layout inflator to call external xml layout ()
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

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

    @Override
    public Order getItem(int arg0) {
        // TODO Auto-generated method stub
        return orderList.get(arg0);
    }

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

    public static class ViewHolder {

        public TextView text1;
        public TextView text2;
        public TextView text3;
        public TextView text4;
        public TextView text5;

    }

    /****** Depends upon data size called for each row , Create each ListView row *****/
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = convertView;
        ViewHolder holder;

        if (convertView == null) {
            view = inflater.inflate(R.layout.tabitem, null);
            holder = new ViewHolder();
            holder.text1 = (TextView) view.findViewById(R.id.text1);
            holder.text1 = (TextView) view.findViewById(R.id.text2);
            holder.text2 = (TextView) view.findViewById(R.id.text3);
            holder.text4 = (TextView) view.findViewById(R.id.text4);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();

        }
        Order order = (Order) orderList.get(position);

        /************ Set Model values in Holder elements ***********/

        holder.text1.setText(order.getpID());
        holder.text2.setText(order.getPrice());
        holder.text3.setText(order.getpTitle());
        holder.text4.setText(order.getQuantity());
        return view;
    }
}
  1. create a custom row layout with name tabitem:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </TextView>

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </TextView>

    <TextView
        android:id="@+id/text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </TextView>

    <TextView
        android:id="@+id/text4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </TextView>

</LinearLayout>
  1. Define ListView to show data:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:layout_weight="1"/>

 </RelativeLayout> 
  1. Than you need to create instance of the class and set the data in your on onPostExecute method.
Order order = new Order(PID, PTitle,Quantity,  Price);
List<Order> orderList = new ArrayList<Order>();
  1. and than pass that list of order data to activity, and activity can than apply adapter to show the data:
ListView list= (ListView) findViewById(R.id.list);  // List defined in XML
OrderAdapter orderAdapter = OrderAdapter(activity, orderList);
list.setAdapter(orderAdapter );
Comments