I was trying to create a Database back up, however, it always return Back up fail. Any help will be appreciated.
Here is my code:
public class SettingsFragment extends Fragment {
public SettingsFragment(){}
Button btnCreateBU, btnRestoreBU;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_settings, container, false);
btnCreateBU = (Button) rootView.findViewById(R.id.crebutton1);
btnRestoreBU = (Button) rootView.findViewById(R.id.resbutton2);
btnCreateBU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exportDB();
}
});
btnRestoreBU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
importDB();
}
});
return rootView;
}
private void importDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "com.my.eclassrecord"
+ "//databases//" + "data.db";
String backupDBPath = "/Android/data/com.my.eclassrecord/files/"; // From SD directory.
File backupDB = new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getActivity().getApplicationContext(), "Import Successful!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Import Failed!", Toast.LENGTH_SHORT)
.show();
}
}
private void exportDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "com.my.eclassrecord"
+ "//databases//" + "data.db";
String backupDBPath = "/Android/data/com.my.eclassrecord/files/";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getActivity().getApplicationContext(), "Backup Successful!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Backup Failed!", Toast.LENGTH_SHORT)
.show();
}
}
}
I also have declared the following permissions to my manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
Aucun commentaire:
Enregistrer un commentaire