Dipti Agravat Dipti Agravat - 5 months ago 56
JSON Question

How to parse JSON dat with HTTP Post method in android studio

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?

Answer
HttpURLConnection is Deprecated from lollipop so please try to defaulthttpclient .
and also check log this at your onPostExecute.
Log.i("Result Ravi", result);

for defaulthttpclient check :-http://stackoverflow.com/questions/20374156/sending-and-parsing-response-using-http-client-for-a-json-list

second way also try to "Retrofit" :- http://square.github.io/retrofit/
Comments