UI does not update after Face Book request...why? - java

I am trying to set text in TextView userEmail, after calling FaceBook request for getting Email.
public TextView userEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
//user_profile_name
userName = (TextView)findViewById(R.id.user_profile_name);
userEmail = (TextView)findViewById(R.id.user_profile_short_bio);
userbday = (TextView) findViewById(R.id.user_bday);
getMyFBProfileRequest();
}
public void getMyFBProfileRequest() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
Log.i("Response",response.toString());
Toast.makeText(MyProfileActivity.this,object.getString("email") ,
Toast.LENGTH_SHORT).show();
// Application code
String email = object.getString("email");
String birthday = object.getString("birthday");
userEmail.setText(email);
} catch (JSONException e) {
e.printStackTrace();
Log.i("Error","");
//profileView.showToast("Error");
}
}
});
// GraphRequest.GraphJSONObjectCallback objectCallback = new JSONObjectCallback();
// GraphRequest request = GraphRequest.newMeRequest(accessToken, objectCallback);
Bundle parameters = new Bundle();
parameters.putString("fields", "email,name,first_name,last_name,gender");
request.setParameters(parameters);
request.executeAsync();
}
And I get a fine response, which I see in toast.
But nothing change in textView. UI does not update… why? I do not know what to do. I used Broadcast Receiver. lost a lot of time. It does not work… Help me, please, anybody.

FB answer has field "birthday"! But my request did't get birthday. It is correct for get it: params.putString("fields", "birthday")
params.putString("fields","email,birthday,picture.type(large)");
2) To surround with try catch all operation with JSONObject:
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}
and set "" in cath if result null;
So, now my request looks like:
Bundle params = new Bundle();
params.putString("fields", "email,birthday,picture.type(large)");
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/", params, HttpMethod.GET,
new GraphRequest.Callback() {
public ImageLoader imageLoader;
public ImageView mImageView;
public UserInfo userModel;
#Override
public void onCompleted( GraphResponse response) {
saveDataInSingletone(response);
profileView.setInfoToView();
}
private void saveDataInSingletone(GraphResponse response) {
JSONObject data = response.getJSONObject();
userModel = UserInfo.getInstance();
String lastName, firstName;
String profilePicUrl;
if (data.has("picture")) {
try {
profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
// getFacebookProfilePicture(profilePicUrl);
// imageView = (ImageView) findViewById(R.id.pic);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
userModel.setAvatar(profilePicUrl);
//mImageView.setImageBitmap(profilePic);
// userModel.setAvatar(profilePic);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
userModel.setEmail( data.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setEmail("");
}
try {
userModel.setBday(data.getString("birthday"));
} catch (JSONException e) {
e.printStackTrace();
userModel.setBday("");
}}).executeAsync();

Related

Can't get Facebook ID and email

I faced with the following problem: I need to get FB id and email after authorization. Here's my code:
#Override
public void onSuccess(LoginResult loginResult) {
final String[] email = new String[1];
final String[] id = new String[1];
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email");
request.setParameters(parameters);
request.executeAsync();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
bundle.putString(EXTRA_EMAIL, email[0]);
bundle.putString(EXTRA_ID, id[0]);
mPresenter.saveUserData(bundle);
}
But when I run my app, I don't get this fields. I checked in debugger and part
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
isn't called at all. I don't understand why it happens. So, what's the matter and how can I solve it?
UPD
Probably, maybe it would help, here's whole fb logic:
mCallbackManager = CallbackManager.Factory.create();
mFacebookButton.setReadPermissions(Collections.singletonList(FB_EMAIL_PERMISSION));
mFacebookButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
final String[] email = new String[1];
final String[] id = new String[1];
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
email[0] = object.getString(FB_EMAIL_PERMISSION);
id[0] = object.getString(FB_ID_PERMISSION);
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,email");
request.setParameters(parameters);
request.executeAsync();
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TOKEN, loginResult.getAccessToken().getToken());
bundle.putString(EXTRA_EMAIL, email[0]);
bundle.putString(EXTRA_ID, id[0]);
mPresenter.saveUserData(bundle);
}
UPD 2
I have one think about this problem, that request is asynchronous and when I put a breakpoint on line mPresenter.saveUserData(bundle); information isn't loaded yet, but how can I make it synchronous? Or maybe I am wrong?
UPD 3
I changed my request in the following way, but it still doesn't work and breakpoints are skipped in this part.
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
(object, response) -> {
try {
if (response.getJSONObject() != null) {
JSONObject data = response.getJSONObject();
if (data.has(FB_EMAIL_PERMISSION)) {
email[0] = response.getJSONObject().getString(FB_EMAIL_PERMISSION);
}
if (data.has(FB_ID_PERMISSION)) {
id[0] = response.getJSONObject().getString(FB_ID_PERMISSION);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
response.getRawResponse();
});
And here's the values of permissions:
private static final String FB_EMAIL_PERMISSION = "email";
private static final String FB_ID_PERMISSION = "id";
did you add permission to your facebook login button
fbLoginButton.setPermissions(Arrays.asList("public_profile,email,user_birthday"));
this is how i am using it
i am not sure of the value of FB_EMAIL_PERMISSION FB_ID_PERMISSION
final GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String id = "", user_email = "", name = "";
Log.d("EHREIUIU", String.valueOf(object));
if (response.getJSONObject() != null) {
JSONObject data = response.getJSONObject();
if (data.has("id"))
id = data.getString("id");
if (data.has("email"))
user_email = data.getString("email");
}
getOneSignalToken();
socialLogin(user_email, name, null, id, "facebook");
} catch (JSONException e) {
e.printStackTrace();
}
}
});

Activity keeps restarting when I leave the activity and come back to it

I have two activities, When I will move from activity A to B, B keeps restarting or "refreshing", when i go back from B to A, it also keeps restarting. The code is very big, here I am posting area where I think problem causes :
Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
deviceStatus();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
this is deviceStatus();
public void deviceStatus(){
try {
RequestQueue requestQueue = Volley.newRequestQueue(InActivate.this);
String URL = "http://gickuwait-dev.com/electionapi/api/DeviceStatus";
JSONObject jsonBody = new JSONObject();
jsonBody.put("device_PK", device_ID2);
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("true")){
Intent intent = new Intent(InActivate.this, Vote.class);
startActivity(intent);
finish();
}else if(response.equals("false")) {
}
// Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<DeviceStatusResponse> list = new ArrayList<DeviceStatusResponse>();
Type listType = new TypeToken<List<DeviceStatusResponse>>() {}.getType();
list = new Gson().fromJson(responseString, listType);
device_Status = list.get(0).getIsActive().toString();
// Toast.makeText(getApplicationContext(), ""+device_Status+" null ", Toast.LENGTH_LONG).show();
return Response.success(device_Status, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
in Activity B, i have the same code to check the device status from the database, any help would be appreciated
You can use Handle to check the repeated task.
private Handler delayHandler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
deviceStatus();
driverDelayHandler.postDelayed(runnable, 1000);
}
};
Don't forgot to cancel on onStop method.
delayHandler.removeCallbacks(runnable);

How to use interface as a Response Listener in android?

I have this code working with me, I am confused with the control flow.
How is the interface used here as a Response Listener? How is the overridden method responseObject(JSONObject resp, String type) in LoginActivity class triggering?
And after calling AsyncTask where the control goes?
public class LoginActivity extends Activity implements ResponseListener{
login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String username = mUsernameField.getText().toString();
String password = mPasswordField.getText().toString();
String[] param = {username, password};
new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);
}
#Override
public void responseObject(JSONObject resp, String type) {
try{
if (resp.has("api_key")) {
String api_key = resp.getString("api_key");
String user_id = resp.getString("user");
Log.i("api_key", api_key);
SharedPreferences settings = LoginActivity.this.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Constants.NADA_API_KEY, api_key);
editor.putString(Constants.NADA_USER_ID, user_id);
editor.putBoolean(Constants.NADA_IS_LOGGED_IN, true);
editor.commit();
Log.i("first Visit", "False");
String should_show_questions_screen = resp.getString("should_set_basic_questions");
if (should_show_questions_screen.compareToIgnoreCase("true")==0){
Intent intent=new Intent(LoginActivity.this,RegistrationSuccessfulScreen.class);
startActivity(intent);
finish();
}else {
Intent intent = new Intent(LoginActivity.this, UserNavigationActivity.class);
startActivity(intent);
finish();
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
//Heres my ServerRequest Class which uses AsyncTask
public class ServerRequests {
public static class LoginUserAsyncTask extends AsyncTask<String, Void, String> {
static JSONObject udetails;
Context mContext;
ResponseListener mResponseListener;
SweetAlertDialog progressDialog;
public LoginUserAsyncTask(Context mContext,ResponseListener listener) {
this.mContext = mContext;
this.mResponseListener = listener;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog =new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
progressDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
progressDialog.setTitleText("please wait connecting..");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = null;
udetails = new JSONObject();
String response_data = "";
if (params.length == 2) {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login");
udetails.put("username", params[0]);
udetails.put("password", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
try {
post = new HttpPost(Config.SERVER_BASE_URL + "/login_with_fb");
udetails.put("fb_id", params[0]);
udetails.put("fb_auth_token", params[1]);
SharedPreferences settings = mContext.getSharedPreferences(Constants.NADA_SP_KEY, 0);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(Config.USER_NAME, params[0]).commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
StringEntity se = new StringEntity(udetails.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
HttpResponse response = client.execute(post);
int response_code = response.getStatusLine().getStatusCode();
response_data = EntityUtils.toString(response.getEntity());
Log.i("api_token", response_data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response_data;
}
#Override
protected void onPostExecute(String response) {
progressDialog.dismiss();
JSONObject resp = new JSONObject();
try {
resp = new JSONObject(response);
if (resp.has("status")) {
if (resp.getString("status").compareToIgnoreCase("unauthorised")==0){
AppMsg appMsg = AppMsg.makeText((Activity)mContext, resp.getString("message"), style);
appMsg.show();
}
}
mResponseListener.responseObject(resp,"LOGIN");
} catch (JSONException e) {
AppMsg appMsg = AppMsg.makeText((Activity)mContext, "Something went wrong", style);
appMsg.show();
e.printStackTrace();
}
}
}
//Here's Interface Which has this method
public interface ResponseListener {
public void responseObject(JSONObject data,String type);
}
Your LoginActivity implements ResponseListener. In this line: new ServerRequests.LoginUserAsyncTask(LoginActivity.this,this).execute(param);, you pass your activity twice into the LoginUserAsyncTask constructor. Notice that the constructor takes in a Context and a ResponseListener. You can do this because your activity implements ResponseListener.
Now LoginUserAsyncTask can call the responseObject method on your activty because it has a refrence to it as a ResponseListener. It does that in the onPostExecute method of the AsyncTask. The activity is kind of listning to when the task is done, then it's responseObject method is called.
Becaus the work of the AsyncTask is done asynchronously it returns "straight away" and the next statement is executed.
I also think your missing part of the first method.

Loading MAMP (Localhost) Data into EditText Issue Android

I've got a MAMP (localhost) database and have a profile loaded. I want to be able to load all my profile data so like 9 fields in my multi-line edit text.
There are no errors just my Log it shows success when it retrieves the data but it only displays one of the fields from the database and not all...Any idea how to get all? My php and everything else is fine as I've tested it.
I was wondering if you could help me?
My Class:
String pid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_get_single_profile = "http://MYIP:8888/android_connect/get_all_profiles.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_USERPROFILE = "UserProfile";
private static final String TAG_PID = "pid";
private static final String TAG_FIRSTNAME = "firstname";
private static final String TAG_LASTNAME = "lastname";
private static final String TAG_ADDRESS = "address";
private static final String TAG_COMMENTS = "comments";
private static final String TAG_AGE = "age";
private static final String TAG_GENDER = "gender";
private static final String TAG_HEIGHT = "height";
private static final String TAG_WEIGHT = "weight";
private static final String TAG_INFORMATION = "information";
Button btnSendSMS;
EditText txtPhoneNo;
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_sms);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
pid = i.getStringExtra(TAG_PID);
// Getting complete product details in background thread
new GetProfileDetails().execute();
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString() + displayLocation();
displayLocation();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
}
private String displayLocation(){
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, new LocationListener(){
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {}
#Override
public void onProviderEnabled(String s) {}
#Override
public void onProviderDisabled(String s) {}
#Override
public void onLocationChanged(final Location location) {}
});
Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
double longitude = myLocation.getLongitude();
double latitude = myLocation.getLatitude();
return "https://www.google.co.id/maps/#"+latitude+","+longitude;
}
//---sends a SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, Home.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case android.telephony.gsm.SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case android.telephony.gsm.SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case android.telephony.gsm.SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case android.telephony.gsm.SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
android.telephony.gsm.SmsManager smms = android.telephony.gsm.SmsManager.getDefault();
smms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
/**
* Background Async Task to Get complete product details
* */
class GetProfileDetails extends AsyncTask<String, String, JSONObject> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SendSMS.this);
pDialog.setMessage("Loading Profile details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected JSONObject doInBackground(String...param) {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_get_single_profile, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_USERPROFILE); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// instead return your product to onPostExecute
return product;
} else {
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONObject product) {
if (product != null) {
// product with this pid found
// Edit Text
txtMessage = (EditText) findViewById(R.id.txtMessage);
// display profile data in EditText
try {
txtMessage.setText(product.getString(TAG_FIRSTNAME));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_LASTNAME));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_ADDRESS));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_COMMENTS));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_AGE));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_GENDER));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_HEIGHT));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_WEIGHT));
} catch (JSONException e) {
e.printStackTrace();
}
try {
txtMessage.setText(product.getString(TAG_INFORMATION));
} catch (JSONException e) {
e.printStackTrace();
}
}
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
You are over-writing the EditText field with each item.
To fix it, just create a StringBuilder and concatenate each item that is available.
Then, call txtMessage.setText at the bottom once you've extracted all of the data.
protected void onPostExecute(JSONObject product) {
if (product != null) {
// product with this pid found
// Edit Text
txtMessage = (EditText) findViewById(R.id.txtMessage);
StringBuilder jsonStringBuilder = new StringBuilder(); //Create StringBuilder for concatenation of JSON results
// display profile data in EditText
try {
//txtMessage.setText(product.getString(TAG_FIRSTNAME)); //Don't set the text here
jsonStringBuilder.append(product.getString(TAG_FIRSTNAME)); //Concatenate each separate item
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_LASTNAME));
jsonStringBuilder.append(product.getString(TAG_LASTNAME));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_ADDRESS));
jsonStringBuilder.append(product.getString(TAG_ADDRESS));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_COMMENTS));
jsonStringBuilder.append(product.getString(TAG_COMMENTS));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_AGE));
jsonStringBuilder.append(product.getString(TAG_AGE));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_GENDER));
jsonStringBuilder.append(product.getString(TAG_GENDER));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_HEIGHT));
jsonStringBuilder.append(product.getString(TAG_HEIGHT));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_WEIGHT));
jsonStringBuilder.append(product.getString(TAG_WEIGHT));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
try {
//txtMessage.setText(product.getString(TAG_INFORMATION));
jsonStringBuilder.append(product.getString(TAG_INFORMATION));
jsonStringBuilder.append(System.getProperty("line.separator"));
} catch (JSONException e) {
e.printStackTrace();
}
txtMessage.setText(jsonStringBuilder.toString());
}
}

twitter4j no authentication challenges found

Been trying to use twitter4j to post a tweet for couple days now without luck, what i want to do is for a person to post their new top score on their timeline from the app at the end of a round. Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tweetr);
Button tweetr = (Button)findViewById(R.id.tweetr);
//create a new twitter configuration using user details
tweetTwitter = new TwitterFactory().getInstance();
tweetTwitter.setOAuthConsumer(TWIT_KEY, TWIT_SECRET);
//create a twitter instance
// tweetTwitter = new TwitterFactory(twitConf).getInstance();
tweetr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dt.execute();
}
});
}
public class TweetTask extends AsyncTask<Object, Void, String> {
#Override
protected String doInBackground(Object... values) {
/* try {
//requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
*/
try {
requestToken = tweetTwitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
String authUrl = requestToken.getAuthenticationURL();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("URI", "DONE");
super.onPostExecute(result);
}
}
#Override
protected void onResume() {
super.onResume();
final Uri uri = getIntent().getData();
if(uri != null ){
Log.d("URI", uri.toString());
Thread th = new Thread(){
public void run(){
try {
String verifier = uri.getQueryParameter("oauth_verifier");
String oauthToken = uri.getQueryParameter("oauth_token");
RequestToken reqToken = tweetTwitter.getOAuthRequestToken(oauthToken,verifier);
AccessToken accessToken = tweetTwitter.getOAuthAccessToken(reqToken);
String token = accessToken.getToken(), secret = accessToken.getTokenSecret();
} catch (TwitterException ex) {
Log.e("Main.onNewIntent", "" + ex.getMessage());
}
}};
th.start();
}else
Log.d("URI", "FAILED");
}
}
This is my error print out
10-23 15:35:18.661: D/TWIT ER(2392): No authentication challenges foundRelevant discussions can be found on the Internet at:
refer to the javadoc of Twitter4J
In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api#twitter.com — all other applications will receive an HTTP 401 error.

Categories