无法使用android

时间:2017-05-11 17:30:43

标签: android session android-sharedpreferences

我想在使用Geocoder获取城市名称后,在Splash Screen中存储城市名称我试图将其存储在Session中并在其他活动中使用它。但是在添加会话对象后,应用程序正在崩溃。

下面的

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

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


}

我能够在

中看到城市名称
Toast.makeText(SplashActivity.this,locality +" "+ postalCode + " " + latitude+ " " + longitude,Toast.LENGTH_SHORT).show();

但无法将其存储在会话中。我的session.jave与其他Activity一起正常工作。波洛是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) 

3 个答案:

答案 0 :(得分:1)

您未初始化首选项编辑器,您必须在下面进行更改

[PXSelector(typeof(Search<TableTwo.someOtherField,
    Where<TableTwo.someRelatedField, Equal<Current<HeaderTable.relatedField>>>))]

答案 1 :(得分:1)

您的public Session(Context context) { sp = PreferenceManager.getDefaultSharedPreferences(context); spEditor = sp.edit(); } 变量为空,因为您没有将其初始化为任何内容。

尝试使用session.java构造函数。

{{1}}

答案 2 :(得分:0)

检查变量SharedPreferences.Editor spEditor;中的所有字段是否已初始化。检查你的setter方法。