Hallo liebes Forum,
ich brauche dringen Hilfe. Ich möchte meine Shared Preferences mit einer Datenbank austauschen. Ich habe die Methoden für eine Datenbank erstellt, doch weiß nun nicht genau weiter. Über Hilfe würde ich mich sehr freuen
liebe Grüße Fabian
Settingsserver.java:
Java
public class SettingsServer {
// Database fields
private SQLiteDatabase database;
private SQLite dbHelper;
public SettingsServer(Context context) {
dbHelper = new SQLite(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public ContentValues getContentValueForSetting(Setting setting){
ContentValues values = new ContentValues();
values.put(SQLite.COL_ID,setting.getId());
values.put(SQLite.COL_TYP,setting.getId());
values.put(SQLite.COL_NAME,setting.getName());
values.put(SQLite.COL_URL,setting.getTyp());
values.put(SQLite.COL_HTUSER,setting.getHtaccess_user());
values.put(SQLite.COL_HTPW,setting.getHtaccess_pw());
return values;
}
public long createSetting(Setting Setting) {
return database.insert(SQLite.TABLE_NAME, null,getContentValueForSetting(Setting));
}
public boolean updateSetting(Setting setting){
long id = setting.getId();
database.update(SQLite.TABLE_NAME,getContentValueForSetting(setting),SQLite.COL_ID + " = " + id,null);
return true;
}
public void deleteSetting(int id) {
System.out.println("Setting deleted with id: " + id);
database.delete(SQLite.TABLE_NAME, SQLite.COL_ID + " = " + id, null);
}
public List<Setting> getAllSettings() {
List<Setting> Settings = new ArrayList<Setting>();
Cursor cursor = database.query(SQLite.TABLE_NAME,SQLite.COLLUMS, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Setting Setting = cursorToSetting(cursor);
Settings.add(Setting);
cursor.moveToNext();
}
// make sure to close the cursor
cursor.close();
return Settings;
}
private Setting cursorToSetting(Cursor cursor) {
long id = cursor.getLong(0);
String name = cursor.getString(2);
Setting setting = new Setting(id,name);
setting.setTyp(cursor.getLong(1));
setting.setUrl(cursor.getString(3));
setting.setHtaccess_user(cursor.getString(4));
setting.setHtaccess_pw(cursor.getString(5));
setting.setSsh_url(cursor.getString(6));
setting.setSsh_pw(cursor.getString(7));
setting.setSsh_key(cursor.getString(8));
dbHelper.addSetting(setting);
return setting;
}
}
Alles anzeigen
SQLite.java:
Java
public class SQLite extends SQLiteOpenHelper {
public static final String TABLE_NAME = "settings";
public static final String COL_ID = "id";
public static final String COL_TYP = "typ";
public static final String COL_NAME = "name";
public static final String COL_URL = "url";
public static final String COL_HTUSER = "htaccess_user";
public static final String COL_HTPW = "htaccess_pw";
public static final String COL_SSHURL = "ssh_url";
public static final String COL_SSHPW = "ssh_pw";
public static final String COL_SSHKEY = "ssh_key";
public static final String COL_PK = COL_ID;
public static final String[] COLLUMS = {COL_ID, COL_TYP, COL_NAME, COL_URL, COL_HTUSER, COL_HTPW, COL_SSHURL, COL_SSHPW, COL_SSHKEY};
private static final String DATABASE_NAME = "settings.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table " + TABLE_NAME +
"(" +
COL_ID + " integer primary key autoincrement," +
COL_NAME + " text," +
COL_URL + "text," +
COL_TYP + " integer," +
COL_HTUSER + " text," +
COL_HTPW + " text," +
COL_SSHURL + " ssh_url text," +
COL_SSHPW + " ssh_password text," +
COL_SSHKEY + " ssh_key text" +
");";
public SQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(SQLite.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addSetting(Setting setting) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_ID, setting.getTyp()); // save COL_TYP
values.put(COL_TYP, setting.getTyp()); // save COL_TYP
values.put(COL_NAME, setting.getName()); // save Name
values.put(COL_URL, setting.getUrl()); // save COL_URL
values.put(COL_HTUSER, setting.getHtaccess_user()); // save COL_HTUSER
values.put(COL_HTPW, setting.getHtaccess_pw()); // save COL_HTPW
values.put(COL_SSHURL, setting.getSsh_url()); // save COL_SSHURL
values.put(COL_SSHPW, setting.getSsh_pw()); // save COL_SSHPW
values.put(COL_SSHKEY, setting.getSsh_key()); // save COL_SSHKEY
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
Alles anzeigen
SettingsActivity.java:
Java
public class SettingsActivity extends PreferenceActivity {
public static final String PREFS_NAME = "serverSettings";
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference.getKey().matches("ssh_typ_(.*)")) {
int test = 1;
}
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference
.setSummary(index >= 0 ? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
String curr_setting_key;
FileDialog fileDialog;
SharedPreferences preferences;
SharedPreferences.Editor preferencesEdit;
SharedPreferences.OnSharedPreferenceChangeListener listener;
PreferenceScreen root;
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(
preference,
PreferenceManager.getDefaultSharedPreferences(
preference.getContext()).getString(preference.getKey(),
""));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
preferencesEdit = preferences.edit();
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (key.matches("server_name_(.*)")) {
setPreferenceScreen(createMyPreference());
} else if (key.matches("server_typ_(.*)")) {
String[] temp = key.split("_");
String id = temp[temp.length - 1];
if ("0".equals(prefs.getString(key, "0"))) {
root.findPreference("ssh_url_" + id).setEnabled(false);
root.findPreference("ssh_user_" + id).setEnabled(false);
root.findPreference("ssh_password_" + id).setEnabled(false);
root.findPreference("ssh_key_" + id).setEnabled(false);
root.findPreference("htaccess_user_" + id).setEnabled(false);
root.findPreference("htaccess_password_" + id).setEnabled(false);
} else if ("1".equals(prefs.getString(key, "0"))) {
root.findPreference("ssh_url_" + id).setEnabled(false);
root.findPreference("ssh_user_" + id).setEnabled(false);
root.findPreference("ssh_password_" + id).setEnabled(false);
root.findPreference("ssh_key_" + id).setEnabled(false);
root.findPreference("htaccess_user_" + id).setEnabled(true);
root.findPreference("htaccess_password_" + id).setEnabled(true);
} else if ("2".equals(prefs.getString(key, "0"))) {
root.findPreference("ssh_url_" + id).setEnabled(true);
root.findPreference("ssh_user_" + id).setEnabled(true);
root.findPreference("ssh_password_" + id).setEnabled(true);
root.findPreference("ssh_key_" + id).setEnabled(true);
root.findPreference("htaccess_user_" + id).setEnabled(false);
root.findPreference("htaccess_password_" + id).setEnabled(false);
}
}
}
};
preferences.registerOnSharedPreferenceChangeListener(listener);
setPreferenceScreen(createMyPreference());
setupActionBar();
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
// TODO: If SettingsServer has multiple levels, Up should navigate up
// that hierarchy.
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Shows the simplified settings UI if the device configuration if the
* device configuration dictates that a simplified, single-pane UI should be
* shown.
*/
private PreferenceScreen createMyPreference() {
// try {
int getMaxServer = preferences.getInt("serverCount", 0);
root = getPreferenceManager().createPreferenceScreen(this);
Preference.OnPreferenceClickListener on;
root.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
root.getDialog().getActionBar().setDisplayHomeAsUpEnabled(true);
final Dialog dialog = root.getDialog();
View homeBtn = dialog.findViewById(android.R.id.home);
if (homeBtn != null) {
View.OnClickListener dismissDialogClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
};
// Prepare yourselves for some hacky programming
ViewParent homeBtnContainer = homeBtn.getParent();
// The home button is an ImageView inside a FrameLayout
if (homeBtnContainer instanceof FrameLayout) {
ViewGroup containerParent = (ViewGroup) homeBtnContainer.getParent();
if (containerParent instanceof LinearLayout) {
// This view also contains the title text, set the whole view as clickable
((LinearLayout) containerParent).setOnClickListener(dismissDialogClickListener);
} else {
// Just set it on the home button
((FrameLayout) homeBtnContainer).setOnClickListener(dismissDialogClickListener);
}
} else {
// The 'If all else fails' default case
homeBtn.setOnClickListener(dismissDialogClickListener);
}
}
return true;
}
});
PreferenceCategory fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle("Servers");
root.addPreference(fakeHeader);
for (int i = 0; i < getMaxServer; i++) {
PreferenceScreen pf = getPreferenceManager().createPreferenceScreen(this);
fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle("Server");
pf.addPreference(fakeHeader);
pf.setKey("screen_preference_" + i);
pf.setTitle(preferences.getString("server_name_" + i, "New Server"));
pf.setSummary("Click to edit");
EditTextPreference serverName = new EditTextPreference(this);
ListPreference serverTyp = new ListPreference(this);
serverTyp.setEntries(R.array.serverTyp);
serverTyp.setEntryValues(R.array.serverTypValues);
serverTyp.setKey("server_typ_" + i);
serverTyp.setTitle("Server Typ");
pf.addPreference(serverTyp);
bindPreferenceSummaryToValue(serverTyp);
serverName.setKey("server_name_" + i);
serverName.setTitle("Name");
serverName.setSummary(preferences.getString("server_name_" + i, ""));
pf.addPreference(serverName);
bindPreferenceSummaryToValue(serverName);
EditTextPreference serverUrl = new EditTextPreference(this);
serverUrl.setKey("server_url_" + i);
serverUrl.setTitle("Url");
pf.addPreference(serverUrl);
bindPreferenceSummaryToValue(serverUrl);
EditTextPreference htaccess_user = new EditTextPreference(this);
htaccess_user.setKey("htaccess_user_" + i);
htaccess_user.setTitle("htaccess user");
pf.addPreference(htaccess_user);
bindPreferenceSummaryToValue(htaccess_user);
EditTextPreference htaccess_password = new EditTextPreference(this);
htaccess_password.setKey("htaccess_password_" + i);
htaccess_password.setTitle("htaccess password");
htaccess_password.getEditText().setTransformationMethod(new PasswordTransformationMethod());
if (!"1".equals(preferences.getString("server_typ_" + i, "0"))) {
htaccess_user.setEnabled(false);
htaccess_password.setEnabled(false);
}
pf.addPreference(htaccess_password);
//bindPreferenceSummaryToValue(htaccess_password);
EditTextPreference ssh_url = new EditTextPreference(this);
ssh_url.setKey("ssh_url_" + i);
ssh_url.setTitle("ssh url");
pf.addPreference(ssh_url);
bindPreferenceSummaryToValue(ssh_url);
EditTextPreference ssh_user = new EditTextPreference(this);
ssh_user.setKey("ssh_user_" + i);
ssh_user.setTitle("ssh user");
pf.addPreference(ssh_user);
bindPreferenceSummaryToValue(ssh_user);
EditTextPreference ssh_password = new EditTextPreference(this);
ssh_password.setKey("ssh_password_" + i);
ssh_password.setTitle("ssh password");
ssh_password.getEditText().setTransformationMethod(new PasswordTransformationMethod());
pf.addPreference(ssh_password);
//bindPreferenceSummaryToValue(ssh_password);
final Preference ssh_key = new Preference(this);
ssh_key.setKey("ssh_key_" + i);
ssh_key.setTitle("ssh key");
//ssh_key.getEditText().setTransformationMethod(new PasswordTransformationMethod());
pf.addPreference(ssh_key);
File mPath = new File(Environment.getExternalStorageDirectory().getPath());
fileDialog = new FileDialog(this, mPath, i);
ssh_key.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(final Preference preference) {
fileDialog.showDialog();
curr_setting_key = preference.getKey();
fileDialog.addFileListener(new FileDialog.FileSelectedListener() {
public void fileSelected(File file, int currServer) {
preferencesEdit.putString(curr_setting_key, file.toString());
preference.setSummary(file.toString());
preferencesEdit.commit();
}
});
return true;
}
});
bindPreferenceSummaryToValue(ssh_key);
if (!"2".equals(preferences.getString("server_typ_" + i, "0"))) {
ssh_url.setEnabled(false);
ssh_user.setEnabled(false);
ssh_password.setEnabled(false);
ssh_key.setEnabled(false);
}
Preference button_del = new Preference(this);
button_del.setTitle("Delete");
button_del.setSummary("click to delete this server");
final PreferenceActivity pfa = this;
final int id = i;
button_del.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
removeServer(id);
return true;
}
});
pf.addPreference(button_del);
root.addPreference(pf);
}
Preference button_add = new Preference(this);
button_add.setTitle("Add");
button_add.setSummary("click to add a server");
button_add.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference arg0) {
addNewServer();
return true;
}
});
root.addPreference(button_add);
fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle("Online Check");
root.addPreference(fakeHeader);
// }
// catch(Exception e)
{
}
return root;
}
private void addNewServer() {
SettingsServer settingsserver = new SettingsServer(this.getBaseContext());
int serverCount = preferences.getInt("serverCount", 0);
preferencesEdit.putInt("serverCount", serverCount + 1);
boolean ok = preferencesEdit.commit();
int getMaxServer = preferences.getInt("serverCount", 0);
this.setPreferenceScreen(createMyPreference());
int pos = root.findPreference("screen_preference_" + (serverCount)).getOrder();
root.onItemClick(null, null, pos, 0);
}
public void removeServer(int removedServer) {
SettingsServer settingserver = new SettingsServer(this.getBaseContext());
settingserver.deleteSetting(removedServer-1);
/* int maxServer = preferences.getInt("server_count", 0);
preferencesEdit.putInt("server_count", removedServer);
int pos = root.findPreference("screen_preference_" + removedServer).getOrder();
root.onItemClick(null, null, pos, 0);*/
//hacky fill the gap with the former last one
}
}
Alles anzeigen