All,
Just want to be straight with everyone that I have no idea what I am doing lol. But I am having an issue implementing SharedPreferences onPause\onResume in this project, and I am wondering if someone can tell me where I am going wrong.
Error details:
`E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.androidlabs, PID: 2260
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.androidlabs/com.example.androidlabs.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3365)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:173)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:174)
at android.content.Context.obtainStyledAttributes(Context.java:744)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:848)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:815)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:640)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:259)
at com.example.androidlabs.MainActivity.<init>(MainActivity.java:19)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1253)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) `
Here is my main activity code. I can tell that the issue is coming from onResume (I think!) but no clue why!
`package com.example.androidlabs;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
//initializing variables
Button next = (Button) findViewById(R.id.next);
EditText name = (EditText) findViewById(R.id.name); //initializing variables
public static final String SHARED_PREF = "sharedprefs";
public static final String TEXT = "text";
private String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sh.edit();
editor.putString("name", name.getText().toString());
editor.apply();
openNameActivity();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String savedName = sh.getString("name",null);
if (savedName != null){
name.setText(savedName);
}
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences sh = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
//save the users name in My Shared Pref
SharedPreferences.Editor editor = sh.edit();
editor.putString("name", name.getText().toString());
editor.apply();
}
public void openNameActivity(){
EditText name = (EditText) findViewById(R.id.name);
String nameText = name.getText().toString();
Intent intent = new Intent(MainActivity.this, NameActivity.class);
intent.putExtra("name", nameText);
startActivityForResult(intent, 1);
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
int result = data.getIntExtra("namePref", 0);
if(result == 0){
Toast.makeText(MainActivity.this,"Choose a new name", Toast.LENGTH_LONG).show();
}else{
finishAndRemoveTask();
}
}
if(resultCode == RESULT_CANCELED){
Toast.makeText(MainActivity.this,"Something went wrong", Toast.LENGTH_LONG).show();
}
}
}
}`
Your app is crashing when you open your app?
It looks like you are doing initialisation of your button and editText at wrong place
can you move below mentioned code to onCreate method and place it below of setContentView method
next = (Button) findViewById(R.id.next);
name = (EditText) findViewById(R.id.name);
and also you will need to declare next and name both variable
Related
I am trying to build this game from GitHub which i migrated to android studio at my best. After all done and this is the error i get after installing on emulator. It builds fine without any problem and installs the app on emulator but nothing happens on emulator. When i see the emulator i see the app is there but if i open it it closes after a blank screen. I got the logcat below. Since i didn't code this project i don't really understand most of it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.puzzles, PID: 3722
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.puzzles/com.example.puzzles.PuzzleActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.puzzles.PuzzleActivity.decodeGameSizeFromIntent(PuzzleActivity.java:128)
at com.example.puzzles.PuzzleActivity.onCreate(PuzzleActivity.java:97)
at android.app.Activity.performCreate(Activity.java:7994)
at android.app.Activity.performCreate(Activity.java:7978)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 3722 SIG: 9
Here is the PuzzleActivity.java file code....
package com.example.puzzles;
import android.app.Activity;
import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ViewSwitcher;
import com.example.puzzles.R;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class PuzzleActivity extends Activity {
public static final int DIALOG_PAUSED_ID = 44;
GameBoard board;
int screenOrientation;
Bitmap sourceImage;
ViewSwitcher inGameViewSwitcher;
private class PauseDialog extends Dialog implements View.OnClickListener{
public PauseDialog(){
super(PuzzleActivity.this, R.style.PauseMenuStyle);
this.setContentView(R.layout.pause_menu);
Button resumeButton = (Button) findViewById(R.id.pausemenu_resumeButton);
resumeButton.setOnClickListener(this);
Button quitButton = (Button) findViewById(R.id.pausemenu_quitButton);
quitButton.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.pausemenu_resumeButton:
this.dismiss();
break;
case R.id.pausemenu_quitButton:
// Intent intent = new Intent(this.getContext(), MainMenuActivity.class);
// startActivity(intent);
finish();
break;
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
screenOrientation = getIntent().getIntExtra(MainMenuActivity.EXTRA_BOARD_ORIENTATION, 1);
// String str = screenOrientation == 0 ? "PORTRAIT" : "HORIZONTAL";
// Log.d("KAMIL", "Orientation recorded by puzzleactivity: " + str);
//locking the app in needed position
if(screenOrientation == GameBoard.ORIENTATION_PORTRAIT)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//making the app full screen
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_puzzle);
//Setting backgrounds to black.
((RelativeLayout) findViewById(R.id.centerLayout)).setBackgroundColor(Color.BLACK);
((FrameLayout) findViewById(R.id.backgroundLayout)).setBackgroundColor(Color.BLACK);
inGameViewSwitcher = (ViewSwitcher) findViewById(R.id.inGameViewSwitcher);
//now the fun begins :>
//Crating a game board.
board = new GameBoard(decodeGameSizeFromIntent(),
(RelativeLayout) findViewById(R.id.centerLayout),
screenOrientation, this);
sourceImage = loadBitmapFromIntent();
ImageView preview = (ImageView) findViewById(R.id.previewImageView);
preview.setImageBitmap(sourceImage);
PuzzleCreator creator = new PuzzleCreator(sourceImage, board);
board.loadTiles(creator.createPuzzle());
board.drawBoard();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_puzzle, menu);
return true;
}
private com.example.puzzles.Dimension decodeGameSizeFromIntent(){
com.example.puzzles.Dimension size = null;
String str = getIntent().getStringExtra(MainMenuActivity.EXTRA_GAMESIZE);
String[] gameSizes = getResources().getStringArray(R.array.gamesizes);
if(str.equals(gameSizes[0])) size = new com.example.puzzles.Dimension(2,3);
else if(str.equals(gameSizes[1])) size = new com.example.puzzles.Dimension(3,5);
else if(str.equals(gameSizes[2])) size = new com.example.puzzles.Dimension(4,7);
else if(str.equals(gameSizes[3])) size = new com.example.puzzles.Dimension(6,10);
else
throw new RuntimeException("Decoding game size from intent failed. String does not match.");
return size;
}
private Bitmap loadBitmapFromIntent(){
Bitmap selectedImage = null;
Uri imgUri = (Uri) getIntent().getParcelableExtra(MainMenuActivity.EXTRA_IMGURI);
try{
InputStream imageStream = getContentResolver().openInputStream(imgUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
}catch(FileNotFoundException ex){
Log.e("LOADING ERROR", "Cannot load picture from the URI given", ex);
}
/*
if(selectedImage.getWidth()>selectedImage.getHeight()){
selectedImage = BitmapOperator.rotateBitmap(selectedImage, 90);
}*/
return selectedImage;
}
#Override
protected void onRestart() {
super.onRestart();
//Intent intent = new Intent(this, MainMenuActivity.class);
//startActivity(intent);
showDialog(DIALOG_PAUSED_ID);
}
#Override
protected Dialog onCreateDialog(int id) {
PauseDialog dialog = new PauseDialog();
if(id == DIALOG_PAUSED_ID){
// dialog.setContentView(R.layout.pause_menu);
}
return dialog;
}
#Override
public void onBackPressed() {
showDialog(DIALOG_PAUSED_ID);
}
public void inGameButtonsOnClick(View view){
switch(view.getId()){
case R.id.previewButton:
inGameViewSwitcher.showNext();
break;
case R.id.backToGameButton:
inGameViewSwitcher.showPrevious();
break;
}
}
}
Help is much appreciated. Thanks
The log tells you that in this line:
if(str.equals(gameSizes[0])) size = new com.example.puzzles.Dimension(2,3);
str Or gameSizes[0] is null, you need to debug this code and check why you getting null
Null is legit so it's not effect your build
I have a problem with my application. It crashes each time whenever I
launch my app on an Emulator and I switch to landscape mode. But it work
fine in portrait mode. Please what can i do to solve this. Thanks in
advance!
I put "android:configChanges="orientation|screenSize|keyboardHidden" in the
activity declaration in my manifest but still crash.
This is the error:java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a1697759.projetintra/com.example.a1697759.projetintra.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
This is my java code:
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import static com.example.a1697759.projetintra.R.id.etTotalPrix;
public class MainActivity extends AppCompatActivity {
Button btnInscription;
EditText etQuantite;
Spinner spinner;
Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInscription = (Button) findViewById(R.id.btnInscription);
etQuantite = (EditText) findViewById(R.id.etQuantite);
EditText etTotalPrix;
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
// Use a TextWatcher to disable/enable button
etQuantite.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int
arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {}
#Override
public void afterTextChanged(Editable string) {
if(string.length() > 0) {
btnInscription.setEnabled(true);
} else {
btnInscription.setEnabled(false);
}
}
});
btnInscription.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
//Demarrer le nouvelle activite
Intent intent = new Intent(MainActivity.this,
ResumeActivity.class);
//Spinner 1
Bundle b = new Bundle();
b.putString("name", spinner.getSelectedItem().toString());
intent.putExtras(b);
//Spinner 2
Bundle b2 = new Bundle();
b2.putString("name2", spinner2.getSelectedItem().toString());
intent.putExtras(b2);
//EditText Quantite
Bundle q = new Bundle();
q.putString("name3", etQuantite.getText().toString());
intent.putExtras(q);
//Reset spinner and editText
spinner.setSelection(0);
spinner2.setSelection(0);
etQuantite.setText("");
Toast.makeText(MainActivity.this, "Vous avez fait votre
commande",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
}
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a1697759.projetintra, PID: 21317
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.a1697759.projetintra/com.example.a1697759.projetintra.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2947)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4974)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.a1697759.projetintra.MainActivity.onCreate(MainActivity.java:56)
at android.app.Activity.performCreate(Activity.java:6912)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2900)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3008)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4974)
at android.app.ActivityThread.-wrap21(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
You have to create a landscape layout for that.
Just go to the design tab in your xml file
click on the Layout Variants button.
Select the Create Landscape Variation
a landscape layout will be created. Then you are free to change the layout according to your requirements.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
the app crashes when i click the button on signup_activ to start userdetail_activ,if i swithc to some other activity istead , the app runs fine
this is my manifest file.
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".login_activ"
android:parentActivityName=".MainActivity" />
<activity
android:name=".signup_activ"
android:parentActivityName=".MainActivity" />
<activity
android:name=".userdetail_activ"
android:parentActivityName=".signup_activ" >
</activity>
<activity android:name=".userdetail_activ2" />
<activity android:name=".infopage_activ"></activity>
</application>
</manifest>
stack,after the app crash.
AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ozairmansuri.myapplication, PID: 1986
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.ozairmansuri.myapplication/com.example.ozairmansuri.myapplication.userdetail_activ}: 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:2567)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
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:118)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189)
at com.example.ozairmansuri.myapplication.userdetail_activ.<init>(userdetail_activ.java:22)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
signup_activ
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class signup_activ extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_activ);
}
public void UserDet_Switch() {
final Intent intent = new Intent(signup_activ.this, userdetail_activ.class);
startActivity(intent);
return;
}
public void Signup(View view) {
EditText editText = (EditText) findViewById(R.id.editTextUserName);
EditText editText2 = (EditText) findViewById(R.id.editTextPassword);
EditText editText3 = (EditText) findViewById(R.id.editTextConfirmPassword);
String A = editText.getText().toString();
String B = editText2.getText().toString();
String C = editText3.getText().toString();
List<String> errorList = new ArrayList<String>();
while (!isValid_pass(B, C, errorList)) { //checking whether password is valid
for (String error : errorList) {
Toast.makeText(getApplicationContext(), error,
Toast.LENGTH_SHORT).show();
return;
}
}
List<String> errorList2 = new ArrayList<String>();
while (!isValid_usern(A,errorList2)){ //checking whethe user name is valid
for (String error : errorList2) {
Toast.makeText(getApplicationContext(), error,
Toast.LENGTH_SHORT).show();
return;
}
}
SQLhelper dbh =new SQLhelper(this) ;
if(dbh.checkUser(A,B)== true){
Toast.makeText(getApplicationContext(),"user alredy exists",
Toast.LENGTH_SHORT).show();
return;
}
dbh.addUser(A,B); //adding the user to database table 1
Toast.makeText(getApplicationContext(), "account created",
Toast.LENGTH_SHORT).show();
//// TODO: 28-09-2017 intent switch activity (userdetil activity)
UserDet_Switch();
return;
}
//function to check userncme
public static boolean isValid_usern(String usern,List<String> errorList){
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (usern.length() < 8) {
errorList.add("user name lenght must have alleast 8 character !!");
flag=false;
}
if (!lowerCasePatten.matcher(usern).find()) {
errorList.add("user name must have atleast one lowercase character !!");
flag=false;
}
if (!digitCasePatten.matcher(usern).find()) {
errorList.add("user name must have atleast one digit character !!");
flag=false;
}
return flag;
}
//function to check password
public static boolean isValid_pass(String passwordhere, String confirmhere, List<String> errorList) {
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (!passwordhere.equals(confirmhere)) {
errorList.add("password and confirm password does not match");
flag=false;
}
if (passwordhere.length() < 8) {
errorList.add("Password lenght must have alleast 8 character !!");
flag=false;
}
if (!lowerCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have atleast one lowercase character !!");
flag=false;
}
if (!digitCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have atleast one digit character !!");
flag=false;
}
return flag;
}
}
userdetail_activ
import android.content.ContentValues;
import android.content.Intent;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class userdetail_activ extends AppCompatActivity {
public static final String EXTRA_HEIGHT = "height";
public static final String EXTRA_WEIGHT = "weight";
public static final String EXTRA_GENDER = "gender";
RadioButton rb;
RadioGroup rg ;
Boolean gend =null;
int A,B;
EditText editText = (EditText) findViewById(R.id.editText6);
EditText editText2 = (EditText) findViewById(R.id.editText9);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userdetail_activ);
rg = (RadioGroup) findViewById(R.id.radio_group);
}
public void rb_click(View view){ //radio button function
int radioButtonid = rg.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(radioButtonid);
if(radioButtonid == (R.id.radioButton2)) gend=true; //male is true
else gend = false; //female is false
return;
}
public void continue_userdetail(View view){
A = Integer.parseInt(editText.getText().toString());
B = Integer.parseInt(editText2.getText().toString());
if(gend == null)
{
Toast.makeText(getApplicationContext(), "please select gender",
Toast.LENGTH_SHORT).show();
return;
}
Intent intent = new Intent(this, userdetail_activ2.class);
intent.putExtra(EXTRA_HEIGHT,A);
intent.putExtra(EXTRA_WEIGHT,B);
intent.putExtra(EXTRA_GENDER,gend);
startActivity(intent);
return;
}
}
EditText editText = (EditText) findViewById(R.id.editText6);
EditText editText2 = (EditText) findViewById(R.id.editText9);
Never call methods that you inherit from Activity until after super.onCreate() has been called, unless documented otherwise.
Never call findViewById() until after the widgets exist, such as being created via a call to setContentView().
Move the initialization of these two fields until after setContentView() is called in onCreate().
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
enter image description hereWhen I open my Android application it crashes. Here is the code:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button requestButton;
private TextView coordinateText;
private LocationManager locationManager;
private LocationListener locationListener;
private Button buttonMap;
private Button buttonCurrentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//reference requestButton
requestButton = (Button) findViewById(R.id.requestButton);
//reference coordText
coordinateText = (TextView) findViewById(R.id.coordinateText);
// Creating button object for buttonMap
buttonMap = (Button) findViewById(R.id.buttonMap);
//Create a button object for buttonCurrentLocation
buttonCurrentLocation = (Button) findViewById(R.id.buttonCurrentLocation);
//Action listener for buttonMap
buttonMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent1);
}
});
// Action listener for buttonCurrentLocation
buttonCurrentLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), GPSShow.class);
startActivity(i);
}
});
//Initialize locationManager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Initialize locationListener
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
coordinateText.append("\n" + location.getLatitude() + " " + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent2 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent2);
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET
}, 10);
}
return;
} else {
configureButton();
}
}
//OUTSIDE ONCREATE METHOD
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
configureButton();
return;
}
}
private void configureButton() {
requestButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
});
}
}
Here is the logcat:
01-15 17:10:18.088 2340-2340/com.example.matt.palt E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.matt.palt, PID: 2340
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.matt.palt/com.example.matt.palt.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
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 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.matt.palt.MainActivity.configureButton(MainActivity.java:124)
at com.example.matt.palt.MainActivity.onCreate(MainActivity.java:103)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
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)
01-15 17:10:20.435 2340-2340/com.example.matt.palt I/Process: Sending signal. PID: 2340 SIG: 9
The first time I ran the application it was running fine.
It seems that the problem is the requestButton. I have tried looking further for a solution but can't find one.
Main XML file and other XML file
R.id.buttonMap is not found, resulting in null from findViewById(R.id.buttonMap).
The id buttonMap should be in your activity_main xml file. It is not.
From logcat its clear that the button requestButton is null. Seems your java code is right and the problem is in your layout. The id requestButton is not exactly the same in your xml file. Do match your xml with java code
this is error m getting.. i have interview.. n i need to show this app.. but getting error.. plz help.. the app was running an hour back fluently.. i was trying to put logout button on main activity to come back on login activity but lost login button function itself...
01-18 11:59:14.938 7321-7321/info.androidhive.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.materialdesign, PID: 7321
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialdesign/info.androidhive.materialdesign.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2373)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5375)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.androidhive.materialdesign.activity.MainActivity.onClickButtonListener3(MainActivity.java:51)
at info.androidhive.materialdesign.activity.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6865)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2326)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5375)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
this is my Login.java
package info.androidhive.materialdesign.activity;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import info.androidhive.materialdesign.R;
import info.androidhive.materialdesign.db.sqlitedb;
public class Login extends Activity {
sqlitedb sqlitehelper;
SQLiteDatabase db;
private static Button btn_login, btn_back;
EditText emailEditText, passwordEditText;
int i;
int flag;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
onClickButtonListener1();
onClickButtonListener2();
btn_login.setClickable(true);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onClickButtonListener1()
{
btn_back = (Button)findViewById(R.id.back_1);
btn_back.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent("info.androidhive.materialdesign.activity.Home");
// startActivity(i);
finish();
}
}
);
}
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
btn_login.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
onLoginClick(v);
}
}
);
}
public void onLoginClick(View v) {
if (v.getId() == R.id.login_1)
{
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password))
{
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
finish();
}
else
{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
You initialize the login button in the onCreate() here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
and then you call the onClickButtonListener2(); in which you initialize the button again in here:
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
So just do this:
call this onClickButtonListener2(); method in onCreate() and modify code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
btn_login.setClickable(true);
onClickButtonListener1();
onClickButtonListener2();
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
and change the onClickButtonListener2(); to:
public void onClickButtonListener2(){
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password)){
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
YourActivity.this.finish();
}else{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
);
}
Hope it helps!!!