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();
}
}
Related
When I run the following code It does not display data.It shows the following error message:
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Response from url: <html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Json parsing error: Value jsonStr of type java.lang.String cannot be converted to JSONObject
2019-11-16 14:40:19.164 17562-17589/com.example.jsonparsing I/OpenGLRenderer: Initialized EGL, version 1.4
2019-11-16 14:40:19.172 17562-17589/com.example.jsonparsing W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayAdapter adapter;
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
adapter = new ArrayAdapter(getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
class getContacts extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "JSON Data is" +
" downloading", Toast.LENGTH_LONG).show();
}
#Override
protected List<HashMap<String, String>> doInBackground(Void... Void) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject("jsonStr");
List<HashMap<String, String>> contactList = new ArrayList<>();
JSONArray contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
return contactList;
} 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(List<HashMap<String, String>> result) {
super.onPostExecute(result);
if (result != null) {
adapter.add(result);
adapter.notifyDataSetChanged();
}
}
}
}
HttpHandler:
class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
HttpHandler() {
}
String makeServiceCall(String reqUrl){
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
}catch (MalformedURLException e){
Log.e(TAG,"MalformException: " + e.getMessage());
}catch (ProtocolException e){
Log.e(TAG,"ProtocolException: " + e.getMessage());
}catch (IOException e){
Log.e(TAG, "IOException: " + 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");
}
is.close();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
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
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);
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.....
I am trying to read phone contacts and send that list to my server, but getting FileNotFound error in some phones but programme is working properly in some phones. following is my class -
public class UpdateNetwork extends Activity {
private String server, server_response;
private String updatenetwork = "/update-network.php";
private String data_to_send;
public JSONArray jacontacts;
public JSONObject jcontacts;
public ArrayList<String> contacts;
private ProgressDialog pd;
private Long user_id;
private MainActivity main;
JSONObject jo = null;
Button update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatenetwork);
server = getString(R.string.server_add_new);
contacts = new ArrayList<String>();
main = new MainActivity();
update = (Button) findViewById(R.id.update);
update.setVisibility(View.INVISIBLE);
user_id = main.getDefaultsint("user_id", UpdateNetwork.this);
Updatenetwork un = new Updatenetwork(true);
un.execute();
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
URL url = null;
try {
url = new URL(server + updatenetwork);
data_to_send = "contacts=" + jcontacts + "&";
data_to_send += "user_id=" + user_id;
Updatenetwork un = new Updatenetwork(url, data_to_send);
un.execute();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class Updatenetwork extends AsyncTask<String, Integer, JSONObject> {
private URL url;
Boolean un_send = false;
String data_to_send;
public Updatenetwork(Boolean b) {
this.un_send = b;
}
public Updatenetwork(URL url, String data_to_send2) {
this.url = url;
this.data_to_send = data_to_send2;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (un_send) {
update.setVisibility(View.VISIBLE);
} else {
finish();
}
pd.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(UpdateNetwork.this, "Please wait...", "Sending...");
}
#Override
protected JSONObject doInBackground(String... params) {
Log.e("value of un_send", "********"+un_send+jcontacts);
if(un_send){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
/* System.out.println("name : " + name );
*/
// get <span id="IL_AD4" class="IL_AD">the phone number</span>
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(phone);
jacontacts = new JSONArray();
/* System.out.println("phone" + phone);*/
}
for(int i=0; i<contacts.size(); i++){
jacontacts.put(contacts.get(i));
}
jcontacts = new JSONObject();
try{
jcontacts.put("contacts", jacontacts);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Log.e("value inside", "json obj"+jcontacts);*/
pCur.close();
jo = jcontacts;
}
}
}
} else {
BufferedReader reader=null;
try
{
Log.e("inside try block ", "get text 11111111" + data_to_send);
URLConnection conn = url.openConnection();
Log.e("inside try block ", "get text 2222222" + data_to_send);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
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 + "\n");
Log.e("inside ", "while loop");
}
server_response = sb.toString();
Log.e("server_response ", "server_response" +server_response);
}
catch(FileNotFoundException(String detailMessage))
{
Log.e("MyTag ", "Failure to get json data in --1--", ex);
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {
Log.e("MyTag", "Failure to get json data in ", ex);
}
}
try {
jo = new JSONObject(server_response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jo;
}
}
}
following is what i got in errorlog
12-18 16:44:21.922: E/MyTag(32005): Failure to get json data in --1--
12-18 16:44:21.922: E/MyTag(32005): java.io.FileNotFoundException: http:// server address/update-network.php
12-18 16:44:21.922: E/MyTag(32005): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:194)