I'm developing an app where I will be getting a GCM notification and I'm sending a broadcast to my main activity so that I could update the UI. UI is updating if I have just opened the app and my Main activity is visible. But when I navigate to any other screen and come back to main activity, this time when i recieve the broadcast, the UI is not updating. I debugged and the code is executing fine and when I check the mText value for textview, its still showing the old value. I have also tried invalidate() and postInvalidate() methods. I dont now what I' doing wrong. Could someone please help me.
Note: I'm using setSelected(true) to apply marquee for my textviews.
Intent newi = new Intent("rating-changed");
newi.putExtra("message", "notify");
LocalBroadcastManager.getInstance(context).sendBroadcast(newi);
private void updateUI(final String pSong, final String pArt, final String cSong, final String cArt, final String nSong, final String nArt){
runOnUiThread(new Runnable() {
public void run() {
ImageView ivPrevSong = (ImageView)findViewById(R.id.ivPrevSong);
ImageView ivCurSong = (ImageView)findViewById(R.id.ivCurSong);
ImageView ivNextSong = (ImageView)findViewById(R.id.ivNextSong);
TextView tvPrevSongName = (TextView)findViewById(R.id.tvPrevSongName);
tvPrevSongName.setSelected(true);
TextView tvCurrSongName = (TextView)findViewById(R.id.tvCurrSongName);
tvCurrSongName.setSelected(true);
TextView tvNextSongName = (TextView)findViewById(R.id.tvNextSongName);
tvNextSongName.setSelected(true);
tvPrevSongName.setText(pSong);
tvCurrSongName.setText(cSong);
tvNextSongName.setText(nSong);
tvPrevSongName.refreshDrawableState();
tvCurrSongName.refreshDrawableState();
tvNextSongName.refreshDrawableState();
}
});
}
Related
I have an activity A which has a progressbar and a textview.
If user clicks a button a service is being started (ServiceB), I am trying to find a way how to update the progressbar in Activity A from the ServiceB and at the same time set the (progress) text in the Textview in Activity A.
I looked around on Google and Stackoverflow and I think I found a way to do it as described here
but I am having difficulties to implement this, any help is highly appreciated.
PS: don`t downvote, I know UI should not be directly accessed from a Service, so I am looking for a way to do it right.
Some relevant code:
Activity A:
#EActivity(R.layout.downloads_activity)
public class DownloadsActivity extends BaseActivity {
#ViewById(R.id.progress_text)
TextView progresstxt;
#ViewById(R.id.progressdownload)
ProgressBar downloadprogress;
// Update Progressbar and set Text sent from ServiceB
}
ServiceB:
public class ServiceB extends IntentService {
...
#Override
public void onProgress(DownloadRequest request, long totalBytes, long downloadedBytes, int progress) {
int id = request.getDownloadId();
if (!isActive) {
downloadManager.cancel(downloadId1);
deleteCancelledFile.deleteOnExit();
} else if (id == downloadId1) {
// How to update progressbar and textview of Activity A?
progresstxt.setText("Downloading: " + progress + "%" + " " + getBytesDownloaded(progress, totalBytes));
downloadprogress.setProgress(progress);
}
}
...
}
You need to use LocalBroadcastManager
Following are the steps which needs to be taken care
Create a LocalBroadcastManager inside activity.
private BroadcastReceiver mLocalBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// take values from intent which contains in intent if you putted their
// here update the progress bar and textview
String message = intent.getStringExtra("message");
int progress = Integer.parseInt(intent.getStringExtra("progress"));
}
};
Register it on activity's onCreate()
LocalBroadcastManager.getInstance(this).registerReceiver(mLocalBroadcast ,
new IntentFilter("myBroadcast"));
UnRegister in activity's onDestroy()
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBroadcast );
Send updates from service to activity to update UI
From IntentService send progress and textView update via intent
Intent intent = new Intent("myBroadcast");
// You can also include some extra data.
intent.putExtra("message", "This is my message!"); // msg for textview if needed
intent.putExtra("progress", progressValue); // progress update
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
It will send these data to mLocalBroadcast which we register inside activity
Hope these help you.
I am try to write a junit test case on selecting a list item and intent to next activity, but i dont know how to simulate this user action by junit coding. Can anyone help?
Also i wanna ask, is there any material teaching the function or syntax on simlate different user action in junit?
The following is a example from my school tutorial notes, and i want to do something like this one, but on a listview item.
public void testKilosToPounds() {
/* INTERACTIONS */
TouchUtils.tapView(this, textKilos); // tap the EditText textKilos
sendKeys("1"); // sent the number 1
TouchUtils.clickView(this, buttonPounds); // click the button buttonPounds
/*CHECK THE RESULT*/
double pounds;
try {
pounds = Double.parseDouble(textPounds.getText().toString());
} catch (NumberFormatException e) {
pounds = -1;
}
//JUnit Assert equals
// message expected actual delta for comparing doubles
assertEquals("1 kilo is 2.20462262 pounds", 2.20462262, pounds, DELTA);
}
I am working on JUnit from last few months to test android applications. And so i am now able to test almost things like webservices and views. Anyway i am sharing my code to test listview with item click and in next activity(InfoActivity) to check data that i sent using intent. InfoActivity is activity where i am sending data of clicked item from ListActivity.
public class ListActivityTest extends ActivityInstrumentationTestCase2<ListActivity> {
private Activity activity;
private ListView lv;
private InfoActivity contextInfoActivity;
private TextView tvInfo;
public ListActivityTest(){
super(ListActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
activity = (ListActivity)getActivity();
lv = (ListView)activity.findViewById(R.id.lv);
}
public void testCase1(){
assertNotNull(activity);
assertNotNull(lv);
}
public void testCase2(){
Instrumentation instrumentation = getInstrumentation();
Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(InfoActivity.class.getName(), null, false);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
lv.performItemClick(lv,4,0);
//lv is listview,4 is item position,0 is default id
}
});
Activity currentActivity = getInstrumentation().waitForMonitor(monitor);
contextInfoActivity = (InfoActivity) currentActivity;
assertNotNull(contextInfoActivity);
tvInfo = (TextView)contextInfoActivity.findViewById(R.id.tvInfo);
assertNotNull(tvInfo);
assertEquals("Karan",tvInfo.getText().toString());
//karan is name at position 4 in listview and i am checking it with name set in textview of next activity i.e infoActivity.
}
#Override
protected void tearDown() throws Exception {
super.tearDown();
activity = null;
lv = null;
tvInfo = null;
contextInfoActivity = null;
}
Hope this ll b helpfull for you.I you want to ask something feel free to ask.Thanks
You can click on a specific row in a ListView by first getting the View that holds that child, and then passing that view in to TouchUtils.clickView.
If you have a ListView view and ActivityInstrumentationTestCase2 this, and you want to click position p in the view:
TouchUtils.clickView(this, view.getChildAt(p));
You probably also want to check if the view is actually on screen too.
I am trying to make a button in one activity (SetupMenu) that, when pressed, puts an int into the intent and carries that over to the next activity (IntroActivity) where a textView will retrieve the int and display it.
Problem is, when the app runs and I get to the activity and press the button, the app crashes and my emulator tells me that "Unfortunately [my app] has stopped working."
I feel like I've tested every possible angle to get this to work. I should note that the button has worked fine, the textview has worked fine, everything else is working smoothly - I only run into issues when I try retrieving the intent and displaying it in textView. I tried passing through a String instead of an Int and also had issues (my string would not appear). Any pointers?
SetupMenu activity (here I put an int into my intent):
public class SetupMenu extends Activity {
public final static String extra_progress_key = "com.example.angelsanddemons.track_players";
public int track_players = 0;
public void to_intro(View view) {
Intent intent = new Intent(this, IntroActivity.class);
intent.putExtra(extra_progress_key, track_players);
startActivity(intent);
}
IntroActivity activity (here I try to retrieve the int from the intent):
public class IntroActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int temp = intent.getIntExtra(SetupMenu.extra_progress_key, 0 );
TextView textView = new TextView(this);
textView.setText(temp);
setContentView(textView);
}
}
One problem is that you can't set a TextView's text to an int; you'll need to first convert it to an string. It's also not a good idea to be manipulating views before you've inflated them, so perhaps your onCreate() should be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int temp = intent.getIntExtra(SetupMenu.extra_progress_key, 0 );
TextView textView = new TextView(this);
setContentView(textView);
textView.setText(String.valueof(temp));
}
I see nothing that ensure that SetupMenu activity is created and in memory when IntroActivity is launched. To make sure, don't pass the variable, but the string itself and check if it work:
int temp = intent.getIntExtra("com.example.angelsanddemons.track_players", 0 );
I have an Activity with a TextView, and I set the label and color of the TextView each time a background thread invokes a method on the Activity. It works properly until I leave the Activity and re-enter it. In that case, the TextView is not updated because the Runnable that is posted for execution on the UI thread is not invoked. Perhaps I need to implement something in onResume(), but I don't know what that would be.
Here is how the TextView is assigned when the Activity is created:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_nameserver);
statusView = (TextView) findViewById(R.id.statusNameserverButton);
...
}
And here's the method called by the background thread, which updates the TextView:
public void running(boolean running) {
final int color;
final String text;
if (running) {
color = Color.GREEN;
text = "Running";
} else {
color = Color.RED;
text = "Stopped";
}
statusView.post(new Runnable() {
#Override
public void run() {
statusView.setTextColor(color);
statusView.setText(text);
}
});
}
In the debugger I see that when running() is invoked after I've re-entered the Activity, the Runnable passed to statusView.post() is never invoked. Inspection of the statusView object properties in the debugger shows no difference between the success and failure cases. I don't know what's different after resuming the Activity that would cause the Runnable to not be invoked. I tried re-assigning the TextView object in onResume(), with the same code used to assign it in onCreate(), but that didn't help.
First check to see if the Activity after resume is the same one as the original Activity, as the original Activity may have been destroyed by Android. Also, check to see if statusView.post(...) returns true.
As the title says, I'm having trouble when updating the contents on my Textview. It all works well, until I change the orientation.
Here is the onCreate of the Activity that holds the Textview:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.transacao);
screenTextView = (TextView) findViewById(R.id.lblStatusTrn);
screenTextView.setText(screenMessage);
//...
}
And here is the code that update the Textview:
private void setScreenMessage(String message) {
screenMessage = message;
screenTextView = (TextView) findViewById(R.id.lblStatusTrn);
screenTextView.setText(screenMessage);
}
Even though I keep getting no errors, the Textview doesn't update after I call setScreenMessage. This all happens after the orientation change. If I don't change the orientation, everything works fine.
I already looked into a number of similar questions here, but none of them seemed to work for me.
EDIT 1: I don't know if it is relevant, but the setScreenMessage is called from another thread, through an Handler.
Code for the Handler:
public void handleMessage(android.os.Message message) {
//...
// This command calls setScreenMessage
command.execute();
}
EDIT 2: Apparently, using Broadcast did the trick. But that makes me think if it is possible that I had an valid reference to an Activity, even though it is not this reference that is been shown. If that is the case, I might have a useless reference stealing away my memory. Is it possible? Is there a way to check this?