android


Unable to store a string in session using SharedPreferences in android


i am trying to store city name at Splash Screen, after getting city name using Geocoder i am trying to store it in Session and use it in anther activity. But app is getting crash after adding session object.
below is my session.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.security.PublicKey;
import java.util.HashMap;
public class Session {
private SharedPreferences sp;
private SharedPreferences.Editor spEditor;
public Session(Context context) {
sp = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setLocation(String city){
spEditor.putString("UserCity", city);
spEditor.commit();
}
and my SplashActivity.java
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.location.LocationTrack;
import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class SplashActivity extends AppCompatActivity {
TextView welcomeText;
ImageView mLogo;
ImageView zbgimg;
Typeface tf1;
private Session session;
private ArrayList<String> permissionsToRequest;
private ArrayList<String> permissionsRejected = new ArrayList<>();
private ArrayList<String> permissions = new ArrayList<>();
private final static int ALL_PERMISSIONS_RESULT = 101;
LocationTrack locationTrack;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
session = new Session(SplashActivity.this);
//GPS Tracker
permissions.add(ACCESS_FINE_LOCATION);
permissions.add(ACCESS_COARSE_LOCATION);
permissionsToRequest = findUnAskedPermissions(permissions);
//get the permissions we have asked for before but are not granted..
//we will store this in a global list to access later.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0)
requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]), ALL_PERMISSIONS_RESULT);
}
locationTrack = new LocationTrack(SplashActivity.this);
if (locationTrack.canGetLocation()) {
double longitude = locationTrack.getLongitude();
double latitude = locationTrack.getLatitude();
Geocoder gcd = new Geocoder(SplashActivity.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getLocality();
String address = addresses.get(0).getAddressLine(0);
String state = addresses.get(0).getAdminArea();
String countryn = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
session.setLocation(locality);
//Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();
}
} else {
locationTrack.showSettingsAlert();
}
welcomeText = (TextView) findViewById(R.id.welcome);
tf1 = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
welcomeText.setTypeface(tf1);
mLogo = (ImageView) findViewById(R.id.applogo);
zbgimg = (ImageView) findViewById(R.id.zbgimg);
zbgimg.setImageResource(R.drawable.splash_screen_option_three);
animation2();
animation3();
new Handler().postDelayed(new Runnable() {
#SuppressLint("PrivateResource")
#Override
public void run() {
if (session.FbLoggedIn()) {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
} else {
Intent i = new Intent(SplashActivity.this,
LoginActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.entry, R.anim.exit);
}
}
}, 3000);
}
private void animation2() {
mLogo.setAlpha(1.0F);
Animation anim = AnimationUtils.loadAnimation(SplashActivity.this, R.anim.translate_top_to_center);
mLogo.startAnimation(anim);
}
private void animation3() {
ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(welcomeText, "alpha", 0.0F, 1.0F);
alphaAnimation.setStartDelay(1700);
alphaAnimation.setDuration(500);
alphaAnimation.start();
}
///GPS Tracker
private ArrayList<String> findUnAskedPermissions(ArrayList<String> wanted) {
ArrayList<String> result = new ArrayList<String>();
for (String perm : wanted) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (canMakeSmores()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
}
}
return true;
}
private boolean canMakeSmores() {
return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case ALL_PERMISSIONS_RESULT:
for (String perms : permissionsToRequest) {
if (!hasPermission(perms)) {
permissionsRejected.add(perms);
}
}
if (permissionsRejected.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissionsRejected.toArray(new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
}
}
});
return;
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(SplashActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
locationTrack.stopListener();
}
}
i could able to see the city name in
Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();
but unable to store it in session. my session.jave is working fine with other Activity. bellow is Logcat:
05-11 22:36:15.966 3836-3836/
zesteve.com.myapplication E/AndroidRuntime:
FATAL EXCEPTION: main
Process: zesteve.com.myapplication, PID: 3836
java.lang.RuntimeException:
Unable to start activity ComponentInfo
{zesteve.com.myapplication/zesteve.com.myapplication.SplashActivity}:
java.lang.NullPointerException: Attempt to invoke interface method
android.content.SharedPreferences$Editor
android.content.SharedPreferences
$Editor.putString(java.lang.String,
java.lang.String)
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2439)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2499) at android.app.ActivityThread.access$900(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
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 interface method android.content.SharedPreferences$Editor
android.content.SharedPreferences$Editor.putString(java.lang.String, java.lang.String)
on a null object reference
at zesteve.com.myapplication.Session.setLocation(Session.java:71)
at zesteve.com.myapplication.SplashActivity.onCreate(SplashActivity.java:100)
at android.app.Activity.performCreate(Activity.java:6556)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2499)
at android.app.ActivityThread.access$900(ActivityThread.java:166)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1360)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
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)
you are not initialized preference editor you have to make change below
public void setLocation(String city){
spEditor=sp.edit();//// make sure sp also initialized
spEditor.putString("UserCity", city);
spEditor.commit();
}
Your spEditor variable is null because you don't initialize it to anything.
Try this for your session.java constructor.
public Session(Context context) {
sp = PreferenceManager.getDefaultSharedPreferences(context);
spEditor = sp.edit();
}
Check that all the fields in variable SharedPreferences.Editor spEditor; are initialized. Check your setter method.

Related Links

Get all Facebook profile pics (From profile album) Android Sdk 4.0
Adding custom button shape to button causes it to increase in height android
Android realm NoSuchMethodError: No virtual method addChangeListener
Uploading multiple artifacts from a gradle project
Android navigation icon alignment to right
Parsing String to int on TextChangedListener
Fail to find provider info com
group the string name in arraylist by the first letter android
Geofencing limit with Android
Osmdroid marker not updating
How to produce dyamic colors for Android visualizer
Hide floating action button child in another fragment
The dimAmount and FLAG_DIM_BEHIND set for DialogFragment are not reflected on UI
want to keep the screen on on a android-device using “FLAG_KEEP_SCREEN_ON” method in delphi (not the wakelock method) [duplicate]
Get unique identifier for ContextMenu in Android?
Force users of a specific devices to install a particular version on Google Play Store

Categories

HOME
grok
polymer
character-encoding
apache-spark-mllib
database-normalization
rom
limit
jetty
pearson-correlation
vsm
vert.x
dkim
xcodebuild
renjin
coin3d
keytool
scsi
job-scheduling
null-pointer
dimensional-modeling
sse
cfml
sar
ksh
php-mysqlidb
dapper-extensions
windows-server-2003
google-cloud-print
fable-f#
oculus
android-maps
winexe
testbed
git-squash
linkedhashmap
reactjs.net
carriage-return
slacktextviewcontroller
graphhopper
cd
bc
demo
cin
unordered-map
apriori
congestion-control
plan-9
double-click
automapper-5
user-defined-fields
dbcontext
activeperl
x-ray
amq
custom-font
boxing
colorbar
git-flow
jqchart
er-diagram
libjpeg
java-websocket
d3-force-directed
trigger.io
swingworker
visual-studio-2008-sp1
chromium-os
pure-css
cubism.js
synonym
eigenvector
embedding
google-query-language
grass
invoke-sqlcmd
false-sharing
asyncdisplaykit
state-restoration
sciruby
jdi
rubaxa-sortable
canalyzer
skspritenode
apache-commons-daemon
botan
mraid
at-job
big-ip
formview
jama
dot42
jammer
model-driven-development
dolby-audio-api
octal
mantle
idn
saleslogix
wcf-configuration
lambdaj
ikimagebrowserview
massive
dataform
msr
codebase
squishit
uideviceorientation
office-2007
eclipse-marketplace
zend-rest
filesystemobject
data-mapping

Resources

Encrypt Message