Talib
Talib

Reputation: 1164

Refreshing activity on some operation

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.

Upvotes: 0

Views: 61

Answers (2)

Md. Monsur Hossain Tonmoy
Md. Monsur Hossain Tonmoy

Reputation: 11085

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();
}
}

Upvotes: 1

Ahmed Ekri
Ahmed Ekri

Reputation: 4651

You can refresh your listview by

myListView.invalidateViews();

and to refresh an acitvity you can use

finish();
startActivity(getIntent());

Upvotes: 1

Related Questions