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");
}
}
}
}
}
Related
i have been using AsyncTask to download a certain file and went through a few tutorials and just failed to get the progress bar to move with the download. the code is and AsyncTask that calls a method to do the HTTP connection and then comes back to assort the data in a proper way to manipulate it for the app
this is my AsynTask that is on the MainActivity
private class getFood extends AsyncTask<Void, Integer, Cursor> {
private ProgressDialog mProgressDialog;
#Override
protected Cursor doInBackground(Void... params) {
// Create URL object
String site = "https://afternoon-ridge-50060.herokuapp.com/allsnacks";
URL url = createUrl(site);
// Perform HTTP request to the URL and receive a JSON response back
String jsonResponse = null;
try {
String jsonResponseEmpty = "";
// If the URL is null, then return early.
if (url == null) {
jsonResponse = jsonResponseEmpty;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
assert url != null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(20000 /* milliseconds */);
urlConnection.setConnectTimeout(25000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "\"token\": " + token);
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
int fileLength = urlConnection.getContentLength();
Log.d("size", String.valueOf(fileLength));
inputStream = urlConnection.getInputStream();
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();
jsonResponse = output.toString();
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Food JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
// Extract relevant fields from the JSON response and create a list of {#link Earthquake}s
//*List<FoodList> Food = extractFeatureFromJson(jsonResponse);
Cursor foodTable = extractFeatureFromJson(jsonResponse);
// Return the list of {#link Earthquake}s
Log.d("food", "done");
return foodTable;
}
#Override
protected void onProgressUpdate(Integer... values) {
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setProgress(values[0]);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create progress dialog
mProgressDialog = new ProgressDialog(loginActivity.this);
// Set your progress dialog Title
mProgressDialog.setTitle("Downloading");
// Set your progress dialog Message
mProgressDialog.setMessage("Downloading Important Files, Please Wait!");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Show progress dialog
mProgressDialog.show();
}
#Override
protected void onPostExecute(Cursor data) {
try {
int foodNumberColIndex = data.getColumnIndex(COLUMN_NDB_NO);
int foodNameColIndex = data.getColumnIndex(COLUMN_NAME);
int waterColIndex = data.getColumnIndex(COLUMN_WATER_G);
int energyColIndex = data.getColumnIndex(COLUMN_ENERGY_KCAL);
int proteinColIndex = data.getColumnIndex(COLUMN_PROTEIN_G);
int lipidColIndex = data.getColumnIndex(COLUMN_LIPID_TOT_G);
int ashColIndex = data.getColumnIndex(COLUMN_ASH_G);
int carboColIndex = data.getColumnIndex(COLUMN_CARBOHYDRT_G);
while (data.moveToNext()) {
Log.d("in", " progress");
FoodList foodItem = new FoodList(data.getInt(foodNumberColIndex),
data.getString(foodNameColIndex).trim().replace(",", "."),
data.getDouble(waterColIndex),
data.getDouble(energyColIndex),
data.getDouble(proteinColIndex),
data.getDouble(lipidColIndex),
data.getDouble(ashColIndex),
data.getDouble(carboColIndex));
allFood.add(foodItem);
}
} finally {
data.close();
}
mProgressDialog.dismiss();
startActivity(intentNew);
}
private 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 Cursor extractFeatureFromJson(String foodJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(foodJSON)) {
return null;
}
try {
// Create a JSONArray from the JSON response string
JSONArray foodArray = new JSONArray(foodJSON);
for (int i = 0; i < foodArray.length(); i++) {
JSONObject foodObject = foodArray.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(COLUMN_NDB_NO, foodObject.optInt(COLUMN_NDB_NO));
values.put(COLUMN_NAME, foodObject.optString(COLUMN_NAME));
values.put(COLUMN_WATER_G, foodObject.optDouble(COLUMN_WATER_G));
values.put(COLUMN_ENERGY_KCAL, foodObject.optDouble(COLUMN_ENERGY_KCAL));
values.put(COLUMN_PROTEIN_G, foodObject.optDouble(COLUMN_PROTEIN_G));
values.put(COLUMN_LIPID_TOT_G, foodObject.optDouble(COLUMN_LIPID_TOT_G));
values.put(COLUMN_ASH_G, foodObject.optDouble(COLUMN_ASH_G));
values.put(COLUMN_CARBOHYDRT_G, foodObject.optDouble(COLUMN_CARBOHYDRT_G));
foodNutriProvider insert = new foodNutriProvider();
insert.insert(CONTENT_URI, values);
}
} catch (JSONException e) {
// If an error is thrown when executing any of the above statements in the "try" block,
// catch the exception here, so the app doesn't crash. Print a log message
// with the message from the exception.
Log.e("foodSearch", "Problem parsing the earthquake JSON results", e);
Log.e("foodSearch", foodJSON);
}
foodNutriProvider getTable = new foodNutriProvider();
// Return the list of earthquakes
return getTable.query(CONTENT_URI, null, null, null, null);
}
}
You have to publish the progress and then only the Integer... values has proper values.
Something like:
#Override
protected String doInBackground(Context... params) {
//Part-1 of the task done
publishProgress(20);
//Part-2 of the task done
publishProgress(50);
//Part-3 of the task done
publishProgress(100);
return “success”;
}
As per android documentation:
"onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field"
use it
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
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:
I am trying to implement vtiger's API to connect my android application to it's server. I have added the API to the libs folder and then compile the .jar file. I then use the documentation to connect to the server in java.
boolean result = true;
WSClient client = new WSClient("http://en.vtiger.com/wip");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
result = client.doLogin("username", "Accesskey");
if(!result)
{
System.out.println("Login failed!");
System.out.println(client.lastError());
}
else
{
System.out.println("Login Successful");
}
}
However, I always get the Login failed and no error present. The problem is that when I open the WSClient.java class from inside the .jar, the program states that no sources can be found. I have downloaded these files from http://forge.vtiger.com/frs/?group_id=181&release_id=573 and do not know what to attach as a source. Maybe this is why I cannot connect to the server since I am using the right username and access key supplied by vtiger.
Try this:-
Its an example based on https://demo.vtiger.com/ for login
public class Login extends Activity {
//URL to get JSON Array
private static String url = "https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
// contacts JSONArray
JSONArray contacts = null;
String token = null;
String sessionId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog = new ProgressDialog(Login.this);
protected void onPreExecute() {
dialog.setMessage("Loging In... Please wait...");
dialog.show();
}
#SuppressWarnings("unused")
JSONObject result;
#Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
result = json.getJSONObject(TAG_RESULT);
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
String username="admin";
String accesskeyvalue = "w9OweWKUS4a5sSL";
String accessKey=md5(token + accesskeyvalue);
//For debugging purpose only
//System.out.println(accesskeyvalue);
//System.out.println(token);
//System.out.println(accessKey);
String data = null;
try {
data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("accessKey", "UTF-8") + "="
+ URLEncoder.encode(accessKey, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
//System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("https://demo.vtiger.com/webservice.php?operation=login");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
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");
}
text = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
// Show response
System.out.println(text);
sessionId = text.substring(41, 62);
//System.out.println("doInBackground()"+sessionId);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
}
}.execute();
}
public String md5(String s)
{
MessageDigest digest;
try
{
digest = MessageDigest.getInstance("MD5");
digest.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, digest.digest()).toString(16);
return hash;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
Change the variables as per your need
you don't need to use any additional jar files.
I want to insert some items into the database. In the main activity, I retrieve information from the user and pass it to the another class to do some parsing. My JSONObject keeps showing up as NULL.
I am sorry if I am not clear with the question . I've tried to explain it as much as possible.
Below is the code your inputs are welcome
public class MainActivity extends Activity {
/** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */
final String TAG = "########-------MAIN ACTIVITY: LOGIN--------######";
final String URL = "http://46.51.193.32/timereport/ses/sessions";
UserHelper userAdapter;
UserHelper db;
EditText edit_password,edit_username,edit_company;
String regName;
int duration = Toast.LENGTH_LONG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new UserHelper(this);
userAdapter = new UserHelper(this);
edit_password = (EditText)findViewById(R.id.password);
edit_username = (EditText)findViewById(R.id.user_name);
edit_company = (EditText)findViewById(R.id.company_string);
Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
JSONObject jsonobj = new JSONObject();
try{
JSONObject subJson = new JSONObject();
subJson.put("username", edit_username.getText().toString());
subJson.put("password", edit_password.getText().toString());
subJson.put("company", edit_company.getText().toString());
jsonobj.put("user", subJson);
}
catch(JSONException e) {
Log.i("","#####-----error at catch jsonexception-----#####");
}
HandleJSON.SendHttpPost(URL, jsonobj);
String regNameSplit[] = regName.split("-");
try{
userAdapter.openDatabase();
long id = db.insertIntoDatabase(edit_username.getText().toString(),edit_company.getText().toString(), edit_password.getText().toString(),regNameSplit[0], regNameSplit[2]);
Toast.makeText(getApplicationContext(), "You have successfully logged in as: " +"\n" +regNameSplit[0], duration).show();
Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id);
userAdapter.closeDatabase();
}
catch(SQLiteException e){
e.printStackTrace();
}
}
});
}
}
This is the class to which I am sending the JSON object to be parsed
public class HandleJSON{
UserHelper userAdapter;
private static final String TAG = "&&----HTTPClient-----**";
public static String SendHttpPost (String URL, JSONObject jsonobj) {
String regName = "";
try{
Log.v("Json object request is ",jsonobj.toString());
DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v(TAG,"The url is "+URL);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
Log.i(TAG, "HTTPRESPONSE RECIEVED" +(System.currentTimeMillis()-t) + "ms");
String resultString = convertStreamToString(response.getEntity().getContent());
Log.v(TAG , "The response is " +resultString);
JSONObject jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
Log.v(TAG,"The session ID is "+sessionId);
Log.v(TAG,"The name is "+name);
regName = name+"-"+sessionId+"-"+URL;
} catch (Exception e){
e.printStackTrace();
}
return regName;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) !=null ){
sb.append(line + "\n");
}
}
catch (IOException e){
e.printStackTrace();
} finally{
try {
is.close();
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
}
I've just added some of the code that was missing at the MainActivity,
String regNameSplit[] = regName.split("-");
keeps showing up as null
Instead of your convertStreamToString() method try using system provided EntityUtils.toString(entity).
IMPORTANT: do not catch generic Exception, this hides unchecked (runtime) exceptions. You might be hiding the JSONException that happens in JSONObject constructor.
Update:
You are calling SendHttpPost and not assigning result to variable:
HandleJSON.SendHttpPost(URL, jsonobj);
should be:
regName = HandleJSON.SendHttpPost(URL, jsonobj);
I don't see anything wrong with this, could you tell me what is the use of regname ?
at your mainactivity just change the following:
regname = HandleJSON.SendHttpPost(URL, jsonobj);
Your not calling back regname to be assigned to name and sessionid that you are returning at the sendhttppost.