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.

gosulove
  • 1,645
  • 2
  • 26
  • 40
  • so whats unclear in `org.json.JSONObject` API? – pskink Sep 11 '16 at 06:41
  • @pskink http://stackoverflow.com/questions/39425837/android-data-display-in-wrong-format-from-jsonobject-to-listview/39425991?noredirect=1#comment66176097_39425991 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? – gosulove Sep 11 '16 at 06:46
  • 1
    ok, so whats unclear in `org.json.JSONArray` API? – pskink Sep 11 '16 at 06:47
  • the following link will help you [link] (https://github.com/loopj/android-async-http) – sajad zohrei Sep 11 '16 at 06:47
  • @pskink I think I should put it in a simple and clearer way. please have a look at this screenshot -> http://www.tiikoni.com/tis/view/?id=758485c .The json data I posted in question is exactly the same as the URL screenshot(mobile version) . What i am trying to do is that get the Json data from mysqli and then display it in Listview , when clicking on the item, it wil open in Dialog. With the unique ID, I can update and delete accordingly. By explaining this, do you have a clearer picture? – gosulove Sep 11 '16 at 06:57
  • so did you even try to play with `org.json.JSONObject` API? if so, where is your code? – pskink Sep 11 '16 at 07:04
  • @pskink hmm, I think yes? I did try ysd . Here is another question i asked ysd -> http://stackoverflow.com/questions/39424112/android-convert-jsonobject-to-hashmap-and-display-in-listview-with-simpleadapter – gosulove Sep 11 '16 at 07:14
  • you have the accepted answer there, so whats the problem? – pskink Sep 11 '16 at 07:19
  • pskink understands you perfectly fine, but it seems, that you haven't even tried to accomplish the task yourself. SO questions should contain a specific problem with a description of what you have tried so far and what difficulties you encountered, it is not a place to outsource your work ("Questions asking us to recommend or find a [...] tutorial [...] are off-topic" http://stackoverflow.com/help/on-topic). – Frederic Klein Sep 11 '16 at 07:22
  • Guys, I think what's wrong with the coding after pskink has hinted me. I think its the constructor in baseadapater that doesn't suit my siutation. Please wait for a while, I am modifying it now and come back later if the issus still there – gosulove Sep 11 '16 at 07:24
  • 1
    you have working solution with `SimpleAdapter` so just use that adapter in `setOnItemClickListener` method – pskink Sep 11 '16 at 07:25
  • @pskink: I said you (hence no @ before your name) understood gosulove and tried to point out, that he should have a look at the API, I wasn't speaking to you. – Frederic Klein Sep 11 '16 at 07:27
  • @pskink but that solution, I couldn't get other data except the position. I need every element in the Array – gosulove Sep 11 '16 at 07:28
  • @F.Klein ah ok sorry for misunderstanding... – pskink Sep 11 '16 at 07:28
  • @F.Klein I think you have misunderstood me. – gosulove Sep 11 '16 at 07:29
  • 1
    so read `Adapter` API, hint: `adapterView.getAdapter().getItem(positionInAdapter)` – pskink Sep 11 '16 at 07:49
  • @pskink still working. in fact, its abit confusing for me now as information overload. – gosulove Sep 11 '16 at 08:33
  • what do you mean? did you call `getItem` or not? – pskink Sep 11 '16 at 08:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/123090/discussion-between-gosulove-and-pskink). – gosulove Sep 11 '16 at 08:35

2 Answers2

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

    });
}
sajad zohrei
  • 377
  • 1
  • 10
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.

android_dev
  • 128
  • 7
  • 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? – gosulove Sep 11 '16 at 08:23
  • 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. – android_dev Sep 11 '16 at 08:45