No JSON output? - java

I am writing a currency exchange android app however when the app is run I do not seem to get a response from the API.
API LINK 1) https://restcountries.eu/rest/v2/all
API LINK 2) http://api.fixer.io/latest
MainActivity Code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
import static java.lang.reflect.Modifier.FINAL;
public class MainActivity extends AppCompatActivity {
//Fill spinner with values from this URL - https://restcountries.eu/rest/v2/all
final String CURRENCY_DATA = "https://restcountries.eu/rest/v2/all";
ArrayList<String> currency_list = new ArrayList();
Button btn;
//The amount entered x's by the curreny exchange rate..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new downloadData().execute();
new downloadExchangeRate().execute();
}
});
}
public class downloadData extends AsyncTask<String, Void, String> {
String result = "";
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(CURRENCY_DATA);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("currencies");
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).optString("code"));
Log.d("list", currency_list.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
}
downloadExchangeRate.java code:
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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 downloadExchangeRate extends AsyncTask<String,Void,String> {
String result = "";
#Override
protected String doInBackground(String... strings) {
final String EXCHANGE_RATE = "http://api.fixer.io/latest";
try {
URL url = new URL(EXCHANGE_RATE);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
for (int i = 0; i<jsonObject.length(); i++){
ArrayList<String> rates = new ArrayList<>();
rates.add(jsonObject.optString("rates"));
Log.d("list", rates.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
Any help is appreciated, I think I am calling the JSON wrong.

Update Code as:
Use StringBuilder for result (Why? See this https://stackoverflow.com/a/14927864/5227589):
StringBuilder result=new StringBuilder();
...
......
result.append(current);
When using String it will take very long time to complete while loop due to use of result += current;: .
When using StringBuilder:
In onPostExecute
JSONArray jsonArray = new JSONArray(result.toString());
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).getJSONArray("currencies").getJSONObject(0).optString("code"));
//Log.d("list", currency_list.toString());
}
Full Code:
public class downloadData extends AsyncTask<String, Void, String> {
StringBuilder result=new StringBuilder();
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(CURRENCY_DATA);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
char current = (char) data;
Log.i("data",current+"");
while (data != -1) {
current = (char) data;
result.append(current);
data = inputStreamReader.read();
// Log.i("data",current+"");
}
//Log.i("data",result+"");
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray jsonArray = new JSONArray(result.toString());
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).getJSONArray("currencies").getJSONObject(0).optString("code"));
//Log.d("list", currency_list.toString());
}
Log.d("list", currency_list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}

Related

Pass global variable to php file through AsyncTask in Android Studio

I am currently populating a RrecyclerView from a remote database but wish to only query the database for dates based on a users ID. I have the userID assigned as a global variable on the LoginActivty of the app but I'm not sure where to pass that information to the php page from my DateActivity.
My Code for the DateActivity is as follows:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
import java.util.List;
public class DateActivity extends AppCompatActivity {
public static String globex_num;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVDateList;
private AdapterDate mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
//Make call to AsyncTask
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(DateActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("thephpfile.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataDate> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jsonArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jsonArray.length();i++){
JSONObject json_data = jsonArray.getJSONObject(i);
DataDate dateData = new DataDate();
dateData.date= json_data.getString("date");
data.add(dateData);
}
// Setup and Handover data to recyclerview
mRVDateList = (RecyclerView)findViewById(R.id.dateList);
mAdapter = new AdapterDate(DateActivity.this, data);
mRVDateList.setAdapter(mAdapter);
mRVDateList.setLayoutManager(new LinearLayoutManager(DateActivity.this));
} catch (JSONException e) {
Toast.makeText(DateActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
I solved the problem by passing it though the link.
url = new URL(www.thephpfile.php?userID=" + LoginActivity.userID);
At the start of the php file I did the following:
$userID = $_GET['userID'];

AsyncTask add to class ArrayList

I am trying to write an AsyncTask that will use the Google Places API to get nearby locations. The actual functionality is working correctly, however, when my task finishes the class variables locationNames and locationIDs aren't written to. I've tried the behavior in my code as both progress updates and as a post execute and neither work. How do I add Strings to my ArrayLists in MainActivity from the AsyncTask?
package billy.cs436.googleplaces;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Location;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.net.URLConnection;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String searchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
private HttpURLConnection urlConnection = null;
Location mLocation;
ArrayList<String> locationNames;
ArrayList<String> locationIDs;
ArrayList<String> locationAddresses;
ArrayList<String> locInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double latitude, longitude;
locationNames = new ArrayList<String>();
locationIDs = new ArrayList<String>();
locationAddresses = new ArrayList<String>();
locInfo = new ArrayList<String>();
// location
mLocation = new Location("");
// sample coordinates
latitude = 38.989697;
longitude = -76.937760;
mLocation.setLatitude(latitude);
mLocation.setLongitude(longitude);
// ASSEMBLE URL
searchURL += "location=" + latitude + "," + longitude + "&";
// radius
searchURL += "radius=100&";
// api key
searchURL += "key=" + getString(R.string.api_key);
// Fill locationNames and locationIDs
new findLocationsNearMe().execute(mLocation);
// NOW USE PLACE IDS TO REQUEST SPECIFIC INFO TO GET FULL ADDRESS
// new getAddresses().execute(locationIDs);
printInfo();
}
public class findLocationsNearMe extends AsyncTask<Location,String[],Void> {
#Override
protected Void doInBackground(Location... locations) {
JSONObject json = getJSON();
try {
JSONArray locationParser = json.getJSONArray("results");
for (int i = 1; i < locationParser.length(); i++) {
JSONObject locationInfo = locationParser.getJSONObject(i);
String[] loc = new String[2];
loc[0] = String.valueOf(locationInfo.get("name"));
loc[1] = String.valueOf(locationInfo.get("place_id"));
publishProgress(loc);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String[]... value) {
String name = String.valueOf(value[0][0]);
String id = String.valueOf(value[0][1]);
Log.d("PROGRESS UPDATE: ", name + " " + id);
locationNames.add(name);
locationIDs.add(id);
}
protected JSONObject getJSON() {
String JSONresult;
try {
// make request
URL url = new URL(searchURL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder builder = new StringBuilder();
if (inputStream == null) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
if (builder.length() == 0) {
return null;
}
// return json object
reader.close();
JSONresult = builder.toString();
return new JSONObject(JSONresult);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON PROBLEM", "return new object failed!");
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return null;
}
}
public void printInfo() {
System.out.println("LocationNames: " + locationNames);
System.out.println("LocationIDs: " + locationIDs);;
}
}
The log shows the correct values for Names and IDs from the ProgressUpdate, but printInfo prints LocationNames: [] and LocationIDs: []
EDIT 1:
Per the suggestion in the comments from #GhostCat, I implemented a NearbyLocation class and I also finished up my method to get addresses. Here is the full code. (I'm not sure if the correct procedure here is to replace my old code or post in this EDIT 1 format. If I should just delete the older code above to shorten this post let me know.)
package billy.cs436.googleplaces;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Location;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.net.URLConnection;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
String searchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?";
private HttpURLConnection urlConnection = null;
Location mLocation;
ArrayList<NearbyLocation> nearbyLocations;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double latitude, longitude;
nearbyLocations = new ArrayList<>();
mLocation = new Location("");
// sample coordinates
latitude = 38.989697;
longitude = -76.937760;
mLocation.setLatitude(latitude);
mLocation.setLongitude(longitude);
// ASSEMBLE URL
searchURL += "location=" + latitude + "," + longitude + "&";
// radius
searchURL += "radius=100&";
// api key
searchURL += "key=" + getString(R.string.api_key);
// Fill locationNames and locationIDs
new findLocationsNearMe().execute(mLocation);
//NOW USE PLACE IDS TO REQUEST SPECIFIC INFO TO GET FULL ADDRESS
new getAddresses().execute();
printInfo();
}
public class findLocationsNearMe extends AsyncTask<Location,NearbyLocation,Void> {
#Override
protected Void doInBackground(Location... locations) {
JSONObject json = getJSON();
try {
JSONArray locationParser = json.getJSONArray("results");
for (int i = 1; i < locationParser.length(); i++) {
JSONObject locationInfo = locationParser.getJSONObject(i);
NearbyLocation loc = new NearbyLocation(String.valueOf(locationInfo.get("name")),
String.valueOf(locationInfo.get("place_id")), null);
publishProgress(loc);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(NearbyLocation... value) {
String name = value[0].getName();
String id = value[0].getId();
Log.d("PROGRESS UPDATE: ", name + " " + id);
nearbyLocations.add(value[0]);
}
protected JSONObject getJSON() {
String JSONresult;
try {
// make request
URL url = new URL(searchURL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder builder = new StringBuilder();
if (inputStream == null) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
if (builder.length() == 0) {
return null;
}
// return json object
reader.close();
JSONresult = builder.toString();
return new JSONObject(JSONresult);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON PROBLEM", "return new object failed!");
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return null;
}
}
public class getAddresses extends AsyncTask<Void, Void, Void> {
String detail = "https://maps.googleapis.com/maps/api/place/details/json?";
#Override
protected Void doInBackground(Void... voids) {
for(NearbyLocation loc : nearbyLocations) {
String detailURL = detail + "placeid=" + loc.getId() + "&key=" + getString(R.string.api_key);
JSONObject json = getJSON(detailURL);
JSONObject locationParser = null;
try {
locationParser = json.getJSONObject("result");
loc.setAddress(locationParser.get("formatted_address").toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
public JSONObject getJSON(String detailURL) {
String JSONresult;
try {
// make request
URL url = new URL(detailURL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder builder = new StringBuilder();
if (inputStream == null) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
if (builder.length() == 0) {
return null;
}
// return json object
reader.close();
JSONresult = builder.toString();
return new JSONObject(JSONresult);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
Log.d("JSON PROBLEM", "return new object failed!");
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return null;
}
}
public void printInfo() {
System.out.println("size... " + nearbyLocations.size());
for(NearbyLocation loc : nearbyLocations) {
System.out.println("LOCATION: " + loc.getName() + " " + loc.getAddress());
}
}
public class NearbyLocation {
String name;
String address;
String id;
public NearbyLocation(String name, String id, String address) {
this.name = name;
this.address = address;
this.id = id;
}
public void setName(String n) {
name = n;
}
public void setAddress(String a) {
address = a;
}
public void setId(String i) {
id = i;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getId() {
return id;
}
}
}

How do I ensure that my list view element do not disappear when I change the orientation of my device?

I am building an app that displays details of a book you have searched. The problem is that every time I change the orientation of my device the list view elements disappear. I want help in how to make them not disappear. I have a feeling that I need to use a Loader but I have no idea in how to implement it. Here are my activities.
MainActivity :-
package com.example.visha.booklistingapp;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BookAdapter mAdapter;
EditText searchtext;
ListView earthquakeListView;
TextView empty;
TextView authorcheck;
TextView titlecheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
earthquakeListView = (ListView) findViewById(R.id.listView);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
earthquakeListView.setAdapter(mAdapter);
searchtext = (EditText) findViewById(R.id.editText);
empty = (TextView) findViewById(R.id.textView);
earthquakeListView.setEmptyView(empty);
}
public void searchclick(View view) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
String parturl = searchtext.getText().toString();
parturl = parturl.replaceAll("\\s","");
StringBuilder urlbuilder = new StringBuilder();
urlbuilder.append(" https://www.googleapis.com/books/v1/volumes?q=");
urlbuilder.append(parturl);
urlbuilder.append("&maxResults=5");
String url = urlbuilder.toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(url); }
else{
Toast.makeText(getApplicationContext(), "You are not connected to the internet",
Toast.LENGTH_LONG).show();
}
}
private class BookAsyncTask extends AsyncTask<String, Void, List<Book>> {
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
QueryUtils :-
package com.example.visha.booklistingapp;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by visha on 14-10-2016.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Book> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Book> Books = extractFeatureFromJson(jsonResponse);
return Books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Book JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Book> extractFeatureFromJson(String BookJSON) {
if (TextUtils.isEmpty(BookJSON)) {
return null;
}
List<Book> Books = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(BookJSON);
JSONArray BookArray = baseJsonResponse.getJSONArray("items");
for (int i = 0; i < BookArray.length(); i++) {
JSONObject currentBook = BookArray.getJSONObject(i);
JSONObject properties = currentBook.getJSONObject("volumeInfo");
String author;
if(properties.has("authors")) {
author = properties.getString("authors");
}
else {
author = "";
}
String title = properties.getString("title");
Book Book = new Book(author, title);
Books.add(Book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the Book JSON results", e);
}
return Books;
}
}
You need to override onSaveInstanceState and onRestoreInstanceState methods of Activity Class.
In onSaveInstanceState, save the list data into the Bundle.
In onRestoreInstanceState, restore the list with the Bundle data and re-create the list adapter.
Cheers!!!
if you do not have a different layout for the activity landscape mode then simply putting android:configChanges="orientation|screenLayout|screenSize" will do the job for you.
Example:
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenLayout|screenSize" />
and if you do have different layout for landscape mode the you need to override the savedInstanceState and save and restore the list accordingly in OnCreate

Android - get distance using google maps api and json

I could retreive data from web with this code:
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View v){
new GetMethodDemo().execute("https://maps.googleapis.com/maps/api/directions/json?origin=Breclav&destination=Brno&sensor=false&units=metric&mode=driving");
}
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
} }
I am able to see in debug that I received data like in this link, but I found that I should use code below for selecting only distance from the data I received. Dont know how to combinate these codes together.. I would like to have in textView how far is the distance between two cities from url.
final JSONObject json = new JSONObject(response);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONArray newTempARr = routes.getJSONArray("legs");
JSONObject newDisTimeOb = newTempARr.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
JSONObject timeOb = newDisTimeOb.getJSONObject("duration");
Log.i("Diatance :", distOb.getString("text"));
Log.i("Time :", timeOb.getString("text"));
I am not the author of these codes... Thank You

Can't Convert to JSONArray for showing in ListView

i'm try to convert json array from internet to listview. the php code in server work correctly and return the json string below.
the result json in logcat is :
11-09 20:47:04.170: I/AllNotes >> jSon >>(429): {"notes":{"3":{"note_subject":"dshjdsfjsdfsdhf","note_id":"4","note_date":"0000-00-00"},"2":{"note_subject":"dshjdsfjsdfsdhf","note_id":"3","note_date":"0000-00-00"},"1":{"note_subject":"dshjdsfjsdfsdhf","note_id":"2","note_date":"0000-00-00"},"0":{"note_subject":"dshjdsfjsdfsdhf","note_id":"1","note_date":"0000-00-00"},"7":{"note_subject":"dshjdsfjsdfsdhf","note_id":"8","note_date":"1391\/8\/19"},"6":{"note_subject":"dshjdsfjsdfsdhf","note_id":"7","note_date":""},"5":{"note_subject":"dshjdsfjsdfsdhf","note_id":"6","note_date":""},"4":{"note_subject":"dshjdsfjsdfsdhf","note_id":"5","note_date":""}},
"success":"1"}
my JSONParser class is :
package ir.mohammadi.android.nightly;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Make HTTP connection
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
Log.i("Input stream >> ", is.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
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();
Log.i("JSON string builder >> ", json.toString());
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json.substring(1, json.length()));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
error is : at notes of type org.json.JSONObject cannot be converted to JSONArray
the code that show json in list view is :
package ir.mohammadi.android.nightly;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AllNotes extends ListActivity {
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> noteList;
JSONArray notes = null;
JSONObject jSon = null;
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR_MSG = "error_message";
private static String KEY_NOTE_ID = "note_id";
private static String KEY_NOTE_SUBJECT = "note_subject";
private static String KEY_NOTE_DATE = "note_date";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_list);
noteList = new ArrayList<HashMap<String, String>>();
new LoadAllNotes().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String note_id = ((TextView) view
.findViewById(R.id.list_lbl_id)).getText().toString();
Intent i = new Intent(getApplicationContext(), NoteDetail.class);
i.putExtra("note_id", note_id);
startActivityForResult(i, 100);
}
});
}
public class LoadAllNotes extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllNotes.this);
pDialog.setMessage("لطفا صبر کنید...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
UserFunctions userFunctions = new UserFunctions();
jSon = userFunctions.getAllNotes("12");
Log.i("AllNotes >> jSon >>", jSon.toString());
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
try {
if (jSon.has(KEY_SUCCESS)) {
String success = jSon.getString(KEY_SUCCESS);
if (success.equals("1")) {
notes = jSon.getJSONArray("notes");
for (int i = 0; i < notes.length(); i++) {
JSONObject c = notes.getJSONObject(i);
String id = c.getString(KEY_NOTE_ID);
String subject = c.getString(KEY_NOTE_SUBJECT);
String date = c.getString(KEY_NOTE_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NOTE_ID, id);
map.put(KEY_NOTE_SUBJECT, subject);
map.put(KEY_NOTE_DATE, date);
noteList.add(map);
}
}
} else {
finish();
Toast.makeText(getApplicationContext(),
jSon.getString(KEY_ERROR_MSG), Toast.LENGTH_SHORT)
.show();
Log.i("AllNotes >> No nightly >>", "...");
Intent i = new Intent(getApplicationContext(), login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(AllNotes.this,
noteList, R.layout.list_item, new String[] {
KEY_NOTE_ID, KEY_NOTE_SUBJECT,
KEY_NOTE_DATE }, new int[] {
R.id.list_lbl_id, R.id.list_lbl_subject,
R.id.list_lbl_date });
setListAdapter(adapter);
}
});
}
}
}
and the php code is :
public function getNotesList($user_id)
{
$result = mysql_query("SELECT `id`, `note_subject`, `note_date` FROM `tbl_notes` WHERE `user_id` = '$user_id'");
if (mysql_num_rows($result) > 0) {
$response = array();
$response["success"] = "1";
$response["notes"] = array();
while ($row = mysql_fetch_array($result)) {
$note = array();
$note["note_id"] = $row["id"];
$note["note_subject"] = $row["note_subject"];
$note["note_date"] = $row["note_date"];
array_push($response["notes"], $note);
}
return $response;
}
}
and
if ($tag == 'getNotesList') {
$user_id = $_POST['user_id'];
$result = $db->getNotesList($user_id);
if ($result) {
error_log("Index getNotesList Json >>" . json_encode($result) . "\r\n", 3,
"Log.log");
echo json_encode($result, JSON_FORCE_OBJECT);
} else {
$response["error"] = "1";
$response["error_message"] = "no row";
echo json_encode($response, JSON_FORCE_OBJECT);
}
}
how can i fix this? thanks.
use
JSONObject notes = jSon.getJSONObject("notes");
instead of
JSONArray notes = jSon.getJSONArray("notes");`
Because your json String is collection of JsonOject's it's not contains any JsonArray.
you can use following json checker site before parsing it to known the structure of Json String
http://jsonviewer.stack.hu/

Categories