Display the HTTPentity response value in ListView android - java

I need to display the HttpEntity response values in the listview
Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
Here am getting the response values
try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "testUser#123");
object.put("Password", "testPassword#123");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 4);
HttpPost postMethod = new HttpPost("url");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
HttpEntity entity = response.getEntity();
String response_value = EntityUtils.toString(entity).toString();
// Log.e(TAG, response_value ); //display the output in logcat
if (entity != null) {
//Convert String to JSON Object
JSONObject result = new JSONObject(response_value);
JSONArray tokenList = result.getJSONArray("Files");
for(int i=0;i<=tokenList.length();i++)
{
JSONObject oj = tokenList.getJSONObject(i);
JSONObject oj1 = (JSONObject) tokenList.getJSONObject(i).get("Borrower");
JSONObject oj2 = (JSONObject) tokenList.getJSONObject(i).get("CoBorrower");
JSONObject oj3 = (JSONObject) tokenList.getJSONObject(i).get("LoanDetails");
JSONObject oj4 = (JSONObject) tokenList.getJSONObject(i).get("PropertyAddress");
String fileid = oj.getString("FileID");
String borrowername = oj1.getString("FirstName");
String coborrowername = oj2.getString("FirstName");
String loannumber = oj3.getString("LoanNumber");
String addrs1 = oj4.getString("Address1");
String city = oj4.getString("City");
Log.e(TAG, fileid + "/" + borrowername + "/"+ coborrowername + "/"+ addrs1 + "/"+ city + "/"+ loannumber );
JSONArray orders = oj.getJSONArray("Orders");
for(int n=0;n<orders.length();n++){
JSONObject oj5 = orders.getJSONObject(n);
String appid = oj5.getString("ApplicationOrderId");
String appid1 = oj5.getString("DueDate");
Log.e(TAG, appid +"/"+ appid1);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {}
}
}
Now am displaying the response value in the log cat but i want to display this values in the List View. If you have any idea please help me, thanks in advance.

Create a model class ! and create a new instance from it and set your values , then pass the instance to your adapter !
See this link to know how create a model class :
http://www.vogella.com/tutorials/AndroidListView/article.html#listadvanced_interactive

Related

Retrieve data to ListView from API in android

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();
}

get JSON object with API client

Im trying to get JSONobject from api but i cant get this piece of code to work.
I am new to android and java and JSON. i keep getting the error: in JSONobject cannot be applied
Main code:
try {
APIClientJSONObject api = new APIClientJSONObject();
JSONObject result = null;
try {
result = api.execute(URL).get();
} catch (Exception e) {
e.printStackTrace();
}
List<CustomListView> contents = new ArrayList<CustomListView>();
try {
JSONObject row = result.getJSONObject(result**ERROR HERE**);
String content = row.optString("FormattedName");
String content2 = row.optString("Title");
String content3 = row.optString("Subtitle");
String content4 = row.optString("Text");
EditText name = (EditText) findViewById(R.id.etInternNaam);
name.setText(content);
EditText titel = (EditText) findViewById(R.id.etName);
titel.setText(content2);
EditText ondertitel = (EditText) findViewById(R.id.etOndertitel);
ondertitel.setText(content3);
EditText EditText = (EditText) findViewById(R.id.etTekst);
EditText.setText(Html.fromHtml(content4));
} catch (JSONException e) {
e.printStackTrace();
}
Api client:
public class APIClientJSONObject extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(params[0]));
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result = new JSONObject(builder.toString());
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
JSON output:
{
"FormattedName": "Home page | Footer grijs",
"Title": null,
"Subtitle": null,
"Text": "<div style=\"text-align: center;\"><img style=\"max-width: 80%;\" src=\"/MoxieManager/code.PNG\" alt=\"\"></div>",
"WebsiteId": "6869a7a1-0d65-4cfa-9df1-b0b0d346212e",
"Id": "b9906cb0-cdb2-484a-b603-020e8b64f97b",
"DateCreated": "2016-01-25T12:09:50.367",
"DateModified": "2016-02-11T08:51:54.223",
"CreatedBy": "Drie-O Automatisering",
"ModifiedBy": "Drie-O Automatisering",
"SortOrder": 0
}
Reason:
You are already getting the JSONObject from AsycnTask. There is no need of
JSONObject row = result.getJSONObject(result);
When you try to used this it means you are trying to find a object result inside object result. Which is not the case here.
Solution:
You should remove the above mentioned call and use result in these calls like below.
String content = result.optString("FormattedName");
String content2 = result.optString("Title");
String content3 = result.optString("Subtitle");
String content4 = result.optString("Text");
Is the error coming at this line?
JSONObject row = result.getJSONObject(result);
result is a JSONObject, and the method requires a String.
Why not try to convert result to String and pass it. Something like.
JSONObject resultJson = new JSONObject();
result.toString();
JSONObject row = result.getJSONObject(resultJson );
You have already got the JSON output as given from the APIClient.
JSONObject row = result.getJSONObject(result);
this line is redundant unless your real response is an array list enclosed object and you are getting only a row from it.
Directly you can access internal elements in main object now.

user information Json data appears only after login ,How to parse that Json data in android

I am working on one application ,in which i got two JSon url
1.(eg.www.xxxxxxx.com )to login application (by giving username and password) and
2.(eg.www.xxxxxx xxxx xxx.com )to get logged in user information,but we can get user information only after login,before login Second url does not show anything..so how to parse second json data from first json data in android...
here is my Login.java(First json url to login)
public class Login extends Activity {
private static final String SERVICE_URI = "http://xxxxxxxxxxxxxxxxxxxx.com/login";
private static Context mContext;
public EditText edittext_username, edittext_password;
Button button_submit,reg;
public static final String TAG = "MYTAG";
Person person;
static TextView txt_Error;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
edittext_password = (EditText) findViewById(R.id.textEmailAddress);
edittext_username = (EditText) findViewById(R.id.txtUsername);
button_submit = (Button) findViewById(R.id.buttonLogin);
txt_Error =(TextView)findViewById(R.id.txtError);
button_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
new MyAsyncTask().execute();
}
});
}
public String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("username", person.getName());
jsonObject.accumulate("password", person.getCountry());
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if(httpResponse.getStatusLine().getStatusCode()==200){
Intent login = new Intent(mContext, MainActivity.class);
mContext.startActivity(login);
}else{
txt_Error.setText("Sorry!! Incorrect Username or Password");
}
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private class MyAsyncTask extends AsyncTask<Void, Void, String> {
ProgressDialog mProgressDialog;
private DefaultHttpClient httpclient;
private String username, password;
private HttpPost httppost;
private ArrayList<NameValuePair> nameValuePairs;
private HttpResponse response;
private HttpEntity entity;
#Override
protected void onPostExecute(String result) {
mProgressDialog.dismiss();
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(Login.this, "", "Loading...");
}
#Override
protected String doInBackground(Void... params) {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://xxxxxxxxxxxxxxxxxxxxxxx.com/login");
person = new Person();
person.setName(edittext_username.getText().toString());
person.setCountry(edittext_password.getText().toString());
return POST(SERVICE_URI, person);
}
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
There are many ways to parse a JSON string into an object representation.
I see you already use JSONObject to create the body of your POST request. You can use new JSONObject(jsonString) to create an object from the response's body, after you've converted it to a String with convertInputStreamToString.
However there are better alternatives that will map the JSON to your own object model, e.g. the Gson library.
Have a look at this answer https://stackoverflow.com/a/31743324/2914666 or any of the related questions listed on the side.

JSON post values in particular format and response for login in android

I need to post the data through URl in this format
{
"Authentication": {
"Username": "test#123",
"Password": "test#123"
},
"RequestType": 7
}
And getting the response value for a particular post value in this format
{
StatusCode: 400
StatusMessage: "Order Request Type is Invalid"
}
In this how can i validate if status message is equal to Ok then only page redirect to Main Activity otherwise show the alert box. please help me if you have any idea.
Here is my code:
public class MainActivity extends Activity{
String oj ;
String response_value ;
private TextView test1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// we will using AsyncTask during parsing
test1=(TextView)findViewById(R.id.text1);
new AsyncTaskParseJson().execute();
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
// post the specific format data to json url
try {
HttpClient httpClient = new DefaultHttpClient();
JSONObject object = new JSONObject();
object.put("Username", "test#123");
object.put("Password", "test#123");
JSONObject jsonObject = new JSONObject();
jsonObject.put("Authentication", object);
jsonObject.put("RequestType", 7);
HttpPost postMethod = new HttpPost("Here i pass url");
postMethod.setEntity(new StringEntity(jsonObject.toString()));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(postMethod);
HttpEntity entity = response.getEntity();
response_value = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}
return response_value;
}
#Override
protected void onPostExecute(String response_value) {
super.onPostExecute(response_value);
// dismiss the dialog after getting all products
try
{
JSONObject result = new JSONObject(response_value);
String strStatusMessage=result.optString("StatusMessage");
if (strStatusMessage.equals("Order Request Type is Invalid")){
Intent ites1=new Intent(MainActivity.this,Test.class);
startActivity(ites1);
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
how can i validate if status message is equal to Ok then only page
redirect to Main Activity otherwise show the alert box
First get StatusMessage message from JSONObject:
JSONObject jsonObject=new JSONObject(server_response);
String strStatusMessage=jsonObject.optString("StatusMessage");
Now compare strStatusMessage to "ok" :
if strStatusMessage equals "ok" Then
// move to next activity
otherwise
// show alert

Array and Object JSON from URL Parsing

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);"

Categories