[android] Get JSON Data from URL Using Android?

I am trying to get JSON data by parsing login url with username and password. I have tried by using below code but I can't get any responses. Please help me.

I am using HTTP Process and API level 23.

I need to parse my URL and get below Response

{
    "response":{
                "Team":"A",
                "Name":"Sonu",
                "Class":"First",
              },
                "Result":"Good",
}

Below My code :

public class LoginActivity extends Activity {

    JSONParser jsonparser = new JSONParser();
    TextView tv;
    String ab;
    JSONObject jobj = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        new retrievedata().execute();

    }

    class retrievedata extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            jobj = jsonparser.makeHttpRequest("http://myurlhere.com");

            // check your log for json response
            Log.d("Login attempt", jobj.toString());

            try {
                ab = jobj.getString("title");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return ab;
        }
        protected void onPostExecute(String ab){

            tv.setText(ab);
        }

    }

}

This question is related to android json android-6.0-marshmallow

The answer is


Don't know about android but in POJ I use

public final class MyJSONObject extends JSONObject {
    public MyJSONObject(URL url) throws IOException {
        super(getServerData(url));
    }
    static String getServerData(URL url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String text = ir.lines().collect(Collectors.joining("\n"));
        return (text);
    }
}

Here in this snippet, we will see a volley method, add below dependency in-app level gradle file

  1. compile 'com.android.volley:volley:1.1.1' -> adding volley dependency.
  2. implementation 'com.google.code.gson:gson:2.8.5' -> adding gson for JSON data manipulation in android.

Dummy URL -> https://jsonplaceholder.typicode.com/users (HTTP GET Method Request)

public void getdata(){
    Response.Listener<String> response_listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("Response",response);
            try {
                JSONArray jsonArray = new JSONArray(response);
                JSONObject jsonObject = jsonArray.getJSONObject(0).getJSONObject("address").getJSONObject("geo");
                Log.e("lat",jsonObject.getString("lat");
                Log.e("lng",jsonObject.getString("lng");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };


    Response.ErrorListener response_error_listener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                //TODO
            } else if (error instanceof AuthFailureError) {
                //TODO
            } else if (error instanceof ServerError) {
                //TODO
            } else if (error instanceof NetworkError) {
                //TODO
            } else if (error instanceof ParseError) {
                //TODO
            }
        }
    };

    StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://jsonplaceholder.typicode.com/users",response_listener,response_error_listener);
    getRequestQueue().add(stringRequest);
}   

public RequestQueue getRequestQueue() {
    //requestQueue is used to stack your request and handles your cache.
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return mRequestQueue;
}

Visit https://github.com/JainaTrivedi/AndroidSnippet-/blob/master/Snippets/VolleyActivity.java


    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null) {
    s = s.append(sResponse);
}
Gson gson = new Gson();

JSONObject jsonObject = new JSONObject(s.toString());
String link = jsonObject.getString("Result");

Easy way to get JSON especially for Android SDK 23:

public class MainActivity extends AppCompatActivity {

Button btnHit;
TextView txtJson;
ProgressDialog pd;

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

    btnHit = (Button) findViewById(R.id.btnHit);
    txtJson = (TextView) findViewById(R.id.tvJsonItem);

    btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute("Url address here");
        }
    });


}


private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}
}

My fairly short code to read JSON from an URL. (requires Guava due to usage of CharStreams).

    private static class VersionTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... strings) {
            String result = null;
            URL url;
            HttpURLConnection connection = null;
            try {
                url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
            } catch (IOException e) {
                Log.d("VersionTask", Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                String version = "";
                try {
                    version = new JSONObject(result).optString("tag_name").trim();
                } catch (JSONException e) {
                    Log.e("VersionTask", Log.getStackTraceString(e));
                }
                if (version.startsWith("v")) {
                    //process version
                }
            }
        }
    }

PS: This code gets the latest release version (based on tag name) for a given GitHub repo.


If you get the server response as a String, without using a third party library you can do

JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");

Here is the documentation

Otherwise to parse json you can use Gson or Jackson

EDIT without libraries (not tested)

class retrievedata extends AsyncTask<Void, Void, String>{
    @Override
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        URL url;
        try {
            url = new URL("http://myurlhere.com");
            urlConnection.setRequestMethod("GET"); //Your method here 
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null)
                buffer.append(line + "\n");

            if (buffer.length() == 0)
                return null;

            return buffer.toString();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            exception = e;
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    exception = e;
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String response) {
        if(response != null) {
            JSONObject json = new JSONObject(response);
            JSONObject jsonResponse = json.getJSONObject("response");
            String team = jsonResponse.getString("Team");
        }
    }
}

private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected JSONObject doInBackground(String... urls) {
        if (urls.length > 0) {
            String url = urls[0];
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);
            httpget.setHeader("x-li-format", "json");
            try {
                HttpResponse response = httpClient.execute(httpget);
                if (response != null) {
                    //If status is OK 200
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String result = EntityUtils.toString(response.getEntity());
                        //Convert the string result to a JSON Object
                        return new JSONObject(result);
                    }
                }
            } catch (IOException e) {

            } catch (JSONException e) {
            }
        }
        return null;
    }
    @Override
    protected void onPostExecute(JSONObject data) {
        if (data != null) {
            Log.d(TAG, String.valueOf(data));
        }
    }

}

I feel your frustration.

Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.

That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.

(Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)

protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
{
    @Override
    protected JSONObject doInBackground(Void... params)
    {

        String str="http://your.domain.here/yourSubMethod";
        URLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        try
        {
            URL url = new URL(str);
            urlConn = url.openConnection();
            bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuffer.append(line);
            }

            return new JSONObject(stringBuffer.toString());
        }
        catch(Exception ex)
        {
            Log.e("App", "yourDataTask", ex);
            return null;
        }
        finally
        {
            if(bufferedReader != null)
            {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(JSONObject response)
    {
        if(response != null)
        {
            try {
                Log.e("App", "Success: " + response.getString("yourJsonElement") );
            } catch (JSONException ex) {
                Log.e("App", "Failure", ex);
            }
        }
    }
}

This would be the json object it is targeted towards.

{
    "yourJsonElement":"Hi, I'm a string",
    "anotherElement":"Ohh, why didn't you pick me"
}

It is working on my end, hope this is helpful to someone else out there.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to android-6.0-marshmallow

Android 6.0 multiple permissions How to check the multiple permission at single request in Android M? Android marshmallow request permission? Get JSON Data from URL Using Android? Storage permission error in Marshmallow Android 6.0 Marshmallow. Cannot write to SD Card How to programmatically open the Permission Screen for a specific app on Android Marshmallow? Neither user 10102 nor current process has android.permission.READ_PHONE_STATE ConnectivityManager getNetworkInfo(int) deprecated getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)