This is goign to be very simple i expect to sort out and just me being a newbie going about in circles.
I have multiple tabs across my screen. The following code should read a text input and assign its value to Shared Preferences when another tab is selected. However, whenever i change to another tab my code fails with a NullPointerException – I believe i have tracked it down to the onPause() of the below code, and I believe it is because i am failing to pass the data within the variable correctly.
Any pointers appreciated!
package com.androidbook.epcsn;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
@SuppressWarnings("unused")
public class jobActivity extends Activity {
public static final String SN_PREFERENCES = "SiteNotePrefs";
SharedPreferences mPrefSettings;
String jobID;
String jobAddress ;
String jobPostcode ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.joblayout);
final SharedPreferences mPrefSettings = getSharedPreferences (SN_PREFERENCES, Context.MODE_WORLD_WRITEABLE);
initjobID();
initjobaddress();
initjobpostcode();
}
private void initjobpostcode() {
EditText jobPostcode = (EditText)findViewById(R.id.jobPostcodeText);
}
private void initjobaddress() {
EditText jobAddress = (EditText)findViewById(R.id.jobAddressText);
}
private void initjobID() {
EditText jobID = (EditText)findViewById(R.id.jobIDText);
}
@Override
protected void onPause(){
super.onPause();
String strjobID = jobID;
String strjobAddress = jobAddress;
String strjobPostcode = jobPostcode;
Editor editor = mPrefSettings.edit();
editor.putString("jobID", strjobID);
editor.putString("jobAddress", strjobAddress);
editor.putString("jobPostcode", strjobPostcode);
editor.commit();
}
}
You set values to local variables in the
initmethods, not the class properties as intended, e.g.:The property
jobIDis shadowed by the localjobIDdeclared in the method.(Java conventions would name the method
initJobId, and the propertyjobId).To set instance properties in the init methods, remove the local declarations and use this pattern: