不在sharedPreferences

时间:2016-04-13 18:38:02

标签: android

我正在尝试在sharedPreferences中保存字符串。我不知道我做错了什么,但它没有保存String值。

这是代码 这里我保存字符串值“电话”。 注意其片段页面

  package com.world.bolandian.watchme;

  import android.app.Fragment;
  import android.content.Context;
  import android.content.Intent;
  import android.content.SharedPreferences;
  import android.os.Bundle;
  import android.preference.PreferenceManager;
  import android.support.annotation.Nullable;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.Toast;

  import com.google.gson.Gson;


  public class LoginFragment extends Fragment implements Listen {
  Button loginBtn;
   ServerRequest ser;
   Connector c;
   LoginCommunicationThread loginT;
   private LoginUser logUser;
   EditText phone,password;

    @Nullable
    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_login, container, false);
}
   public void setInterface(Connector c){
     this.c=c;
 }

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    ser=new ServerRequest();
    ser.addServerName(Params.SERVER_URL);
    ser.addServletName(Params.LOGIN_SERVLET);
    ser.setResponse(this);
    loginT = new LoginCommunicationThread(ser);


    phone = (EditText)getActivity().findViewById(R.id.userTxt);
    password = (EditText)getActivity().findViewById(R.id.passwordTxt);
    loginBtn = (Button) getActivity().findViewById(R.id.loginBtn);



    loginBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //save phone number in sharedpreferences
            SharedPreferences pref = getActivity().getPreferences(0);
            SharedPreferences.Editor edt = pref.edit();
            edt.putString("PHONE",String.valueOf(phone.getText()));
            edt.commit();

            Context context = getActivity();
            PreferenceManager.getDefaultSharedPreferences(context).edit().putString("PHONE", String.valueOf(phone.getText()));
            logUser = new LoginUser(phone.getText().toString(),password.getText().toString());
            if (phone.getText().toString() == null)
            {
                Toast.makeText(getActivity(),"Please enter phone number", Toast.LENGTH_LONG).show();
            }
            if(password.getText().toString() == null)
            {
                Toast.makeText(getActivity(),"Please enter password", Toast.LENGTH_LONG).show();
            }
            else {
                Gson g = new Gson();
                String ans = g.toJson(logUser, LoginUser.class);
                login(logUser);
            }
        }
    });
}

public void login (LoginUser user)
{
    LoginCommunicationThread con;
    ServerRequest ser = new ServerRequest();
    ser.setResponse(this);
    Gson gson = new Gson();

    String send = gson.toJson(user,LoginUser.class);

    ser.addParamaters(Params.USER,send);
    ser.addServerName(Params.SERVER_URL);
    ser.addServletName(Params.LOGIN_SERVLET);
    con = new LoginCommunicationThread(ser);
    con.start();
}

@Override
public void good() {
    Toast.makeText(getActivity(), "Welcome", Toast.LENGTH_LONG).show();
    Intent i = new Intent(getActivity(),MainActivity.class);
    startActivity(i);
}

@Override
public void notGood() {
        Toast.makeText(getActivity(),"Wrong password or phone",Toast.LENGTH_LONG).show();
}

@Override
public void notGoodServerEroorr() {
    Toast.makeText(getActivity(), "Connection Error please try again", Toast.LENGTH_LONG);
}

 }

这里我提取值“PHONE”,但我一直变为空。由于某种原因,它没有得到值,默认值为null(此页面为活动)

  package com.world.bolandian.watchme;

  import android.app.Activity;
  import android.content.SharedPreferences;
  import android.graphics.Color;
  import android.os.Bundle;
  import android.preference.PreferenceManager;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.view.View;
  import android.widget.TabHost;
  import android.widget.TextView;

  import com.google.gson.Gson;


  public class MainActivity extends Activity implements Listen {
   private LockAndUnLock sendnotf;
  TextView status;
   @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

    status = (TextView)findViewById(R.id.status);
    TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
    tabHost.setup();

    TabHost.TabSpec tabspec = tabHost.newTabSpec("main");
    tabspec.setContent(R.id.main);
    tabspec.setIndicator("Main");
    tabHost.addTab(tabspec);


    tabspec = tabHost.newTabSpec("gps");
    tabspec.setContent(R.id.GPS);
    tabspec.setIndicator("GPS");
    tabHost.addTab(tabspec);


    tabspec = tabHost.newTabSpec("info");
    tabspec.setContent(R.id.INFO);
    tabspec.setIndicator("Info");
    tabHost.addTab(tabspec);

}

public void Lock (View view)
{
      SharedPreferences sharedPreferences =    
       PreferenceManager.getDefaultSharedPreferences(this);
       String phone = sharedPreferences.getString("PHONE", null);
      PreferenceManager.getDefaultSharedPreferences(this).getString("PHONE",
   null);

     sendnotf = new LockAndUnLock(phone,1); // 1 = true = lock
     Gson g = new Gson();
    String ans=g.toJson(sendnotf, LockAndUnLock.class);
    sendLockAndUnlock(sendnotf);

    if (status.getVisibility() != View.VISIBLE) {
        status.setVisibility(View.VISIBLE);
    }
    status.setText("LOCKED");
    status.setTextColor(Color.RED);
}


public void UnLock (View view)
{
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    String phone = sharedPreferences.getString("PHONE",null);

    sendnotf = new LockAndUnLock(phone,0); // 0 = false = unlock
    Gson g = new Gson();
    String ans=g.toJson(sendnotf, LockAndUnLock.class);
    sendLockAndUnlock(sendnotf);

    if (status.getVisibility() != View.VISIBLE) {
        status.setVisibility(View.VISIBLE);
    }
    status.setText("OPEN");
    status.setTextColor(Color.GREEN);
}


@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
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

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

    return super.onOptionsItemSelected(item);
}

@Override
public void good() {

}

@Override
public void notGood() {

}

@Override
public void notGoodServerEroorr() {

}

public void sendLockAndUnlock(LockAndUnLock sendnotf){

    RegisterCommunicationThread con;
    ServerRequest ser = new ServerRequest();
    ser.setResponse(this);
    Gson gson = new Gson();

    String send = gson.toJson(sendnotf, LockAndUnLock.class);

    ser.addParamaters(Params.LOCKANDUNLOCK,send);
    ser.addServerName(Params.SERVER_URL);
    ser.addServletName(Params.LOCKANDUNLOCK_SERVLET);
    con = new RegisterCommunicationThread(ser);
    con.start();
    }
 }

1 个答案:

答案 0 :(得分:0)

问题在于不同的共享偏好对象。根据官方文件:

  

getPreferences(int mode)

     

在API级别1中添加检索SharedPreferences对象以进行访问   此活动专用的首选项。这简单地称之为   传入此基础的getSharedPreferences(String,int)方法   activity的类名作为首选项名称。

我的建议是使用特殊实体来处理共享首选项。在您的情况下,它可能看起来像下面的代码

public class SharedPreferencesManager {

  private static final String PREFERENCES_NAME = "your_name";//name for xml file

  private final SharedPreferences sharedPreferences;

  public SharedPreferencesManager(Context context) {
    sharedPreferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
  }

  public String getPhone() {
    return sharedPreferences.getString("PHONE", null);
  }

  public void savePhone(@NonNull String phone) {
    sharedPreferences.edit().putString("PHONE", phone).apply(); //or commit for blocking save
  }
}

然后将您对SharedPreferences Activity的所有直接电话替换为Fragment以上对象。