My list view item has 3 or 4 buttons and I am calling a web service with each button, which I am doing by using asynch task, now my questions is that I want to show button clicked by changing background of button according to the result of web service call.
Can someone please tell me how to do it?
Try this out
Pass the reference of the button you clicked(view Obtained
from its onClickListener) to the asyncTask you are about to execute
Start the asyncTask
In the Post execute, change the background of the view.
You can make the changes to your button's setBacgroundColor() method in the onPostExecute() method in the AsyncTask.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do what ever you want depending on the result that you
//you pass in the return of the doInBackGround....
button.setBackGroundColor(Color.GREEN);
}
Related
It is common knowledge to call notifyDataSetChanged() or notifyItemChanged() when you mutate an array that is being handled by a RecyclerView adapter in order to update the view and reflect the changes made. But I spun up a sample application in which neither are called when I add items to an array immediately after calling .setAdapter() in the same block, and the view updates! This behavior doesn't happen when I try to add items via a button's onClickListener or from a background thread (both require notifyDataSetChanged for the view to update).
What's going on here? Shouldn't adding items to the list immediately after calling .setAdapter() in the same block require something like notifyDataSetChanged()?
i.e.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
myList.add("a");
myList.add("b");
recyclerView.setAdapter(adapter);
myList.add("c"); // the recyclerView is updating and shows "c" here! why???
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myList.add("e"); // the recyclerView will NOT update here unless you call `notifyDataSetChanged`
}
});
...
If you're passing an ArrayList to your Adapter, and you're adding elements in onCreate, that would be before the app has drawn your first frame.
There is a moment where you're able to add elements, because the adapter hasn't laid out the items.
And within your onClick, that would be after onCreate has finished, which means the adapter is already laid out.
You could try moving add("c"); to onPostCreate or onResume and you may see similar result as your onClick.
i have used asynctask in my programme i have dismiss dialog before intent is passed in postexecute method but in other activity data displays but it still display progress dialog how to remove or what is problem my code is at
http://pastebin.com/bGrMbGCJ
to clear any existing dialog window, use:
dialog.cancel();
You can not have two spinner at a time. Need to use any trick in this case,
Use one common flag set on PostExecute.
Before step#3, on postExecute of both AsyncTask check the flag is already set, if yes just cancel the spinner.
Refer below pseudo code.
postExecute(){
If(taskCompletedFlag == true){
//Code to cancel the spinner.
taskCompletedFlag = false;
}else{
taskCompledtedFlag = true;
}
}
P.S. - In case you are not aware which AsyncTask will initiate first, you can use same mechanism over there.
I have a button and while this button is playing an animation, I'm not able to click on button. I've set click listener and touch listener but in debug mode it's not entering in OnClick and in onTouch methods. Do you know why? Thanks
edit: I've tried something like:
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object... objects) {
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast toast = Toast.makeText(MyActivity.this, button1.getText(), Toast.LENGTH_SHORT);
toast.show();
}
});
return null;
}
;
};
task.execute(button1);
but it's not working
Edit: here is the full source code
Before Android 3.0, using any of the animation classes only changes where the view is drawn - it won't adjust its touchable-bounds during (or after) the animation:
http://android-developers.blogspot.com/2011/02/animation-in-honeycomb.html
You could:
Make a ViewGroup which moves its children every onDraw
Override your View's onDraw to move itself - Could use margin or padding, or position (if view is in a FrameLayout or something similar).
Only use 3.0+ devices
Override the parent's onTouch (or onInterceptTouchEvent), calculate where the View is being drawn (you can get how far into and the offset from real position from the Animation *) and handle accordingly... * Looking at your code (since you generate a random direction each time it finishes), this might not be possible without tracking which directions you've previously take..
you are facing same issue that i was recently ... when you apply animation on button or any other view and use setFillAfter(True) it means that the image of view is moved not the actual view thats why its not listening to your click listener because its just image of view not your actual view you have to do something like that i explained in answer to my own question according to your situation... means you have to also move the actual view on the end place of animation and use setFillAfter(false) so that when you click after anmation then it should be an actual view not just image used for animation purpose by android
check this link....
EditText stucks after animation and alive back on scrolling......?
In your code use setFillafter(false) and actually place your button at end position of animation by somehow like setting margin or according to your layout use appropriate properties for placement. By Applying these changes your click listener will work perfectly.
==> if you are trying that your button's click listener work while its moving (being animate) then as far as i know its not possible because android uses just image of your view to perform animation not the actual.
This might be a threading problem. You should read Event dispatch thread and how to do thing in android async by reading painless threading and take a look at AsyncTask JavaDoc.
In short: the main thread should not be blocked, since it is used for responing to UI events, such as button presses. Therefore, whenever you do something that take more than some milliseconds, you should do it asynchroniously in another thread.
I think there are two things
1)You can handle one event at one time for one object.Like animation is playing on you button that means you can not click on that untill one work get completed(As i understand you animation is on button not on other part of screen)
2)Second if you have playing on rest part of screen and you want to stop it on click of button.Then i think its a problem of focus.once set onfoucslistener to button and check that when you are clicking it Is it getting focus?
I would put the animation into the async task and then the button click should be handled normally on the main thread I think. Because the way you do it at the moment is: The animation starts and blocks the main thread. This means that the click event can't be excecuted in the async task
You must try to use AsyncTask . Programming Android without it would be and horrible usability serious problem.
See this link for how use an asynctask.
Here an example:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialisation of the Activity
MyLongTask task = new MyLongTask();
task.execute("http://blog.fr4gus.com/api/test.json");
}
#Override
protected void onPause() {
// If you wanna make something in the pause of the Asynctask
}
class MyLongTask extends AsyncTask<String, Void, Void>{
#Override
protected void onPreExecute() {
// Before executing what you want to execute
}
#Override
protected Void doInBackground(String... params) {
// what you want to execute come here :D
return null; // Or whatever you want pass to onPostExecute
}
#Override
protected void onPostExecute(Void result) {
// Here we can update for example the UI with something (who knows :? )
}
}
}
MODIFIED
You must always extend the Asynctask Activity , since you are trying to pass params through it , you must define them in the head of your extended class :
class MyLongTask extends AsyncTask<String, Void, Void>{ ...
Then first is the doInBAckground param , next is the onPreExecute param , and the last is the onPostExecute param . That way you can send the params like a Button.
You can learn more about here or in my first link.
I am developing a new app for android 2.2(Froyo), I need to know how to forcefully display a leyout before loading it with dynamic data. I have a LinearLayout with a empty List, wen the appropriate menu is selected I load it with dynamic data which takes some time to load, but wat happens is the screen is empty till the layout is filled with data. I need to display the empty layout which has ly title and show a ProgreesDialog till the list is filled with data. Here is my Activity class.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deals);
loadDeals();//fills the list with data(URL call)
}
You can user AsyncTask for loading data. During which you will be able to show ProgressDialog as well
http://developer.android.com/reference/android/os/AsyncTask.html
Use AsynchronousTask Class and call loadDeals() from doInBackground Method.Just capture the data on that method.Then work ur UI in postExecute method.It will solve your problem
I have defined a HomeActivity with three tabs and each tab is a seperate activity.I used the example in the android developer site. http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
Tab B's (second tab) UI conatins a text and button (named Search).When the user clicks the search button,it should contact a REST webservice and show the results as a list.
In Order to do this,inside TAB B activity,on the click of the button,i call a method which creates an intent and calls a new SearchResultsActivity(referring as SRA henceforth).Inside the SRA(extends List Activity),i have the logic for connecting to the webservice and parsing the JSON result returned which displays the results as a list.I am able to achieve this functionality.But i see some drawbacks here and my questions are:
Is it fine to define a new activty (SRA) to handle the search results? or would it be better to have it handled in TAB B activity itself?The main reason why i went for a seperate activity is,the SRA extends ListActivity which would be needed if i want to display it as List and TabB is just extending Activity and wouldnt allowme to display teh results.So,is there a better way to do this?
Given the above implementation,when i navigate from TabB (click search button) to SRA,the tabs are not seen anymore.As TabB is calling a new activity(
Intent srchIntent = new Intent(TabB.this, SearchResultActivity.class);
TabB.this.startActivity(srchIntent);),the tab goes away.What could be the best solution in this case so that the tabs appear/results shown within Tab B ?
While navigating from TabB to SRA,i am trying to show a Progress dialog/Loading defined in TabB before calling StartActivity and cancel it afterwards.But the loading icon does not appear.I have tried showing the dialog and canceling in SRA as well.But the loading does not appear.
Hey Bala, what i have to say is:
1) It would be best to extend the TAB B as a ListActivity and the search done by a helper class. This way you are making your code more independent.
2) Implement 1) and you will be ok.
3) You should show a progress dialog when you start the request, and stop it when you got results. I would implement a broadcast receiver to achieve that (I can help you out, if you choose to do that).
There are two approaches to achieve this goal..
Whenever you make start your another activity (i.e. search activity), just before that set your search activity to your desired tab. You can achieve this by taking a instance of your TabActivity (i.e. your activity which is extending this class) and calling new Intent().setClass(TABACTIVITY_INSTANCE,ACTIVITY YOU_WANT_TO_SET_TO_THIS_TAB). But make to make the different objects of intent as member class .. Don't do something like this (new Intent().setClass()).
Declare the no of intent objects as no of Tabs you are holding and then use setClass method.
(This will solve your problem of the tab disappearing)
Now for taking data from server, I suggest you to implement AsyncTask (wonderful api available on Android):
private class DownloadImageTask extends AsyncTask<String, Void, String>
{
AbousUsHandler aboutHandeler;
#Override
protected void onPreExecute()
{
mProgress.setMessage("Please wait");
mProgress.show();
super.onPreExecute();
}
protected String doInBackground(String... urls)
{
/* Do you your background task i.e. getting data from server
but don't do ui related things here as this method is called in Thread
pool not on Android Ui thread.*/
return null;
}
protected void onPostExecute(String result)
{
try
{
mProgress.dismiss();
/* set Your List View Adapter here */
}
}
}
Execute this from your UI thread only by calling new DownloadImageTask().execute().
First preExecute will be called and then doInBackground and when you get your data from the server, onPostExecute will be called.
I hope this solves your problem.