Parsing JSON in Android from url - android

I am making an App in which i have to parse the following JSON from the url="http://www.omdbapi.com/?t=drishyam"
JSON is :
{"Title":"Drishyam","Year":"2015","Rated":"N/A","Released":"31 Jul 2015","Runtime":"163 min","Genre":"Drama, Mystery, Thriller","Director":"Nishikant Kamat","Writer":"Jeethu Joseph (original story), Upendra Sidhaye (adapted by)","Actors":"Ajay Devgn, Shriya Saran, Tabu, Rajat Kapoor","Plot":"Desperate measures are taken by a man who tries to save his family from the dark side of the law, after they commit an unexpected crime.","Language":"Hindi","Country":"India","Awards":"N/A","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYyMjgyNDY3N15BMl5BanBnXkFtZTgwOTMzNTE5NTE#._V1_SX300.jpg","Metascore":"N/A","imdbRating":"8.9","imdbVotes":"16,509","imdbID":"tt4430212","Type":"movie","Response":"True"}
MainActivity.java
private class GetContacts extends AsyncTask<String, Void, Bitmap> {
#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 Bitmap doInBackground(String... abc) {
html = new Parsing();
html.JsonParse(url);
contactList = new ArrayList<LinkedHashMap<String, String>>();
contactList.clear();
contactList=html.contactList;
System.out.println("Size od cintactlist in Main " + contactList.size());
int c=0;
for (LinkedHashMap<String, String> map : contactList) {
for (Map.Entry<String, String> mapEntry : map.entrySet()) {
if (c == 0) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
if(!key.equals("poster"))
ans="key "+" is "+value+"\n\n";
else
poster=value;
System.out.println("Value of key and value is " + key + " " + value);
} else
break;
}
c++;
}
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(poster).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
// Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
#Override
protected void onPostExecute(Bitmap result) {
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
lbName.setText(ans);
imgview.setImageBitmap(result);
// lblEmail.setText(ans);
}
}
Parsing.java
package com.movie.comparemovie;
import android.content.Context;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class Parsing {
Context context;
ArrayList<LinkedHashMap<String, String>> contactList;
public void JsonParse(String URL1) {
contactList = new ArrayList<LinkedHashMap<String, String>>();
String logoLink = null;
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
JSONObject json = jParser.getJSONFromUrl(URL1);
String Title = json.getString("Title");
System.out.println("Title is "+Title);
String tab1_text = json.getString("tab1_text");
int active = json.getInt("active");
System.out.println("Movie Title is :" + Title);
// // Storing each json item in variable
// String year = json1.getString("Year");
// String released = json1.getString("Released");
// String runtime = json1.getString("Runtime");
// String poster = json1.getString("Poster");
LinkedHashMap<String, String> value = new LinkedHashMap<String, String>();
value.put("title", Title);
// value.put("Year", year);
// value.put("Runtime", runtime);
// value.put("Poster", poster);
contactList.add(value);
// System.out.println("Size od cintactlist in Prasing " + contactList.size());
} catch (JSONException e1) {
e1.printStackTrace();
}
}
public class JsonParser {
final String TAG = "JsonParser.java";
InputStream is = null;
JSONObject jObj = null;
String json = "";
public JSONObject getJSONFromUrl(String ul) {
System.out.println("Inside jsonparser class");
try {
URL url = new URL(ul);
URLConnection connection = url.openConnection();
//connection.addRequestProperty("Referer", "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%22mixorg.com%22&rsz=8");
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
System.out.println(builder.toString());
}
json = builder.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing json data " + e.toString());
} catch (Exception e) {
}
// return JSON String
return jObj;
}
}
}
where JsonParser is a class and getJSONfromURL returns jsonobject.
But it wont work.
How can i parse this JSON ?

Try this :
try {
JSONObject json = new JSONObject("Your String");
String title = json.getString("Title");
String year = json.getString("Year");
//get your all other keys just like title and year
} catch (JSONException e) {
e.printStackTrace();
}

First get the Xml code from link and then parse through the resulting_xml code in your console using XMLpullparser.Xmlpullparser provides built in methods to store in a single json object or multiple json objects if u have many movies in the same link(url="http://www.omdbapi.com/)

Do like that,
public class getData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading category....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
String response = null;
try {
URL url = new URL("http://www.omdbapi.com/?t=drishyam");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
try {
JSONObject c = new JSONObject(result);
String Title = c.getString("Title");
String Year = c.getString("Year");
String Rated = c.getString("Rated");
String Released = c.getString("Released");
String Runtime = c.getString("Runtime");
String Genre = c.getString("Genre");
String Genre = c.getString("Genre");
String Writer = c.getString("Writer");
String Actors = c.getString("Actors");
String Plot = c.getString("Plot");
String Language = c.getString("Language");
String Country = c.getString("Country");
String Awards = c.getString("Awards");
String Poster = c.getString("Poster");
String Metascore = c.getString("Metascore");
String imdbRating = c.getString("imdbRating");
String imdbVotes = c.getString("imdbVotes");
String imdbID = c.getString("imdbID");
String Type = c.getString("Type");
String Response = c.getString("Response");
Log.e("", "TAG : - " + id);
} catch (Exception e) {
Log.e("", "Home Exception : " + e.toString());
}
}
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListView.setAdapter(
new MenuAdapter(getActivity(), arrayList, 0));
}
});
}
}
Happy Coding and Happy To Help.....

Related

Text in textview is not showing strings from java file - openweathermap

I am trying to use openweathermap to get basic data about weather and paste it into textview, but strings to which I am getting data doesn't refresh texts in textviews.
Code:
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
result.append((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
txtCity = findViewById(R.id.txtCity);
txtTemp = findViewById(R.id.txtTemp);
DownloadJSON downloadJSON = new DownloadJSON();
try {
String result = downloadJSON.execute(url).get();
JSONObject jsonObject = new JSONObject(result);
String temp = jsonObject.getJSONObject("main").getString("temp");
String feel_like = jsonObject.getJSONObject("main").getString("feels_like");
txtCity.setText(City);
txtValueFeelLike.setText(feel_like);
txtTemp.setText(temp);
} catch (ExecutionException | InterruptedException | JSONException e) {
e.printStackTrace();
}
}
'''
String City = "Warsaw";
String url = "http://api.openweathermap.org/data/2.5/weather?q="+City+"&units=metric&appid=eace0bd8251cf6ab043ab9858b796256";
TextView txtCity, txtValueFeelLike, txtTemp;
What am I doing wrong?
Ok, I made a change, tried to make it from the scratch again, but now with onPostExecute(). Still nothing...
public class Weather {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?q=Warsaw&units=metric&appid=eace9b6857889076855263cfdb5707c0d00";
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON();
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
public void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
#SuppressLint("DefaultLocale") String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn);
}
} catch (JSONException e) {
}
}
}
public static JSONObject getWeatherJSON() {
try {
URL url = new URL(OPEN_WEATHER_MAP_URL);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder json = new StringBuilder(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if (data.getInt("cod") != 200) {
return null;
}
return data;
} catch (Exception e) {
return null;
}
}}
And Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
Weather.placeIdTask asyncTask = new Weather.placeIdTask() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
}
};
No idea what to do now.

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
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();
}
}
MainActivity.java
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 = "https://someLink";
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("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// 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[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

Android is not reading JSON array from PHP file

So I've been following a tutorial that shows how to connect android to MySQL db. I've done everything, but it didn't work. The PHP file works when i enter it's location in chrome -> it shows me the array in JSON format. However, in android it's not working maybe because I am hosting the file on a local server. Any help?
Thanks.
Android:
package com.example.mohammadel_ghali.icare;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
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.URL;
import java.util.ArrayList;
public class login extends AppCompatActivity {
String JSON_STRING ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void getJSON(View view){
new BackgroundTask().execute();
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
String JSON_URL;
#Override
protected void onPreExecute() {
JSON_URL ="10.0.2.2/ApplicationDemoNewNew/admin/android/json_get_login.php";
}
#Override
protected String doInBackground(Void... voids) {
try {
StringBuilder JSON_DATA = new StringBuilder();
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((JSON_STRING = reader.readLine())!=null) {
JSON_DATA.append(JSON_STRING).append("\n");
}
return JSON_DATA.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView json = (TextView) findViewById(R.id.tv_result);
json.setText(result);
}
}
}
PHP:
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='root123';
$con = #mysqli_connect($mysql_host,$mysql_user,$mysql_password);
if(!$con){
die('Failed to connect to the database');//if not successful
}else{
//echo "Successfully connected to MySQL!";//if successful
if(#mysqli_select_db($con, 'application_database')){//selecting the database
//echo '<br>'."Connected to the specified database!";
}else{
die('<br>'."Could not connect to the specified database!");
}
}
$sql = "select * from users;";
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("id"=>$row[0],"username"=>$row[1],"password"=>$row[2],"first_name"=>$row[3],"last_name"=>$row[4]));
}
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
This is my entire class that takes in a JSON file......
Mine goes through a json provided by NFL and I grab the teams and scores
private class GetWeekScores extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplication(),"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler httpHandler = new HttpHandler();
// Making a request to url and getting response
for (int i = 0; i <list.size(); i++) {
String url = NFL_LIVEUPDATE_URL + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = httpHandler.makeServiceCall(url);
Log.e(TAG, "Response from url: " + url);
if (jsonStr != null) {
try {
JSONObject id = new JSONObject(jsonStr);
JSONObject home = new JSONObject(jsonStr);
JSONObject away = new JSONObject(jsonStr);
// Getting JSON Array node
final JSONObject getid = id.getJSONObject(list.get(i));
JSONObject homeScore = getid.getJSONObject("home");
JSONObject homeScore2 = homeScore.getJSONObject("score");
homeTeamABBR = homeScore.getString("abbr");
getHomeScore = homeScore2.getString("T");
JSONObject awayScore = getid.getJSONObject("away");
JSONObject awayScore2 = awayScore.getJSONObject("score");
awayTeamABBR = awayScore.getString("abbr");
getAwayScore = awayScore2.getString("T");
HashMap<String, String> homeaway = new HashMap<>();
homeaway.put("matchup", awayTeamABBR + "vs" + homeTeamABBR);
homeaway.put("homeScore", homeTeamABBR + "->" + getHomeScore + " points ");
homeaway.put("awayScore", awayTeamABBR + "->" + getAwayScore + " points ");
if (Integer.parseInt(getHomeScore) > Integer.parseInt(getAwayScore)) {
homeaway.put("winner", homeTeamABBR);
} else {
homeaway.put("winner", awayTeamABBR);
}
gameIDList.add(homeaway);
} 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 {
MethodContants.showLog(TAG, "JSON File does not exist from NFL", true);
// 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);
MethodContants.showLog(TAG, "Number of games being parsed through: " + list.size(), false);
for (int i = 0; i < gameIDList.size(); i++){
System.out.println(gameIDList.get(i).get("matchup") + " -> " + gameIDList.get(i).get("homeScore") + "-> " + gameIDList.get(i).get("awayScore") + ". " + gameIDList.get(i).get("winner") + " WON!");
}
}
}
I am not sure what else your PHP file does, but if you just need info from JSON, then create a JSON file....no need to create a PHP file.
I forgot to add the HttpHandler class.
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();
}
}

Android ListView Parsing data with Json

Here i am sharing my code how i can parse this data in list view .first i am using Json Parser now this cannot work .Now i am parsing this so we cannot see the list view .Please help me in this Thanks.
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeScreen extends Activity {
ListView listview;
String url;
ArrayList<ParticipantItem> participantArrayList;
ParticipantsAdapter pAdapter;
JSONArray jsonOuterArray;
private ProgressDialog pDialog;
ImageView menu, refresh;
Integer a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
participantArrayList = new ArrayList<ParticipantItem>();
listview = (ListView) findViewById(R.id.listview);
url = "http://findcourse.net/search_result.php?search=&study_field=17";//"http://findcourse.net/search_result.php?search=" + keywordvalue_get + sf_spinner_get + sl_spinner_get + si_spinner_get + sm_spinner_get;
refresh = (ImageView) findViewById(R.id.refresh);
menu = (ImageView) findViewById(R.id.menu);
new GetData().execute();
System.out.println("The square root of " + url);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
//////////////////////
private class GetData extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeScreen.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
if (jsonOuterArray.length() > 0) {
for (int i = 0; i <= jsonOuterArray.length(); i++) {
a = jsonOuterArray.length();
JSONObject jsonObj;
try {
jsonObj = jsonOuterArray.getJSONObject(i);
JSONObject message = jsonObj.getJSONObject("result");
String offered_by_detail = message.getString("offered_by");
String course = message.getString("course");
String logo = message.getString("logo");
String total_views = message.getString("total_views");
String total_course_offered = message.getString("total_course_offered");
String feature_course = message.getString("feature_course");
String total_views_course = message.getString("total_views_course");
String course_info = message.getString("course_info");
String duration = message.getString("duration");
String tution_fee = message.getString("tution_fee");
String other_payable_fee = message.getString("other_payable_fee");
String intake = message.getString("intakesandroid");
String campus = message.getString("campusandroid");
String entry_requirement = message.getString("entry_requirement");
String longitude = message.getString("longitude");
String latitude = message.getString("latitude");
String search_filter = message.getString("search_filter");
String institute_info = message.getString("institute_info");
// Toast.makeText(HomeScreen.this, institute_info, Toast.LENGTH_SHORT).show();
TextView search_filtera = (TextView) findViewById(R.id.search_filter);
// search_filtera.setText("Search for " + String.valueOf(a) + " institutions offering in Agriculture courses");
search_filtera.setText(search_filter);
participantArrayList.add(new ParticipantItem(offered_by_detail, logo, course, total_views, course_info, duration, tution_fee, other_payable_fee, intake, campus, entry_requirement, longitude, latitude, search_filter, institute_info, total_course_offered, feature_course, total_views_course));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
pDialog.dismiss();
}
}
} else {
}
pAdapter = new ParticipantsAdapter(getApplicationContext(), participantArrayList);
listview.setAdapter(pAdapter);
}
protected String doInBackground(final String... args) {
HttpHandler sh = new HttpHandler();
jsonOuterArray = new JSONArray();
String jsonOuterArray = sh.makeServiceCall(url);
return null;
}
}
}
the error may be because of returning null in your doInBackground().
to make your Json mapping simple, add this to your gradle file
compile 'com.fasterxml.jackson.core:jackson-databind:2.3.2'
then to retrive List of Object from Json
try {
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<List<ParticipantItem>> mapType = new
TypeReference<List<ParticipantItem>>() {};
participantArrayList= objectMapper.readValue(jsonOuterArray,mapType) ;
} catch (IOException e) {
e.printStackTrace();
}
Your JsonArray length is empty you need to assign from the response in your Asyntask.Refer the below code it works.
HttpManager:Java
public class HttpManager {
public static String getResponse(RequestPackage p) {
BufferedReader reader = null;
String uri = p.getUri();
//Managing GET request using appending parameter to the url
if(p.getMethod().equals("GET")) {
uri += "?" + p.getEncodedParams();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(p.getMethod());
//Managing POST request using OutPutStream
if (p.getMethod().equals("POST")) {
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(p.getEncodedParams());
writer.flush();
}
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
}
}
}
RequestPackage.Java
public class RequestPackage {
private String uri;
private String method = "GET";
private Map<String,String> params = new HashMap<>();
public Map<String, Integer> getParamsInt() {
return paramsInt;
}
public void setParamsInt(Map<String, Integer> paramsInt) {
this.paramsInt = paramsInt;
}
private Map<String,Integer> paramsInt = new HashMap<>();
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParams(String key, String value) {
params.put(key,value);
}
public String getEncodedParams() {
StringBuilder sb = new StringBuilder();
for(String key : params.keySet()) {
String value = null;
try{
value = URLEncoder.encode(params.get(key),"UTF-8");
}
catch(UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length() > 0)
{
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}
}
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private ProgressDialog pDialog;
ArrayList<Result> participantArrayList;
ParticipantsAdapter pAdapter;
Integer a;
JSONArray jsonOuterArray=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//For GET request parameter pass through the url.
RequestPackage regPackage = new RequestPackage();
regPackage.setMethod("GET");
regPackage.setUri("http://findcourse.net/search_result.php?search=&study_field=17");
new webTask().execute(regPackage);
}
public class webTask extends AsyncTask<RequestPackage, String, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
//You can also use progress dialog here
Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show();
}
#Override
protected String doInBackground(RequestPackage... requestPackages) {
String content = HttpManager.getResponse(requestPackages[0]);
return content;
}
#Override
protected void onPostExecute(String result) {
//Webserver will return response in a result variable.
String response = result;
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
pDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = (JSONObject) jsonArray.get(i);
JSONObject message = item.getJSONObject("result");
String offered_by_detail = message.getString("offered_by");
String course = message.getString("course");
String logo = message.getString("logo");
String total_views = message.getString("total_views");
String total_course_offered = message.getString("total_course_offered");
Toast.makeText(MainActivity.this,
logo+ offered_by_detail + course, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
pDialog.dismiss();
}
}
}
}

AsyncTask with timeout

I want my application throws timeout after 10 seconds in AsyncTask.So what should i do ? If i am not using this so my application is crash.
And sorry for my bad English.
this is my AsyncTask
LoginTask
public class LoginTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
/* JSONParser jParser = new JSONParser();
// JSONArray data = null;
String jsonstr = jParser.makeServiceCall(URL, JSONParser.POST);*/
BufferingH call = new BufferingH();
jsonstr = call.makeBufferCall(URL);
System.out.println("Json url view string " + jsonstr);
return null;
}
#SuppressLint("ShowToast")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (jsonstr != null) {
try {
JSONObject jobj = new JSONObject(jsonstr);
URLmessage = jobj.getString("message").toString();
JSONArray jarray = jobj.getJSONArray("Data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobjj = jarray.getJSONObject(i);
Username = jobjj.getString("r_name");
Password = jobjj.getString("r_password");
FirstName=jobjj.getString("first_name");
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid username password", Toast.LENGTH_SHORT).show();
Log.e("Login Screen", "Couldn't get any data from the url");
}
try {
if (URLmessage.matches("Invalid Login")) {
Toast.makeText(getApplicationContext(), "Invalid Login.....",
Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Login.this, Register.class);
// startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login Successful...",
Toast.LENGTH_SHORT).show();
Password = et_password.getText().toString();
Username = et_username.getText().toString();
Intent k = new Intent(getBaseContext().getApplicationContext(),
MainActivity.class);
k.putExtra("regId", regId);
startActivity(k);
finish();
SettingsFragment.setDefaults("Username", Username, getApplicationContext());
SettingsFragment.setDefaults("Password", Password, getApplicationContext());
SettingsFragment.setDefaults("FirstName", Login.FirstName, getApplicationContext());
Toast.makeText(getApplicationContext(), "FirstName = "+FirstName, Toast.LENGTH_SHORT).show();
// gcmregister_from_sharedpref
gcmafterregistration();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
} catch (Exception e) {
e.printStackTrace();
}
progress.setVisibility(View.INVISIBLE);
}
}
And this is my logcat so you can batter understand.
I have put one dummy code change your code by referring this.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (commonUtils.isNetworkAvailable(mContext)) {
NewHistoryAsync task = new NewHistoryAsync(getContext(), listDataHeader, listDataChild);
task.execute(CommonUtils._History + "ID=" + userUhid);
} else {
Toast.makeText(mContext, "No Network Available!!",
Toast.LENGTH_LONG).show();
}
private class NewHistoryAsync extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
Context mContext;
List listDataHeader;
HashMap listDataChild;
public NewHistoryAsync(Context context, List listDataHeaderList, HashMap listDataChildMap) {
mContext = context;
listDataHeader = listDataHeaderList;
listDataChild = listDataChildMap;
this.listDataHeader = new ArrayList<String>();
this.listDataChild = new HashMap<String, List<String>>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog = ProgressDialog.show(mContext, Html.fromHtml(
"<b>Heading<b>"), Html.fromHtml("<medium>Downloading Details..</medium>"), true);
// progressDialog.setTitle("Downloading Details");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String resResult = NewHistoryService(params[0]);
JSONObject jsonResponse;
try {
//JSONObject jsonObject = new JSONObject(resResult);
JSONArray jsonArray = new JSONArray(resResult);
// Log.i("doinb---> ", resResult);
/* ArrayList<ClaimsHistoryNewSearchModel> listDataHeader=new ArrayList<ClaimsHistoryNewSearchModel>();*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
List<String> historyResult = new ArrayList<String>();
historyResult.add((jsonObject.get("AdmissionDate").toString()));
historyResult.add((jsonObject.get("DischargeDate").toString()));
//AdmissionDate= exact name to ur json response from server
listDataHeader.add(KeyString);
listDataChild.put(KeyString, historyResult);
}
} catch (Exception e) {
e.printStackTrace();
}
return resResult;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String result) {
if (progressDialog != null && progressDialog.isShowing() == true) {
progressDialog.dismiss();
if (result.equals("[]")) {
Toast.makeText(mContext, "No Details found!!",
Toast.LENGTH_LONG).show();
} else
// Log.i("Result:", result);
// Log.i("listDataHeader:", listDataHeader.toString());
// Log.i("listDataChild:", listDataChild.toString());
listAdapter = new ClaimHistoryNewAdapter(getActivity(), listDataHeader, listDataChild);
if (listDataHeader != null && listDataHeader.size() > 0 && listDataChild != null && listDataHeader.size() > 0) {
expListView.setAdapter(listAdapter);
} else {
// setting list adapter
tClaimHistory.setVisibility(View.VISIBLE);
}
}
}
public String NewHistoryService(String serviceUrl) {
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
//ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
//response.append("Error");
}
Log.v("Response:", response.toString());
return response.toString();
}
}
}
Use this JsonParser class
Hope it will help you
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONParser {
public JSONParser() {
}
public String makeServiceCall(String serviceUrl) {
Boolean registered = false;
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
registered = true;
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
/* ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
response.append("Error");*/
}
Log.v("Response:", response.toString());
return response.toString();
}
}
setConnectionTimeout(Your Time);

Categories

Resources