如何将共享首选项从一个活动传递到另一活动?

时间:2019-03-22 13:17:24

标签: android android-intent sharedpreferences

我的项目中有两个活动,一个活动是MainActivity,另一个活动是  Main2activity,在Main2activity中,我从用户那里获取输入并将其存储在SharedPreference中,现在我想将此数据传递给MainActivity并将其显示给用户。

Main2activity的代码是

 package com.example.to_doapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import java.io.Serializable;
import java.util.ArrayList;
public class Main2Activity extends AppCompatActivity {




public void BackMain ( View view )
{
    Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) ;
    SharedPreferences sharedPreferences = this.getSharedPreferences( "com.example.to_doapp;", Context.MODE_PRIVATE);
    EditText editText = ( EditText) findViewById( R.id.editText3) ;
    String s = editText.getText().toString();
    sharedPreferences.edit().putString("task" , s ) .apply();

    //intent.putStringArrayListExtra("key",arr);
    startActivity(intent);



}

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

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

}

代码敌人主要活动是

package com.example.to_doapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


public void onclick (View view){

    Intent intent = new Intent(getApplicationContext(), Main2Activity.class );
    startActivity(intent);
}

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

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    Intent intent = getIntent();


 }

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

}

我想知道如何传递共享首选项以及如何在列表视图中向用户显示该数据。 谢谢您的帮助。

6 个答案:

答案 0 :(得分:0)

您可以在第二个活动中使用area = z.shape[0] * z.shape[1] #length * height z = z.reshape(-1) #was trying to reduce to just z = [area] SharedPreferences方法。 这是文档:https://developer.android.com/reference/android/content/SharedPreferences.html#getString(java.lang.String,%20java.lang.String)

答案 1 :(得分:0)

def timer_handler():
    #start timer 2 if it is off
    if not timer_on:
        timer2.start()
    #stop timer 1
    timer.stop()

def timer2_handler():
    #simulates repeated keypresses if the key is held down
    global timer_on
    timer_on=True
    if len(held_keys)==0:
        timer2.stop()
        timer_on=False
    else:
        for item in held_keys:
            action(item)

def action(key):
    #this is where all the code to make something happen goes
    if key==upkey:
        #do something
        print('up key pressed')
    elif key==downkey:
        #do something else
        print('down key pressed')

def key_handler(key):
    #handles user keypresses
    #add key to held keys
    global held_keys
    held_keys.append(key)
    #do something with key
    action(key)
    #start timer 1 if timer 2 is off
    if not timer_on:
        timer.start()

def release_handler(key):
    #handles key releases
    #remove the key from the list
    global held_keys
    if key in held_keys:
        held_keys.remove(key)
    #if no keys are held, stop both timers
    global timer_on
    if len(held_keys)==0:
        timer.stop()
        timer2.stop()
        timer_on=False

import simplegui

timer_on=False
held_keys=[]

#starts timer 2
timer = simplegui.create_timer(300, timer_handler)
#automatic keypress
timer2 = simplegui.create_timer(100, timer2_handler)

#map whatever keys you need
spacekey=simplegui.KEY_MAP['space']
leftkey=simplegui.KEY_MAP['left']
rightkey=simplegui.KEY_MAP['right']
upkey=simplegui.KEY_MAP['up']
downkey=simplegui.KEY_MAP['down']

#create a frame and set key down/up handlers
frame=simplegui.create_frame('Click the box, then use arrow keys to move', 100, 100)
frame.set_keydown_handler(key_handler)
frame.set_keyup_handler(release_handler)
frame.start()

您可以随时使用以上代码从共享首选项中获取数据,直到将其清除为止。 但我建议您为此创建一个类,并在同一条件下执行所有与首选项相关的任务

答案 2 :(得分:0)

最简单的方法是:

设置SharedPref:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = prefs.edit();
editor.putString(PREF_NAME, "someValue");
editor.commit();

获取SharedPref:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
String yourValue = prefs.getString(PREF_NAME, "");

答案 3 :(得分:0)

无需传递SharedPreferences。您会在SharedPreferences值上得到任何活动或片段。

SharedPreferences shared = getSharedPreferences("Your SharedPreferences name", MODE_PRIVATE);
String data= shared.getString("key", "");

注意:密钥应与编辑或保存使用的数据时间相同。也是SharedPreferences名称 相同。

答案 4 :(得分:0)

我正在向您分享设置和获取sharedpreference数据的最简单方法:

首先像这样为Shared Preference创建一个类:

public class MySharedPreferences {

private static String MY_PREFS = "MyPrefs";
private static String IS_LOGGED_IN = "is_logged_in";
private static String USERNAME_ID = "username"

public static MySharedPreferences instance;
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;


public static MySharedPreferences getInstance(Context context) {
    if (instance == null)
        instance = new MySharedPreferences(context);
    return instance;
}

private MySharedPreferences(Context context) {
    this.context = context;
    sharedPreferences = context.getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();
}

public void deleteAllSharePrefs(Context context){
    this.context = context;
    sharedPreferences = context.getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
    editor.clear().commit();
}

public Boolean getIsLoggedIn(boolean b) {
    return sharedPreferences.getBoolean(IS_LOGGED_IN, false);
}

public void setIsLoggedIn(Boolean isLoggedIn) {
    editor.putBoolean(IS_LOGGED_IN, isLoggedIn);
    editor.commit();
}


public String getUsername() {
    return sharedPreferences.getString(USERNAME_ID, "");
}

public void setUsername(String username) {
    editor.putString(USERNAME_ID, username);
    editor.commit();
}

然后您要在其中设置SharedPreference的地方:

public void BackMain ( View view ){
EditText editText = ( EditText) findViewById( R.id.editText3) ;
MySharedPreferences.getInstance(Main2Activity.this).setUsername(editText.getText().toString());
Intent intent = new Intent( getApplicationContext() ,MainActivity.class ) 
startActivity(intent);
}

现在,在您的第二个活动中获取SharedPreference:

MySharedPreferences.getInstance(ACTIVITYNAME.this).getUsername();

或在片段中:

MySharedPreferences.getInstance(getActivity()).getUsername();

或在适配器中:

MySharedPreferences.getInstance(context).getUsername();

答案 5 :(得分:0)

为应用添加共享首选项时,可以从应用内的任何位置访问它。

SharedPreferences shared = PreferenceManager.getDefaultSharedPreferences(getContext());
String data= shared.getString("nameOfValue", "");