According to the code sample I have shown, responseJson returns the value of FirstName. I want to get that value out of responseJson because i want to pass it to next activity. Any help will be highly appreciated.
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("Status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
intent.putExtra("FirstName", firstname);
contxt.startActivity(intent);
} else {
Toast.makeText(contxt,
"Login Error, invalid Email or Password", Toast.LENGTH_SHORT)
.show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is the my responseJson value {"LastName":"A","UserID":"1","Status":"200","FirstName":"P"}
Change
intent.putExtra("FirstName", firstname);
to
intent.putExtra("FirstName", responseJson.getString("FirstName"));
OR
firstname=responseJson.getString("FirstName");
if(firstname!=null)
intent.putExtra("FirstName", firstname);
Related
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());
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am android beginner and trying to fetch pnr status using json here is my code which is not working please help me .
Also tell me which parsing method is goo xml parse or json parse.
When you asking questions, using some more words to describe your problem will always help. If there are really nothing more to say, just copy some random paragraph from internet, but make sure you mark them as dummy text so that people won't pay attention on them.
public class JSON extends Activity {
String completeData="";
TextView tv;
EditText et;
Button bt;
HttpClient client;
JSONObject jsonobj;
final static String URI="http://pnrapi.alagu.net/api/v1.0/pnr/";
String pnr_no=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
tv=(TextView) findViewById(R.id.textView1);
et=(EditText) findViewById(R.id.editText1);
bt=(Button) findViewById(R.id.button1);
client=new DefaultHttpClient();
}
public void showpnr(View v){
pnr_no=et.getText().toString();
if(pnr_no.equals("")){
Toast.makeText(this, "Enter the Valid Pnr", Toast.LENGTH_LONG).show();
return;
}
GetPNR pnr=new GetPNR();
pnr.execute("train-name");
completeData="";
}
public JSONArray pnr(String username){
JSONArray jarray=null;
try
{
StringBuilder builder=new StringBuilder(URI);
builder.append(username);
HttpGet get=new HttpGet(builder.toString());
HttpResponse response=client.execute(get);
int status =response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity=response.getEntity();
String data=EntityUtils.toString(entity);
jarray=new JSONArray(data);
}
else{
Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
}
}catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
catch(JSONException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
return jarray;
}
JSONObject js_pnr=new JSONObject();
public class GetPNR extends AsyncTask<String, Integer, ArrayList<String>>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
tv.setText("Loading Pnr status");
super.onPreExecute();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<String> al_texts=new ArrayList<String>();
try{
JSONArray data =pnr(pnr_no);
if(data==null){
return null;
}
int count=data.length();
JSONObject jobj=new JSONObject();
for(int i=0;i<count;i++){
jobj=data.getJSONObject(i);
al_texts.add(jobj.getString("train-name").toString());
}
return al_texts;
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<String> al_pnrText) {
if(al_pnrText==null){
tv.setText("Pnr not found");
return;
}
for(String string:al_pnrText){
completeData+=string+System.getProperty("line.seperator")
+System.getProperty("line.seperator");
}
tv.setText("pnr status:"+System.getProperty("line.seperator")+completeData);
}
}
}
Inside your button onclick just write:
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String details = "";
GetPNR pnrDetails = new GetPNR();
try {
details = pnrDetails.execute(URI+et.getText().toString()).get();
Log.d("train", details);
tv.setText(details);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
And the Asynctask is like:
public class GetPNR extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String al_texts = "";
for(String newUrl:params){
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(newUrl);
HttpResponse response;
try {
response = client.execute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String webData = "";
while((webData = reader.readLine()) != null){
Log.i("data", webData);
JSONObject myAwway = new JSONObject(webData);
JSONObject data = myAwway.getJSONObject("data");
Log.i("data", data.toString());
JSONObject travelDate = data.getJSONObject("travel_date");
JSONObject from = data.getJSONObject("from");
JSONObject to = data.getJSONObject("to");
JSONObject alright = data.getJSONObject("alight");
JSONObject board = data.getJSONObject("board");
JSONArray passenger = data.getJSONArray("passenger");
al_texts = data.getString("train_name");
Log.i("data", al_texts);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return al_texts;
}
}
here I'm showing/returning only a string(train name).Like this you can show every details .
this is your modified code and working fine.
I want to wait till i get my user name and my id, and also to wait until I get the user names and users id of my friends in facebook. how can I implement it?
I wrote a code after these two Request however sometimes one Request didn't finish and I get null in one of the variables (for example the userName variable)
therefor I want to wait till these two requests finish.
Or maybe there is another better implementation?
this is my code:
final CountDownLatch isForFinish = new CountDownLatch(1);
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
if( session.isOpened() ){
Request.executeMyFriendsRequestAsync(session, new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users, Response response) {
for (int i=0;i<users.size();i++){
friendsId+= (users.get(i).getId()+",");
friendsName+=(users.get(i).getName()+",");
}
isForFinish.countDown();
}
});
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
String userName = user.getName();
String userId = user.getId();
Intent i = new Intent(getApplicationContext(), TabMainActivity.class);
String email=null;
try {
email = (String) user.getInnerJSONObject().getString("email");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(email!=null){
String newemail=new String(email);
newemail = email.replace("#", "_");
newemail = newemail.replace(".", "_");
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) getSystemService
(Context.TELEPHONY_SERVICE);
String phoneNumber = mTelephonyMgr.getLine1Number();
String password = "facebook";
ParseUser Puser = new ParseUser();
Puser.setUsername(userId);
Puser.setPassword("facebook");
Puser.setEmail(email);
Puser.put("Name", userName);
try {
isForFinish.await();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Puser.put("friendsId",friendsId );
Puser.put("friendsName",friendsName );
try {
Puser.signUp();
ParseObject saleObj =new ParseObject("sale_"+idOfUser);
saleObj.saveInBackground();
ParseObject deliverObj =new ParseObject("deliver_"+idOfUser);
deliverObj.saveInBackground();
ParseObject group =new ParseObject("group_"+idOfUser);
group.saveInBackground();
ParseObject freind =new ParseObject("freind"+idOfUser);
freind.saveInBackground();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i.putExtra("friendsId", friendsId);
i.putExtra("emailOwner", newemail);
i.putExtra("phone", phoneNumber);
i.putExtra("email",email );
i.putExtra("password",password );
i.putExtra("id",userId );
i.putExtra("name",userName );
startActivity(i);
}
}
});
}
For dependent threads, you can use a countdown latch :
http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html
Here is an example:
http://www.javacodegeeks.com/2011/09/java-concurrency-tutorial.html
Using Android Facebook 3.0 setup the Fragment to manage the states using this tutorial
https://developers.facebook.com/docs/tutorials/androidsdk/3.0/scrumptious/authenticate/
You can use the prebuilt facebook login button to also login using the xml
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp" />
Then either using the Session StatusCallback
https://developers.facebook.com/docs/reference/android/3.0/Session.StatusCallback
or the overrides you created in the fragment in the previous tutorial you can initiate a call to retrieve your friends which would look like this
void getFriendsWithApp(final Intent intent){
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Loading...");
mDialog.setCancelable(false);
mDialog.show();
String fqlQuery = "SELECT uid, name, pic_square FROM user WHERE uid IN " +
"(SELECT uid2 FROM friend WHERE uid1 = me())";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session,
"/fql",
params,
HttpMethod.GET,
new Request.Callback(){
public void onCompleted(Response response) {
try {
mDialog.dismiss();
Type listType = new TypeToken<ArrayList<Friend>>(){}.getType();
Utils.friends = new Gson().fromJson(response.getGraphObject().getInnerJSONObject().getJSONArray("data").toString(), listType);
startActivity(intent);
//This is where you would do what you want after you retrieve your json with friends
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);
}
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.
As I can refresh the content of an activity?, for example, I have a menu and a button send me an application content that displays information online, but to go back and return again, the information is not updated.
This is my Activity.
public class Bovalpo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bovalpo);
Button buttonExit = (Button)this.findViewById(R.id.cerrar);
buttonExit.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
System.exit(0);
}
}
);
TextView myListView = (TextView) findViewById(R.id.tv);
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getPage() throws MalformedURLException, IOException {
HttpURLConnection con = (HttpURLConnection) new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=1").openConnection();
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return inputStreamToString(con.getInputStream());
} else {
return null;
}
}
private String inputStreamToString(InputStream in) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append("Mercado: " + line + "\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
public void lanzar(View view){
Intent i = new Intent(this, xml7009.class);
startActivity(i);
}
public void lanzar3(View view){
Intent i = new Intent(this, tabla7009.class);
startActivity(i);
}
public void lanzar4(View view){
Intent i = new Intent(this, xml6503.class);
startActivity(i);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
put your code here
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// make your work to data bind
}
The code that fetches your data and sets list view color should be put in onResume() instead of onCreate if you want it to run each time your Activity is shown.
Simply you can put your update code in the onResume() method of the activity. OnResume() method will be called when ever you return from the other activity.
But onResume() method is often called when your activity is resume for example. If you open and dismiss the dialog then your activity will be Resume. SO if you are calling some network call in onResume then it will consume the process and Network speed.
The alternate solution is use startActivityForResult() method to receive the result from the next activity and bases of the activity result you can call your web API or any work. You can get the result of the next activity in onActivityResult() method.
But before using the startActivityForResult method ensure that the next activity will set the result by calling setResult() method.
If you want to update your data every time you came to activity, you need to set your updated values in onResume
like below
#Override
protected void onResume() {
super.onResume();
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}