I want to parse the following JSON file but is starting with [ indicating to me that is an array, and then continues with { objects, my current parser is returning a JSON object.
My question is: how to modify the parser to parse this file? So that the parser will serve me for other JSON files, starting with objects or arrangements.
JSON FILE:
[{"codigo":1,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"1 lomo completo y 1 cerveza de lt","precio":100.0},{"codigo":2,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"2 lomo completo y 2 cerveza de lt","precio":190.0},{"codigo":3,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"3 lomo completo y 3 cerveza de lt","precio":280.0},{"codigo":4,"contenido":[{"codigo":1,"descripcion":"Lomo completo"},{"codigo":2,"descripcion":"Cerveza 1 Lt."}],"descripcion":"4 lomo completo y 4 cerveza de lt","precio":370.0}]
JSON PARSER
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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;
}
}
Try to parser JSON FILE
public class OfertaService extends Service {
private static final String URL = "http://192.168.0.13:8080/ofertas/listado";
private static final String TAG_CODIGO = "codigo";
private static final String TAG_CONTENIDO = "contenido";
private static final String TAG_DESCRIPCION = "descripcion";
private static final String TAG_PRECIO = "precio";
private static final String TAG_CODIGO_PRODUCTO = "codigo";
private static final String TAG_DESCRIPCION_PRODUCTO = "descripcion";
#SuppressWarnings("rawtypes")
private List listaOfertas = new ArrayList();
public List getListaOfertas() {
return listaOfertas;
}
public void setListaOfertas(List listaOfertas) {
this.listaOfertas = listaOfertas;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("unchecked")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
new DoInBack().execute();
} catch (Exception e) {
System.out.println("error en proceso de segundo plano DoInBack");
}
return 0;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
private class DoInBack extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONArray ofertasArray = null;
JSONArray productos = null;
JSONObject json = jParser.getJSONFromUrl(URL);
try {
String codigo = json.getString(TAG_CODIGO);
for (int i = 0; i < ofertasArray.length(); i++) {
JSONObject of;
of = ofertasArray.getJSONObject(i);
String id = of.getString(TAG_CODIGO);
// productos = json.getJSONArray(0);
List listaProductos = new ArrayList();
for (int j = 0; j < productos.length(); j++) {
JSONObject pro = productos.getJSONObject(j);
String idProducto = pro.getString(TAG_CODIGO_PRODUCTO);
String descProducto = pro
.getString(TAG_DESCRIPCION_PRODUCTO);
Hashtable<String, String> producto = new Hashtable<String, String>();
producto.put(TAG_CODIGO_PRODUCTO, idProducto);
producto.put(TAG_DESCRIPCION_PRODUCTO, descProducto);
listaProductos.add(producto);
}
String descripcionOferta = of.getString(TAG_DESCRIPCION);
String precio = of.getString("precio");
Hashtable ht = new Hashtable();
ht.put(TAG_CODIGO, id);
ht.put(TAG_CONTENIDO, listaProductos);
ht.put(TAG_DESCRIPCION, descripcionOferta);
ht.put(TAG_PRECIO, precio);
listaOfertas.add(ht);
}
System.out.println("parseo finalizado");
} catch (Exception e) {
}
return null;
}
}
I want to parse the following JSON file but is starting with [
indicating to me that is an array
When json string starting with [ means string is JSONArray
how to modify the parser to parse this file?
1. Convert json String to JSONArray instead of JSONObject:
JSONArray jsonArray = new JSONArray(json);
2. Change return type of getJSONFromUrl method to JSONArray from JSONObject
3. In doInBackground get response from getJSONFromUrl method in JSONArray:
JSONArray jsonArray = jParser.getJSONFromUrl(URL);
Related
I need to retrieve data to listview from this link http://www.autotrack.rs/android_juzna_backa/get_voznja.php?. I need to send key, with value-POST method, to get something like this: http://www.autotrack.rs/android_juzna_backa/get_voznja.php?voznja_id=42. My code is bellow: Thanks. ERROR Value null at data of type org.json.JSONObject$1 cannot be converted to JSONArray
public class fetchData extends AsyncTask<String, String, String> {
#Override
public void onPreExecute() {
super.onPreExecute();
swipeRefresh.setRefreshing(true);
}
#Override
protected String doInBackground(String... params) {
arrayList.clear();
String result = null;
try {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("voznja_id", "42")
.build();
Request request = new Request.Builder()
.url("http://www.autotrack.rs/android_juzna_backa/get_voznja.php")
.method("POST", body)
.build();
try {
response = client.newCall(request).execute();
// System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
public void onPostExecute(String rezultat) {
try {
rezultat = response.body().string();
}catch (Exception m)
{
m.printStackTrace();
}
Intent intent;
Gson gson = new Gson();
Type type = new TypeToken<Voznja>() {
}.getType();
Voznja voznja = gson.fromJson(rezultat, type);
Intent im = new Intent(getApplicationContext(), Unos.class);
im.putExtra("voznja", voznja);
// startActivity(im);
swipeRefresh.setRefreshing(false);
try {
JSONObject object = new JSONObject(rezultat);
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
VoznjaAdapter adapter = new VoznjaAdapter(ListaVoznji.this, arrayList);
listView.setAdapter(adapter);
Your api response is JSONObject.
{"data":{"id":"42","vozilo_id":"777777003561","vozac_id":"2","pocetna_kilometraza":"50000","pocetno_vreme":"2020-12-25 07:15:00","projekat":null,"razlog":"Sastanak","zavrsna_kilometraza":"50150","zavrsno_vreme":"2020-12-25 10:45:00","moto_sati":"3","insert_time":"2021-01-08 10:47:33.683885","id_projekat_jb":"330"}}
So you should use JSONObject instead JSONArray
try {
JSONObject object = new JSONObject(rezultat);
JSONObject jsonObject = object.getJSONObject("data");
String id = jsonObject.getString("id");
String vozilo_id = jsonObject.getString("vozilo_id");
String vozac_id = jsonObject.getString("vozac_id");
String pocetna_kilometraza = jsonObject.getString("pocetna_kilometraza");
String pocetno_vreme = jsonObject.getString("pocetno_vreme");
String razlog = jsonObject.getString("razlog");
String zavrsna_kilometraza = jsonObject.getString("zavrsna_kilometraza");
String zavrsno_vreme = jsonObject.getString("zavrsno_vreme");
String moto_sati = jsonObject.getString("moto_sati");
String id_projekat_jb = jsonObject.getString("id_projekat_jb");
ItemModel model = new ItemModel();
model.setVoznja_id(id);
model.setVoziloId(vozilo_id);
model.setVozac_id(vozac_id);
model.setPocetnaKilometraza(pocetna_kilometraza);
model.setPocetnoVreme(pocetno_vreme);
model.setRazlog(razlog);
model.setZavrsnaKilometraza(zavrsna_kilometraza);
model.setZavrsnoVreme(zavrsno_vreme);
model.setMotoSati(moto_sati);
model.setProjekatId(id_projekat_jb);
arrayList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
I use below code to produce JSON string and parse it in php. I create an instace of this class and call setData method
//#PART1
String s = "{\"Category\":";
List<CategoryModel> pmo = new ArrayList<CategoryModel>();
pmo = CategoryModule.getAllRecords(c);
s += new JSONSerializer().serialize(pmo);
s += ",\"Data\":";
//#PART2
List<DataModel> amo = new ArrayList<DataModel>();
amo = DataModule.getAllRecords(c);
s += new JSONSerializer().serialize(amo);
s += "}";
I decode the result by below code
$categories = json_decode($data)->{'Category'};
$datas = json_decode($data)->{'Data'};
$username = "kkk";
foreach($categories as $category){
$id = $category->{'id'};
$name = $category->{'name'};
$sql = "INSERT INTO category (id,name,username) VALUES ('$id','$name','$username')";
$link->query($sql);
}
foreach($datas as $data){
$id = $data->{'id'};
$text = $data->{'text'};
$date = $data->{'date'};
$sql = "INSERT INTO data (id,text,date,username) VALUES ('$id','$name','$date','$username')";
$link->query($sql);
}
When I just use #PART1 to produce json string in the php code the decoding occurs in success. But when I add #PART2 to JSON string no one of them decodes successfully. I guess the problem can be from java code.
Please guide me
JSON result is http://aiga.ir/webservice/datastore/a.txt
I use this code for sending data
package ir.aiga.apps.network;
public class WebServiceComm extends AsyncTask<String, Void, Void> {
// Required initialization
private String Content;
private String Error = null;
private ProgressDialog Dialog;
private String data ="";
private boolean visible=true;
private InterFace doInPreExecute=new InterFace() {
#Override
public void doSomething() {
// TODO Auto-generated method stub
}
#Override
public void getResult(String output) {
// TODO Auto-generated method stub
}
#Override
public void getJSONArray(JSONArray array) {
// TODO Auto-generated method stub
}
};
private InterFace doInPostExecute=new InterFace() {
#Override
public void doSomething() {
// TODO Auto-generated method stub
}
#Override
public void getResult(String output) {
// TODO Auto-generated method stub
}
#Override
public void getJSONArray(JSONArray array) {
// TODO Auto-generated method stub
}
};
public WebServiceComm(Context context,String title,String text){
try {
data +="&" + URLEncoder.encode("data", "UTF-8") + "=";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dialog=new ProgressDialog(context,ProgressDialog.STYLE_SPINNER);
Dialog.setTitle(title);
Dialog.setMessage(text);
}
public WebServiceComm(){
try {
data +="&" + URLEncoder.encode("data", "UTF-8") + "=";
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setData(String data){
this.data+=data;
}
protected void onPreExecute() {
// NOTE: You can call UI Element here.
if(visible)
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
if (Error != null) {
} else {
// Show Response Json On Screen (activity)
/****************** Start Parse Response JSON Data *************/
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
doInPostExecute.getJSONArray(jsonMainNode);
doInPostExecute.doSomething();
if(visible)
Dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* #return the doInPreExecute
*/
public InterFace getDoInPreExecute() {
return doInPreExecute;
}
/**
* #param doInPreExecute the doInPreExecute to set
*/
public void setDoInPreExecute(InterFace doInPreExecute) {
this.doInPreExecute = doInPreExecute;
}
/**
* #return the doInPostExecute
*/
public InterFace getDoInPostExecute() {
return doInPostExecute;
}
/**
* #param doInPostExecute the doInPostExecute to set
*/
public void setDoInPostExecute(InterFace doInPostExecute) {
this.doInPostExecute = doInPostExecute;
}
/**
* #return the visible
*/
public boolean isVisible() {
return visible;
}
/**
* #param visible the visible to set
*/
public void setVisible(boolean visible) {
this.visible = visible;
}
}
please try to use this code for sending and receiving JSON with utf-8 encoding:
try {
URL url = new URL("your url");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(
conn.getOutputStream(), "UTF-8");
String request = "your json";
writer.write(request);
writer.flush();
System.out.println("Code:" + conn.getResponseCode());
System.out.println("mess:" + conn.getResponseMessage());
String response = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
response += line;
}
System.out.println(new String(response.getBytes(), "UTF8"));
writer.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It's very bad to manually build JSON manually.
Using a JSON Mapper library
public class MyCustomModel {
public List<CategoryModel> Category;
public List<DataModel> Data;
public class CategoryModel{
//code here
}
public class DataModel{
//code here
}
}
Then use it GSON to serialize that object into JSON
MyCustomModel customModel = new MyCustomModel();
//populate object
//......
Gson gson = new Gson();
String json = gson.toJson(customModel);
Using standard library
JSONArray categoryArr = new JSONArray();
List<CategoryModel> categories = CategoryModule.getAllRecords(c);
for (CategoryModel category : categories) {
JSONObject categoryObj = new JSONObject();
categoryObj.put("class", category.getClass());
categoryObj.put("id", category.getId());
categoryObj.put("name", category.getName());
categoryArr.put(categoryObj);
}
Then do the same with the other list then combine both array
JSONObject jObject = new JSONObject();
jObject.put("Category", categoryArr);
jObject.put("Data", dataArr);
I was a novice at the json parsing from url. yesterday I've tried parsing json simple data. Now I am confused to form a json parsing the data as below. I still can not how to parse arrays and objects in json. Please help me guys ..
here my MainActivity.java
public class MainActivity extends ListActivity {
/** Called when the activity is first created. */
private static String URL = "http://api.themoviedb.org/3/genre/18/movies?api_key=d397dd2d354f088c6f0eb91c6b160bb0";
// tag
private static final String TAG_ID = "id";
private static final String TAG_page = "page";
private static final String TAG_results = "results";
private static final String TAG_backdrop_path = "backdrop_path";
private static final String TAG_id = "id";
private static final String TAG_original_title = "original_title";
private static final String TAG_release_date = "release_date";
private static final String TAG_poster_path = "poster_path";
private static final String TAG_title = "title";
private static final String TAG_vote_average = "vote_average";
private static final String TAG_vote_count = "vote_count";
private static final String TAG_total_pages = "total_pages";
private static final String TAG_total_results = "total_results";
JSONArray results = null;
JSONArray id = null;
JSONArray page = null;
JSONArray pages = null;
JSONArray tot_result = null;
// panggil class parser
JSONparser parser = new JSONparser();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> genreList = new ArrayList<HashMap<String, String>>();
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getJSONArray(TAG_ID);
page = json.getJSONArray(TAG_page);
pages = json.getJSONArray(TAG_total_pages);
tot_result = json.getJSONArray(TAG_total_results);
for (int i = 0; i < results.length(); i++) {
JSONObject data = results.getJSONObject(i);
String backdrop = data.getString(TAG_backdrop_path);
String idd = data.getString(TAG_id).toString();
String ori = data.getString(TAG_original_title);
String releas = data.getString(TAG_release_date);
String poster = data.getString(TAG_poster_path);
String title = data.getString(TAG_title);
String average = data.getString(TAG_vote_average);
String count = data.getString(TAG_vote_count);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_backdrop_path, backdrop);
map.put(TAG_ID, idd);
map.put(TAG_original_title, ori);
map.put(TAG_release_date, releas);
map.put(TAG_poster_path, poster);
map.put(TAG_title, title);
map.put(TAG_vote_average, average);
map.put(TAG_vote_count, count);
genreList.add(map);
}
// Sort by
/*********************************
* Collections.sort(genreList, new Comparator<HashMap<String,
* String>>() {
*
* #Override public int compare(HashMap<String, String> a,
* HashMap<String, String> b) { return
* a.get(TAG_NAMA).compareTo(b.get(TAG_ID)); } });
******************************/
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
// tampilkan ke listadapter
ListAdapter adapter = new SimpleAdapter(this, genreList,
R.layout.list_data, new String[] { TAG_ID, TAG_page,
TAG_results, TAG_backdrop_path, TAG_id,
TAG_original_title, TAG_release_date, TAG_poster_path,
TAG_title, TAG_vote_average, TAG_vote_count,
TAG_total_pages, TAG_total_results }, new int[] {
R.id.id, R.id.page, R.id.result, R.id.backdrop_path,
R.id.idd, R.id.original_title, R.id.release_date,
R.id.poster_path, R.id.title, R.id.vote_average,
R.id.vote_count, R.id.total_pages, R.id.total_results });
setListAdapter(adapter);
}
}
here my JSONparser.java
public class JSONparser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONparser() {
}
public JSONObject getJSONFromUrl(String url) {
// http request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 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) {
// TODO: handle exception
Log.e("BUffer Error", "Error converting result" + e.toString());
}
// try parse string to a json
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
// TODO: handle exception
Log.e("Json parser", "error parsing data" + e.toString());
}
return jObj;
}
}
here my json data.
{
"id": 18,
"page": 1,
"results": [
{
"backdrop_path": "/6xKCYgH16UuwEGAyroLU6p8HLIn.jpg",
"id": 238,
"original_title": "The Godfather",
"release_date": "1972-03-24",
"poster_path": "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg",
"title": "The Godfather",
"vote_average": 9.1999999999999993,
"vote_count": 125
},
{
"backdrop_path": "/ooqPNPS2WdBH7DgIF4em9e0nEld.jpg",
"id": 857,
"original_title": "Saving Private Ryan",
"release_date": "1998-07-24",
"poster_path": "/35CMz4t7PuUiQqt5h4u5nbrXZlF.jpg",
"title": "Saving Private Ryan",
"vote_average": 8.9000000000000004,
"vote_count": 83
}
],
"total_pages": 25,
"total_results": 499
}
JSONObject jObject_Main= new JSONObject(jsonstring);
//get json simple string
String id = jObject_Main.getString("id");
String page = jObject_Main.getString("page");
//get json Array and parse it.
JSONArray jsonArray = jObject_Main
.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String backdrop_path=jsonObject.getString("backdrop_path");
}
i hope its useful to you.
please change this in your code:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString("id");
page = json.getString("page");
tot_result = json.getJSONArray(results);
i hope you understand it.
Try this..
In your Global:
JSONArray results = null;
String id = null;
String page = null;
String pages = null;
String tot_result = null;
Inside Try Catch:
JSONObject json = parser.getJSONFromUrl(URL);
try {
id = json.getString(TAG_ID); // Changes here
page = json.getString(TAG_page); // Changes here
pages = json.getString(TAG_total_pages); // Changes here
tot_result = json.getString(TAG_total_results); // Changes here
results = json.getJSONArray(TAG_results); // Add this line
for (int i = 0; i < results.length(); i++) {
// Remaining all correct
}
EDIT:
new DownloadImageTask()
.execute("your image url");
}
and DownloadImageTask.class
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
imageview.setImageBitmap(result);
}
}
Your JSON is JSONObject and it contains JSONArray
Parse Object
Parse Array
Example:
JSONObject jsonObj = new JSONObject(your_json_string);
String id = jsonObj.getString("id");
String page = jsonObj.getString("page"); // or getInt("page");
JSONArray results = jsonObj.getJSONArray("results");
int len = results.length(); // length or size, I don't remember, you can check it
for (int i = 0; i < len; i++) {
JSONObject obj = results.getJSONObject(i);
String backdropPath = obj.getString("backdrop_path");
// ...
}
you need add " results= json.getJSONArray(TAG_results);" below
"tot_result = json.getJSONArray(TAG_total_results);"
I'm attempting to implement asynctask into my existing source code but I'm getting an error stating Syntax error on token "extends", throws expected
If I change
public void run() extends AsyncTask {
to
public void run() throws AsyncTask {
as eclipse seems to be asking me to do - I end up with:
No exception of type AsyncTask can be thrown; an exception type must be a subclass of Throwable
I simply need to figure out what I've done wrong in my asyncTask implementation.
JAVA
public class GetYouTubeUserVideosTask implements Runnable {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
#Override
public void run() extends AsyncTask {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
videos.add(new Video(title, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
}
protected void onPostExecute(String result) {
// do something
}
protected void onPreExecute() {
// do something
}
protected void onProgressUpdate(String... text) {
// do something
}
}
Your asyncTask should be like the following, the class should extends AsyncTask not implements Runnable:
public final class GetYouTubeUserVideosTask extends AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
/*
* #see android.os.AsyncTask#doInBackground(Params[])
*/
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
videos.add(new Video(title, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
/*
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(Void result) {
}
}
I have used httpclient to call a restapi written in django. It returned the json output. My httpresponse variable stored it and later convert the reponse to string and then to json object, i think its lengthy though it is working . I am really new to java , can anybody advise me , what is the best alternative logic to the code below
public void onClick(View v) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://10.0.2.2:8000/api/ca/entry/?
format=json&username=pragya");
try {
// Add your data
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("username", un.getText().toString()));
//nameValuePairs.add(new BasicNameValuePair("username", pw.getText().toString()));
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
JSONObject jsonObject = new JSONObject(sb.toString());
JSONObject meta = jsonObject.getJSONObject("meta");
String limit = meta.getString("limit");
Toast.makeText(HelloWorldActivity.this, limit, Toast.LENGTH_SHORT).show();
JSONArray array = jsonObject.getJSONArray("objects");
String key = array.getJSONObject(0).getString("api_key");
String uname = array.getJSONObject(0).getString("username");
Toast.makeText(HelloWorldActivity.this, uname + " " + key,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Toast.makeText(HelloWorldActivity.this, sb.toString(), Toast.LENGTH_SHORT).show();
} catch (ClientProtocolException e) {
Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
the json is as follows
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"api_key": "c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e", "homeAddress": "kathmandu", "resource_uri": "/api/ca/entry/1/", "username": "sumit"}]}
Use Gson library from google, it is perfect for these kind of tasks.
All you need to do is define a new class that contains fields with the names of the keys in the json object and then use Gson to parse the Json string directly into the object or vice versa.
So for example:
Json looks like this: "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1.
Java Class will be:
public class MyClass {
private int limit;
private int next;
private int offset;
private int previous;
private int total_count;
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getNext() {
return next;
}
public void setNext(int next) {
this.next = next;
}
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getPrevious() {
return previous;
}
public void setPrevious(int previous) {
this.previous = previous;
}
public int getTotal_count() {
return total_count;
}
public void setTotal_count(int total_count) {
this.total_count = total_count;
}
}
And use Gson code like that:
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyClass myClass = gson.fromJson(json, MyClass.class); // deserializes json into MyClass
Please note that the name of the class fields have to match exactly the name of the keys in the json string.
Always perform lengthy non-UI task using AsyncTask. All the operations you described, fetching of json and parsing them, can be performed in AsyncTask. Write the entire code which you have currently written in onClick event and write it doInBackground() of an AsyncTask.
Check the following for more details:
http://developer.android.com/reference/android/os/AsyncTask.html