-2

JSONParser.class

package com.example.diptiagravat.myapplication;

public class JSONParser {

    public String getJSON(String url, int timeout) {
        HttpURLConnection c = null;
        try {
            URL u = new URL(url);
            c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setRequestProperty("Content-length", "0");
            c.setUseCaches(false);
            c.setAllowUserInteraction(false);
            c.setConnectTimeout(timeout);
            c.setReadTimeout(timeout);
            c.connect();
            int status = c.getResponseCode();

            switch (status) {
                case 200:
                case 201:
                    BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    br.close();
                    return sb.toString();
            }

        } catch (MalformedURLException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (c != null) {
                try {
                    c.disconnect();
                } catch (Exception ex) {
                    Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        return null;
    }

    public String sendHTTPData(String urlpath, String id) {
        HttpURLConnection connection = null;
        try {
            URL url=new URL(urlpath);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
            streamWriter.write(id);
            streamWriter.flush();
            StringBuilder stringBuilder = new StringBuilder();
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
                InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(streamReader);
                String response = null;
                while ((response = bufferedReader.readLine()) != null) {
                    stringBuilder.append(response + "\n");
                }
                bufferedReader.close();

                Log.d("test", stringBuilder.toString());
                return stringBuilder.toString();
            } else {
                Log.e("test", connection.getResponseMessage());
                return null;
            }
        } catch (Exception exception){
            Log.e("test", exception.toString());
            return null;
        } finally {
            if (connection != null){
                connection.disconnect();
            }
        }
    }
}

MainActivity.java

package com.example.diptiagravat.myapplication;

public class MainActivity extends AppCompatActivity {

    private TextView txtid, txtcname;
    Spinner spcnt, spstate;
    public ArrayList<String> clist;
    ArrayAdapter<String> cad;
    public ArrayList<String> slist;
    ArrayAdapter<String> sad;
    public String strcnt;
    private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php";
    private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php";
    private static final String TAG_USER = "country";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "country_name";
    private ArrayList<Country> clistModels;

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

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

        initViews();

        CountryAsyncTask countryAsyncTask= new CountryAsyncTask();
        countryAsyncTask.execute();
    }

    private void initViews() {

        txtid = (TextView) findViewById(R.id.tvid);
        txtcname = (TextView) findViewById(R.id.tvcname);
        spcnt = (Spinner) findViewById(R.id.spcnt);
        spstate = (Spinner) findViewById(R.id.spstate);
        clist = new ArrayList<String>();
        slist = new ArrayList<String>();

    }


    public class CountryAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL
            JSONObject json = null;
            try {
                json = new JSONObject(jParser.getJSON(url, 5000));
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return json.toString();
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            Log.i("Result Ravi", result);

            try {
                JSONObject obj = new JSONObject(result);
                JSONArray cntArray = obj.getJSONArray("country");

                if (cntArray.length() > 0) {
                    for (int i = 0; i < cntArray.length(); i++) {
                        final JSONObject temp = cntArray.getJSONObject(i);
                        //  txtid.setText(temp.getString("id"));
                        //  txtcname.setText(temp.getString("country_name"));


                        Country country = new Gson().fromJson(temp.toString(), Country.class);
                        clist = new ArrayList<String>();
                        clistModels = new ArrayList<Country>();
                        clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
                        clist.add(temp.getString("country_name"));
                        cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist);
                        spcnt.setAdapter(cad);
                        spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                                strcnt = clistModels.get(position).getId();
                                //strcnt = parent.getItemAtPosition(position).toString();
                                Log.i("id", strcnt);
                                new StatesAsyncTask().execute();

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });

                        // txtid.setText(temp.getString(country.getId()));
                        // txtcname.setText(temp.getString(country.getCountryName()));
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public class StatesAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONParser jParser = new JSONParser();

            // Getting JSON from URL


            JSONObject json = null;
            try {
                json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt));
            } catch (JSONException e) {
                e.printStackTrace();
            }

             return json.toString();


        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            try {
                JSONObject obj = new JSONObject(s);
                JSONArray stArray = obj.getJSONArray("statelist");

                if (stArray.length() > 0) {
                    for (int i = 0; i < stArray.length(); i++) {
                        final JSONObject temp = stArray.getJSONObject(i);
                        //  txtid.setText(temp.getString("id"));
                        //  txtcname.setText(temp.getString("country_name"));


                        Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class);
                        slist = new ArrayList<String>();
                        // clistModels = new ArrayList<Country>();
                        //clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
                        slist.add(temp.getString("state_name"));
                        sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist);
                        spstate.setAdapter(sad);
                        spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                                // strcnt = clistModels.get(position).getId();
                                //strcnt = parent.getItemAtPosition(position).toString();
                                // Log.i("id", strcnt);
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });

                        // txtid.setText(temp.getString(country.getId()));
                        // txtcname.setText(temp.getString(country.getCountryName()));
                    }
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

}

My response is null?

5
  • This will be helpfull tutorialspoint.com/android/android_json_parser.htm or androidhive.info/2012/01/android-json-parsing-tutorial Commented Jun 10, 2016 at 5:33
  • Thanks but i already seen this tutorial.in my JSONParser class response variable is null. i cant get data. Commented Jun 10, 2016 at 5:47
  • What is the status code from the server Commented Jun 10, 2016 at 5:49
  • Three have no problem in getJson method but problem arise in sendHttpData method i cant get response in stringBuilder object Commented Jun 10, 2016 at 6:02
  • Trying Volley and it works. Commented Jun 20, 2016 at 12:00

1 Answer 1

0

HttpURLConnection is deprecated in Android Lollipop, so please try to use DefaultHttpClient instead. Also, check your logs, this is at your onPostExecute():

Log.i("Result Ravi", result);

For DefaultHttpClient check this post.

Another way is to try Retrofit

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

3 Comments

Yes i got the json in Log, but When i passed sendHttpData in Json i get json=null.
in this url urmiinfotech.com/demo/ifirst/app_api/get_state_list.php you got json null ,so please check pasing parameter and fire this url in browser with proper parameter
I found the solution using volley. Thanks to all

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.