0

My question is I have an Json object called name in Rest Api. I need to fetch it and display in my App in the field textView15 after I login/Signup. I have no idea about fetching and displaying Json. Any help would be appreciable.

Api is:

{
  "users": {
    "_id": "gcx8ksa4XepvYRyWH",
    "emails": [
      {
        "address": "[email protected]",
        "verified": false
      }
    ]
  },
  "user": {
    "_id": "wWHmKn5ciWAHZGt2m",
    "user_id": "gcx8ksa4XepvYRyWH",
    "name": "[email protected]",
    "hubs": [],
    "username": "selenium",
    "industry": "selenium",
    "profession": "selenium"
  }
}

My code:

 AsyncHttpClient client = new AsyncHttpClient();
        applyJobItems.clear();
        List<String> userCredentials = UserUtils.getLoginDetails();
        client.addHeader("x-user-id", userCredentials.get(0));
        client.addHeader("x-auth-token", userCredentials.get(1));
        client.get("https://", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                final String response = new String(responseBody);
                android.util.Log.e("Response", "" + response);

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    final JSONArray jsonArray = jsonObject.getJSONArray("user");


                    final List<String> names = new ArrayList<String>();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject inter = new JSONObject(jsonArray.get(i).toString());
                        ApplyJobItem jobItem = new ApplyJobItem();
                        jobItem.setName(inter.getString("name"));
                        names.add(inter.getString("name"));
                        applyJobItems.add(jobItem);
                        android.util.Log.e("name", inter.getString("name"));
                    }
                }catch (Exception e) {
                        e.printStackTrace();
                    }
1
  • Put, What you tried in your code & then ask queries otherwise it will reject. Commented Feb 16, 2016 at 15:58

3 Answers 3

1

You can easily fetch the data and render into view by using volley as follow...

After login this code to get executed...

List<Users> list = new ArratList<Users>();
CustomUserAdapter adapter;
JsonArrayRequest getJsonData = new JsonArrayRequest("<your_url>,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            Users mList = new Users();

                            JSONObject obj = response.getJSONObject(i);

                            JSONArray answers = obj.getJSONArray("emails");

                            long count = answers.length();
                            if(count > 0){
                                //setter methods
                            }

                            mList.setIDL(obj.getString("_id"));
                            list.add(mList);

                        } catch (JSONException e) {
                            Log.d("JSONError", e.toString());
                        }

                    }
                    adapter.notifyDataSetChanged();
                    //your listview findViewById().....
                    listView.setVisibility(View.VISIBLE);

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),"Error in fetchinf data",Toast.LENGTH_LONG).show();

        }
    });

    AppController.getInstance().addToRequestQueue(getJsonData);

App configuration class for volley (need to add volley library)

Learn more about volley Get Volley

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {
    getRequestQueue();
    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {

    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

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

Comments

1

Take this json in JSONObject variable in android and parse it like

String name = jsonObject.getJSONObject('user').getString('name');

here jsonObject is name of main json object you got from server..

Edit: Json Parsing tutorial.

here is some guide how to parse json

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

Comments

-1

Use Retrofit. It would do the parsing for you.

http://square.github.io/retrofit/

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.