Refreshing activity on some operation - java

In my activity I am receiving the messages which are stored in the database and then in the list. In my scenario activity doesn't know when the message is received so the list remain un-updated .Please suggest me how to refresh activity and keep activity alive.
Thanks.

You can refresh your listview by
myListView.invalidateViews();
and to refresh an acitvity you can use
finish();
startActivity(getIntent());

I must prefer refresh data of listview rather than refresh activity. But if you think refreshing activity is necessary for you then the following code may help you. You can use a timer which will trigger after some interval.
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private Timer RefreshActivity;
#Override
public void onResume() {
super.onResume();
RefreshActivity = new Timer();
RefreshActivity.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
refresh();
}
});
}
}, 10000, 10000); // updates each 10 secs
}
private void refresh() {
Toast.makeText(this, "update", 1).show();
//you can fetch data here and update the list if possible.
//or just finish activity and then recreate the activity
finish();
startActivity(getIntent());
}
#Override
public void onPause() {
RefreshActivity.cancel();
super.onPause();
}
}

Related

I need to cancel the Timer started in a service class from MainActivity, but get null reference exception

I have a service type class which starts a timertask in onCreate method and I need to stop the timer from MainActivity when user press the button. I know I have to keep the reference to the timer in my service, but I cannot figure out how to do that and need some help, please!
please take a look at my code
package com.example.timertest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(this);
startService(new Intent(this, TimeService.class));
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button){
// i need here to call mTimer.cancel() in TimeService.class
//
}
}
}
// and here is the TimeService.java
package com.example.timertest;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TimeService extends Service {
public Timer mTimer;
private Handler mHandler = new Handler();
long NOTIFY_INTERVAL = 60 * 1000 * 1; // 1 min
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
if (mTimer != null) {
mTimer.cancel();
} else {
mTimer = new Timer();
}
mTimer.scheduleAtFixedRate(new RefreshDataTimerTask(), 0, NOTIFY_INTERVAL);
}
class RefreshDataTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), getDateTime(), Toast.LENGTH_LONG).show();
}
});
}
private String getDateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
}
//and service registered in manifest
<service android:name=".TimeService"/>
I have tried to call the mTimer.cancel(), but got a null reference, because seems I have created a new instance of the service class.
This example shows a Toast with date and time each minute, i want when for example 15 seconds have past and i press the button, the timer to be canceled and to start counting 60 seconds again from the beginning. Inside this service i have many other things like notifications,channels, shared preferences and so on, so it will be good if i can operate only with the timer object.
Take a look on this API documentaion and this. There is example of how to bind service to activity after what you can get direct access to service methods.
After successful binding you can add method inside your service to stop the timer:
public void stopMyTimer() {
mTimer.cancel();
}
And call this method from Activity
This might not be best practice, but you can access public values by directly referring to the class:
TimeService.mTimer.cancel()
Which should work because Services function similarly to Singletons, in that each call of startService should be calling the same instance.

Android: onBackPressed not being recognized

EDIT: Realized and solved the problem on my own. Thank you.
Please bear with me it's actually my first time using Android Studio and Stackoverflow. What I am trying to make is a music player, there are 2 activities. In the second activity when the user taps the play button, the music plays. If the user backs, the music will stop playing and go back to the first activity. Somehow on back pressed is not working. It's grayed out and it tells me that the Method is never used.
package com.radiantminds.radiantminds;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
}
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
}
You have to put it on an Activity, don't forget to call #Override
#Override
public void onBackPressed()
{
super.onBackPressed(); //if you want to do something new remove this line
}
The problem is that you have to place the onBackPressedMethod() outside, as follows :
public class player1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player1);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.mozardpianosonata); //create mediaplayer with song
ImageButton yButton = (ImageButton) findViewById(R.id.imageButton5);
yButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //play music on click
if (mp.isPlaying()) {
mp.pause();
} else {
mp.start();
}
}
});
}
#Override
public void onBackPressed(){ //this is not working
if(mp.isPlaying())
{
mp.stop(); // stop music on backpress
}
//if you want to do the back action aswell, uncomment the following line
//super.onBackPressed();
}
Make sure the #override is there above the method and you don't declare the method twice.
other alternative is:
onKeyDown()
or add:
super.onBackPressed();
in the method onBackPressed (though i dont suggest it really)

Executing multiple activities in Android

I was trying to execute one activity after executing another,by using threads and using sleep method of thread class.
Here is the code,
package com.example.admin.myapplication;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layo);
Thread th=new Thread() {
public void run()
{
try
{
Thread.sleep(3000);
}
catch(InterruptedException i)
{
i.printStackTrace();
}
finally
{
Intent io=new Intent("com.example.admin.myapplication.NEWATTEMPT");
startActivity(io);
}
}
};
th.start();
}
Code for layo.xml is-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#drawable/pic">
</LinearLayout>
and NewAttempt is another java class-
My question here is this-
In line no. 16 of MainActivity,I am setting the content to layo.xml,and after that I am creating an instance of thread class and starting it,
but,If I put setContentView(R.layout.layo) in the try block,then its showing an error,on starting the application.Why is it so??Can somebody explain why?
And can somebody please explain how an execution happens in android,i.e,order in which files are read?I am a beginner in Android and I doesn't have much idea how the control flows from one activity to another?
Whenever you want to modify your view inside Activity, you need to do it on your activity(ui) thread. UI thread is synchronized. Activity has a method that can handle your Runnable
runOnUiThread(new Runnable() {
#Override
public void run() {
//your method that modify view
}
});
In your case, you can put method above inside your thread
Thread th = new Thread() {
public void run()
{
try
{
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//your method that modify view
MainActivity.this.setContentView(R.layout.layo);
}
});
Thread.sleep(3000);
}
catch(InterruptedException i)
{
i.printStackTrace();
}
finally
{
Intent io = new Intent("com.example.admin.myapplication.NEWATTEMPT");
startActivity(io);
}
}
};
th.start();
If you want to make a splash screen model activities, then try timer() class and schedule it.
try this code inside onCreate() method
eg:
Timer timer=new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Intent intent=new Intent(MainActivity.this, NEWATTEMPT.class);
startActivity(intent);
}
},1000);

handler, runnable and services: I put everything together and it doesn't really work

I wanted to create a service, that runs a method after 10 seconds over and over again, until I stop it. It doesn't work. Can somebody help me?
package com.example.tauben;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Reminder extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
TimerTask task = new TimerTask() {
public void run(){
f();
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 10000);
}
public void f(){
Toast t = Toast.makeText(this, "Service is still running", Toast.LENGTH_SHORT);
t.show();
}
}
And this is how I start the service.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(Log_TAG,"_____________RESTART__________");
Intent i= new Intent(this, Reminder.class);
startService(i);
}
Well I can think of 2 alternatives to what you are trying to achieve here.
1- Use TimerTask in set a repeating task that will call call the required method every 10 seconds.
2- Use setRepeating method of AlarmManager.
Both these alternatives are way better. You can google search the examples of both to get a better understanding.
Happy Coding :)
Edit:- I seem to got your original code working using Handler's postDelayed()
package com.example.tauben;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class Reminder extends Service {
Handler mHandler;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
mHandler = new Handler();
Runnable r = new Runnable() {
#override
public void run() {
f();
mHandler.postDelayed(this, 10000);
}
};
mHandler.postDelayed(r, 10000);
}
public void f(){
Toast t = Toast.makeText(this, "Service is still running", Toast.LENGTH_SHORT);
t.show();
}
}
What you have to do is bind to service and declare a method where service clients can stop the service. Inside that method you have to call handler.removeCallbacksAndMessages(null) to cancel all runable tasks.

setOnClickListener in simple Android does not work

I try to learn JAVA and I try to write an app for Android. My Code is simple and often I've seen code like this. But when I push the second time a button, the message does not return. The first time it works. What is my error?
package com.test.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class HelloWorldApp extends Activity {
private Button closeButton;
private Button buttonAnswer1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonAnswer1 = (Button)findViewById(R.id.button1);
closeButton = (Button)findViewById(R.id.buttonEnde);
buttonAnswer1.setFocusable(false);
closeButton.setFocusable(false);
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("1");
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.main);
showToastMessage("2");
}
});
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
Don't call the setContentView method inside the click listener:
buttonAnswer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("1");
}
});
In your onClick functions, you are replacing the entire content view, which will replace the existing button objects with new instances. These new instances no longer have any OnClickListeners.
There is no reason to replace the content view in this case, so the solution is to eliminate those calls from the onClick functions. But if for some reason you needed to replace the content view, then you would need to go through the entire process of finding the new buttons and calling setOnClickListener for each.

Categories