Best Method to Save and Read Data in Android

社会主义新天地 提交于 2019-12-04 02:27:46

问题


I have an apps that using proxy to browse the url connection. But proxy host, port, username and password that i used are using hardcode. I already achieved that. But now i want to replace that hardcode with just an object that refer to the data. so the user can input the proxy that they want and can use their username and password. here is what my flow look like.

So first user can enter the name of the connection, host, port, etc that they want. And after that "save" it. And then in next activity it will read the data of that connection and if it exist, user can just to click and browse it. and if it dont, they can create the connection. If want to create it (it will back to creating connection form).

Thanks,


回答1:


if you simply want to send data to next actvity you can use intent.putExtra(); and in next activity call getIntent().getStringExtras();

if you want to save data until user change it next time you can user SharedPrefrance as you have small amount of data.

and if your data is sensitive (want to provide more security) you can put in database or encrypt and put in database

as you are handling username and password of user you should go with sqlite database. otherwise SharedPrefrance was best.

here's my pref class:

public class GreetingCardData {
    public static final String SHARED_PREF_FILE     =   "greetingCardData";
    public static final String KEY_DO_NOT_SHOW      =   "doNotShow";
    public static final String KEY_CATEGORIES_JSON  =   "categoriesJson";   
    private SharedPreferences sharedPrefs;
    private Editor prefsEditor;

    public GreetingCardData(Context context) {
        this.sharedPrefs = context.getSharedPreferences(SHARED_PREF_FILE, 0);
        this.prefsEditor = sharedPrefs.edit();
    }   

    public void setDoNotShowFlag ( boolean flag ){
        prefsEditor.putBoolean( KEY_DO_NOT_SHOW, flag );
        prefsEditor.commit();
    }

    public boolean getDoNotShowFlag(){
        return sharedPrefs.getBoolean( KEY_DO_NOT_SHOW, false );
    }

    public void setGreetingcardJson( String jsonString ){
        prefsEditor.putString( KEY_CATEGORIES_JSON, jsonString );
        prefsEditor.commit();
    }

    public String getGreetingcardJsonString(){
        return sharedPrefs.getString(KEY_CATEGORIES_JSON, "");
    }    
}

call from Activity: to save data:

new  GreetingCardData(ActivityMain.this).setDoNotShowFlag(flag);

to get data:

boolean flag =  new  GreetingCardData(ActivityMain.this).getDoNotShowFlag();


来源:https://stackoverflow.com/questions/16832607/best-method-to-save-and-read-data-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!