在设置中存储新数据

时间:2013-02-18 09:38:15

标签: android settings store android-preferences

在我的应用程序中,用户可以保存程序随后将连接的服务器配置文件。 由于我不知道用户将添加的连接配置文件的数量,因此我不能简单地将其放在SettingsActivity中。

由于我不想再次使用XML文件,我想我可以像这样保存SharedPreferences:

server1hostname
server1username
server1password
server2hostname
server2username
server2password
server3hostname
server3username
server3password

第一个问题:如果我想将所有内容保留在标准首选项文件中(与在某处创建自己的文件相反),是否有更好的方法?

第二个问题:我已经或多或少地实现了这一点。奇怪的是:它适用于现有设置(最初通过SettingsActivity创建),但不适用于新条目。

这是源代码(Powerline是服务器配置文件的类名):

@Override
public void onBackPressed() {
    super.onBackPressed();

    // Save powerline item
    Powerline newPowerline = new Powerline();
    newPowerline.setAddress(etAddress.getText().toString());
    newPowerline.setSendPort(Integer.parseInt(etSendPort.getText().toString()));

    newPowerline.setReceivePort(Integer.parseInt(etReceivePort.getText().toString()));
    newPowerline.setUsername(etUsername.getText().toString());
    newPowerline.setPassword(etPassword.getText().toString());

    int powerlinePositionInSettings = getIntent().getIntExtra("powerlinePositionInSettings", -1);

    if (option.equals("create"))    {
        if (newPowerline.create(this, powerlinePositionInSettings))
            finish();
    } else {
        if (powerlinePositionInSettings >= 0)
            if (newPowerline.change(this, powerlinePositionInSettings))
                finish();
    }
}

以下是Powerline类的创建函数:

public boolean create(Context context, int powerlinePositionInSettings) {
    String positionString = String.valueOf(powerlinePositionInSettings);        
    Log.i("Powerline", "Saving new powerline to settings to position " + positionString + ".");

    try {
        SharedPreferences.Editor prefsEditor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        prefsEditor.putString("powerline" + positionString + "Address", this.getAddress());
        prefsEditor.putString("powerline" + positionString + "SendPort", String.valueOf(this.getSendPort()));
        prefsEditor.putString("powerline" + positionString + "ReceivePort", String.valueOf(this.getReceivePort()));
        prefsEditor.putString("powerline" + positionString + "Username", this.getUsername());
        prefsEditor.putString("powerline" + positionString + "Password", getPassword());

        Log.i("Prefs", "Saving \"" + "powerline" + positionString + "Address" + "\" to be \"" + this.getAddress() + "\"");

        return prefsEditor.commit();
    } catch(Exception e) {
        e.printStackTrace();
        return false;
    }
}

以下是Powerline类的更改功能:

public boolean change(Context context, int powerlinePositionInSettings) {
    String positionString = String.valueOf(powerlinePositionInSettings);
    Log.i("Powerline", "Saving powerline to settings to position " + positionString + ".");

    try {
        SharedPreferences.Editor prefsEditor = PreferenceManager.getDefaultSharedPreferences(context).edit();
        prefsEditor.putString("powerline" + positionString + "Address", this.getAddress());
        prefsEditor.putString("powerline" + positionString + "SendPort", String.valueOf(this.getSendPort()));
        prefsEditor.putString("powerline" + positionString + "ReceivePort", String.valueOf(this.getReceivePort()));
        prefsEditor.putString("powerline" + positionString + "Username", this.getUsername());
        prefsEditor.putString("powerline" + positionString + "Password", getPassword());

        Log.i("Prefs", "Saving \"" + "powerline" + positionString + "Address" + "\" to be \"" + this.getAddress() + "\"");

        return prefsEditor.commit();
    } catch(Exception e) {
        e.printStackTrace();
        return false;
    }
}

更改功能存储的值确实已保存。 create function保存的新值不是。

有人有想法吗?我没有看到这两个功能有任何显着差异。

2 个答案:

答案 0 :(得分:0)

首先:不要创建用于存储用户数据的文件。而不是这个,创建一个数据库。因此,您可以读取,写入或更改数据。有一些关键:  http://thenewboston.org/list.php?cat=6在此页面中,您可以观看从#111到#124的内容。他们会教你。

答案 1 :(得分:0)

我将使用这种方法。

用法:

//创建电力线

new Powerline("hostname", "username", "password", 8080, 9090).create(this);

//更新所有电力线

List<Powerline> powerlines = Powerline.getAll(this);
    for (Powerline p : powerlines) {
        p.hostname = p.hostname + " updated";
        p.update(this);
    }

PS:经测试的代码,根据您的要求进行修改:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class Powerline {
private int _id;
public String hostname;
public String username;
public String password;
public int inPort;
public int outPort;

public Powerline(String hostname, String username, String password,
        int inPort, int outPort) {
    super();
    this.hostname = hostname;
    this.username = username;
    this.password = password;
    this.inPort = inPort;
    this.outPort = outPort;
}

public Powerline(String powerlineString) {
    String[] vars = powerlineString.split(":");
    _id = Integer.parseInt(vars[0]);
    hostname = vars[1];
    inPort = Integer.parseInt(vars[2]);
    outPort = Integer.parseInt(vars[3]);
    password = vars[4];
    username = vars[5];
}

public void create(Context context) {
    save(context, increamentKey(context));
}

public void update(Context context) {
    save(context, _id);
}

private void save(Context context, int id) {
    SharedPreferences.Editor ed = PreferenceManager
            .getDefaultSharedPreferences(context).edit();
    ed.putString("powerline:" + id, toString());
    ed.commit();
}

@Override
public String toString() {
    return _id + ":" + hostname + ":" + inPort + ":" + outPort + ":"
            + password + ":" + username;
}

public static List<Powerline> getAll(Context context) {
    SharedPreferences p = PreferenceManager
            .getDefaultSharedPreferences(context);
    List<Powerline> powerlines = new ArrayList<Powerline>();
    Map<String, ?> all = p.getAll();
    for (String key : all.keySet()) {
        if (key.startsWith("powerline:")) {
            powerlines.add(new Powerline(p.getString(key, null)));
        }
    }
    return powerlines;
}

private int increamentKey(Context context) {
    int key = PreferenceManager.getDefaultSharedPreferences(context)
            .getInt("_id", -1);
    PreferenceManager.getDefaultSharedPreferences(context).edit()
            .putInt("_id", ++key).commit();
    // also assign it to current object
    _id = key;
    return key;
}
}