使用SharedPreferences的.setText不起作用

时间:2018-06-05 08:37:41

标签: java android sharedpreferences

我带着另一个问题来到这里,这次它涉及Android应用程序。

我已经使用登录活动(没有 NavigationView )创建了一个应用程序,它在登录到主页活动后移动我们,其中是NavigationView 。用户数据保存在 SharedPreferences 中,我使用常量类。 我的问题是我无法使用 SharedPreferences 主页活动中 setText ,但它正在登录活动(电子邮件地址插入 EditText )。 这是我的代码:

Login.java

package com.example.appname;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.appname.models.ServerRequest;
import com.example.appname.models.ServerResponse;
import com.example.appname.models.User;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Login extends AppCompatActivity {


private CoordinatorLayout coordinatorLayout;

private AppCompatButton btn_login;
private EditText et_email,et_password;
private TextView tv_register;
private ProgressBar progress;
private SharedPreferences pref;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout);

    pref = getPreferences(0);


    btn_login = (AppCompatButton)findViewById(R.id.btn_login);
    tv_register = (TextView)findViewById(R.id.tv_register);
    et_email = (EditText)findViewById(R.id.et_email);
    et_email.setText(pref.getString(Constants.EMAIL, ""));
    et_password = (EditText)findViewById(R.id.et_password);

    progress = (ProgressBar)findViewById(R.id.progress);

    btn_login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            String email = et_email.getText().toString();
            String password = et_password.getText().toString();

            if(!email.isEmpty() && !password.isEmpty()) {

                progress.setVisibility(View.VISIBLE);
                loginProcess(email,password);

            } else {

                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, R.string.empty_fields, Snackbar.LENGTH_LONG);

                View sbView = snackbar.getView();
                TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setTextColor(Color.GREEN);
                snackbar.show();
            }
        }

    });

    tv_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(getApplicationContext(), Register.class);

            startActivity(intent);
            finish();
        }
    });


}






private void loginProcess(String email,String password){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.LOGIN_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();
            Snackbar.make(coordinatorLayout, resp.getMessage(), Snackbar.LENGTH_LONG).show();

            if(resp.getResult().equals(Constants.SUCCESS)){
                SharedPreferences.Editor editor = pref.edit();
                editor.putBoolean(Constants.IS_LOGGED_IN,true);
                editor.putString(Constants.EMAIL,resp.getUser().getEmail());
                editor.putString(Constants.NAME,resp.getUser().getName());
                editor.putString(Constants.UNIQUE_ID,resp.getUser().getUnique_id());
                editor.putString(Constants.POINTS,resp.getUser().getPoints());
                editor.apply();
                goToHome();

            }
            progress.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

            progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG,"failed");
            Snackbar.make(coordinatorLayout, t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();

        }
    });
}



private void goToHome(){

    Intent intent = new Intent(getApplicationContext(), Home.class);

    startActivity(intent);
}
}

Home.java

package com.examle.appname;

import android.app.ActivityOptions;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.internal.NavigationMenuPresenter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class Home extends AppCompatActivity implements 
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private SharedPreferences pref;
private TextView tvname, tvpoints;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    pref = getPreferences(0);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    tvname = (TextView)findViewById(R.id.tv_name);
    tvpoints = (TextView)findViewById(R.id.tv_points);
    tvname.setText(pref.getString(Constants.NAME, ""));
    tvpoints.setText(pref.getString(Constants.POINTS, "") +R.string.act_points);



    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nvView);
    navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
    View headerView = navigationView.getHeaderView(0);
    TextView tvemail = (TextView) headerView.findViewById(R.id.tv_email);
    tvemail.setText(pref.getString(Constants.EMAIL, ""));

}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();     
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")


public boolean onNavigationItemSelected(MenuItem item) {

    int id=item.getItemId();
    switch (id){

        case R.id.navigation_home:
            Intent h= new Intent(Home.this,Home.class);
            startActivity(h);
            break;
        case R.id.navigation_showall:
            Intent i= new Intent(Home.this,ShowAllUsers.class);
            startActivity(i);
            break;
        case R.id.navigation_about:
            Intent g= new Intent(Home.this,About.class);
            startActivity(g);
            break;
        case R.id.navigation_settings:
            Intent s= new Intent(Home.this,AccountSettings.class);
            startActivity(s);
        case R.id.navigation_support:
            Intent t= new Intent(Home.this,Support.class);
            startActivity(t);
            break;
    }



    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
}

3 个答案:

答案 0 :(得分:0)

使用getSharedPreferences代替此getPreferences

答案 1 :(得分:0)

试试这种方式

 SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    if (sharedpreferences.contains(Constants.NAME)) 
    {
        tvname.setText(sharedpreferences.getString(Constants.NAME, ""));
    }

答案 2 :(得分:0)

因为您在不同活动中使用两个不同的SharedPreference实例使用单个实例。了解更多信息 - https://stackoverflow.com/a/11567825/3912847