Home > Software design >  Cannot get the value from sharedPrefenced
Cannot get the value from sharedPrefenced

Time:12-01

Hey guys again with my question
So as in the title, my apps need data from another activity using sharedPreferenced
So far so good I got the data I store WHEN I click the button but when i tried to get the data on the onCreate it just crashing with this error code:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.test.aplikasirevisi, PID: 28272
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.aplikasirevisi/com.test.aplikasirevisi.Information}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
        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:1831)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6810)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.test.aplikasirevisi.Information.onCreate(Information.java:33)
        at android.app.Activity.performCreate(Activity.java:7224)
        at android.app.Activity.performCreate(Activity.java:7213)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) 
        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:1831) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:201) 
        at android.app.ActivityThread.main(ActivityThread.java:6810) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
I/Process: Sending signal. PID: 28272 SIG: 9

It says it's null but when I click the button it's giving me the data though

Here is my code:
Information.Java

package com.test.aplikasirevisi;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;

public class Information extends Activity {
    SharedPreferences sharedpreferences;
    TextView name;
    TextView phonenum;
    TextView highest;
    TextView lowest;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String PhoneNum = "phonenumKey";
    public static final String Highest = "highestKey";
    public static final String Lowest = "lowestKey";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.information);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(PhoneNum)) {
            phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
        }
        if (sharedpreferences.contains(Highest)) {
            highest.setText(sharedpreferences.getString(Highest, ""));
        }
        if (sharedpreferences.contains(Lowest)) {
            lowest.setText(sharedpreferences.getString(Lowest, ""));
        }
    }
    public void Save(View view) {
        String n = name.getText().toString();
        String p = phonenum.getText().toString();
        String h = highest.getText().toString();
        String l = lowest.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(PhoneNum, p);
        editor.putString(Highest, h);
        editor.putString(Lowest, l);
        editor.commit();
    }
    public void clear(View view) {
        name = (TextView) findViewById(R.id.etName);
        phonenum = (TextView) findViewById(R.id.etPhoneNum);
        highest = (TextView) findViewById(R.id.etHighest);
        lowest = (TextView) findViewById(R.id.etLowest);
        name.setText("");
        phonenum.setText("");
        highest.setText("");
        lowest.setText("");
    }
    public void Get(View view) {
        name = (TextView) findViewById(R.id.etName);
        phonenum = (TextView) findViewById(R.id.etPhoneNum);
        highest = (TextView) findViewById(R.id.etHighest);
        lowest = (TextView) findViewById(R.id.etLowest);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(PhoneNum)) {
            phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
        }
        if (sharedpreferences.contains(Highest)) {
            highest.setText(sharedpreferences.getString(Highest, ""));
        }
        if (sharedpreferences.contains(Lowest)) {
            lowest.setText(sharedpreferences.getString(Lowest, ""));
        }
    }

}

MonitoringScreen.Java

package com.test.aplikasirevisi;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import static com.test.aplikasirevisi.Information.Highest;
import static com.test.aplikasirevisi.Information.Lowest;
import static com.test.aplikasirevisi.Information.mypreference;


public class MonitoringScreen extends Activity {
    private static final String TAG = "BlueTest5-MainActivity";
    private int mMaxChars = 50000;//Default
    private UUID mDeviceUUID;
    private BluetoothSocket mBTSocket;
    private ReadInput mReadThread = null;
    TextView highest;
    TextView lowest;
    private boolean mIsUserInitiatedDisconnect = false;

    private TextView mTxtReceive;
    private Button mBtnClearInput;
    private Button mBtnGetBPM;
    private ScrollView scrollView;
    private CheckBox chkScroll;
    private CheckBox chkReceiveText;


    private boolean mIsBluetoothConnected = false;

    private BluetoothDevice mDevice;

    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitoring_screen);
        ActivityHelper.initialize(this);

        Intent intent = getIntent();
        Bundle b = intent.getExtras();
        mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
        mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
        mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
        Log.d(TAG, "Ready");
        mTxtReceive = (TextView) findViewById(R.id.txtReceive);
        chkScroll = (CheckBox) findViewById(R.id.chkScroll);
        chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
        scrollView = (ScrollView) findViewById(R.id.viewScroll);
        mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
        mBtnGetBPM = (Button) findViewById(R.id.mBtnGetBPM);
        mTxtReceive.setMovementMethod(new ScrollingMovementMethod());

        mBtnClearInput.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                mTxtReceive.setText("");
            }
        });
        mBtnGetBPM.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {

                highest = (TextView) findViewById(R.id.etHighest);
                lowest = (TextView) findViewById(R.id.etLowest);
                SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
                        Context.MODE_PRIVATE);
                if (sharedpreferences.contains(Highest)) {
                    highest.setText(sharedpreferences.getString(Highest, ""));
                }
                if (sharedpreferences.contains(Lowest)) {
                    lowest.setText(sharedpreferences.getString(Lowest, ""));
                }
            }
        });
    }
    private class ReadInput implements  Runnable{
        private boolean bStop = false;
        private Thread t;

        public ReadInput() {
            t = new Thread(this, "Input Thread");
            t.start();
        }

        public boolean isRunning() {
            return t.isAlive();
        }

        @Override
        public void run() {
            InputStream inputStream;

            try {
                inputStream = mBTSocket.getInputStream();
                while (!bStop) {
                    byte[] buffer = new byte[256];
                    if (inputStream.available() > 0) {
                        inputStream.read(buffer);
                        int i;
                        /*
                         * This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
                         */
                        for (i = 0; i < buffer.length && buffer[i] != 0; i  ) {
                        }
                        final String strInput = new String(buffer, 0, i);
                        String getHi = null;


                        SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
                                Context.MODE_PRIVATE);
                        if (sharedpreferences.contains(Highest)) {
                            highest.setText(sharedpreferences.getString(Highest, ""));
                            getHi=highest.getText().toString();
                        }
                        if (sharedpreferences.contains(Lowest)) {
                            lowest.setText(sharedpreferences.getString(Lowest, ""));
                        }
                        int hi = Integer.parseInt(getHi);

                        /*
                         * If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
                         */

                        if (chkReceiveText.isChecked()) {
                            mTxtReceive.post(new Runnable() {
                                @Override
                                public void run() {
                                    int data = Integer.parseInt(strInput);
                                    mTxtReceive.append(strInput);

                                    int txtLength = mTxtReceive.getEditableText().length();
                                    if(txtLength > mMaxChars){
                                        mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);
                                        Log.d(TAG, "text longer than allowed:"   mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars));
                                        Log.d(TAG, strInput);
                                        if(data > hi){
                                            Log.d(TAG, "Success");
                                        }
                                    }

                                    if (chkScroll.isChecked()) { // Scroll only if this is checked
                                        scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
                                            @Override
                                            public void run() {
                                                scrollView.fullScroll(View.FOCUS_DOWN);
                                            }
                                        });
                                    }
                                }
                            });
                        }

                    }
                    Thread.sleep(500);
                }
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public void stop() {
            bStop = true;
        }

    }
    private class DisConnectBT extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Void doInBackground(Void... params) {

            if (mReadThread != null) {
                mReadThread.stop();
                while (mReadThread.isRunning())
                    ; // Wait until it stops
                mReadThread = null;

            }

            try {
                mBTSocket.close();
            } catch (IOException e) {
// TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mIsBluetoothConnected = false;
            if (mIsUserInitiatedDisconnect) {
                finish();
            }
        }

    }
    private void msg(String s) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onPause() {
        if (mBTSocket != null && mIsBluetoothConnected) {
            new DisConnectBT().execute();
        }
        Log.d(TAG, "Paused");
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mBTSocket == null || !mIsBluetoothConnected) {
            new ConnectBT().execute();
        }
        Log.d(TAG, "Resumed");
        super.onResume();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "Stopped");
        super.onStop();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    private class ConnectBT extends AsyncTask<Void, Void, Void> {
        private boolean mConnectSuccessful = true;

        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MonitoringScreen.this, "Hold on", "Connecting");// http://stackoverflow.com/a/11130220/1287554
        }

        @Override
        protected Void doInBackground(Void... devices) {

            try {
                if (mBTSocket == null || !mIsBluetoothConnected) {
                    mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    mBTSocket.connect();
                }
            } catch (IOException e) {
// Unable to connect to device
                e.printStackTrace();
                mConnectSuccessful = false;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (!mConnectSuccessful) {
                Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
                finish();
            } else {
                msg("Connected to device");
                mIsBluetoothConnected = true;
                mReadThread = new ReadInput(); // Kick off input reader
            }

            progressDialog.dismiss();
        }

    }
}

As you can see I tried to automatically get the Highest bpm dan Lowest bpm but it spans the same error so I'm in a pickle now so if anyone can help with it dan fast I'll be grateful for that. And sorry for my English it's not my first language so I can't express it really well.

CodePudding user response:

The TextView in your Information.Java are not assigned to anything within your onCreate method before you try calling the setText method. This is what the error is complaining about.

Your assignments are in the clear(View view) method for some reason.... they should be in the onCreate method.

i.e move

        name = (TextView) findViewById(R.id.etName);
        phonenum = (TextView) findViewById(R.id.etPhoneNum);
        highest = (TextView) findViewById(R.id.etHighest);
        lowest = (TextView) findViewById(R.id.etLowest);

out of the clear and get methods and into the onCreate method like:

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.information);

        name = (TextView) findViewById(R.id.etName);
        phonenum = (TextView) findViewById(R.id.etPhoneNum);
        highest = (TextView) findViewById(R.id.etHighest);
        lowest = (TextView) findViewById(R.id.etLowest);

        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(PhoneNum)) {
            phonenum.setText(sharedpreferences.getString(PhoneNum, ""));
        }
        if (sharedpreferences.contains(Highest)) {
            highest.setText(sharedpreferences.getString(Highest, ""));
        }
        if (sharedpreferences.contains(Lowest)) {
            lowest.setText(sharedpreferences.getString(Lowest, ""));
        }
    }
  • Related