Android Fragment Update TextView From AsyncTask onPostExecute - android

I have an AsyncTask that uses HttpGet to fetch content from a remote server. I have tested and this is working fine, now I want to update a TextView with the result of this AsyncTask. Here is what I have done.
From the OnCreateView of the Fragment, I get reference to a Button and a TextView, I initially hide the TextView and then in the OnClickListener for the button I want to unhide the textview and update that textview with the result of my AsyncTask
View rootView = inflater.inflate(R.layout.fragment_programs_list, container, false);
Button btnLoadPrograms = (Button) rootView.findViewById(R.id.btnLoadPrograms);
TextView tvShowPrograms = (TextView) rootView.findViewById(R.id.tvRestCall);
tvShowPrograms.setVisibility(View.GONE);
btnLoadPrograms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startNewAsyncTask();
}
});
return rootView;
Now in the onPostExecute of the AsyncTask, I want to update the Textview
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
getView().findViewById(R.id.tvRestCall).setVisibility(View.SHOW); //Does not exit
}
How do I get a reference to the TextView from within the AsyncTask in a Fragment and then update that TextView with the result of the doinbackground.

Try to Use getView().findViewById(R.id.tvRestCall).setVisibility(View.VISIBLE);

Try this way,
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvShowPrograms.setVisibility(View.VISIBLE);
}

I agree with https://stackoverflow.com/users/1113949/ksarmalkar - you can send a reference to AsyncTask and then use this reference to set Visibility by mYourView.setVisibility(View.VISIBLE);

I ended up solving the issue as follows
Set a public property for the textView
public TextView tvShowPrograms;
Then in OnCreateView I initialize the TextView and set the text to null
tvShowPrograms = (TextView) rootView.findViewById(R.id.tvRestCall);
tvShowPrograms.setText("");
And then the onPostExecute, I simply set the textView to the result.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvShowPrograms.setText(result);
}
Thanks for the answers, I am glad it is working

Related

Nullpointerexception when trying to read textfield - Android

I have a button with a method that is invoked upon clicking.
The method:
public void addToList(View view) {
System.out.println(1);
String str = "";
try{
str = edit.getText().toString();}
catch (Exception ex){
System.out.println( ex );
}
System.out.println(2);
new QueryInList( ).execute(helper, str);
System.out.println(3);
edit.setText(null);
System.out.println(4);
//adapter.notifyDataSetChanged();
}
Well, I always get the exception, it is a Nullpointerexception.
This quite baffles me, because edit IS initalized:
It is declared in the class:
private EditText edit;
and besides, it is initialized in onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edit = (EditText)findViewById(R.id.textfield);
setContentView(R.layout.activity_view);
......}
So I wonder why I always get a Nullpointer?
Set the content view, before looking for the items. You dont have a view to find the items in until you set the content view.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
edit = (EditText)findViewById(R.id.textfield);
......}
Move edit = (EditText)findViewById(R.id.textfield); after your setContentView statement.
Here is a nice explanation from user #Squonk from another question:
setContentView(...) perfoms something called 'layout inflation'. What that means is it parses the XML in the relevant file (main.xml in your case) and creates instances of all the UI elements within it. It then attaches that view to the Activity. When you call findViewById(...) it doesn't reference your main.xml directly - instead it references the content view attached to the Activity, in other words the one inflated by setContentView(...)

app closes during setText

I have a checkedbox that when, onClick (checked/unchecked), would setText to an activity.
When I run the application, it stopped and will return to the previous page.
What is wrong with my code?
My OrderActivity.java has:
public class OrderActivity extends ActionBarActivity {
CheckBox OrderMenuBiggDeal, OrderMenuCrispyChicken, OrderMenuExtremeBurger, OrderMenuTenderloinTips;
TextView ReceiptTextMenuBiggDeal, ReceiptTextMenuCrispyChicken, ReceiptTextMenuExtremeBurger, ReceiptTextMenuTenderloinTips;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
OrderMenuBiggDeal = (CheckBox) findViewById(R.id.checkBoxMenu1);
ReceiptTextMenuBiggDeal = (TextView) findViewById(R.id.textViewReceiptMenuPrice1);
and
public void onClickBiggDeal(View view){
if(OrderMenuBiggDeal.isChecked()){
ReceiptTextMenuBiggDeal.setText("" + "hello");
}
else{
ReceiptTextMenuBiggDeal.setText(R.string.default_value);
}
the application closes on the ReceiptTextMenuBiggDeal.setText("" + "hello"); line.
The setContentView is activity_order.xml.
The location of the TextView that I want to setText (ReceiptTextMenuBiggDeal) is on a different xml file, the activity_receipt.xml
You should change this
setContentView(R.layout.activity_order);
to
setContentView(R.layout.activity_receipt);
It's because your TextView with id textViewReceiptMenuPrice1 belong to activity_receipt layout and you trying to find it on activity_order layout.
You cannot set text on textview that is in other xml, just in one that is set in setcontentview

Draw 50 button dynamically after full activity loaded

This is on create of my activity and after setting content view , I am calling LoadButton().
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Loadbuttons();
}
public void LoadButtonss()
{
Here I am fetching data from database ,and plotting 50 buttons dynamically
}
So My Problem is : It is taking time in loading activity.
Any Idea how to LoadButtons() after Loading full activity. It should not wait for the ButtonLoad() function.
Any Idea how to do that?
paste this code in your activity class block:
#Override
protected void onStart() {
// TODO Auto-generated method stub
LoadButtons();
super.onStart();
}
According to the activity life cycle, you must call LoadButtons in onStart overrided method. Because activity will be visible in this state.
You could set the buttons to invisible and if you fetch the data you can update the UI through an AsyncThread. It is not the nicest way, but it works. Otherwise use instead of Buttons a CustomListView.
I would try this: Load buttons in onCreate and set View invisible. in onResume make it visible again.
View v;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
v= findViewById(R.layout.main);
v.setVisibility(View.INVISIBLE);
Loadbuttons();
}
#Override
protected void onResume() {
v.setVisibility(View.VISIBLE);
super.onResume();
}
public void LoadButtons()
{
FrameLayout layout = (FrameLayout) findViewById(R.id.MarkerLinearlayout);
//Here I am fetching data from database ,and plotting 50 buttons dynamically
}

Refresh listview onpost execute asynctask

i know this question has been posted multiple times and i browsed almost all of them but there is not result, i am performing a deleting an item from mysql database but it is not refreshing, here is the code of the onclicklistener and the button:
onClick listener:
holder.void_button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
adapter = new CustomListViewVoidAdapter(context,R.layout.mytemp, items);
item_selected= items.get(position);
new DeleteOrder().execute();
}});
vi.setTag(holder);
}
OnPostExecute from AsyncTask:
protected void onPostExecute(String unused){
adapter.remove(item_selected);
adapter.notifyDataSetChanged();
}
the adapter is instatiated globally, can you please check where the problem might be?
it is not returning any error, just deleting the item and not refreshing.
Regards
Ralph
Throwing it out there, but, have you tried adapter.notifyDataSetInvalidated();? That forces an update.
Also, put the code in the asynctask!
Like such:
protected void onPostExecute() {
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
}
You better set the adapter again to the list view in onPostExecute with the new values. And you don't need to call notifyDataSetChangedin this case. Also don't re-intialize the adapter in onClick, this is not neccessary.
Add below line in postExecute.
if(adapter != null) {
adapter = new CustomListViewVoidAdapter(context,R.layout.mytemp, items);
YourListviewObject.setAdapter(adapter);
}

ListView update after complete AsyncTask [duplicate]

This question already has answers here:
Android Updating ListView
(2 answers)
Closed 7 months ago.
I want to update TextView's text using AsyncTask.
I have list view in that there is Two TextView and one is ImageView
When user press ImageView button the Song will be played from server side. So i have put code in AsyncTask task
This is an custom Adapter from that i am calling ImageView's on Click event below is my code sample like this
public View getView(final int position, View convertView,
ViewGroup parent) {
holder.imgPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
and onclick event i am passing textview in asynctask, that i want to change after getting data from internet so below is my code
new MetadataTask2().execute(holder.txtMetadata);
now AsyncTask's Code is below
class MetadataTask2 extends AsyncTask<TextView, Void, IcyStreamMeta> {
TextView txtView;
#Override
protected IcyStreamMeta doInBackground(
TextView... arg0) {
//SOME OPERATION
txtView = arg0[0];
return streamMeta;
}
#Override
protected void onPostExecute(IcyStreamMeta result) {
txtView.setText("Hiiiiiiii");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = ProgressDialog.show(CompaniesList.this, "Tuning...",
"Please Wait...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now here u can see that with textView.setText("Hiii") the text will be updated but it will not reflect in Listview for that i have to update ListView or Adapter but do not know how to do that so i can see text on listview can any body help me
i have used below code for updating listview but still does nothing
adapter.notifyDataSetChanged();
mainListView.setAdapter(adapter);
mainListView.invalidate();
Have your adapter be a member variable of your activity class. Then you will be able to reference it from onPostExecute.
Also, from your code it's not clear to me if your TextView is actuallly the one that you intend to modify (the one that you inflated presumably) just in case, remember that you have to call setContentView in the main thread before doInBackground attempts to modify any component. Make sure that this Textview variable (arg0[0]??) is the one that you are inflating

Categories

Resources