Dear developers I'm try to save data from Facebook I'm getting other all data but can't get the email and gender.
This is my code
loginButton.setReadPermissions("public_profile");
loginButton.setReadPermissions("email");
loginButton.setReadPermissions("user_friends");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
if (response != null) {
try {
email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,gender");
request.setParameters(parameters);
request.executeAsync();
Profile profile = Profile.getCurrentProfile();
userid = profile.getId();
userfirstname = profile.getFirstName();
middlename = profile.getMiddleName();
userlastname = profile.getLastName();
userimage = profile.getProfilePictureUri(30, 40);
linkuri = profile.getLinkUri();
name = profile.getName();
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
WebService ws = new WebService(URL);
Map<String, String> data = new HashMap<String, String>();
data.put("user_fb_id", userid);
data.put("first_name", userfirstname);
data.put("middle_name", userfirstname);
data.put("gender", gender);
data.put("email", email);
data.put("last_name", userfirstname);
data.put("user_fb_profile_name", name);
data.put("fb_profile_pic", userimage.toString());
try {
String response = ws.makeHTTPRequest(data, "POST");
JSONObject jsonObject = new JSONObject(response);
Log.e("Response", jsonObject.toString());
} catch (Exception e) {
Log.d("", "Exception : " + e.getMessage());
}
return null;
}
}.execute();
}
#Override
public void onCancel() {
//info = ("Login attempt canceled.");
}
#Override
public void onError(FacebookException e) {
// info = ("Login attempt failed.");
}
});
now I will let you know what is the error in my above code.
when i run the GraphRequest it will execute successfully but didn't get the email and gender. The email and gender is equal to null After the GrapRequest method i am running AsyncTask and send that data in my web services post class my class give me error of null email and gender but when i hover the email and gender after execution of AsyncTask they have that data please help me how to solve that issue.
what i want i want to store the user basic data if there is another way also let me know that i will try.
The problem occurs because In your code two Asynctask runs simultaneously.
Means that the GraphRequest class also runs an asynctask to get user data and you are also running a async to send the user data to server.
Async tasks always runs on separate thread(not on Main thread) and they don't wait for completion of other task.
So the solution is call your Async task in onCompleted() method. LIKE..
Write this async class for upload data to server outside of registerCallback.
private class Upload_Data extends AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
WebService ws = new WebService(URL);
Map<String, String> data = new HashMap<String, String>();
data.put("user_fb_id", userid);
data.put("first_name", userfirstname);
data.put("middle_name", userfirstname);
data.put("gender", gender);
data.put("email", email);
data.put("last_name", userfirstname);
data.put("user_fb_profile_name", name);
data.put("fb_profile_pic", userimage.toString());
try {
String response = ws.makeHTTPRequest(data, "POST");
JSONObject jsonObject = new JSONObject(response);
Log.e("Response", jsonObject.toString());
} catch (Exception e) {
Log.d("", "Exception : " + e.getMessage());
}
return null;
}
}
then call this async class in onCompleted method after getting the email and gender value and also check that email and gender is not null before calling Asynctask class.
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
if (response != null) {
try {
email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
}
}
if(email!=null && gender!=null){
new Upload_Data().execute();
}
}
});
Hope this will helpful.
Related
I'm using volley for my post requests and the issue is when I send 362 requests on queue to the server the data will save even though there's an error response as I assumed, or there are repeating data stored in the database.Sometimes my network connectivity is slow. Let's say I send 362 data to my server and I have 3 error response, when the sync was done the overall total of the saved data is still 362 and it should 359 since I have 3 error response, currently I have condition when the error response received the data should not save to the server.
This is what I've tried
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject data = new JSONObject(response);
String status = data.getString("status");
String description = data.getString("description");
JSONObject dataObject = data.getJSONObject("data");
String household = dataObject.getString("hh_id");
if (status.matches("success")){
progressCC[0]++;
progressPercent = findViewById(R.id.progressCount);
progressBar = findViewById(R.id.progressBar);
progressCount = findViewById(R.id.progressFigure);
Double progressCalc = progressCC[0] / countEmvDetails * 100;
progressCount.setText(String.valueOf(progressCC[0].intValue()));
progressPercent.setText(String.valueOf(progressCalc.intValue()));
progressBar.setProgress(progressCalc.intValue());
lst.add(description + "household id: " + household);
gvMain.setAdapter(adapter);
if (progressPercent.getText().toString().matches("100")) {
Toasty.success(SyncData.this, "Completed", Toast.LENGTH_SHORT, true).show();
Toasty.success(SyncData.this, "Updating local data please wait!", Toast.LENGTH_SHORT, true).show();
updaterEmvMonitoring();
}
sqLiteHelper.storeLogs("sync", hh_id);
sqLiteHelper.deleteEmvMonitoringDetails(id);
}
else{
btnSync.setEnabled(true);
lst2.add("Error on syncing the data!");
gvMain2.setAdapter(adapter2);
Toasty.error(getApplicationContext(), "Error on pulling data.", Toast.LENGTH_SHORT, true).show();
}
} catch (JSONException e) {
btnSync.setEnabled(true);
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
btnSync.setEnabled(true);
sqLiteHelper.storeLogs("error", hh_id);
try {
String responseBody = new String(error.networkResponse.data, "utf-8");
Integer responseCode = error.networkResponse.statusCode;
if (responseCode == 401) {
JSONObject data = new JSONObject(responseBody);
JSONArray errors = data.getJSONArray("errors");
JSONObject jsonMessage = errors.getJSONObject(0);
String message = jsonMessage.getString("message");
Toasty.warning(SyncData.this, message, Toast.LENGTH_SHORT, true).show();
lst2.add(message);
gvMain2.setAdapter(adapter2);
} else if (responseCode == 404) {
JSONObject data = new JSONObject(responseBody);
String desc = data.getString("description");
Toasty.error(SyncData.this, "Error 404:" + desc, Toast.LENGTH_SHORT, true).show();
lst2.add(desc);
gvMain2.setAdapter(adapter2);
}
} catch (Exception e) {
Log.d("Error co", String.valueOf(e));
lst2.add(String.valueOf(e));
gvMain2.setAdapter(adapter2);
Toasty.error(SyncData.this, "Network not found.", Toast.LENGTH_SHORT, true).show();
}
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + token);
return headers;
}
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<>();
params.put("full_name", full_name);
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 5,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
I have this MainActivity which does two HTTP calls and return the JSON object back to the MainActivity class. I have seperately implemented the AsyncTask class and used the AsyncResponse interface to get the JSON object to the MainActivity by using the processFinish function call.
At first I came up with one HTTP call which worked perfectly.
Secondly I wanted to do another HTTP call in the same activity class. So I edit the code to cater the second HTTP call.
When I run the application, only the first HTTP call is working. When I call the second HTTP call it throws an exception saying reference to a null object
Then I checked by logging the onPostExecute method which calls the processFinish function. There I could see the JSON Object. So, that means the second JSON object doesn't get to the processFinish
How do I manage the second HTTP call? Please help me! I am new to Android.
Following is my AsyncTask class...
public class ServiceHandler extends AsyncTask<String, Void, JSONObject> {
String startStationID;
String endStationID;
String searchDate;
String startTime;
String endTime;
public ServiceHandler(String startStationID, String endStationID, String searchDate, String startTime, String endTime) {
this.startStationID = startStationID;
this.endStationID = endStationID;
this.searchDate = searchDate;
this.startTime = startTime;
this.endTime = endTime;
}
public interface AsyncResponse {
void processFinish(JSONObject output);
}
public AsyncResponse delegate=null;
public ServiceHandler(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected JSONObject doInBackground(String... params) {
String method = params[0];
JSONObject JSON_Object = null;
if (method.equals("getStations")) {
JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/station/getAll?lang=en");
} else if (method.equals("searchTrains")) {
JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/train/searchTrain?" +
"startStationID="+this.startStationID+"&" +
"endStationID="+this.endStationID+"&" +
"searchDate="+this.searchDate+"&" +
"startTime="+this.startTime+"&" +
"endTime="+this.endTime+"&" +
"lang=en");
}
return JSON_Object;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(JSONObject obj) {
try{
Log.d("onPostExecute",obj.toString());
delegate.processFinish(obj);
}catch (Exception e){
Log.e("onPostExecute",e.getMessage());
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Following is my processFinish function...
#Override
public void processFinish(JSONObject output) {
Log.d("processFinish",output.toString());
if(!isSearchClicked) {
//Get all the stations...
if (output != null) {
Toast.makeText(MainActivity.this, "Successfully Connected!", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = output.getJSONObject("RESULTS");
output = null;
JSONArray dataArray = obj.getJSONArray("stationList");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject object1 = dataArray.getJSONObject(i);
String stationID = object1.getString("stationID");
String stationName = object1.getString("stationName");
stationNames.add(stationName);
stationIDs.add(stationID);
// stations.put(stationID,stationName);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
}
}else {
//search click action...
if (output != null) {
Toast.makeText(MainActivity.this, "Successfully Searched!", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = output.getJSONObject("RESULTS");
JSONArray directTrains = obj.getJSONArray("directTrains");
// Log.d("array size",String.valueOf(directTrains.length()));
// for (int i = 0; i < directTrains.length(); i++) {
// JSONObject object1 = directTrains.getJSONObject(i);
//
// String stationID = object1.getString("stationID");
// String stationName = object1.getString("stationName");
// Log.d("JArr", stationID + " : " + stationName);
//
// stationNames.add(stationName);
// stationIDs.add(stationID);
//// stations.put(stationID,stationName);
// }
// Log.d("stationNames", stationNames.toString());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
Log.d("output",output.toString());
}
}
}
Following is my first HTTP call...
ServiceHandler sh = new ServiceHandler(this);
String method = "getStations";
sh.execute(method);
Following is my second HTTP call...
String method = "searchTrains"
ServiceHandler sh = new ServiceHandler(startStationID,endStationID,searchDate,startTime,endTime);
sh.execute(method);
Although I don't understand exactly what your problem is. There are few things I suggest you to do.
Here I go.
Don't use AsyncTask to make your http calls , use an intent services instead.
Use a OkHTTP library for your networking source
On your intent service send local broadcast with LocalBroadcastManager to broadcast your results from the http call.
Register broadcastsReceivers within your activities or fragments that will listen for those broadcasts that comes from the intent service
Why not to use AsyncTask: Because of configuration change - if you rotate your device you will lose that network calls-
Read about intent services here
I have method in which i am making a volley request and depending on the response I need to change a global boolean variable but for some reason the variable only gets changed after the method is executed completely giving me wrong data for the variable. I need to somehow changed the variable only after the response is recieved.. please help me with it
I need to change the value of variable 'chk' on response but it does not change.
public boolean checkSourceCode() {
pDialog.setMessage("Please Wait ...");
pDialog.show();
final String entered_source_code = source_code.getText().toString();
if(entered_source_code!=null || !entered_source_code.isEmpty()) {
testString = entered_source_code;
final StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String web_response) {
try {
response = new JSONObject(web_response);
Log.e("Resp SUCCESS", "" + response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
hasBeenValidated = true;
if (response.getBoolean("success")) {
Log.e("Resp SUCCESS", "" + response);
validateCode = true;
chk=true; // THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
// Utils.reference_id = source_code.getText().toString().trim();
pDialog.hide();
input_layout_source_code.setError(null);
input_layout_source_code.setErrorEnabled(false);
Utils.reference_id = source_code.getText().toString().trim();
source_code.setBackground(source_code.getBackground().getConstantState().newDrawable());
} else {
validateCode = false;
chk=false;// THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
pDialog.hide();
input_layout_source_code.setErrorEnabled(true);
input_layout_source_code.setError("Invalid reference Id.");
Utils.reference_id = null;
Toast.makeText(getContext(), "Invalid reference Id", Toast.LENGTH_SHORT).show();
}
// chk = validateSourceCode();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String json = null;
if (error instanceof NoConnectionError) {
String strerror = "No internet Access, Check your internet connection.";
displayMessage(strerror);
}
NetworkResponse response = error.networkResponse;
if (null != response && response.statusCode != 200) {
Log.e("Resp code", "" + response.statusCode);
displayMessage("Please contact administrator for error code " + response.statusCode);
}
if (response != null && response.data != null) {
switch (response.statusCode) {
case 400:
json = new String(response.data);
json = trimMessage(json, "message");
if (json != null) displayMessage(json);
break;
default:
json = new String(response.data);
json = trimMessage(json, "message");
if (json != null) displayMessage(json);
}
}
}
}
) {
#Override
public Request.Priority getPriority() {
return Priority.IMMEDIATE;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("referral_code", entered_source_code);
// params.put("email", "abc#androidhive.info");
// params.put("password", "password123");
return requestParams;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Auth-Token", auth_token);
return params;
}
};
sr.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
MaintainRequestQueue.getInstance(mContext).addToRequestQueue(sr, "tag");
}
else{
pDialog.hide();
chk=true;// THIS VALUE DOES NOT CHANGE ON FIRST CALL OF THE METHOD HOWEVER ON SECOND TIME CALLING THE METHOD IT CHANGED
}
Toast.makeText(mContext, String.valueOf(chk), Toast.LENGTH_LONG).show();
return chk;
}
chk variable can not reinitialize again inside a thread
try this
setchk(boolean chk)
{
this.chk=chk;
}
and call it from request method;
Your variable inside the volley request is not initialized by the time you reach: Toast.makeText(mContext, String.valueOf(chk), Toast.LENGTH_LONG).show(); Use a get method to obtain the chk value within volley and call that getter where you need it.
I'm developing an Android app, which is supposed to connect to a web service and save data into the app's local database. I'm using AsyncTask to connect to said web service from my "Login" class, which then returns the result to the processFinish method in "Login." The problem is that I need to separate the data I bring in several methods in the web service, and as far as I have seen, the result is always handled by processFinish. This is a problem because I'll need to handle the data differently depending on the method I call.
Is there a way to tell processFinish which method in my web service I called, so it can handle the result differently? I thought about sending the method's name from the web service itself as part of the result, but it feels forced, and I was hoping to do this in a cleaner way.
Here's the code I'm using:
LoginActivity.java (shortened):
public class LoginActivity extends ActionBarActivity implements AsyncResponse {
public static DBProvider oDB;
public JSONObject jsonObj;
public JSONObject jsonUser;
WebService webService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
oDB = new DBProvider(this);
}
/*Function that validates user and password (on button press).*/
public void validateLogin(View view){
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (!isConnected){
Toast.makeText(this, "No connection!", Toast.LENGTH_LONG).show();
}else{
/* params contains the method's name and parameters I send to the web service. */
String[][][] params = {
{
{"MyWebServiceMethod"}
},
{
{"user", "myUserName", "string"},
{"pass", "myPass", "string"}
}
};
try{
webService = new WebService();
webService.delegate = this;
webService.execute(params);
}catch(Exception ex){
Toast.makeText(this, "Error!: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
public void processFinish(String result){
try{
// Here I handle the data in "result"
}
}catch(JSONException ex){
Toast.makeText(this, "JSONException: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
WebService.java:
public class WebService extends AsyncTask<String[][][], Void, String> {
/**
* Variable Declaration................
*
*/
public AsyncResponse delegate = null;
String namespace = "http://example.net/";
private String url = "http://example.net/WS/MyWebService.asmx";
public String result;
String SOAP_ACTION;
SoapObject request = null, objMessages = null;
SoapSerializationEnvelope envelope;
HttpTransportSE HttpTransport;
/**
* Set Envelope
*/
protected void SetEnvelope() {
try {
// Creating SOAP envelope
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//You can comment that line if your web service is not .NET one.
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransport = new HttpTransportSE(url);
HttpTransport.debug = true;
} catch (Exception e) {
System.out.println("Soap Exception---->>>" + e.toString());
}
}
#Override
protected String doInBackground(String[][][]... params) {
// TODO Auto-generated method stub
try {
String[][][] data = params[0];
final String methodName = data[0][0][0];
final String[][] arguments = data[1];
SOAP_ACTION = namespace + methodName;
//Adding values to request object
request = new SoapObject(namespace, methodName);
PropertyInfo property;
for(int i=0; i<arguments.length; i++){
property = new PropertyInfo();
property.setName(arguments[i][0]);
property.setValue(arguments[i][1]);
if(arguments[i][2].equals("int")){
property.setType(int.class);
}
if(arguments[i][2].equals("string")){
property.setType(String.class);
}
request.addProperty(property);
}
SetEnvelope();
try {
//SOAP calling webservice
HttpTransport.call(SOAP_ACTION, envelope);
//Got Webservice response
result = envelope.getResponse().toString();
} catch (Exception e) {
// TODO: handle exception
result = "Catch1: " + e.toString() + ": " + e.getMessage();
}
} catch (Exception e) {
// TODO: handle exception
result = "Catch2: " + e.toString();
}
return result;
}
#Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
/************************************/
}
AsyncResponse.java:
public interface AsyncResponse {
void processFinish(String output);
}
You can use different AsyncResponse classes. Anonymous classes make this more convenient:
// in one place
webService.delegate = new AsyncResponse() {
#Override
void processFinish(String response) {
// do something
}
};
// in another place
webService.delegate = new AsyncResponse() {
#Override
void processFinish(String response) {
// do something else
}
};
I followed the tutorial on how to build a backend for mobile devices and was able to create a backend for my Android app and store Entites on GAE.The problem is, i don't know how to retrieve the properties of my entity.To store entites i used the following code:
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... contexts) {
Userendpoint.Builder endpointBuilder = new Userendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Userendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
User user = new User();
String username;
if (responseCheckbox.isChecked()) {
username = MainActivity.getPersonName();
}
else {
username = usernameTextField.getText().toString();
}
String location = locationTextField.getText().toString();
String tempAge = ageTextField.getText().toString();
String tempWeight = weightTextField.getText().toString();
String gender = genderTextField.getText().toString();
String occupation = occupationTextField.getText().toString();
int age = Integer.parseInt(tempAge);
int weight = Integer.parseInt(tempWeight);
user.setUsername(username);
user.setLocation(location);
user.setAge(age);
user.setWeight(weight);
user.setGender(gender);
user.setOccupation(occupation);
#SuppressWarnings("unused")
User result;
result = endpoint.insertUser(user).execute();
} catch (IOException e) {
e.printStackTrace();
}
return (long) 0;
}
}
with a call to new EndpointsTask().execute(getApplicationContext()); in my onCreate() method.
To retrieve the properties of the Entity and display them using TextViews this is what i have tried:
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... contexts) {
Userendpoint.Builder endpointBuilder = new Userendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Userendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
User user = new User();
usernameTextView.setText(user.getUsername());
locationTextView.setText(user.getLocation());
ageTextView.setText(user.getAge());
occupationTextView.setText(user.getOccupation());
weightTextView.setText(user.getWeight());
genderTextView.setText(user.getGender());
User result = endpoint.getUser(user.getUsername()).execute();
} catch (Exception e) {
e.printStackTrace();
}
return (long) 0;
}}
and then called new EndpointsTask().execute(getApplicationContext()); in my onCreate() method.When i tried to run the app, i don't get anything.
I have spent several hours looking for how to do it but i only find tutorials on saving entites.
Any help would be appreciated.
Your problem is that you are trying to update the ui in a background thread. After retrieving the user from GAE, you should pass it as a result to onPostExecute which get executed on the main thread, and then update your UI there. Here is a quick draft of the change you need in your code to make it work.
public class EndpointsTask extends AsyncTask<Context, Integer, User> {
protected User doInBackground(Context... contexts) {
Userendpoint.Builder endpointBuilder = new Userendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Userendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
User user = null;
try {
user = endpoint.getUser("username").execute();
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
protected void onPostExecute(User user) {
//update your UI here
usernameTextView.setText(user.getUsername());
locationTextView.setText(user.getLocation());
ageTextView.setText(Integer.toString(user.getAge()));
occupationTextView.setText(user.getOccupation());
weightTextView.setText(Integer.toString(user.getWeight()));
genderTextView.setText(user.getGender());
}
}
The line "User user = new User()" should be replaced with " User result = ...". You're creating a new (probably empty) instance of user, which you're using to fill the TextViews. You should use the instance fetched from the server instead.
EDIT: like this: https://gist.github.com/TomTasche/e574b4d98269f6533405
Moreover, it's best practice to do UI stuff in the main thread. So what you should do is return the "User result" and use it in onPostExecuted() to fill your TextView.