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
Related
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");
}
}
}
}
}
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);
}
I'm trying to create a library for my apps, in all my apps have push notification.
I would like to take this package and create a library
In GCM do I have any limitations? Because it looks like it gets the package name to generate ID_TOKEN
I have an APP that has a package with the classes I use for PUSH notification, it works perfectly!
Now I've migrated this package and created a library, because so all other apps are just pointing the lib and it will be working.
Only that for some reason he does not call the lib, I've done everything and I can not.
The code to register the ID in GCM and start the service is this below:
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
This code above is in my MainActivity
I thought that by doing so he would already call the library
EDIT:
I am using Eclipse and GCM
My class `RegistrationIntentService`
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegServicePush";
String newRegID = "";
String GetEmail = "";
public RegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// TODO: Implement this method to send any registration to your
// app's servers.
sendRegistrationToServer(token, email);
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
}
// Notify UI that registration has completed, so the progress indicator
// can be hidden.
}
private void sendRegistrationToServer(String token, String email) {
//MainActivity.newRegID = token;
WebServerRegistrationTask webServer = new WebServerRegistrationTask();
webServer.execute();
}
public class WebServerRegistrationTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(RegistrationIntentService.this);
URL url = null;
try {
url = new URL(Constants.WEB_SERVER_URL);
} catch (MalformedURLException e) {
e.printStackTrace();
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, "").apply();
}
Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put("regID", newRegID);
dataMap.put("appID", Constants.APP_ID);
StringBuilder postBody = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = dataMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> param = (Entry<String, String>) iterator.next();
postBody.append(param.getKey()).append('=').append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
String response = "";
InputStream is = null;
try {
is = conn.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
response = sb.toString();
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
is.close();
}
}
int status = conn.getResponseCode();
if (status == 200) {
if (response.equals("1")) {
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, newRegID).apply();
Intent registrationComplete = new Intent(Constants.SERVER_SUCCESS);
LocalBroadcastManager.getInstance(RegistrationIntentService.this)
.sendBroadcast(registrationComplete);
}
} else {
throw new IOException("Request failed with error code " + status);
}
} catch (ProtocolException pe) {
pe.printStackTrace();
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, "").apply();
} catch (IOException io) {
io.printStackTrace();
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, "").apply();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
}
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.
My app is currently crashing whenever it cannot connect to the server. How do I handle this, and instead let the user know that the server is down and to try again.
private void sendPostRequest(String givenEmail, String givenPassword) {
class SendPostRequestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String emailInput = params[0];
String passwordInput = params[1];
String jsonUserInput = "{email: " + emailInput + ", password: "
+ passwordInput + "}";
try {
HttpClient httpClient = new DefaultHttpClient();
// Use only the web page URL as the parameter of the
// HttpPost argument, since it's a post method.
HttpPost httpPost = new HttpPost(SERVER_URL);
// We add the content that we want to pass with the POST
// request to as name-value pairs
json = new JSONObject(jsonUserInput);
jsonString = new StringEntity(json.toString());
httpPost.setEntity(jsonString);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpParams httpParameters = httpPost.getParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// HttpResponse is an interface just like HttpPost.
// Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor does
// nothing.
// So we can't initialize InputStream although it is not an
// interface
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
Log.i(LOGIN, "ClientProtocolException");
cpe.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (IOException ioe) {
Log.i(LOGIN, "IOException");
ioe.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(LOGIN, result);
try {
serverResponse = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if ((serverResponse.has("status"))
&& (serverResponse.get("status").toString()
.equals("200"))) {
Toast.makeText(getApplicationContext(), "SUCCESS!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Incorrect Email/Password!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SendPostRequestTask sendPostRequestTask = new SendPostRequestTask();
sendPostRequestTask.execute(givenEmail, givenPassword);
}
LogCat Error Log
11-11 16:26:14.970: I/R.id.login_button(17379): IOException
11-11 16:26:14.970: W/System.err(17379): org.apache.http.conn.HttpHostConnectException: Connection to http://* refused
11-11 16:26:14.980: W/System.err(17379): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
I can see that you are already catching the Exceptions and have a String as parameter type to onPostExecute. From inside the exceptions, you can pass a string like "error" to the onPostExecute, whenever an error occurs. Inside the onPostExecute you can check:
if the string is equal to "error":
then create a Alert dialog box from within `onPostExecute` and show it.
else:
continue as desired
Ideally a boolean would do the trick but since you already have a string, you can also use that. Otherwise you can have a struct with a string and a boolean and then pass it to onPostExecute. Hope it gives you the idea.
Or you can create new Object
public class AsyncTaskResult<T> {
private T result;
private Exception error;
public T getResult() {
return result;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T result) {
super();
this.result = result;
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
public void setError(Exception error) {
this.error = error;
}
}
and pass it to onPostExecute
return new AsyncTaskResult<String>(result)
or
return new AsyncTaskResult<String>(exception)
in onPostExecute you may check exception exists or not
asynctaskresult.getError() != null
You can use droidQuery to simplify everything and include HTTP error handling:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.timeout(1000)
.success(new Function() {
#Override
public void invoke($ d, Object... args) {
Toast.makeText(this, "SUCCESS!", Toast.LENGTH_SHORT).show();
JSONObject serverResponse = (JSONObject) args[0];
//handle response
}
})
.error(new Function() {
#Override
public void invoke($ d, Object... args) {
AjaxError error = (AjaxError) args[0];
//toast shows the error code and reason, such as "Error 404: Page not found"
Toast.makeText(this, "Error " + error.status + ": " + error.reason, Toast.LENGTH_SHORT).show();
}
}));