Null Pointer using SharedPreferences - java

I am passing and showing values from one activity to another activity, and making file name using those string like this:
AU_20140312_160107_65.jpg
AU - simple prefix
20140312_160107 - yyyyMMdd_HHmmss
6 - event_id (getting from LoginActivity.java)
5 - operative_id (getting from LoginActivity.java)
see my code below:
LoginActivity.java:
static SharedPreferences sharedprefs;
static String event_id, operative_id ;
sharedprefs = getApplicationContext().getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Intent intent = getIntent();
event_id = intent.getStringExtra("event_id");
sharedprefs.edit().putString("EVENT_ID", event_id).commit();
operative_id = intent.getStringExtra("operative_id");
sharedprefs.edit().putString("OPERATIVE_ID", operative_id).commit();
CameraLauncherActivity.java:
static File getOutputMediaFile() {
String event_ID = LoginActivity.sharedprefs.getString("EVENT_ID", null);
Log.d("shared >>> eventID : ", event_ID);
String operative_ID = LoginActivity.sharedprefs.getString("OPERATIVE_ID", null);
Log.d("shared >>> operativeID : ", operative_ID);
timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
// file name
mediaFile = new File(LoginActivity.mediaStorageDir.getPath() + File.separator
+ "AU_" + timeStamp + "_" + event_ID + operative_ID + ".jpg");
return mediaFile;
}
when launching first time, Log says:
shared >>> eventID :(29917): 12
shared >>> operativeID :(29917): 4
like you can see above, everything works fine, and getting eventID and operativeID using log as well
but once i will launch my app again, after closing it, and caputre image, then getting NPE and Log :
FATAL EXCEPTION: main
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native(Native Method)
at android.util.Log.d(Log.java:155)
app.mac.Camera.CameraLauncherActivity.getOutputMediaFile(CameraLauncherActivity.java:386)
at app.mac.Camera.CameraLauncherActivity$2.onPictureTaken(CameraLauncherActivity.java:362)
at android.hardware.Camera$EventHandler.handleMessage(Camera.java:789)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)
at dalvik.system.NativeStart.main(Native Method)

Instead of assigning the values directly to the variables event_id and operative_id store them in the db or preferences.
Instead of directly assigning like this this :
event_id = intent.getStringExtra("event_id");
operative_id = intent.getStringExtra("operative_id");
check the intent.getStringExtra("event_id") and intent.getStringExtra("operative_id") for null.
If null fetch from stored values.
If not null assign to variables and overwrite stored values with the new one for next time.

//Initialization
SharedPreferences _mypref = getApplicationContext().getSharedPreferences("mypref", 0);
//store data in shared preferences
Editor editor = _mypref.edit();
//Storing boolean - true/false;
editor.putBoolean("key_name", true);
//Storing string
editor.putString("key_name", "string value");
//Storing integer
editor.putInt("key_name", "int value");
//Storing float
editor.putFloat("key_name", "float value");
//Storing long
editor.putLong("key_name", "long value");
//commit changes
editor.commit();
// retrive data
//getting String
_mypref .getString("key_name", null);
//getting Integer
_mypref .getInt("key_name", null);
//getting Float
_mypref .getFloat("key_name", null);
//getting Long
_mypref .getLong("key_name", null);
//getting boolean
_mypref.getBoolean("key_name", null);
//remove Data
editor.remove("name");
editor.commit();
//Clear all Data
editor.clear();
editor.commit();

Related

How to properly append text to TextView from SharedPreferences file instead of overwriting it?

I have two classes, one class is saving weight, then in the other class/ activity I want a log that appends the weight along with the date and time, then makes a new line and displays the next weight. This way the user can keep track of their daily weight changes.
Problem is I'm brand new to Java and clearly am getting stuck on a silly problem. Each time I try append it instead just overwrites. I probably need to save it and then add it? maybe? I've tried a few different things and nothing is working all that well.
This is day 3 of Java. Apologies.
Tried making a list that is saved with sharedpreferences. Either did it wrong or it didnt work. Also tried just calling for the weight and appending it, but it overwrites it all.
My Logging activity:
public class LogActivity extends AppCompatActivity {
TextView logger;
//TextView more;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Button back = findViewById(R.id.btnBack);
logger = findViewById(R.id.txtLog);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
SharedPreferences log = getSharedPreferences("MyPrefsFile", 0);
//Float value = log.getFloat("floatingLog",0);
Float value = log.getFloat("weight", 0);
//more.append(logger + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
logger.append("Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n");
// Adding back button
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v){
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
// SharedPreferences settings7 = getSharedPreferences("PREFS",0);
// String wordsString = settings7.getString("words","");
// String[] itemWords = wordsString.split(",");
// List<String> items = new ArrayList<String>();
// for (int i = 0; i < itemWords.length; i++){
// items.add(itemWords[i]);
// }
// for (int i = 0; i < items.size(); i++){
// Log.d("list", items.get(i));
// }
}
}
This is getting the sharedpreferences from here, in my ProfileActivity:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((TextView) findViewById(R.id.txtWeight)).setText(findViewById(R.id.txtNewWeight).toString());
floatingLog = weight.toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
floatingWeight = Float.valueOf(newWeight.getText().toString());
editor.putString("floatingLog", floatingLog);
editor.putFloat("weight", floatingWeight);
editor.apply();
editor.commit();
weight.setText(String.valueOf(floatingWeight));
Hello and welcome to SO!
actually in TextView, you can access to current value via TextView#getText() and after that you can update the text value similarly using TextView#setText(String text)
so you need to write something like this:
String currentText = logger.getText();
String updatedText = currentText + "Weight: " + value.toString() + " at: " + dateFormat.format(date) + "\n";
logger.setText(updatedText)
tada !
UPDATE
I think your problem is with how you save your records in your sharedPrefs
in this line
editor.putFloat("weight", floatingWeight); in this part you are overwriting the existing value,
simplest approach that comes to my mind is that instead of saving weight like this, you create an array of weights and append to end of it every day and store the array.
how ever it will be far more better if you use data base for this which gives you far more flexibility.
to use database take a look at Android official orm Android Room it is very simple and straightforward

Skip inserting if value is null in SQLite

While inserting to Android SQLite Database I want to skip the values that user did not fill.
But I am getting null pointer exception.
In my DBHelper class I tried both "... NOT NULL" and without not null option but I think it is not the solution.
public void addToDb(View view) {
SharedPreferences sharedPreferences = getSharedPreferences("entry",0);
float lastlatitude = sharedPreferences.getFloat("latitude",0f);
float lastlongitude = sharedPreferences.getFloat("longitude",0f);
if (mTitleInput.getText().length() == 0 ||
mEntryInput.getText().length() == 0) {
return;
}
try {
Date a = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, ''yy");
String o = sdf.format(a);
title = mTitleInput.getText().toString();
entry = mEntryInput.getText().toString();
dateStr = o;
image = getApplicationContext().getFilesDir().getAbsolutePath() + String.valueOf(System.currentTimeMillis()) + ".jpg";
rating = mRatingBar.getRating();
latitude = lastlatitude;
longitude = lastlongitude;
} catch (NumberFormatException ex) {
Log.e(LOG_TAG, "Failed to parse party size text to number: " + ex.getMessage());
}
// Add to mDb
addNewEntry(title, entry, dateStr, image, rating, latitude, longitude);
//clear UI text fields
mTitleInput.getText().clear();
mEntryInput.getText().clear();
}
EDIT 1 : Stacktrace.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aok.secretdiarywithlock, PID: 29148
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
at com.aok.secretdiarywithlock.CreateEntry.addNewEntry(CreateEntry.java:157)
at com.aok.secretdiarywithlock.CreateEntry.addToDb(CreateEntry.java:139)
at com.aok.secretdiarywithlock.CreateEntry$1.onClick(CreateEntry.java:93)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
EDIT 2 : Error code
private long addNewEntry(String title, String entry, String date, String image, Float rate, Float latitude, Float longitude){
ContentValues cv = new ContentValues();
cv.put(EntryContract.EntryEntry.COLUMN_TITLE,title);
cv.put(EntryContract.EntryEntry.COLUMN_TEXT,entry);
cv.put(EntryContract.EntryEntry.COLUMN_DATE,date);
cv.put(EntryContract.EntryEntry.COLUMN_IMAGE,image);
cv.put(EntryContract.EntryEntry.COLUMN_TEXT,entry);
cv.put(EntryContract.EntryEntry.COLUMN_RATING,rate);
cv.put(EntryContract.EntryEntry.COLUMN_LOCATION_LAT,latitude);
cv.put(EntryContract.EntryEntry.COLUMN_LOCATION_LONG,longitude);
// Next line is throwing error
return mDb.insert(EntryContract.EntryEntry.TABLE_NAME, null, cv);
}
Hi you have to check if they are null for example
dateStr = o == null ? "" : o;
this will check if o is null if it is it will set dateStr to empty, if not it will use o. you can use that for all of your variables.

How to save web page informations?

I want my app to check some web page only once a day, so I want the data to be saved anded reloaded upon starting the app again.
I followed this tutorial, but I can not save the result with MainActivity extends AppCompatActivity:
String url = "https://en.wikipedia.org/wiki/Main_Page";
SharedPreferences data;
SharedPreferences.Editor dataEditor;
String sDate = date.getString("date", "");
DateFormat df = new SimpleDateFormat("MMMM d");
String date = df.format(Calendar.getInstance().getTime());
if(sDate != date){ // <-- this does not work
new Date().execute();
}
and Date extends AsyncTask<Void, Void, Void>:
Document document = Jsoup.connect(url).get();
Elements date = document.select("div#mp-otd p b");
String sDate = date.getText();
dataEtitor.setString("date", sDate)
dataEtitor.commit;
The "Date extends AyncTask" class always start.
editor.commit() is used in order to save changes to shared preferences.
Add below line of code after setString
dataEtitor.commit(); // commit changes
SharedPreferences Example as follow
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing or Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes
You muss use !(sDate.equals(date) in place of sDate != date, because the Strings are new and so they can not be compare each other.

Creating arraylist from a string with shared preferences

I want to know how to take a simple string that is being saved in shared preferences but then save each one of those strings and display them into an array list. The user will save the string once a day. And I want the strings to display as an array list. Here's the code for what I'm working with. I have "physical_fragment.java"(SAVES THE DATA) & "MainActivity.java"(LOADS THE DATA).
PHSYICAL_FRAGMENT.JAVA
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
MAINACTIVITY.JAVA
resultPhysical= (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String result= sharedPreferences.getString("result",DEFAULT);
if (result.equals(DEFAULT))
{
Toast.makeText(this, "No data found", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(this, "Load Successful", Toast.LENGTH_LONG).show();
resultPhysical.setText(result);
}
I'd say use GSON for that.
To convert a list of strings to JSON to be stored in preferences you use this:
List<String> list = ...
Type type = new TypeToken<List<String>>(){}.getType();
String json = gson.toJson(list, type);
and store json in SharedPreferences using putString.
To read from SharedPreferences you use something like this:
String result = sharedPreferences.getString("result", DEFAULT);
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = gson.fromJson(result, type);
you can do as follows:
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
ArratList<String> dataList;
String data = "";
for(String itemData:dataList){
data = itemData + String.format(stringDate, date) + " - " + text_view5.getText().toString()+ "/";
editor.putString(data);
}
editor.commit();
Now get the string from Shared preference and split it.
String result= sharedPreferences.getString("result",DEFAULT);
String[] splited = str.split("/");
This helps with out having support of Libraries which can effect size of apk file

Create a List of saves from one button

I need help with my project. I need to be able to press a save button that uses shared preferences, and every time I press that button, I need it to take the saved data and stack it underneath each other like a list. The key value is "result". So the save button takes the string and integer and places it onto my Main activity XML layout. But, if I press save again with different integers or string it will replace the original string and integer I had originally saved. I want it to be able to keep the original string and integer if i save it for the first time and make a new string and integer underneath the original if i do a second time and so on forever. Please help!
This is under my saving activity:
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
This is under my loading activity:
resultPhysical = (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String physicalresult = sharedPreferences.getString("result", DEFAULT);
String physicalresult2= sharedPreferences.getString("result2", DEFAULT);
if (physicalresult.equals(DEFAULT)){
Toast.makeText(this,"No Data Found", Toast.LENGTH_LONG).show();
}
else{
resultPhysical.setText(physicalresult);
}
}
You can easily save them, just create an extra variable that refers to the size of saved results so that you can loop over them. To start saving, get the size then save with the index
int size = sharedPreferences.getInt("size", 0); // if it doesn't exist, get 0
// then save the result like
editor.putString("result" + String.valueOf(size), String.format(stringDate, date) + " - " + text_view5.getText().toString()); // just add index to result
// then increase the size
editor.putInt("size", ++size);
editor.commit();
To load the results
StringBuilder results = new StringBuilder();
int size = int size = sharedPreferences.getInt("size", 0); // get the size to start looping
if(size == 0){ // if results are empty
// show toast there is no saved result
} else { //start looping
for(int i = 0; i < size; i++){
String temp = sharedPreferences.getString("result" + String.valueOf(i), DEFAULT);
results.append(temp + " ");
}
resultPhysical.setText(results.toString());
}

Categories