1

I am new to Android Development.

I purely like to work with JSON Objects and Arrays for my simple application considering the lightness of the JSON Carrier compared to XMLs.

I had challenges with ArrayAdapter to populate the ListView.

This is how I overcome and need your suggestions on it.

Extend the Adaptor class.

Then pass the JSONArray to the constructor.
Here the constructor calls super with dummy String array setting the length of the JSONArray.
Store the constructor arguments in class for further use.

public myAdaptor(Context context, int resource, JSONArray array)
{
    super(context, resource, new String[array.length()]);
    // Store in the local varialbles to the adapter class.
    this.context = context;
    this.resource = resource;
    this.profiles = objects;
}

The getView() will do the job of fetching JSONObjects from JSONArray to build view.

public View getView(int position, View convertView, ViewGroup parent)
{
    View view;
    if (convertView == null)
    {
        LayoutInflater inflater = (LayoutInflater) 
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(resource, parent, false);
    }
    else
    {
        view = convertView;
    }

    // Here 
    JSONObject item = (JSONObject) profiles.getJSONObject(position);

    // READY WITH JSONObject from the JSONArray
    // YOUR CODE TO BUILD VIEW OR ACCESS THE 
}

Now Any improvements/suggestions/thoughful-question??

3
  • this seems ok. another thing you can try is to convert json array in array/arraylist of objects and then can start processing. Commented Dec 9, 2013 at 9:25
  • imo, instead of provide the JSONArray you should pass the result of passing and avoid to parse the information every time you scroll up/down your list Commented Dec 9, 2013 at 9:29
  • instead of doing to much work in getView use data structure like ArrayList,HashMap,.. to pass parsed values in myAdaptor class. Commented Dec 9, 2013 at 9:33

4 Answers 4

7

I would advise you to use google GSON instead JSON. It is a library that gives you a create objects from JSON-request, and you don't need to parse JSON everymore. Just create an object which contains all the fields from your JSON request and are named the same, and do with it whatever you want - for example:

Your JSON request
{
    [
        {
            "id": "2663",
            "title":"qwe"

        },
        {
            "id": "1234",
            "title":"asd"
        },
        {
            "id": "5678",
            "title":"zxc"
        }

    ]
}

Your class - item of JSON-Array

 public class MyArrayAdapterItem{
     int id;
     String title;
 }

Somwhere in your code where you downloading data. I didn't know how are you doing it so i'll post my code for example:

mGparser = new JsonParser();
Gson mGson = new Gson();

Url url = "http://your_api.com"
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Connection", "close");
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

JsonArray request = (JsonArray) mGparser.parse(in.readLine());
in.close();
ArrayList<MyArrayAdapterItem> items = mGson.fromJson(request, new TypeToken<ArrayList<MyArrayAdapterItem>>() {}.getType());

So that's all, for now just put "items" instead JSON-array in your adapter's constructor

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

2 Comments

thanks for the suggestion, this seems interesting. its new learning.
In future projects you'll get "a big profit" in using gson instead json, it's will save a lot of your time. So to get the data from request you'll need to add a few lines in your code instead annoying, boring and unwidely JSON-parsing.
3

You can pass null to super instead of creating a string array and implement getCount method:

public myAdaptor(Context context, int resource, JSONArray array)
{
    super(context, resource, null);
    // Store in the local varialbles to the adapter class.
    this.context = context;
    this.resource = resource;
    this.profiles = array;
}

public int getCount(){
   return profiles.length();
}

1 Comment

This is tricky one.. nice.. Suggestion. Cannot pass null to super constructer. instead pass only first 2 arguments. that will do.
0

create one textview and assign with item.getString("key") and add that string to the local string array and return that view

Comments

0

This is the listview adapter class.

public class Adapter extends BaseAdapter {
    Context context = null;
    ArrayList<OffersAvailable> offers = null;


    public Adapter(Context context, ArrayList<OffersAvailable> offer) {
        this.context = context;
        this.offers = offer;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return offers.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return offers.get(position).getTitle();
    }

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

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        View v;
        final TextView tvpoints;
        final TextView tv,tv_quantity;
        if (convertView == null) {
            LayoutInflater li = ((Activity) context).getLayoutInflater();
            v = li.inflate(R.layout.design_userlist, null);

        } else {
            v = convertView;
        }
        tvpoints = (TextView) v.findViewById(R.id.tvpointlist);
        tv_quantity= (TextView) v.findViewById(R.id.tv_quantity);
        tv = (TextView) v.findViewById(R.id.tvdatalist);
        ((Activity) context).runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                tv.setText(offers.get(position).getTitle().toUpperCase());
                tv_quantity.setText(offers.get(position).getQuatity().toUpperCase());
                tvpoints.setText(offers.get(position).getPoint() + "");
            }
        });

        return v;
    }

}

Object class

public class OffersAvailable {
    String title, point, quatity, description,nid;

    public String getNid() {
        return nid;
    }

    public void setNid(String nid) {
        this.nid = nid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getPoint() {
        return point;
    }

    public void setPoint(String point) {
        this.point = point;
    }

    public String getQuatity() {
        return quatity;
    }

    public void setQuatity(String quatity) {
        this.quatity = quatity;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

Use the json in the main class and store it inthe Arraylist of type OffersAvailable.

and pass it to the listviews adapter. if you are getting the response from the internet use asynchttpclient method.And parse the json.

Comments

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.