android - studio - response optjsonarray
Parse simple JSON desde URL en Android y mostrar en lista (7)
Como HttpClient
está en desuso, here un buen ejemplo de cómo hacerlo usando URLConnection
:
Crea una clase con el nombre de clase como
HttpHandler.java
. A continuación, he incluido el archivoHttpHandler.java
.
import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; public class HttpHandler { private static final String TAG = HttpHandler.class.getSimpleName(); public HttpHandler() { } public String makeServiceCall(String reqUrl) { String response = null; try { URL url = new URL(reqUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); response = convertStreamToString(in); } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException: " + e.getMessage()); } catch (ProtocolException e) { Log.e(TAG, "ProtocolException: " + e.getMessage()); } catch (IOException e) { Log.e(TAG, "IOException: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } return response; } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; try { while ((line = reader.readLine()) != null) { sb.append(line).append(''/n''); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }
Ahora, debe abrir
activity.main.xml
hacer la lista de datos de análisis de JSON . El códigoactivity_main.xml
like,
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="in.vetbossel.androidjsonparse.MainActivity"> <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </RelativeLayout> Hereafter create one xml file, the name is `list_item.xml` used for list the all values from *JSON*. The code is, <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="@dimen/activity_horizontal_margin"> <TextView android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip" android:textColor="#3498db" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/email" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#16a085" android:textStyle="bold" /> <TextView android:id="@+id/mobile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#e74c3c" android:textStyle="bold" /> </LinearLayout>
Analizando JSON en MainActivity
Obtenga el valor de JSON , para hacer que la llamada
Http
busque el valor JSON . Hay muchos archivos de biblioteca disponibles para recuperar los valores de JSON , como volley library y retrofit library, etc. La biblioteca de volley y la biblioteca de actualización comúnmente utilizada para analizar el valor de JSON . Finalmente, el códigoMainActivity.java
como,
import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private String TAG = MainActivity.class.getSimpleName(); private ProgressDialog pDialog; private ListView lv; // URL to get contacts JSON private static String url = "http://demos.vetbossel.in/ajson/sample"; ArrayList<HashMap<String, String>> contactList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contactList = new ArrayList<>(); lv = (ListView) findViewById(R.id.list); new GetContacts().execute(); } /** * Async task class to get json by making HTTP call */ private class GetContacts extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Please wait..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { HttpHandler sh = new HttpHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url); Log.e(TAG, "Response from url: " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node JSONArray contacts = jsonObj.getJSONArray("contacts"); // looping through All Contacts for (int i = 0; i < contacts.length(); i++) { JSONObject c = contacts.getJSONObject(i); String id = c.getString("id"); String name = c.getString("name"); String email = c.getString("email"); String address = c.getString("address"); String gender = c.getString("gender"); // Phone node is JSON Object JSONObject phone = c.getJSONObject("phone"); String mobile = phone.getString("mobile"); String home = phone.getString("home"); String office = phone.getString("office"); // tmp hash map for single contact HashMap<String, String> contact = new HashMap<>(); // adding each child node to HashMap key => value contact.put("id", id); contact.put("name", name); contact.put("email", email); contact.put("mobile", mobile); // adding contact to contact list contactList.add(contact); } } catch (final JSONException e) { Log.e(TAG, "Json parsing error: " + e.getMessage()); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG) .show(); } }); } } else { Log.e(TAG, "Couldn''t get json from server."); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Couldn''t get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG) .show(); } }); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( MainActivity.this, contactList, R.layout.list_item, new String[]{"name", "email", "mobile"}, new int[]{R.id.name, R.id.email, R.id.mobile}); lv.setAdapter(adapter); } } }
Y no te olvides de agregar el permiso de internet a tu archivo de manifiesto:
<uses-permission android:name="android.permission.INTERNET" />
Estoy tratando de analizar un resultado JSON obtenido de una URL en mi aplicación de Android ...
He intentado algunos ejemplos en Internet, pero no puedo hacerlo funcionar. Los datos JSON se ven así:
[
{
"city_id": "1",
"city_name": "Noida"
},
{
"city_id": "2",
"city_name": "Delhi"
},
{
"city_id": "3",
"city_name": "Gaziyabad"
},
{
"city_id": "4",
"city_name": "Gurgaon"
},
{
"city_id": "5",
"city_name": "Gr. Noida"
}
]
¿Cuál es la forma más sencilla de recuperar la URL y analizar los datos JSON? Mostrarlo en la lista
Podría usar AsyncTask
, deberá personalizar para satisfacer sus necesidades, pero algo como lo siguiente
La tarea asincrónica tiene tres métodos principales:
onPreExecute()
: más comúnmente utilizado para configurar e iniciar un diálogo de progresodoInBackground()
- Hace conexiones y recibe respuestas del servidor (NO intente asignar valores de respuesta a los elementos de la GUI, este es un error común, que no se puede hacer en una cadena de fondo).-
onPostExecute()
- Aquí estamos fuera del hilo de fondo, por lo que podemos hacer la manipulación de la interfaz de usuario con los datos de respuesta, o simplemente asignar la respuesta a tipos de variables específicos.
Primero comenzaremos la clase, inicializamos un String
para mantener los resultados fuera de los métodos pero dentro de la clase, luego ejecutamos el método onPreExecute()
configurando un diálogo de progreso simple.
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream inputStream = null;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
MyAsyncTask.this.cancel(true);
}
});
}
Entonces tenemos que configurar la conexión y cómo queremos manejar la respuesta:
@Override
protected Void doInBackground(String... params) {
String url_select = "http://yoururlhere.com";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
// HttpClient is more then less deprecated. Need to change to URLConnection
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "/n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
} // protected Void doInBackground(String... params)
Por último, aquí analizaremos el retorno, en este ejemplo fue una matriz JSON y luego descartar el diálogo:
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONArray jArray = new JSONArray(result);
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String name = jObject.getString("name");
String tab1_text = jObject.getString("tab1_text");
int active = jObject.getInt("active");
} // End Loop
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
} // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>
Sugeriría usar la clase JSONParser
. Es muy fácil de usar.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws IOException {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (Exception ex) {
Log.d("Networking", ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Luego, en su aplicación, cree una instancia de esta clase. Es posible que desee pasar el constructor ''GET'' o ''POST'' si lo desea.
public JSONParser jsonParser = new JSONParser();
try {
// Building Parameters ( you can pass as many parameters as you want)
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("age", 25));
// Getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(YOUR_URL, "POST", params);
} catch (JSONException e) {
e.printStackTrace();
}
prueba como:
// your get json request to server..
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if(entity != null){
JSONObject respObject = new JSONObject(EntityUtils.toString(entity));
String active = respObject.getString("active");
String name = respObject.getString("name");
String tab1_text = respObject.getString("tab1_text");
//....
}
else{
//Do something here...
}
vea este ejemplo para obtener y analizar la respuesta json del servidor:
http://adblogcat.com/parse-json-data-from-a-web-server-and-display-on-listview/
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
String line = "";
while ((line = in.readLine()) != null) {
JSONObject jObject = new JSONObject(line);
if (jObject.has("name")) {
String temp = jObject.getString("name");
Log.e("name",temp);
}
}
JSONObject(html).getString("name");
Cómo obtener la cadena html
: hacer una solicitud HTTP con android
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class GetJsonFromUrl {
String url = null;
public GetJsonFromUrl(String url) {
this.url = url;
}
public String GetJsonData() {
try {
URL Url = new URL(url);
HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
line = sb.toString();
connection.disconnect();
is.close();
sb.delete(0, sb.length());
return line;
} catch (Exception e) {
return null;
}
}
}
y esta clase utiliza para datos de correos
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by user on 11/2/16.
*/
public class sendDataToServer {
public String postdata(String requestURL,HashMap<String,String> postDataParams){
try {
String response = "";
URL url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
Log.d("test", response);
return response;
}catch (Exception e){
return e.toString();
}
}
public String postjson(String url,String json){
try {
URL obj = new URL(url);
HttpURLConnection con= (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
String urlParameters = ""+json;
// Send post request
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("/nSending ''POST'' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}catch(Exception e){
return e.toString();
}
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
/* public String postdata(String url) {
}*/
}