1

I have setup a Listview with BaseAdapter and so far its working fine with setOnItemClickListener. But it's hard coding.

enter image description here

Main2Activity.java

String sku[]={"1","2","3","4"};
String name[]={"Bad Food","Very Bad Food","Extremly Bad Food","Super Bad Food"};
String price[]={"99","999","9999","99999"};
String quantity[]={"123","456","789","101112"};

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

    ListView listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(new my_adapter(Main2Activity.this,sku,name,price,quantity));

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(Main2Activity.this, "Sku->"+sku[i]
                    +" Name->"+name[i]
                    +" Price->"+price[i]
                    +" Quantity->"+quantity[i]
                    ,Toast.LENGTH_SHORT).show();
        }
    });

}

my_adapter.java

public class my_adapter extends BaseAdapter {

Context ctx;
LayoutInflater inflater=null;

String sku[];
String name[];
String price[];
String quantity[];

public my_adapter(Context ctx, String sku[], String name[], String price[],String quantity[]){
    this.ctx=ctx;
    this.sku=sku;
    this.name=name;
    this.price=price;
    this.quantity=quantity;
}

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

@Override
public Object getItem(int i) {
    return null;
}

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

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    View row=view;

    if(row==null){
        inflater=(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row=inflater.inflate(R.layout.rows,null);
    }

    TextView product_sku=(TextView)row.findViewById(R.id.sku);
    TextView product_name=(TextView)row.findViewById(R.id.name);
    TextView product_price=(TextView)row.findViewById(R.id.price);
    TextView product_quantity=(TextView)row.findViewById(R.id.quantity);

    product_sku.setText(sku[i]);
    product_name.setText(name[i]);
    product_price.setText(price[i]);
    product_quantity.setText(quantity[i]);

    return row;
}
}

Next, I need to do something similar which is to convert JsonArray to Array and then use it in setOnItemClickListener. That means, I need to store all the data from json into 4 arrays and then use any of the elements later on when they click on the item. Just like my hard coding example.

I have seen some examples with HashMap as well as some JsonArray to array templates coding but not sure how to combine them with my ListView and baseAdapter.

getting json data

JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        // working with HashMap or Arraylist?????
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
    }
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsObjRequest);

localhost/web_service/ohno.php

{
"482":["1","Chicken Rice","1","1"],  //Unique ID, sku,name,price,quantity
"483":["1","French Fries","1","1"],
"484":["1","apple","1","1"],
"492":["1","western+italian","1","1"],
"493":["1","no_cat","1","1"]
}

The format that I have setup in Listview is exactly same as The above Json format(4 columns) except Json format has an extra element that is Unique product ID.

19
  • so whats unclear in org.json.JSONObject API? Commented Sep 11, 2016 at 6:41
  • @pskink stackoverflow.com/questions/39425837/… ysd I have asked some related questions(simple adapter) BUT that one are mainly Strings. But my above example is Array, any example that works something similar? Commented Sep 11, 2016 at 6:46
  • 1
    ok, so whats unclear in org.json.JSONArray API? Commented Sep 11, 2016 at 6:47
  • 1
    you have working solution with SimpleAdapter so just use that adapter in setOnItemClickListener method Commented Sep 11, 2016 at 7:25
  • 1
    so read Adapter API, hint: adapterView.getAdapter().getItem(positionInAdapter) Commented Sep 11, 2016 at 7:49

2 Answers 2

2

try this

  public void getJson() { 
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(localhost/web_service/ohno.php, new JsonHttpResponseHandler()   {

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            ArrayList<String> listData = new ArrayList<>();
            JSONArray jsonArray482=response.optJSONArray("482");
            if (jsonArray482 != null) {
                for (int i=0;i<jsonArray482.length();i++){
                    try {
                        listData.add(jsonArray482.get(i).toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

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

Comments

1

It will be ideal to actually create a Model class or say POJO class with member variables like sku, name, price, quantity, id. The code may look like

public class Item {
    private int id;
    private String sku;
    private String name;
    private String price;
    private String quantity;
}

After getting the json parse it and create a list of Item something like

public void parseJson(String data) {
    ArrayList<Item> items = new ArrayList<Item>();

    //Parsing logic goes here
}

Once you are done with creating list of items you can have an ArrayAdapter or BaseAdapter accept that and then just iterate over the list and set appropriate values. This, to me, seems to be correct approach rather than creating separate arrays and then passing it to BaseAdapter.

Hope this helps you out.

2 Comments

sounds ok, trying it now. Just to confirm that public class Item is in my_adapter.java and public void parseJson(String data) in Main2Activity.java?
It's upto you how you design it. Item can be an altogether an independent class. You can also have a look at JSON marshalling using JacksonJson or GSON. I think you are using Volley for making Http calls and there is a way of using JacksonJson with Volley.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.