Android App Keeps Crashing In Avd, But Is Built Properly In Gradle
Solution 1:
You are trying to access **xml**
instances before it get's created that's makes app causing to crashed.
To check the caused due to your app crashed you may refer to check Logcat
into your IDE.
Put Your instantiation code inside onCreate()
callback:-
package com.example.android.testapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
publicclassMainActivityextendsAppCompatActivity {
final TextView mShowCounter;
final Button button;
privateintmCount=0;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowCounter = (TextView) findViewById(R.id.text_view_counter);
button = (Button) findViewById(R.id.toast_button);
}
publicvoidshowToast(View view) {
Toasttoast= Toast.makeText(this,
R.string.toast_popup,Toast.LENGTH_LONG);
toast.show();
}
publicvoidcounterUp(View view) {
mCount++;
if(mShowCounter != null) {
mShowCounter.setText(Integer.toString(mCount));
}
}
}
Solution 2:
Android app keeps crashing in AVD, but is built properly in Gradle
Because you are doing findViewById
outside onCreate()
without doing setContentView()
Do findViewById
inside onCreate()
method after setContentView()
Declare your TextView mShowCounter
and Button button;
as Global
SAMPLE CODE
publicclassMainActivityextendsAppCompatActivity {
TextView mShowCounter ;
Button button ;
privateintmCount=0;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mShowCounter = (TextView) findViewById(R.id.text_view_counter);
button = (Button) findViewById(R.id.toast_button);
}
publicvoidshowToast(View view) {
Toasttoast= Toast.makeText(this,
R.string.toast_popup,Toast.LENGTH_LONG);
toast.show();
}
publicvoidcounterUp(View view) {
mCount++;
if(mShowCounter != null) {
mShowCounter.setText(Integer.toString(mCount));
}
}
}
Solution 3:
The problem lies in these lines.
finalTextViewmShowCounter= (TextView) findViewById(R.id.text_view_counter);
finalButtonbutton= (Button) findViewById(R.id.toast_button);
Your app crashes because during the class init phase, the Views don't exist yet. findViewById
will not work.
You should instead move these lines inside onCreate
.
Solution 4:
Your component initializations should go in the onCreate()
i.e put your
mShowCounter = (TextView) findViewById(R.id.text_view_counter);button = (Button) findViewById(R.id.toast_button);
inside of onCreate()
.
Post a Comment for "Android App Keeps Crashing In Avd, But Is Built Properly In Gradle"