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();
}
}
Related
there is a method to play a music when the splash screen is run?
this is my splash screen code:
// Splash screen timer
private static int SPLASH_TIME_OUT= 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start main activity
Intent i = new Intent(SplashScreen.this, MyActivity.class);
startActivity(i);
// close activity
finish();
}
}, SPLASH_TIME_OUT);
}
I created the raw folder in res / raw and put in my song, how can I play it when the run splash screen?
Simply you can use,
myMediaPlayer = MediaPlayer.create(this, R.raw.loveme);
if (myMediaPlayer != null) {
myMediaPlayer.start();
} else {
myMediaPlayer.reset();
try {
myMediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myMediaPlayer.start();
}
}
MediaPlayer mPlayer = MediaPlayer.create(xxx.this, R.raw.xxx);
It is stated in d.android.com for onPreExecute() that it runs on the UI thread before doInBackground(Params...) so it should easily access the TextView and perform setText() method from the Activity from which it was executed().
But here in the below codes the loading TextView is privately declared inside the class SplashScreen that extends Activity. Inside the onCreate() it is linked with the TextView widget of the UI. But when AsyncTask extended class Atom the function onPreExecute() is executed which throws a NullPointerExcepction for the statement loading.setText("Loading..."); executed inside it.
Here the code
public class SplashScreen extends Activity implements AnimationListener{
...
TextView loading=null;
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
...
loading = (TextView) findViewById(R.id.textView2);
....
}
public class Atom extends AsyncTask<RSSFeed, Void, RSSFeed>{
private RSSReader reader;
private RSSFeed feed = null;
private String uri = "http://website.com/feed/";
#Override
protected void onPreExecute() {
super.onPreExecute();
//------------problem----area-------------------
loading.setText("Loading...");
//------------problem----area-------------------
}
#Override
protected RSSFeed doInBackground(RSSFeed... arg0) {
reader = new RSSReader();
try {
feed = reader.load(uri);
Log.d("rss", feed.getTitle());
} catch (RSSReaderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return feed;
}
#Override
protected void onPostExecute(RSSFeed result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prg.cancel();
t(result.getTitle().toString());
}
}
}
The stack:
03-09 10:50:12.793: W/System.err(14214): java.lang.NullPointerException
03-09 10:50:12.813: W/System.err(14214): at in.edu.ss.er.splash.SplashScreen$Atom.onPreExecute(SplashScreen.java:158)
03-09 10:50:12.827: W/System.err(14214): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
03-09 10:50:12.833: W/System.err(14214): at android.os.AsyncTask.execute(AsyncTask.java:534)
03-09 10:50:12.833: W/System.err(14214): at in.edu.ss.er.splash.SplashScreen.onCreate(SplashScreen.java:45)
Try to initialize TextView before executing asyntask. Like following.
try {
loading = (TextView) findViewById(R.id.textView2);
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
I don't know this is correct or not, This my guessing, So, Please let me know what happened.
Thanks
just initialize your text view before calling AsyncTask. do something like this
loading = (TextView) findViewById(R.id.textView2);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
You have to initialize your textview before then call asynctask. Change your code into following-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
loading = (TextView) findViewById(R.id.textView2);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
}
I've been trying to get this to work for a while. I'm trying to send a message from my phone to a simple server on my laptop. I keep getting the NetworkOnMainThreadException, I've tried making a new Thread(new Runnable() etc. and an ASynchTask but I am still getting the error and the app is force closing. I have read through 3 or 4 of the questions similar to this but none have worked for me. Here is my code:
final Button post2 = (Button) findViewById(R.id.postbutton2);
post2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
// TODO Auto-generated method stub
#Override
public void run() {
// TODO Auto-generated method stub
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
try {
clientSocket = new Socket("10.0.0.2", 4445);
printWriter = new PrintWriter(clientSocket
.getOutputStream(), true);
printWriter.write(message);
printWriter.flush();
printWriter.close();
clientSocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, e.toString(),
Toast.LENGTH_SHORT).show();
}
}
}).start();
}
});
try removing the following part from your code.
message = text.getText().toString(); //Message is a string, text is an EditText.
text.setText("");
It does not look right to do this in this thread.
You must do YourActivity.this.runOnUiThread(new Runnable() { public void run() { /* show your toast here */ });
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.
I was just testing mediaplayer in android, i started a stream in the onCreate method and I have a button that calls the finish() method. After clicking the button I can still hear the stream playing even though the activity is close, I am wondering if this is a leak of sorts and i will have to stop the player first before calling the finish() method, or if finish() method actually does not full kill the app to free up resources. Thank you for reading
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button add_function,exit_btn;
add_function = (Button) findViewById(R.id.view_chat);
exit_btn = (Button) findViewById(R.id.exit_btn);
MediaPlayer mp = new MediaPlayer();
String URL_OF_FILE = "http://stream.radiosai.net:8002/";
try {
mp.setDataSource(URL_OF_FILE);
mp.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
exit_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}// EOF ONCREATE
Calling finish() does not kill the application, it just destroys the current Activity that you're finishing. Although I would think finishing the Activity would stop the MediaPlayer, what you should probably do in this case is override onDestroy(), and release your MediaPlayer object there. For instance:
#Override
public void onDestroy() {
if(mediaPlayer != null) mediaPlayer.release();
super.onDestroy();
}