1

This is my code to get JSON data in textview .JSON data is inside my code only. Now if my data is in some URL, then how can I get those data?
The old answers uses defaultHTTPClient which is no more supported and I tried using retrofit and volley but not able to understand.

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView output = (TextView) findViewById(R.id.textView1);

    String strJson="{ \"Employee\" :[{\"id\":\"101\",\"name\":\"Sonoo Jaiswal\",\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"Vimal Jaiswal\",\"salary\":\"60000\"}] }";

    String data = "";
    try {
        // Create the root JSONObject from the JSON string.
        JSONObject  jsonRootObject = new JSONObject(strJson);

        //Get the instance of JSONArray that contains JSONObjects
        JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");

        //Iterate the jsonArray and print the info of JSONObjects
        for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            int id = Integer.parseInt(jsonObject.optString("id").toString());
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());

            data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
        }
        output.setText(data);
    } catch (JSONException e) {e.printStackTrace();}
}
Shwetabh Singh
  • 197
  • 5
  • 15

4 Answers4

1

EDIT

Use Volley if httpclient you can't find.

Moreover parsing script is same which mentioned below.

I already written a Blog. Refer that. Hope it helps. Let me clone my blog to match your requirement. Please use proper naming for that. Here is parsing output.

 public class GridUI extends Activity {
 ArrayList<Persons> personsList;
 GridView gridView;
 GridAdapter gridAdapter;
private static final String   url="http://www.zippytrailers.com/funlearn/topicsMap";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gridview);
    personsList= new ArrayList<Persons>();
 new JSONAsyncTask().execute(url);
 gridView=(GridView)findViewById(R.id.gridview);
 gridAdapter = new GridAdapter(this, R.layout.gridview_row, personsList);
 gridView.setAdapter(gridAdapter);

 }
 class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
 ProgressDialog dialog;
 @Override
  protected void onPreExecute() {
  // TODO Auto-generated method stub
  super.onPreExecute();
  dialog=new ProgressDialog(GridUI.this);
  dialog.setMessage("Loading, please wait");
  dialog.setTitle("Connecting server");
  dialog.show();
  dialog.setCancelable(false);

  }


   @Override
  protected Boolean doInBackground(String... urls) {
      try {

//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);

// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();

 if(status==200){
 HttpEntity entity = response.getEntity();
 String data = EntityUtils.toString(entity);
  JSONObject jsono=new JSONObject(data);
  JSONArray jarray = jsono.getJSONArray("results");
  for (int i = 0; i < jarray.length(); i++) {
   JSONObject object = jarray.getJSONObject(i);

   Persons name = new Persons();

   name.setName(object.getString("syllabus"));
   name.setDescription(object.getString("grade"));
   name.setDob(object.getString("subject"));
   name.setCountry(object.getString("topic"));
   name.setHeight(object.getString("id"));

   personsList.add(name);
  }
  return true;
 }

} catch (ParseException e1) {
 e1.printStackTrace();
} catch (IOException e) {
 e.printStackTrace();
} catch (JSONException e) {
 e.printStackTrace();
}
return false;

}

   @Override
  protected void onPostExecute(Boolean result) {
  super.onPostExecute(result);
  dialog.cancel();
  gridAdapter.notifyDataSetChanged();
  if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from   server", Toast.LENGTH_LONG).show();
 }

}
Community
  • 1
  • 1
Shadow
  • 6,864
  • 6
  • 44
  • 93
1
{  
   "Employee":[  
      {  
         "id":"101",
         "name":"Sonoo Jaiswal",
         "salary":"50000"
      },
      {  
         "id":"102",
         "name":"Vimal Jaiswal",
         "salary":"60000"
      }
   ]
}

Remove "\" from your string data like above.then try to parse.your json is not valid one.

check it on https://jsonformatter.curiousconcept.com/

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

Like this:

String myURL = "https://www.myurl.com/file.json";
String jsonResponse = null;
try {
    jsonResponse = (String) new RetrieveJSONTask(myURL).execute().get();
} catch (ExecutionException | InterruptedException e) {
    // Do something
}

If you need to get an object you can do:

JSONObject jsonObject = null;
try {
    jsonObject = new JSONObject(jsonResponse);

    // Here you get an specific tag named "title" from the first object of an array named "itens"
    String title = jsonObject.getJSONArray("items").getJSONObject(0).getString("title");

} catch(JSONException e) {
     // Do something
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Gomes
  • 11
  • 2
0

Try this code:

try {
    URL url = new URL("http://www.zippytrailers.com/funlearn/topicsMap");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    String result = sb.toString();
    System.out.println("result"+result);
} catch (Exception e){
    System.out.println(" error"+e);
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
User6006
  • 597
  • 4
  • 21