Google Maps API and custom polyline route between Markers - java

I'd like to make a custom route for an android app, I'm not sure which API should I use and if it is compatible with Java.
As far as I know I need to use waypoints to make a route (I don't need to know the distance between the two points, just to make a route).
The objective is to choose an option from a menu on the side of the map and show one of the custom routes between two Markers.

You can do this using the Google Maps API v2 for Android, and the Google Maps Directions webservice API
For getting started with the Google Maps API, there are plenty of other good answers already. See here for a complete working example of a simple map Activity. Note that you'll also need to get an API key set up to work with your project.
As for using the Google Maps Directions webservice API, you should first read the documentation. You can use an API key and enable the API in your developer console, but it still works currently without using an API key.
Here is the basic code you'll need in order to use the Google Maps API to draw a Polyline between two points, note that the points returned from the API are encoded in a base 64 encoded String that needs to be decoded.
First, ensure that your project includes the Google Maps Utility library, which will be used to decode the base64 encoded polyline:
dependencies {
compile 'com.google.maps.android:android-maps-utils:0.5+'
//.......
}
Here is the AsyncTask, that you should give two LatLng points to when calling it.
You would call the AsyncTask with two LatLng objects, for example between two Markers:
new GetDirectionsAsync().execute(markerOne.getPosition(), markerTwo.getPosition());
Here is the AsyncTask code:
class GetDirectionsAsync extends AsyncTask<LatLng, Void, List<LatLng>> {
JSONParser jsonParser;
String DIRECTIONS_URL = "https://maps.googleapis.com/maps/api/directions/json";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<LatLng> doInBackground(LatLng... params) {
LatLng start = params[0];
LatLng end = params[1];
HashMap<String, String> points = new HashMap<>();
points.put("origin", start.latitude + "," + start.longitude);
points.put("destination", end.latitude + "," + end.longitude);
jsonParser = new JSONParser();
JSONObject obj = jsonParser.makeHttpRequest(DIRECTIONS_URL, "GET", points, true);
if (obj == null) return null;
try {
List<LatLng> list = null;
JSONArray routeArray = obj.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
list = PolyUtil.decode(encodedString);
return list;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<LatLng> pointsList) {
if (pointsList == null) return;
if (line != null){
line.remove();
}
PolylineOptions options = new PolylineOptions().width(5).color(Color.MAGENTA).geodesic(true);
for (int i = 0; i < pointsList.size(); i++) {
LatLng point = pointsList.get(i);
options.add(point);
}
line = mMap.addPolyline(options);
}
}
The AsyncTask references some member variables of the Activity, namely the Polyline and the GoogleMap, the Activity definition would look like this:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback{
GoogleMap mMap;
Polyline line;
//.....
Here's the JSONParser class used in this example, note that this is a modified version updated for android-23 that I wrote a blog post about:
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params, boolean encode) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
if (encode) {
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
}
else{
sbParams.append(key).append("=")
.append(params.get(key));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
Log.d("JSONParser", "full GET url: " + url);
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
Result of drawing a route between two Markers:

Related

Async Task to Save data in SQL server in Android

I am trying to save edit box data in SQL server by using android app. I am trying to use async task to save data.I already developed web service and host in the IIS which is running fine. So i Need now code in android to save data.
This is my Aysnc Task
class SaveScan extends AsyncTask<String,Void, String>{
String status = null;
protected void onPreExecute(){
}
protected String doInBackground(String... connUrl){
HttpURLConnection conn = null;
BufferedReader reader;
try{
final URL url = new URL(connUrl[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setChunkedStreamingMode(0);
conn.addRequestProperty("Content-Type","application/json: charset=utf-8");
conn.setRequestMethod("POST");;
JSONObject jsonObject = new JSONObject();
jsonObject.put("scans",Scan1);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(jsonObject.toString().getBytes());
out.close();
int result = conn.getResponseCode();
if (result == 200) {
InputStream in = new BufferedInputStream(conn.getInputStream());
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while((line =reader.readLine()) != null){
status = line;
}
}
}catch(Exception ex){
}
return status;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result != null){
Toast.makeText(MainActivity.this,"Scan Saved ",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Not Saved",Toast.LENGTH_LONG).show();
}
}
}
This is Mine Button Call
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.CAMERA},
100);
Intent intent = new Intent(MainActivity.this, Scan.class);
startActivity(intent);
}
});
private void onSaveClicked() {
new SaveScan(url).execute();
}
private class SaveScan extends AsyncTask<String,Void, String>{
String status = null;
protected String doInBackground(String... connUrl){
try {
// This is getting the url from the string we passed in
URL url = new URL(connUrl[0]);
// Create the urlConnection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
// OPTIONAL - Sets an authorization header
urlConnection.setRequestProperty("Authorization", "someAuthString");
JSONObject jsonObject = new JSONObject();
jsonObject.put("scans","someString");
// Send the post body
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(jsonObject.toString());
writer.flush();
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertInputStreamToString(inputStream);
status=response ;
// From here you can convert the string to JSON with whatever JSON parser you like to use
} else {
// Status code is not 200
// Do something to handle the error
status=null;
}
} catch (Exception e) {
Log.d("SaveScan", e.getMessage());
}
return status;
}
private String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
try {
while((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result != null){
Toast.makeText(MainActivity.this,"Scan Saved ",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Not Saved",Toast.LENGTH_LONG).show();
}
}
}
You can choose between different storage frameworks such as Room, SQLite or Preferences depending on your data. Room and SQLite are relational databases, where SQLite requires developers to create tables and map relationships, Room takes care of those with the help of annotation processing. Preferences are android's storage framework where you can store minimal amount of data for example settings for your app, map app's flow and vital data such as user information. In the end, it all depends on the time you can spend and the data that you are trying to save. I suggest you go through all these frameworks and identify what's best for you.

SharedPreferences not getting saved

So I have been trying to figure out a way to save the Access Token I get from my API. I can successfully get the JSON response from my API and store it in my result variable within my doInBackground.
However, for some reason it is not getting saved in SharedPreferences in my onPostExecute.
The result variable contains this JSON string {"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}, which I received from my API.
I have an algorithm that is supposed to save only the access_token for now.
My code is below:
WSAdapter.java
public class WSAdapter {
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
static String MyPREFERENCES = "API Authentication";
String accessToken = "Access Token";
private WeakReference<Context> mLoginReference;
// constructor
public SendAPIRequests(Context context){
mLoginReference = new WeakReference<>(context);
}
#Override
protected String doInBackground(String... params) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
//String data = "";
StringBuilder result = new StringBuilder();
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[2]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept","application/json");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// Tells the URL that I want to read the response data
httpURLConnection.setDoInput(true);
// JSON object for the REST API
JSONObject jsonParam = new JSONObject();
jsonParam.put("client_id", "mYIHBd321Et3sgn7DqB8urnyrMDwzDeIJxd8eCCE");
jsonParam.put("client_secret", "qkFYdlvikU4kfhSMBoLNsGleS2HNVHcPqaspCDR0Wdrdex5dHyiFHPXctedNjugnoTq8Ayx7D3v1C1pHeqyPh1BjRlBTQiJYSuH6pi9EVeuyjovxacauGVeGdsBOkHI3");
jsonParam.put("username", params[0]);
jsonParam.put("password", params[1]);
jsonParam.put("grant_type", "password");
Log.i("JSON", jsonParam.toString());
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes(jsonParam.toString());
// Flushes the jsonParam to the output stream
wr.flush();
wr.close();
// // Representing the input stream
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// reading the input stream / response from the url
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", result.toString());
return result.toString();
}
#Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// retrieves the context passed
Context context = mLoginReference.get();
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// edits shared preferences for authentication and authorization
PrefEditor = ShPreference.edit();
// to save the Access Token from the API
try {
JSONObject pJObject = new JSONObject(result);
PrefEditor.putString(accessToken, pJObject.getString("access_token"));
PrefEditor.apply();
// algorithm for parsing the JSONArray from the Django REST API
/*for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
PrefEditor.putString(accessToken, pJObj_data.getString("access_token"));
PrefEditor.apply();
}*/
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
This code below includes the code that reads the SharedPreferences. Which should be in the doInBackground of this AsyncTask as I need to put the access_token to the header.
This is supposed to be in the same class.
public class SendPostsRequest extends AsyncTask<String, String, String> {
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
// gets the activity context
private WeakReference<Context> mPostReference;
// to be able to access activity resources
Activity activity;
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
String accessToken = "Access Token";
// constructor
public SendPostsRequest(Context context, Activity activity){
mPostReference = new WeakReference<>(context);
this.activity = activity;
}
#Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
// retrieves the context passed
Context context = mPostReference.get();
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String APIAuthentication = "Bearer " + ShPreference.getString(accessToken, "");
try {
// Sets up connection to the URL (params[0] from .execute in "login")
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", APIAuthentication);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// gets the JSON files stored in the posts details class from Posts Activity
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// retrieves the context passed
Context context = mPostReference.get();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
// checks if context is not null before updating posts page
if (context != null){
postsSect = (TextView) activity.findViewById(R.id.PostsSection);
int lastFrJSONArray = postsHelper.getPostID().size() - 1;
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + postsHelper.getPostID().get(lastFrJSONArray - 2) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + postsHelper.getPostTitle().get(i) + "\n");
postsSect.append("content: " + postsHelper.getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + postsHelper.getPostID().get(i) + "\n");
}
}
}
}
}
UPDATE:
I have edited my JSON parsing algorithm.
Instead of parsing my JSON object from result as an array, this code here now parses it as an object. The JSONarray algorithm should be commented out.
The response you get from your webservice is actually not a JSONArray, but just a simple JSONObject. Hence change this line:
JSONArray pJObjArray = new JSONArray(result);
to
JSONObject pJObjArray = new JSONObject(result);
If You are not getting token just follow this code. it may help you.
//member variable
SharedPreferences ShPreference;
SharedPreferences.Editor PrefEditor;
String ApiToken;
OnCreate(){
ShPreference = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
ApiToken = ShPreference.getString(accessToken, "");
// call wherever you want
new SendPostsRequest(ApiToken).execute()
}
public class SendPostsRequest extends AsyncTask<String, String, String> {
private String APIToken;
TextView postsSect;
// Add a pre-execute thing
HttpURLConnection urlConnection;
// gets the activity context
// constructor
public SendPostsRequest(String APIToken){
this.APIToken = APIToken;
}
#Override
protected String doInBackground(String... params) {
StringBuilder result = new StringBuilder();
// retrieves the context passed
Context context = mPostReference.get();
String APIAuthentication = APIToken; // or you can direct pass
try {
// Sets up connection to the URL (params[0] from .execute in "login")
urlConnection = (HttpURLConnection) new URL(params[0]).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty ("Authorization", APIAuthentication);
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
// gets the JSON files stored in the posts details class from Posts Activity
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// retrieves the context passed
Context context = mPostReference.get();
// For posts
try {
JSONArray pJObjArray = new JSONArray(result);
// algorithm for parsing the JSONArray from the Django REST API
for (int i = 0; i < pJObjArray.length(); i++) {
// puts the current iterated JSON object from the array to another temporary object
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
// inputs necesarry elements to the ListPosts function
postsHelper.setPost(pJObj_data.getInt("id"), pJObj_data.getString("post_title"), pJObj_data.getString("post_content"));
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
// checks if context is not null before updating posts page
if (context != null){
postsSect = (TextView) activity.findViewById(R.id.PostsSection);
int lastFrJSONArray = postsHelper.getPostID().size() - 1;
// outputs the id of the very first post, something to put to the textview
postsSect.setText("id: " + postsHelper.getPostID().get(lastFrJSONArray - 2) + "\n");
for (int i = lastFrJSONArray; i >= 0; i--)
{
// appending the titles and contents of the current post
postsSect.append("title: " + postsHelper.getPostTitle().get(i) + "\n");
postsSect.append("content: " + postsHelper.getPostContent().get(i) + "\n");
// if this is the last post, then don't need to append id for the next post.
if (i != 0) {
postsSect.append("id: " + postsHelper.getPostID().get(i) + "\n");
}
}
}
}
}

Getting Response code as 400 from geo location api

I am trying to use geo location api to get lattitude and longitude of the location. So for this I created a project on developer console and created an api key. I used this api key with this api https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY
So this when I executed the request in postman it works well.
But when I tried to execute same request in an app its giving response as response code 400.
Response code 400 as per developer guide
https://developers.google.com/maps/documentation/geolocation/intro#errors
shows it comes when the api key is wrong. But how the key works in postman and not in the app?
Here is the code for server request:
public JSONObject sendPostRequest1(String data) {
try {
URL url = new URL(api);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
// con.setRequestProperty("content-type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
try {
writer.write(data);
} catch (Exception e) {
Log.e("Exception111", e.toString());
}
writer.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
Log.d("ServerResponse", new String(sb));
String output = new String(sb);
return new JSONObject(output);
} else {
Log.e("Exception", "" + responseCode);
}
}
catch (JSONException je)
{
je.printStackTrace();
return Excpetion2JSON.getJSON(je);
}
catch(IOException e)
{
}
return null;
}
Async Task :
public class GetLocationAsyncTask extends AsyncTask<String, Void, JSONObject> {
String api;
JSONObject jsonParams;
Context mContext;
private ProgressDialog loadingDialog;
private String number,code;
public GetLocationsCallBack getLocationsCallBack;
public GetLocationAsyncTask(Context context,GetLocationsCallBack getLocationsCallBack) {
this.mContext = context;
this.getLocationsCallBack = getLocationsCallBack;
}
public interface GetLocationsCallBack {
void doPostExecute(ArrayList<Location> list);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
try {
api = "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCArRAX4oHdfFWrTWhXrOVBQtbs";
jsonParams = new JSONObject();
jsonParams.put("cellId", params[0]);
jsonParams.put("locationAreaCode",params[1]);
ServerRequest request = new ServerRequest(api, jsonParams);
return request.sendPostRequest1(jsonParams.toString());
} catch (Exception ue) {
return Excpetion2JSON.getJSON(ue);
}
} //end of doInBackground
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
if(response.has("location"))
{
try {
Location location = new Location();
location.setLattitude(response.getString("lat"));
location.setLongitude(response.getString("lng"));
ArrayList<Location> locations = location.getLocationArrayList();
locations.add(location);
}
catch (JSONException je)
{
Log.d("JsonException",je.toString());
}
}
if (loadingDialog.isShowing())
loadingDialog.dismiss();
}
}
Executing async task:
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
int cellid= cellLocation.getCid();
int celllac = cellLocation.getLac();
Log.d("CellLocation", cellLocation.toString());
Log.d("GSM CELL ID", String.valueOf(cellid));
Log.d("GSM Location Code", String.valueOf(celllac));
GetLocationAsyncTask getLocationAsyncTask = new GetLocationAsyncTask(MainActivity.this,MainActivity.this);
getLocationAsyncTask.execute(String.valueOf(cellid),String.valueOf(celllac));
Whats going wrong with this? Please help. Thank you..
You have to tell the receiving side that it is json that you send
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

How to access HttpResponse returned by HttpURLConnection InputStream in Android?

I have adopted the code in this Stack Overflow answer to successfully POST JSON from my Android app to a Python/Django server. Here is my (very close) adaptation of the POST code:
// In my activity's onCreate method
try {
JSONObject obj = new JSONObject(strJSON);
new postJSON().execute("https://www.placeholder.com/generate_json", obj.toString());
} catch (Throwable t) {
Log.e("JSON Error", "Could not parse malformed JSON: " + strJSON);
}
// Outside onCreate
private class postJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes("PostData=" + params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result);
}
}
I now want to access the HttpResponse returned by the server, which I think is contained in data (but I'm not sure about this). If data does contain the HttpResponse, I would like to print it in a Toast.
Does data already contain the HttpResponse from the server or do I need to take additional steps to get it from InputStream? If it is already there, where should I put my Toast.makeText code to print the HttpResponse (i.e. data) in a Toast?
The variable data is a String containing the response body from the server and will be available to you on your UI thread as the variable result in the method onPostExecute
There are many patterns for getting the result from an async task. Here is one simple way to do it, try this approach to get a toast.
Write your execution of the task as such:
// In your activity's onCreate method
try {
JSONObject obj = new JSONObject(strJSON);
new postJSON() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}.execute("https://www.placeholder.com/generate_json", obj.toString());
} catch (Throwable t) {
Log.e("JSON Error", "Could not parse malformed JSON: " + strJSON);
}

Value Connection of type java.lang.String cannot be converted to JSONObject in getting objects from the database

I am trying to retrieve json records from the database. On retrieving the GET request over the browser my json responce is of this structure and returning appropriate data
[{"name":"OOGOGOGO","address":"OPOPOPOP","gender":"OPOPOPOP","email":"OPOPOPOP","phonenumber":"OPOPOPOP","nationality":"OPOOPOPO","fk":1}]
I am calling the endpoint url in the assync task doinbackground and this is the endpoint
url = new URL("http://10.0.2.2:88/example/web/app_dev.php/get/1");
the above endpoint returns 405 status code error. On attempting to catch a json exception I get this error
error gotten org.json.JSONException: Value Connection of type java.lang.String cannot be converted
confused on what could be wrong with this endpoint as it returns a 200 ok json response from postman. Kindly assist
Here's the code snippet.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Fetch network data
new NetworkAsyncTask().execute("http://www.mocky.io/v2/591f32f4110000d10307b4c7");
}
private class NetworkAsyncTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(String result) {
if (result != null) {
Log.d("TAG", "Success! Result: " + result);
processResult(result);
} else {
Log.d("TAG", "Failed, no data");
}
}
private void processResult(String result) {
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject nameObject = jsonArray.getJSONObject(0);
String name = nameObject.optString("name");
Log.d("TAG", "name: " + name);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
For more information on networking and JSON on Android, i suggest you read this guide:
https://guides.codepath.com/android/Sending-and-Managing-Network-Requests
https://guides.codepath.com/android/Converting-JSON-to-Models

Categories

Resources