如何提取Textview值以保存在共享首选项中

时间:2017-11-06 09:21:22

标签: java android database textview sharedpreferences

我有这个用户配置文件,其中数据来自数据库(SQL),因此我的textview值来自数据库,而不是来自用户输入。如何从数据库中保存设置为Textview的值。图片附件。

数据成功显示

image 1

我需要将这些值保存到共享首选项,以便当活动销毁时我可以再次显示数据。

数据丢失

image 2

这是我的代码从登录时抛出的数据库获取意图。

greetingTextView = (TextView) findViewById(R.id.greeting_text_view);
        totpoints = (TextView) findViewById(R.id.au_tpresult);
        totshare = (TextView) findViewById(R.id.au_tsresult);
        btnLogOut = (Button) findViewById(R.id.logout_button);
        cardshow = (ImageView) findViewById(R.id.card_stack);


        Intent intent = getIntent();
        String user = intent.getStringExtra("customers_firstname");
        String user1 = intent.getStringExtra("customers_lastname");
        String user2 = intent.getStringExtra("reward_points");
        String user3 = intent.getStringExtra("NoShares");
        String user4 = intent.getStringExtra("CardType_ID");
        String user5 = intent.getStringExtra("Card_No");


        greetingTextView.setText(user + " " + user1);
        totpoints.setText(user2);
        totshare.setText(user3);


        if (user4 == (null)) {
            ((ImageView) findViewById(R.id.card_stack)).setImageResource(R.drawable.thar_silver);
        } else if (user4.equals("0")) {
            ((ImageView) findViewById(R.id.card_stack)).setImageResource(R.drawable.thar_silver);
        } else if (user4.equals("1")) {
            ((ImageView) findViewById(R.id.card_stack)).setImageResource(R.drawable.thar_gold);

        }

        // Progress dialog
        btnLogOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                session.logoutUser();
                Toast.makeText(getApplicationContext(), "Session Ended", Toast.LENGTH_SHORT).show();
                Intent i = new Intent(getApplicationContext(), LoginActivityEN.class);
                startActivity(i);
            }
        });

        session.checkLogin();

        //CARD NUMBER to Bitmap to Barcode


        // barcode data
        String barcode_data = user5;

        // barcode image
        Bitmap bitmap = null;
        bmbc = (ImageView) findViewById(R.id.bitmap_barcode);
        bmbc_text = (TextView) findViewById(R.id.bitmap_barcode_text);

        try {

            bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 800, 150);
            bmbc.setImageBitmap(bitmap);
            bmbc_text.setText(user5);


        } catch (WriterException e) {
            e.printStackTrace();

    String output_name, output_points, output_share, output_id;


    output_name = greetingTextView.getText().toString();
    output_points = totpoints.getText().toString();
    output_share = totshare.getText().toString();
    output_id =  bmbc_text.getText().toString();

    session.createUserSession(output_name, output_points, output_share, output_id);
        Toast.makeText(getApplicationContext(), "Session Override", Toast.LENGTH_SHORT).show();
        }

    session.getUserDetails();

    if (session != null) {
        SharedPreferences sharedPreferences = getSharedPreferences("AFCOOP", Context.MODE_PRIVATE);
        String getvaluefromname = sharedPreferences.getString("custoname", new String());
        String getvaluefrompoints = sharedPreferences.getString("totalpoints", new String());


        Toast.makeText(getApplicationContext(), "Not null", Toast.LENGTH_SHORT).show();
        greetingTextView.setText(getvaluefromname);
        totpoints.setText(getvaluefrompoints);



    } else if (session == null) {
    }
}

最后一部分无效,因为只有用户输入保存在共享首选项中。我需要从文本视图中提取值并将其保存在共享首选项中并显示它。谢谢!

MySessionManager

//共享偏好设置的编辑器     编辑编辑;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharedpref file name
private static final String PREF_NAME = "AFCOOP";

// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";

// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";

// Email address (make variable public to access from outside)
public static final String KEY_UNAME = "custoname";

// Email address (make variable public to access from outside)
public static final String KEY_UPOINTS = "totalpoints";

// Email address (make variable public to access from outside)
public static final String KEY_USHARE = "totalshare";

// Email address (make variable public to access from outside)
public static final String KEY_UCARDNUM = "cardnumber";




// Constructor
public SessionManager(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

/**
 * Create login session
 * */
public void createLoginSession(String name, String password) {
    // Storing login value as TRUE
    editor.putBoolean(IS_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_NAME, name);

    // Storing email in pref
    editor.putString(KEY_EMAIL, password);

    // commit changes
    editor.commit();
}

public void createUserSession(String custoname, String totalpoints, String totalshare, String cardnumber){
    // Storing login value as TRUE
    editor.putBoolean(IS_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_UNAME, custoname);

    // Storing email in pref
    editor.putString(KEY_UPOINTS, totalpoints);
    // Storing email in pref

    editor.putString(KEY_USHARE, totalshare);
    // Storing email in pref

    editor.putString(KEY_UCARDNUM, cardnumber);

    // commit changes
    editor.commit();
}

/**
 * Check login method wil check user login status
 * If false it will redirect user to login page
 * Else won't do anything
 * */
public void checkLogin(){
    // Check login status
    if(!this.isLoggedIn()){
        // user is not logged in redirect him to Login Activity
        Intent i = new Intent(_context, LoginActivityEN.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Starting Login Activity
        _context.startActivity(i);
    }

}





/**
 * Get stored session data
 * */
public HashMap<String, String> getUserDetails(){
    HashMap<String, String> user = new HashMap<String, String>();
    // user name
    user.put(KEY_NAME, pref.getString(KEY_NAME, null));

    // user email id
    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));

    user.put(KEY_UNAME, pref.getString(KEY_UNAME, null));

    user.put(KEY_UPOINTS, pref.getString(KEY_UPOINTS, null));

    user.put(KEY_USHARE, pref.getString(KEY_USHARE, null));

    user.put(KEY_UCARDNUM, pref.getString(KEY_UCARDNUM, null));



    // return user
    return user;
}

/**
 * Clear session details
 * */
public void logoutUser(){
    // Clearing all data from Shared Preferences
    editor.clear();
    editor.commit();

    // After logout redirect user to Loing Activity
    Intent i = new Intent(_context, LoginActivityEN.class);
    // Closing all the Activities
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Add new Flag to start new Activity
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Staring Login Activity
    _context.startActivity(i);
}

/**
 * Quick check for login
 * **/
// Get Login State
public boolean isLoggedIn(){
    return pref.getBoolean(IS_LOGIN, false);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    setContentView(R.layout.activity_user);

}

}

1 个答案:

答案 0 :(得分:0)

创建一个静态函数而不是构造函数,并在主活动中初始化它,如下所示。

public static void initialize(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

主要活动

SharePreferences myPref; //Global Variable

在onCreate内部

myPref = SessionManger.initialize(getApplicationContext());

现在您可以使用共享的首选项。

我建议你把getter放在SessionManager Class里面

另外,Private_Mode值是0吗?您可以尝试使用Android常量Context.MODE_PRIVATE中定义的那个。