android - 使用 SharedPreferences 从 Edittext 中检索用户名以进行下一个 Activity

标签 android android-sharedpreferences

我想我可以在登录后绕过登录 Activity ,但如何检索用户名并将其传递给下一个 Activity 。我得到用户名的值为 NULL

这是登录 Activity

public class LoginActivity extends AppCompatActivity {
    /*
     * Database helper field
     */
    private DatabaseHelper databaseHelper;
    /*
    Edittext username and password
     */
    private EditText uName, pwd;
    /*
    Button login and signup
     */
    private Button loginButton, signupButton;
    private String username, password;

    /**
     * Create activity when register button and log in button clicked
     * @param savedInstanceState saved instance state
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar)findViewById(R.id.login_toolbar);
        toolbar.setTitle("LOGIN");

        databaseHelper = new DatabaseHelper(this);

        uName = (EditText)findViewById(R.id.uNameToLogin_editText);
        pwd = (EditText)findViewById(R.id.pwdToLogin_editText);

        SharedPreferences sharedPreferences = getSharedPreferences
                (getString(R.string.SHARED_PREFS), MODE_PRIVATE);
        boolean isLoggedIn = sharedPreferences.getBoolean(getString(R.string.LOGGEDIN), false);
        if (isLoggedIn){
            Intent newIntent = new Intent(LoginActivity.this, FinderActivity.class);
            newIntent.putExtra("Username", username);
            startActivity(newIntent);
            finish();
        }
        /*
        * Sign up button clicked takes user to registration form
         */
        signupButton = (Button)findViewById(R.id.signupButton);
        signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        /*
        *Log in activity
         */
        loginButton = (Button)findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = uName.getText().toString();
                password = pwd.getText().toString();
                //log in successfull using correct username and password
                String pass = databaseHelper.searchPassword(username);
                if (pass.equals(password)){

                    SharedPreferences sharedPreferences = getSharedPreferences
                            (getString(R.string.SHARED_PREFS), MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putBoolean(getString(R.string.LOGGEDIN), true);
                    editor.commit();

                    Toast.makeText(LoginActivity.this, "Welcome! " + username,
                            Toast.LENGTH_LONG).show();
                    //change to new search intent
                    Intent newIntent = new Intent(LoginActivity.this, FinderActivity.class);
                    newIntent.putExtra("Username", username);
                    startActivity(newIntent);
                    finish();
                } else {
                    //error shows if inccorrect password or username
                    Toast.makeText(LoginActivity.this, "Username or Password Incorrect!, Try Again",
                            Toast.LENGTH_LONG).show();
                }

            }
        });

    }

}

这是我的 NextActivity,它包含菜单栏中的注销操作

public class FinderActivity extends AppCompatActivity {

    private static final String TAG = "FinderActivity";
    private String address = "";
    public List<LocationInfo> locationList;
    public ListView mListView;
    public ArrayAdapter<LocationInfo> locationAdapter;
    private int numberOfLocation;
    public LocationAddress locationAddress;
    public String api_url, uName;
    public double lat, lng;

    SharedPreferences mSharePreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_finder);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Intent intent = getIntent();
        uName = intent.getStringExtra("Username");
        String welcomeString = "Welcome, " + uName;
        getSupportActionBar().setTitle(welcomeString);

        Log.i(TAG, "On create called");

        View b = findViewById(R.id.customButton);
        b.setVisibility(View.GONE);

        /*
        retrieve search button actions
         */
        Button searchButton = (Button) findViewById(R.id.search_button);
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //pass address to location class
                EditText search = (EditText) findViewById(R.id.search_EditText);
                address = search.getText().toString();
                LocationAddress.setAddress(address);
                if (locationList != null) {
                    locationList.clear();
                }
                if (address.equals("")) {
                    Toast.makeText(FinderActivity.this, "PLease enter your address!",
                            Toast.LENGTH_LONG).show();
                } else {
                /*
                * manging connection from the application to networking service
                * before attempting to fetch url, make sure there is a network connection
                */
                    ConnectivityManager connectivityManager = (ConnectivityManager)
                            getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networtInfo = connectivityManager.getActiveNetworkInfo();
                    if (networtInfo != null && networtInfo.isConnected()) {
                        GetAddressTask task = new GetAddressTask();
                        task.execute();
                        View b = findViewById(R.id.customButton);
                        b.setVisibility(View.GONE);
                        Log.i(TAG, "connected");
                    } else {
                        Log.i(TAG, "not connected");
                    }

                /*
                Retrieve data to listview
                 */
                    showListView();
                    /*
                    itemClick listener for each item in the list view
                     */
                    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            Intent intent = new Intent(FinderActivity.this, ParkingLocation.class);
                            api_url = locationList.get(position).getUrl_api();
                            intent.putExtra("key_api_url", api_url);
                            intent.putExtra("username", uName);
                            startActivity(intent);
                        }
                    });

                }
            }
        });

        /*
        Custom search button actions if and only if search button gives null results
         */
        Button customSearch = (Button) findViewById(R.id.customButton);
        customSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (address.equals("")) {
                    Toast.makeText(FinderActivity.this, "PLease enter your address!",
                            Toast.LENGTH_LONG).show();

                } else if (LocationAddress.getNumOfLocations() > 0) {
                    Toast.makeText(FinderActivity.this, "This action is only available if no parking locations found!!",
                            Toast.LENGTH_LONG).show();
                } else { //open custom search activity
                    Intent newIntent = new Intent(FinderActivity.this, CustomSearchActivity.class);
                    Bundle b = new Bundle();
                    b.putDouble("key_lat", lat);
                    b.putDouble("key_lng", lng);
                    b.putString("username", uName);
                    newIntent.putExtras(b);
                    startActivity(newIntent);
                }
            }
        });

    }


    @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();

        switch (id) {
            //log out action
            case R.id.action_logout:
                mSharePreferences = getSharedPreferences(getString
                        (R.string.SHARED_PREFS), MODE_PRIVATE);
                SharedPreferences.Editor editor = mSharePreferences.edit();
                editor.putBoolean(getString(R.string.LOGGEDIN), false);
                editor.commit();
                Intent backIntent = new Intent(FinderActivity.this, LoginActivity.class);
                startActivity(backIntent);
                return true;
            //show my saved places view
            case R.id.action_show:
                Intent intent = new Intent(FinderActivity.this, MyDestination.class);
                intent.putExtra("username", uName);
                startActivity(intent);
                return true;
        }
        //show list of destination once this button clicked
        return super.onOptionsItemSelected(item);
    }

最佳答案

如果你想通过 Intent 传递数据,你应该在 FinderActivity.java 的 onCreate 上设置它

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

    if (getIntent() != null) {
        final Bundle extras = getIntent().getExtras();
        if (extras != null) {
            userName = extras.getString("Username");
        }
    }

}

如果你想在 SharedPreferences 上保存,你必须在 LoginActivity 上保存并在 FinderActivity.java 上保存 解释如何的链接 -> How to use SharedPreferences in Android to store, fetch and edit values

关于android - 使用 SharedPreferences 从 Edittext 中检索用户名以进行下一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34072492/

相关文章:

android - ConstraintLayout 没有响应

java - 在 SharedPreference 中保存通用类型的列表

具有不同模块的Android项目(sharedPreferences)

android - 编译gradle库项目失败

Android NDK 套接字连接问题

android - 我可以通过蓝牙同时向多个设备发送消息吗?

android - 应用程序设置中的 "clear data"有什么作用?

android - 使用 SharedPreferences 显示字符串不起作用

java - 如何仅更改共享首选项中存储的 Json 对象中的一个值

android - 如何在单击 "Search"菜单时更改操作栏背景?