简体   繁体   English

SharedPreferences提供某些设备上的默认值

[英]SharedPreferences gives default values on some devices

I am using this code to save key-value pair in shared preferences and its working fine on my device but on emulators and other real devices, it always returns the default values. 我正在使用此代码将键值对保存在共享首选项中,并且可以在我的设备上正常工作,但是在模拟器和其他实际设备上,它始终返回默认值。

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

public static final String USER_PREFS = "com.aamir.friendlocator.friendlocator.USER_PREFERENCE_FILE_KEY";
SharedPreferences sharedPreferences;

private static String userKey="";

GoogleApiClient mGoogleApiClient;
Location mLastLocation;

static final int PERMISSION_ACCESS_FINE_LOCATION = 1;
boolean FINE_LOCATION_PERMISSION_GRANTED = false;



TextView textViewLocationData;
TextView textViewKeyDisplay;
Button buttonRefresh;
Button btnCopyKey;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            goToActivityFriends();
        }
    });
    fab.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_people_white_48dp));
    textViewLocationData = (TextView) findViewById(R.id.textViewLocationData);
     textViewKeyDisplay =(TextView) findViewById(R.id.tvKeyDisplay);
    buttonRefresh = (Button) findViewById(R.id.buttonRefresh);
    btnCopyKey = (Button) findViewById(R.id.btnCopyKey);
    sharedPreferences = getApplicationContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
    String key = sharedPreferences.getString("key", "");
    if(!key.equals("")) {
        textViewKeyDisplay.setText(key);
    }
    // Create an instance of GoogleAPIClient.
    buildGoogleApiClient();

    //user_sp = getSharedPreferences(USER_PREFS, 0);

    buttonRefresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            displayLocation();
        }
    });

    btnCopyKey.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("userKey", textViewKeyDisplay.getText().toString());
            clipboard.setPrimaryClip(clip);
            Toast.makeText(getBaseContext(), "Key copied !", Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
protected void onStart() {
    super.onStart();
    if (mGoogleApiClient != null) mGoogleApiClient.connect();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
}

private void displayLocation() {

    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    if ( permissionCheck != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_ACCESS_FINE_LOCATION);

    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (mLastLocation != null) {
        double latitude = mLastLocation.getLatitude();
        double longitude = mLastLocation.getLongitude();

        textViewLocationData.setText(latitude + ", " + longitude);
        sharedPreferences = getApplicationContext().getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE);
        String key = sharedPreferences.getString("key", "");
        Log.d("User Key",key);
        updateServers(latitude, longitude,key);

    } else {
        textViewLocationData
                .setText("Couldn't get the location. Make sure location is enabled on the device");
    }
}
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_ACCESS_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                FINE_LOCATION_PERMISSION_GRANTED = true;
                //displayLocation();
            } else {
                FINE_LOCATION_PERMISSION_GRANTED = false;
            }
            return;
        }
    }
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    Log.i("", "Connection failed: ConnectionResult.getErrorCode() = "
            + result.getErrorCode());
}

@Override
public void onConnected(Bundle arg0) {

    // Once connected with google api, get the location
    //displayLocation();
}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();
}

public void goToActivityFriends () {
    Intent intent = new Intent(this, com.aamir.friendlocator.friendlocator.Friends.class);
    startActivity(intent);
}

public void updateServers(Double lat,Double lon,String Key) {
    if (Key.equals("")) {
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl("")
                .addConverterFactory(GsonConverterFactory.create());
        Retrofit retrofit = builder.build();
        SendLocation cleint = retrofit.create(SendLocation.class);

        Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call = cleint.registerUser(String.valueOf(lat), String.valueOf(lon), Key);

        call.enqueue(new Callback<com.aamir.friendlocator.friendlocator.Models.SendLocation>() {
            @Override
            public void onResponse(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Response<com.aamir.friendlocator.friendlocator.Models.SendLocation> response) {
                Log.d("Response", response.body().getUserKey());
                if (!response.body().getUserKey().isEmpty()) {

                    String key_user = response.body().getUserKey();
                    textViewKeyDisplay.setText(key_user);

                    // Writing data to SharedPreferences
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("key", userKey);
                    if(editor.commit()){
                        Log.d("saved","saved");
                    }



                }

            }

            @Override
            public void onFailure(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Throwable t) {
                Log.e("Response", t.toString());
            }
        });


    }
    else {
        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl("http://demoanalysis.com/pro03/FriendLocator/")
                .addConverterFactory(GsonConverterFactory.create());
        Retrofit retrofit = builder.build();
        SendLocation cleint = retrofit.create(SendLocation.class);

        Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call = cleint.updateLocation(String.valueOf(lat), String.valueOf(lon), Key);

        call.enqueue(new Callback<com.aamir.friendlocator.friendlocator.Models.SendLocation>() {
            @Override
            public void onResponse(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Response<com.aamir.friendlocator.friendlocator.Models.SendLocation> response) {
                Log.d("Response", response.body().getLocationStatus());
                if (!response.body().getLocationStatus().isEmpty()) {
                    Toast.makeText(MainActivity.this,response.body().getLocationStatus(),Toast.LENGTH_LONG).show();

                }

            }

            @Override
            public void onFailure(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Throwable t) {
                Log.e("Response", t.toString());
            }
        });

    }


}

} }

On some devices, it's working perfectly. 在某些设备上,它运行良好。 I did change context from this to getApplicationContext but no progress. 我确实将上下文从此更改为getApplicationContext,但是没有任何进展。 I have updated the code. 我已经更新了代码。

Edit: 编辑:

tl;dr : you write the wrong variable into the preferences. tl; dr :您在首选项中写入了错误的变量。

Your variable userKey is never written and always an empty string. 您的变量userKey永远不会被写入,并且始终是一个空字符串。 In your retrofit onResponse you put userKey as value of "key" into the preferences. 在改造onResponse ,将userKey作为“ key”的值放入首选项中。 This writes an empty string into the preferences. 这会将空字符串写入首选项。 This will work and give you no error. 这将起作用,并且不会给您任何错误。

Please assign userKey with the value of key_user . 请为key_user分配userKey的值。 Your response is only stored to key_user . 您的回复仅存储到key_user

Or directly remove the local variable key_user as follows: 或者直接删除本地变量key_user,如下所示:

public void onResponse(Call<com.aamir.friendlocator.friendlocator.Models.SendLocation> call, Response<com.aamir.friendlocator.friendlocator.Models.SendLocation> response) {
                Log.d("Response", response.body().getUserKey());
                if (!response.body().getUserKey().isEmpty()) {

                    String userKey = response.body().getUserKey();
                    textViewKeyDisplay.setText(userKey);

                    // Writing data to SharedPreferences
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("key", userKey);
                    if(editor.commit()){
                        Log.d("saved","saved");
                    }
                }  
            }

Before: 之前:

In your code to save, you directly try to gather the previously saved value using editor.apply(); 在要保存的代码中,您直接尝试使用editor.apply();来收集以前保存的值editor.apply();

As documentation states out, apply will save your changes in background on a different thread. 如文档所述, apply将您的更改保存在后台的其他线程中。

Therefore your changes might not be saved at the time you try to get the value, some lines below. 因此,在您尝试获取该值时,可能不会保存您的更改,以下几行。

Try to use editor.commit(); 尝试使用editor.commit(); instead and check if the problem is still there. 而是检查问题是否仍然存在。

I'm share here my own Preference Class it's too easy so you can put in any project. 我在这里分享我自己的首选项类,这太简单了,因此您可以放入任何项目。

Put this class into your util folder or anywhere. 将此类放入您的util文件夹或任何位置。

AppPreference.java AppPreference.java

package util;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by Pranav on 25/06/16.
 */
public class AppPreference {

    public static final String PREF_IS_LOGIN = "prefIsLogin";

        public static final class PREF_KEY {
        public static final String LOGIN_STATUS = "loginstatus";
    }

    public static final void setStringPref(Context context, String prefKey, String key, String value) {
        SharedPreferences sp = context.getSharedPreferences(prefKey, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, value);
        edit.commit();
    }

    public static final String getStringPref(Context context, String prefName, String key) {
        SharedPreferences sp = context.getSharedPreferences(prefName, 0);
        return sp.getString(key, "");
    }

} }

Set Preference Value in Login.java when user Login set value like this : 当用户登录设置值时,在Login.java中设置首选项值:

 AppPreference.setStringPref(context, AppPreference.PREF_IS_LOGIN, AppPreference.PREF_KEY.LOGIN_STATUS, "0");

Then you will get Login Status Value in any Class by Calling like this : 然后,您将通过以下调用获得任何类中的登录状态值:

 String LoginStatus = AppPreference.getStringPref(context, AppPreference.PREF_IS_LOGIN, AppPreference.PREF_KEY.LOGIN_STATUS);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM