Home > Net >  Android Studio: Issue with OnResume and SharedPreferences: Fatal Error at Runtime
Android Studio: Issue with OnResume and SharedPreferences: Fatal Error at Runtime

Time:02-01

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();
            }

        }

    }
}`

CodePudding user response:

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