Why is my intent not able to recognize my activity [duplicate] - java

This question already has answers here:
Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?
(9 answers)
Closed 6 years ago.
new Android Dev here. Okay so I made a simple intent to take me to another activity. The problem is that it is not able to take me to that specific activity (but it does open other activities just fine.). Here is the error it is giving me:
FATAL EXCEPTION: main
Process: com.shahrukhraza.app, PID: 5628
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.shahrukhraza.app/com.shahrukhraza.app.otherAppActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:68)
at android.support.v7.app.AppCompatDelegateImplV7.<init>(AppCompatDelegateImplV7.java:146)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:28)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:41)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:29)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:188)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:172)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:512)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:184)
at com.shahrukhraza.app.otherAppActivity.<init>(otherAppActivity.java:14)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
And this is my MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other_app);
Button b1 = (Button) findViewById(R.id.btn1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, otherAppActivity.class);
startActivity(intent);
}
});
}
}
And this is the java class that is causing problems :
public class otherAppActivity extends AppCompatActivity {
EditText eText1 = (EditText) findViewById(R.id.eText1);
EditText eText2 = (EditText) findViewById(R.id.eText2);
Button btn = (Button) findViewById(R.id.button);
TextView result = (TextView)findViewById(R.id.textView);
double n1,n2,sum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other_activity_app);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
n1 = Double.parseDouble(eText1.getText().toString());
n2 = Double.parseDouble(eText2.getText().toString());
sum = n1 +n2;
result.setText(Double.toString(sum));
}
});
}
}

You should initilize the button and all the stuff in OnCreate or they will be null.
EditText eText1, eText2;
TextView result;
double n1,n2,sum;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.);
eText1 = (EditText) findViewById(R.id.eText1);
eText2 = (EditText) findViewById(R.id.eText2);
btn = (Button) findViewById(R.id.button);
result = (TextView)findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
n1 = Double.parseDouble(eText1.getText().toString());
n2 = Double.parseDouble(eText2.getText().toString());
sum = n1 +n2;
result.setText(Double.toString(sum));
}
});
}

Is your otherAppActivity.class in your manifest file as a activity?
Like this
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PromotionMain"
android:label="Promotions"
android:theme="#style/AppTheme.NoActionBar"
>
</activity>
<activity
android:name=".MyWebViewMain"
android:label="MyWebView"
android:theme="#style/AppTheme.NoActionBar"
>
</activity>
if the class is not set up in your Manifest file like this then the class will never load from a intent.
You intent is set up right and should work as far as I can tell

in the otherActivity, in the setContentView you only have R.layout. without specifying the layout id. This might cause the error

Related

startActivity sending to wrong activity: Android

I'm trying to have it to where after the my "Overview" Button is clicked the next button "Variables" is enabled. The button enables, however the setOnClickListener for my "Variables" sends me to my OverviewActivity, rather than my VariablesActivity. I've been stuck on this for a while.
The Variables Activity is just a multiple choice screen, but i was just setting it up.
I'm really new to Java and Android Studio, so this is getting confusing fast
Code:
public class HomeActivity extends AppCompatActivity {
public Button signOutBtn;
public Button overviewBtn;
public Button varBtn;
FirebaseAuth auth;
boolean overviewDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
signOutBtn = findViewById(R.id.signOutBtn);
overviewBtn = findViewById(R.id.overviewBtn);
varBtn = findViewById(R.id.varBtn);
auth = FirebaseAuth.getInstance();
overviewDone = false;
signOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
finish();
}
});
overviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent overviewBtnIntent = new Intent(HomeActivity.this, OverviewActivity.class);
startActivity(overviewBtnIntent);
}
});
if (getIntent().hasExtra("state")) {
if (getIntent().getStringExtra("state").equals("enable")) {
overviewDone = true;
varBtn.setEnabled(true);
} else {
varBtn.setEnabled(false);
}
} else {
varBtn.setEnabled(false);
}
varBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent varbiesButtonIntent = new Intent(HomeActivity.this, VariablesActivity.class);
startActivity(varbiesButtonIntent);
Log.i("Variable Button", "Going to Variable Activity");
}
});
}
}
public class OverviewActivity extends AppCompatActivity {
public Button backBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_overview);
backBtn = findViewById(R.id.ov_backButton);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(OverviewActivity.this, HomeActivity.class);
intent.putExtra("state", "enable");
startActivity(intent);
}
});
}
}
public class VariablesActivity extends AppCompatActivity {
public RadioGroup radioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_variables);
radioGroup = (RadioGroup)findViewById(R.id.RadioGroup);
// getting value of radio button checked
final String value = ((RadioButton)findViewById(radioGroup.getCheckedRadioButtonId())).getText().toString();
if(radioGroup.getCheckedRadioButtonId() == -1){
// no radio buttons checked
} else{
// one the radio buttons are checked
Log.i("Radio Button Clicked", value);
}
}
}
Stacktrace:
2021-11-22 21:45:23.550 4535-4535/com.example.codehorizonapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.codehorizonapplication, PID: 4535
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.codehorizonapplication/com.example.codehorizonapplication.VariablesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
at com.example.codehorizonapplication.VariablesActivity.onCreate(VariablesActivity.java:24)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
int checkedId = radioGroup.getCheckedRadioButtonId();
String value = "";
if(checkedId != -1){
value = ((RadioButton)findViewById(checkedId)).getText().toString();
}
radioGroup.getCheckedRadioButtonId() returns -1 if there is nothing checked, -1 isn't a valid Id thus findViewById returns null.
null.getText() is a java.lang.NullPointerException
This is under the assumption that there is nothing selected and the fact that calling radioGroup.getCheckedRadioButtonId() doesn't crash only when you call getText() does it crash means your radioGroup = (RadioGroup)findViewById(R.id.RadioGroup); is correct.
The reason the OverviewActivity is created instead is due to a stack problem caused by the premature end to VariablesActivity due to the exception.

Trying to create a Journal in Android Studio but App Crashes

Upon opening the first activity of my app in Android Studio, app opens fine. I copied and pasted the same main activity code to open the journal activity, and changed the variable names that were needed, but app crashes upon opening the journal up.
here is the code for opening up the journal:
public class Activity2 extends AppCompatActivity {
private Button buttonJournal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
buttonJournal = (Button) findViewById(R.id.buttonJournal);
buttonJournal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openJournalActivity();
}
});
}
public void openJournalActivity () {
Intent intent = new Intent(this, JournalActivity.class);
startActivity(intent);
}
}
The journal activity I am opening up: (This might be my problem)
public class JournalActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.add_note){
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_journal);
ListView listView = findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.anxty", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if(set == null) {
notes.add("Example note");
} else{
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId",i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
new AlertDialog.Builder(getApplicationContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.anxty", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(JournalActivity.notes);
sharedPreferences.edit().putStringSet("notes",set).apply();
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
}
LogCat when app crashes:
-06-11 11:55:55.744 6677-6677/com.example.anxty E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.anxty, PID: 6677
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anxty/com.example.anxty.JournalActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.anxty.JournalActivity.onCreate(JournalActivity.java:79)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
at android.app.ActivityThread.access$800(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5293) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.anxty">
<dist:module dist:instant="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/anxty_logo"
android:label="#string/app_name"
android:roundIcon="#mipmap/anxty_logo"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".NoteEditorActivity"></activity>
<activity android:name=".JournalActivity" />
<activity
android:name=".ui.login.LoginActivity"
android:label="#string/title_activity_login" />
<activity
android:name=".Activity2"
android:label="#string/title_activity_2"
android:theme="#style/AppTheme.NoActionBar" /> <!-- Main Activity -->
<activity
android:name=".MainActivity"
android:screenOrientation="portrait" /> <!-- Splash Screen Activity -->
<activity
android:name=".SplashScreen"
android:noHistory="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Main activity not launching after updating Kotlin

I had built the app 3 days ago and the app was working fine.
yesterday I updated the Kotlin plugin to 1.3.71-studio3.6-1
after that when I build my app and run it on my phone then after login, the main activity does not launch and the app stops working but I am getting a successful login in my Firebase.
If I try to reopen the app, it does not open.
all other activities are working fine but main_activity does not.
the code of main activity was not modified
this is my manifest file
<application
android:allowBackup="false"
android:icon="#mipmap/g_c"
android:label="#string/app_name"
android:roundIcon="#mipmap/g_c_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".otp" />
<activity android:name=".Register" />
<activity android:name=".Login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
</application>
</manifest>
logcat error
03-30 01:40:05.051 6724-6724/com.trackerbin.guardchecker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.trackerbin.guardchecker, PID: 6724
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.trackerbin.guardchecker/com.trackerbin.guardchecker.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)' on a null object reference
at com.trackerbin.guardchecker.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) 
at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7325) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
MainActivity
public class MainActivity extends AppCompatActivity {
private Button mreport;
private Button mon;
private Button msignout;
private FirebaseAuth fAuth;
private Spinner mtower;
private ProgressBar mBar;
//AD
private AdView mAdView;
// Access a Cloud Firestore instance from your Activity
private final FirebaseFirestore db = FirebaseFirestore.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mreport = findViewById(R.id.button);
mon = findViewById(R.id.onn);
fAuth = FirebaseAuth.getInstance();
mtower = findViewById(R.id.tower);
msignout = findViewById(R.id.signout);
mBar = findViewById(R.id.bar);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adViewR);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
if (fAuth.getCurrentUser() == null) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
final String email = fAuth.getCurrentUser().getEmail();
final String phone = fAuth.getCurrentUser().getPhoneNumber();
mreport.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
mBar.setVisibility(View.VISIBLE);
String tower = mtower.getSelectedItem().toString();
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
Map<String, Object> values = new HashMap<>(); values.put(currentTime,email + phone);
db.collection("tower").document(tower)
.collection(currentDate).document("duty")
.collection("off").document(currentTime).set(values);
mBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "THANK YOU FOR REPORTING !", Toast.LENGTH_SHORT).show();
}
});
mon.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
mBar.setVisibility(View.VISIBLE);
String tower = mtower.getSelectedItem().toString();
String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
Map<String, Object> values = new HashMap<>(); values.put(currentTime,email + phone);
db.collection("tower").document(tower)
.collection(currentDate).document("duty")
.collection("on").document(currentTime).set(values);
mBar.setVisibility(View.INVISIBLE);
Toast.makeText(MainActivity.this, "THANK YOU FOR REPORTING !", Toast.LENGTH_SHORT).show();
}
});
msignout.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
fAuth.signOut();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
}
);
}
#Override
public void onBackPressed() {
finishAffinity();
}
}
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
insert your own admob app id inside value="XXXXXXX"/>

New Activity crashes on startup [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
When clicking a Button to switch from the main Activity to my "ColoursGame" Activity the app crashes.
I'm still a beginner so not an expert at debugging.
The main activity code
Button colorsGame = (Button) findViewById(R.id.colours);
colorsGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, ColoursGame.class));
}
});
Manifest new activity
<activity android:name=".ColoursGame"
android:label="ColourGame"
android:theme="#style/AppTheme.NoActionBar"></activity>
ColoursGame Activity OnCreate code
public class ColoursGame extends Activity {
int livesCount = 3;
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colours_game);
Button start = (Button) findViewById(R.id.startColors);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vSwitch.showNext();
x = String.valueOf(livesCount);
lives.setText(x);
text();
textColor();
backgroundColor();
start();
}
});
}
The Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aynaar.numbersgameforkids, PID: 3278
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.aynaar.numbersgameforkids/com.aynaar.numbersgameforkids.ColoursGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2323)
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
at com.aynaar.numbersgameforkids.ColoursGame.<init>(ColoursGame.java:42)
Don't call findViewById outside of onCreate, there's no Window to call findViewById at that point.
If you still get a NullPointer, then you must have #+id/startColors in activity_colours_game.xml
Answer explanation here
Button start = (Button) findViewById(R.id.startColors);
According to the error you are trying to reach a button that doesnt exist in your activity layout file (whatever it is). Check the id of your button and make sure it is placed on the layout page that related with your "ColoursGame" Activity.

How to add a class to AndroidManifest.xml file in Android Studio? [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I switched over from eclipse to android studio and I'm trying to add an activity to my manifest file, I dont know the code I'm supposed to use and my app keeps crashing heres the code from my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="penis.jason.payday" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="settings"
android:label="Pay Day!!">
</activity>
<activity android:name="statistics"
android:label="Pay Day!!">
</activity>
</application>
what i have it doing is when the user pushes the settings button than it takes the to that class and new xml. heres the code i used to send the intent
Settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent GoToSettings = new Intent(getApplicationContext(), settings.class);
startActivity(GoToSettings);
finish();
}
});
heres my logcat
08-24 10:41:52.098 21750-21750/penis.jason.payday E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: penis.jason.payday, PID: 21750
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{penis.jason.payday/penis.jason.payday.settings}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2259)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$900(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1986)
at penis.jason.payday.settings.<init>(settings.java:23)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2250)
this is the whole settings class
package penis.jason.payday;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import java.util.Calendar;
#SuppressWarnings("unused")
public class settings extends Activity {
boolean FullScreen;
Button SaveAndExit = (Button) findViewById(R.id.SaveAndExit);
Button Save = (Button) findViewById(R.id.Save);
Button Cls = (Button) findViewById(R.id.Cls);
CheckBox FullScreenOnOff = (CheckBox) findViewById(R.id.fullScreen);
CheckBox SaveWarningOnOff = (CheckBox) findViewById(R.id.SaveWarningOnOff);
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month= cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DATE);
String FullDate = (" "+month+"/"+day+"/"+year);
String Date=(String.valueOf(FullDate));
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settings);
FullScreen = getSharedPreferences("Settings",MODE_PRIVATE).getBoolean("FullScreen",false);
if(FullScreen==true){
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.settings);
}
SaveAndExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent GoToMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(GoToMain);
finish();
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Cls.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
if(FullScreenOnOff.isChecked()){
FullScreen = true;
SharedPreferences FullScreenSave = getSharedPreferences("Settings", Context.MODE_PRIVATE);
SharedPreferences.Editor FullScreenE = FullScreenSave.edit();
FullScreenE.putBoolean("FullScreen", FullScreen);
FullScreenE.commit();
}
}
}
_______UPDATE______
i found the problem!
i had to change the way i declared my button varables to this
boolean FullScreen;
Button SaveAndExit,Save,Cls;
CheckBox FullScreenOnOff,SaveWarningOnOff;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month= cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DATE);
String FullDate = (" "+month+"/"+day+"/"+year);
String Date=(String.valueOf(FullDate));
#Override
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settings);
FullScreen = getSharedPreferences("Settings",MODE_PRIVATE).getBoolean("FullScreen",false);
if(FullScreen==true){
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.settings);
}
SaveAndExit = (Button) findViewById(R.id.SaveAndExit);
Save = (Button) findViewById(R.id.Save);
Cls = (Button) findViewById(R.id.Cls);
FullScreenOnOff = (CheckBox) findViewById(R.id.fullScreen);
SaveWarningOnOff = (CheckBox) findViewById(R.id.SaveWarningOnOff);
}
From the looks of your class name it should be as below, case is important.
<activity android:name=".Settings"
android:label="Pay Day!!">
</activity>
<activity android:name=".Statistics"
android:label="Pay Day!!">
</activity>
Declare <uses-sdk android:minSdkVersion="minimum_integer_value" android:targetSdkVersion="your_target_integer_value" /> in your manifest. May be your trying to run it on lower version using API's of higher level

Categories