Skip to content

Instantly share code, notes, and snippets.

@singhangadin
Last active January 22, 2019 14:02
Show Gist options
  • Save singhangadin/fca769dcbfdbfb0dd6d46c55452da971 to your computer and use it in GitHub Desktop.
Save singhangadin/fca769dcbfdbfb0dd6d46c55452da971 to your computer and use it in GitHub Desktop.
Utility functions used regularly
public class Utility {
public static void copyDatabaseToSdcard(Context context, String databaseName) {
if(BuildConfig.DEBUG) {
String currentDBPath = context.getDatabasePath(databaseName).getAbsolutePath();
String downloadDir = Environment.getExternalStorageDirectory() + "/Dump/" + databaseName + ".db";
File dataBase = new File(currentDBPath);
File file = new File(downloadDir);
try {
file.delete();
if(!file.exists()) {
file.createNewFile();
}
copyFileUsingFileStreams(dataBase, file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void copyFileUsingFileStreams(File source, File dest) throws IOException {
try (InputStream input = new FileInputStream(source); OutputStream output = new FileOutputStream(dest)) {
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
output.flush();
}
}
public void requestPermissions() {
int courseLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
int fineLocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
int readPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
int writePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (courseLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (fineLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (readPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (writePermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(
MainActivity.this,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
REQUEST_ID_MULTIPLE_PERMISSIONS
);
}
}
}
private static @Nullable AppCompatActivity scanForActivity(Context context) {
if (context == null)
return null;
else if (context instanceof AppCompatActivity)
return (AppCompatActivity) context;
else if (context instanceof ContextWrapper)
return scanForActivity(((ContextWrapper) context).getBaseContext());
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment