Error in AsyncTask onPostExecute - java

I'm trying to setText on a TextView, I get an error on the phone, and in the LogCat all I get is tag: androidruntime, text: at com.examp... onPostExecute (AsyncSomething.java).
Here is my pseudo code:
TextView display_car_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
display_name_tv = (TextView) findViewById(R.id.display_name_tv);
.....
setContentView(R.layout...);
}
I have a button that affected to the methode that does only:
new AsyncSomething(this,display_car_tv).execute();
The code of AsyncSomething:
private Context context;
private TextView tv;
public AsyncSomethin(Context context, TextView tv){
this.context=context;
this.tv=tv;
}
protected String doInBackground(String...arg0){
//some code that works
return sb.toString();
}
protected void onPreExecute() {}
#Override
protected void onPostExecute(String result){
this.tv.append(result);
}
What do I do wrong?
How can I get more information from LogCat?
PS : sorry for not giving the entire code, but it is not relevant.

from the code you posted the only mistake I can see, probably leading your app to crash for NullPointerException, is that you are using findViewById before setContentView. You have always to call setContentView before every findViewByIds otherwise you will not have any widgets to find

Related

Preserving Value When Orientation Changes

I am developing a very basic Android App that adds a number in TextView whenever I hit the Button. The digit showing in TextView is also preserved when the orientation of the Mobile changes using the onSaveInstanceState() and onRestoreInstanceState() functions.
The problem is when orientation changes the value is preserved but when the Button is pressed once again after the changing of the orientation it again starts the counting from 0 rather then starting it from the preserved value.
My code:
public class MainActivity extends AppCompatActivity {
TextView showValue;
int counter=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showValue = (TextView) findViewById(R.id.CounterValue);
}
public void countIN(View view)
{
counter++;
showValue.setText(Integer.toString(counter));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("my_text", showValue.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
showValue.setText(savedInstanceState.getString("my_text"));
}
}
Thank You for your response.
add
counter=Integer.parseInt(savedInstanceState.getString("my_text"));
inside onRestoreInstanceState method
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
showValue.setText(savedInstanceState.getString("my_text"));
counter=Integer.parseInt(savedInstanceState.getString("my_text"));
}
You can save and get data using several methods
First If your data is small, then you can use onSavedInstanceState and onRestoreInstanceState .. for details follow this answer or this one
Second if you have too much data to store, then use ViewModel instead; this is a tutorial that you can start from.

Setting EditText in Bundle test not working

Hi I am practicing how Bundle savedInstanceState works in Activity creation and it restoration. I have tried this:
private EditText mTextBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextBox = (EditText) findViewById(R.id.etName);
mTextBox.setText("hello");
if(savedInstanceState != null){
Toast.makeText(this, savedInstanceState.getString("name"),
Toast.LENGTH_SHORT).show();
mTextBox.setText(savedInstanceState.geteString("name"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("name", "Joe");
super.onSaveInstanceState(outState);
}
On first onCreate() obviously this will set the EditText field with "hello" as savedInstanceState is null the if block will not be executed. When I change the orientation the Activity goes through all callbacks and Toast the String in the if block, however, it does not set the mTextBox with value from Bundle passed in. The EditText is still set to hello instead of Joe, however, the Toast in if block shows Joe.
Can anyone point out why this is not working as my expectation?
Thanks
This is happening as a result of TextView.getFreezesText, which will:
Return whether this text view is including its entire text contents in
frozen icicles. For EditText it always returns true.
And some more info from TextView.setFreezesText:
Control whether this text view saves its entire text contents when
freezing to an icicle, in addition to dynamic state such as cursor
position. By default this is false, not saving the text. Set to true
if the text in the text view is not being saved somewhere else in
persistent storage (such as in a content provider) so that if the view
is later thawed the user will not lose their data. For EditText it is
always enabled, regardless of the value of the attribute.
icicles is referring to savedInstanceState, that's just what it used to be called.
If you'd like to save and restore the text yourself, you could create a custom EditText and override getFreezesText, something like:
public class NonFreezingEditText extends AppCompatEditText {
public NonFreezingEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean getFreezesText() {
return false;
}
}
You could also use View.post:
mTextBox.post(() -> mTextBox.setText(savedInstanceState.getString("name")));
or Activity.onRestoreInstanceState
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTextBox.setText(savedInstanceState.getString("name"));
}
You need setText different "hello". see example
private EditText mTextBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextBox = (EditText) findViewById(R.id.etName);
mTextBox.setText("hello");
if(savedInstanceState != null){
Toast.makeText(this, savedInstanceState.getString("name"),
Toast.LENGTH_SHORT).show();
mTextBox.setText(savedInstanceState.getString("name"));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
mTextBox.setText("Joe");
outState.putString("name", mTextBox.getText().toString());
super.onSaveInstanceState(outState);
}
OR you must override onRestoreInstanceState. Not call onCreate when text not change.
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if(savedInstanceState != null){
mTextBox.setText(savedInstanceState.getString("name"));
}
}

App is crashing when I run it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I do not get any errors but when I run the app it crashes:
public class MainActivity extends AppCompatActivity {
ImageButton Nr1 = (ImageButton) findViewById(R.id.ImageButton1);
public void machwas(View v) {
Nr1.setImageResource(R.drawable.x);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
This here is wrong:
public class MainActivity extends AppCompatActivity {
ImageButton Nr1 = (ImageButton)findViewById(R.id.ImageButton1);
because findViewById() should be called INSIDE the onCreate method, the reason is that after that are layouts inflated and you are ready to get the views and initialize the widgets...
so what you are doing is initializing the ImageButton wrongly, probably will be null after that line and then this here
public void machwas(View v){
Nr1.setImageResource(R.drawable.x);
}
is going to explode with a NullPointer Exception...
but this is only an inference because you dont post the LogCat...
For more info please take a look to the Activity lifeCycle and the Official Android Documentation
findViewById() searches the view that is set by setContentView(). In your code findViewById() is called before onCreate() so there's no view set yet and due to that all finds will fail and you will always get null there.
BTW: consider using helpers like ButterKnife
You have to call findViewById after view created.
public class MainActivity extends AppCompatActivity {
ImageButton Nr1 ;
public void machwas(View v){
Nr1.setImageResource(R.drawable.x);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Nr1 = (ImageButton)findViewById(R.id.ImageButton1);
machwas(0);
}
}

Setting onSeekBarChangeListener causes null object exception

I'm trying to update a textview with the value of a seekbar, and I'm having trouble setting an OnSeekBarChangeListener. I don't have any compile errors, but every time I try to run the app, I get a null pointer exception.
The error says:
Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
I can't for the life of me figure out why, despite trawling through StackOverflow. Every similar problem, or tutorial on how to set an OnSeekBarChangeListener seems to suggest I do exactly what I've done. Help!
public class MainActivity extends AppCompatActivity {
public TextView time;
public SeekBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
time = (TextView) findViewById(R.id.time);
bar = (SeekBar) findViewById(R.id.bar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar.setOnSeekBarChangeListener(listener);
}
private SeekBar.OnSeekBarChangeListener listener = new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
time.setText((String.valueOf(progress/100) + ":" + String.valueOf(progress % 100)));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};}
I would try to set these lines
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
first in the onCreate-method, and after that, try to find the seekBar view with
bar = (SeekBar) findViewById(R.id.bar);
Please, let me know if it solves your problem!
The findViewById() method will try to find the view with the specified ID. But to do that, it has to know which layout file is used for the activity, so that it knows where to search. That's what you point out with the setContentView, and that's why it has to come first.
Replace your onCreate with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (TextView) findViewById(R.id.time);
bar = (SeekBar) findViewById(R.id.bar);
bar.setOnSeekBarChangeListener(listener);
}
You should call setContentView() before using findViewById!
This error occur too when you call an wrong activity or when you call the correct activity and call another wrong activity that do not have the component you want, example
setContentView(R.layout.correct_activity_with_your_component);
some code.... setContentView(R.layout.wrong_activity_without_your_component_bar_activity_main);
bar = (SeekBar) findViewById(R.id.bar);
So one solution is write the line similar to
setContentView(R.layout.correct_activity_with_your_component);
before your componenet and verify if there is not another command
similar to
setContentView(R.layout.correct_activity_with_your_component);
before you call your component with:
bar = (SeekBar) findViewById(R.id.bar);

TextView doesn't show the required text

My MainActivity class has an if that checks is something is true it starts a new Activity which sets the text of a TextView to what I want.
MainActivity:
public static int caseA = 1;
if(caseA) {
Intent i = new Intent(Timer.this, WorkTimerNotification.class);
startActivity(i);
}
then it goes to the new Activity and it should check the value of caseA.
WorkTimerNotification:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_timer_notification);
TextView timerMetric = (TextView)findViewById(R.id.tester_texter);
if(MainActivity.caseA) {
timerMetric.setText("min");
}
Problem: It does not change the text. Also, lets say I have many other if statements in mainactivity like:
if(caseB) {}
if(caseC) {}
//and so on..
How would I perform the checks? More importantly, how do I get this caseA check to work though.
You need to call findViewById() in onCreate():
private TextView timerMetric;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_timer_notification);
timerMetric = (TextView)findViewById(R.id.tester_texter);
if(caseA) {
timerMetric.setText("min");
}
}
Right now you are calling it before calling setContentView(), before the view hierarchy is generated. For this reason, your code fails.

Categories