Skip to content

Instantly share code, notes, and snippets.

@MostafaAnter
Created August 5, 2015 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MostafaAnter/7129ad8c4f90c83621b6 to your computer and use it in GitHub Desktop.
Save MostafaAnter/7129ad8c4f90c83621b6 to your computer and use it in GitHub Desktop.
simple preferences with java
package com.mostafaanter.preferenceswithjava;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import utils.UIHelper;
public class MainActivity extends AppCompatActivity {
public static String LOGTAG = "information";
public static String USERNAME = "userName";
private SharedPreferences settings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = getPreferences(MODE_PRIVATE);
}
@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);
}
public void set_preferences(View view) {
Log.i(LOGTAG, "clicked set");
SharedPreferences.Editor editor = settings.edit();
String prefValue = UIHelper.getText(this, R.id.editText1);
editor.putString(USERNAME, prefValue);
editor.commit();
UIHelper.displayText(this, R.id.text1, "Preference Saved");
}
public void show_preferences(View view) {
Log.i(LOGTAG,"clicked show");
String prefValue = settings.getString(USERNAME, "username not found!");
UIHelper.displayText(this, R.id.text1, prefValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment