在我的代码中我已经在共享首选项中存储了一些值,并且我在同一页面中检索了。但是现在我需要在我的设备内存中备份我的所有共享首选项值。我参考了一些教程,我得到了代码。但是我不知道如何实现它。请帮我备份我的共享偏好值。
public class medicalinfo extends Activity {
String namee,dobb,agee,heightt,weightt,lastt,nextt,Medicinee,allergies;
Button submit;
Button r,slide;
Button logout;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name = "name";
public static final String Dob= "dob";
public static final String Age = "age";
public static final String Height = "height";
public static final String Weight = "weight";
public static final String Last = "last";
public static final String Next = "next";
public static final String Medicine="medicine";
public static final String Allergies = "allergies";
// static final String PREFS_BACKUP_KEY = "prefs";
EditText nam1,dob1,age1,height1,weight1,last1,medicine1,allergies1;
String Value1,Value2,Value3,Value4,Value5,Value6,Value7,Value8,Value9,Value10,Value11,Value12,v,Value13,Value14,Value15,Value16,Value17;
TimePicker myTimePicker;
Button buttonstartSetDialog;
TextView textAlarmPrompt;
TimePickerDialog timePickerDialog;
final static int RQS_1 = 1;
Calendar cale;
private TextView pDisplayDate;
private Button pPickDate;
private int pYear;
private int pMonth;
private int pDay;
/** This integer will uniquely define the dialog to be used for displaying date picker.*/
static final int DATE_DIALOG_ID = 0;
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear;
pDay = dayOfMonth;
updateDisplay();
//displayToast();
}
};
/** Updates the date in the TextView */
private void updateDisplay() {
try {
pPickDate.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(pDay).append("/")
.append(pMonth + 1).append("/")
// .append(pDay).append("/")
.append(pYear));
String date1=new StringBuilder()
// Month is 0 based so add 1
.append(pDay).append("/")
.append(pMonth + 1).append("/")
//.append(pDay).append("-")
.append(pYear).toString();
Calendar cal = Calendar.getInstance();
String currDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("&&&&&curr"+currDate);
System.out.println("&&&&&pick"+date1);
SimpleDateFormat formatter1=new SimpleDateFormat("dd/M/yyyy");
java.util.Date date2 = formatter1.parse(date1);
java.util.Date date3 = formatter1.parse(currDate);
System.out.println("&&&&&ggg"+date2);
System.out.println("&&&&&gggcccccccc" +date3);
if(date2.before(date3)){
Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicalinfo);
sharedpreferences = getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor=sharedpreferences.edit();
/* SharedPreferences settings = getSharedPreferences(MyPREFERENCES, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
*/
//String nam1,dob1,age1,height1,weight1,last1,next1,medicine1,allergies1;
//final EditText nam1,dob1,age1,height1,weight1,last1,next1,medicine1,allergies1;
nam1= (EditText) findViewById(R.id.name);
dob1=(EditText) findViewById(R.id.dob);
age1 = (EditText) findViewById(R.id.age);
height1 = (EditText) findViewById(R.id.height);
weight1 = (EditText) findViewById(R.id.weight);
last1= (EditText) findViewById(R.id.last_visited);
pPickDate=(Button) findViewById(R.id.next_visit);
// accno=(EditText) findViewById(R.id.bankaccno);
medicine1=(EditText) findViewById(R.id.regular_medicine);
allergies1=(EditText) findViewById(R.id.allergies);
submit = (Button) findViewById(R.id.submit1);
r=(Button) findViewById(R.id.r1);
logout = (Button) findViewById(R.id.logout);
Value1 = (sharedpreferences.getString(Name, ""));
Value2 = (sharedpreferences.getString(Dob, ""));
Value3 = (sharedpreferences.getString(Age, ""));
Value4 = (sharedpreferences.getString(Height, ""));
Value5 = (sharedpreferences.getString(Weight, ""));
Value6 = (sharedpreferences.getString(Last, ""));
Value7 = (sharedpreferences.getString(Next, ""));
//Value8 = (sharedpreferences.getString(Accno, ""));
Value9 = (sharedpreferences.getString(Medicine, ""));
Value10 = (sharedpreferences.getString(Allergies, ""));
System.out.println("@@Value1 :"+Value1);
System.out.println("@@Value2 :"+Value2);
System.out.println("@@Value3 :"+Value3);
System.out.println("@@Value4 pass :"+Value7);
//EditText mno,ano,lno,pno,lano,rno,passno,accno,saccno,caccno,odaccno,dno,cno,cerno,bno;
// EditText nam1,dob1,age1,height1,weight1,last1,next1,medicine1,allergies1;
System.out.println("Date"+Value7);
nam1.setText(""+Value1);
dob1.setText(""+Value2);
age1.setText(""+Value3);
height1.setText(""+Value5);
weight1.setText(""+Value4);
last1.setText(""+Value6);
//accno.setText(""+Value8);
medicine1.setText(""+Value9);
allergies1.setText(""+Value10);
pPickDate.setText(""+Value7);
slide = (Button) findViewById(R.id.slide);
// saveSharedPreferencesToFile(File med);
slide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(medicalinfo.this, logo.class));
overridePendingTransition(R.anim.push_out_right, R.anim.pull_in_left);
finish();
}
});
// saveSharedPreferencesToFile(File;
/*
slide = (Button) findViewById(R.id.slide);
slide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDrawerLayout.openDrawer(mDrawerList);
}
});
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// mDrawerLayout.setBackground(Color.parseColor("FFFFFF"));
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new medicalinfo.DrawerItemClickListener());
mDrawerList.setOnItemClickListener(new medicalinfo.DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
*/
/*getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(true);*//*
mDrawerToggle = new ActionBarDrawerToggle(
this, */
/* host Activity *//*
mDrawerLayout, */
/* DrawerLayout object *//*
R.drawable.ic_drawer, */
/* nav drawer image to replace 'Up' caret *//*
R.string.drawer_open, */
/* "open drawe.r" description for accessibility *//*
R.string.drawer_close */
/* "close drawer" description for accessibility *//*
) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
View head = (View) this.getLayoutInflater().inflate(R.layout.test, null);
//mDrawerList.addHeaderView(head);
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(medicalinfo.this, login.class));
overridePendingTransition(R.anim.push_out_right, R.anim.pull_in_left);
}
});
System.out.println("name222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222");
*/
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(medicalinfo.this,login .class));
overridePendingTransition(R.anim.push_out_right, R.anim.pull_in_left);
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// String namee,dobb,agee,heightt,weightt,lastt,nextt,Medicinee,allergies;
// EditText nam1,dob1,age1,height1,weight1,last1,next1,medicine1,allergies1;
namee = nam1.getText().toString();
dobb=dob1.getText().toString();
agee= age1.getText().toString();
heightt = height1.getText().toString();
weightt = weight1.getText().toString();
lastt=last1.getText().toString();
nextt=pPickDate.getText().toString();
// acc=accno.getText().toString();
Medicinee=medicine1.getText().toString();
allergies=allergies1.getText().toString();
System.out.println("gggggggggggggggggggggggggggggggg"+allergies);
editor.putString(Name, namee);
editor.putString(Dob, dobb);
editor.putString(Age, agee);
editor.putString(Height, heightt);
editor.putString(Weight, weightt);
editor.putString(Last, lastt);
editor.putString(Next, nextt);
//editor.putString(Accno, acc);
editor.putString(Medicine, Medicinee);
editor.putString(Allergies, allergies);
System.out.println("ffffffffffff"+nextt);
editor.commit();Toast.makeText(medicalinfo.this, "Updated Successfully", Toast.LENGTH_SHORT).show();
SimpleDateFormat formatter1=new SimpleDateFormat("dd/M/yyyy");
try {
Calendar cale = Calendar.getInstance();
java.util.Date date2 = formatter1.parse(nextt);
System.out.println("LLLLLLLLLLLLL"+date2);
cale.setTime(date2);
//Calendar calendar = Calendar.getInstance();
cale.set(Calendar.HOUR_OF_DAY, 9);
cale.set(Calendar.MINUTE, 00);
cale.set(Calendar.SECOND, 00);
Intent intent = new Intent(getBaseContext(), AlarmReceiver1.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
cale.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
intent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
intent.putExtra("date", "pPickDate");
PendingIntent broadcast = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, cale.getTimeInMillis(), broadcast);
/*
Intent intent = new Intent(getBaseContext(), AlarmReceiver1.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cale.getTimeInMillis(), AlarmManager.INTERVAL_DAY , pendingIntent); //set repeating every 24 hours
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// cal = Calendar.getInstance();
//cal.add(Calendar.SECOND, 15);
intent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
intent.putExtra("date", "pPickDate");
//intent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, cale.getTimeInMillis(), broadcast);
*/
} catch (ParseException e) {
e.printStackTrace();
}
}
});
pPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
Calendar cal;
cal = Calendar.getInstance();
pYear = cal.get(Calendar.YEAR);
pMonth = cal.get(Calendar.MONTH);
pDay = cal.get(Calendar.DAY_OF_MONTH);
System.out.println("***************");
// updateDisplay();
// String currDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
pDateSetListener,
pYear, pMonth, pDay);
}
return null;
}
public void onBackPressed() {
super.onBackPressed();
// Intent i = new Intent(info_values.this, home.class);
startActivity(new Intent(medicalinfo.this,logo.class));
overridePendingTransition(R.anim.pull_in_left,R.anim.push_out_right);
finish();
}
private void openTimePickerDialog(boolean is24r){
Calendar calendar = Calendar.getInstance();
timePickerDialog = new TimePickerDialog(
medicalinfo.this,
onTimeSetListener,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
is24r);
timePickerDialog.setTitle("Set Alarm Time");
timePickerDialog.show();
}
TimePickerDialog.OnTimeSetListener onTimeSetListener
= new TimePickerDialog.OnTimeSetListener(){
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
calSet.set(Calendar.MINUTE, minute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
if(calSet.compareTo(calNow) <= 0){
//Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet);
}};
private void setAlarm(Calendar targetCal) {
textAlarmPrompt.setText(
"\n\n***\n"
+ "Alarm is set@ " + targetCal.getTime() + "\n"
+ "***\n");
下面是我的共享偏好代码。我不知道如何在我的java文件中包含该代码,并且不确定代码是否正确..请帮助我备份我的共享我的设备内存中的偏好值。
private boolean saveSharedPreferencesToFile(File dst) {
boolean res = false;
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(dst));
SharedPreferences sharedPreferences =
getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
output.writeObject(sharedPreferences.getAll());
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (output != null) {
output.flush();
output.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
@SuppressWarnings({ "unchecked" })
private boolean loadSharedPreferencesFromFile(File src) {
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
SharedPreferences.Editor editor = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE).edit();
editor.clear();
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Map.Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
editor.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
editor.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
editor.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
editor.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
editor.putString(key, ((String) v));
}
editor.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
答案 0 :(得分:0)
您只需在medicalinfo
活动结束时添加这两种方法,然后通过传递文件来调用saveSharedPreferencedToFile
或loadSavedPreferencesFromFile
。
您可以像这样创建一个文件:File file = new File(getFilesDir(), "shared-prefs.txt");
您需要传递相同的文件来写入和读取您的设备内存。
如果您从活动外部调用它,则需要传递一个上下文来调用context.getFilesDir()
。