How can I fix my save function? [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have an file list and when a file is clicked its contents are displayed in an EditText. That file is set as currentFile. If the user tries to open a new file before saving the old one they are shown a save dialog. The OK button on the dialog should save the current working file but instead saves it as the file the user is trying to open. Where is the problem in my code that's causing the currentfile to be saved over the new one trying to be opened.
public boolean exists;
public File currentFile;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
et = (EditTextLineNumbers) findViewById(R.id.ide);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
File dir = new File(Environment.getExternalStorageDirectory() + "/My Webs");
currentDirectory = dir;
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
changed = false;
}
#Override
public void afterTextChanged(Editable s) {
changed=true;
}
});
changed=false;
if(dir.isDirectory()) {
browseToRoot();
}else{
dir.mkdir();
}
}
private void openFile(File aFile){
String nullChk = et.getText().toString();
exists = true;
currentFile = aFile;
if(!changed || nullChk.matches("")){
try {
et.setText(new Scanner(aFile).useDelimiter("\\Z").next());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save first?");
alert.setMessage("(Will be saved in the current working directory)");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String temptxt = et.getText().toString();
if(exists){
saveFile(currentFile.getPath(), temptxt);
}else{
saveAs();
}
}
});
final File tempFile = aFile;
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
et.setText(new Scanner(tempFile).useDelimiter("\\Z").next());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
changed=false;
}
});
alert.show();
}
}
private void saveFile(String sFileName, String sBody){
//Toast.makeText(this, exists +"", Toast.LENGTH_SHORT).show();
if (exists) {
try {
File tempfile = new File(sFileName);
FileWriter writer = new FileWriter(tempfile);
writer.write(sBody);
writer.flush();
writer.close();
changed=false;
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
}
}else{
Toast.makeText(this, "Save as", Toast.LENGTH_SHORT).show();
saveAs();
}
}
private void saveAs(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save as");
alert.setMessage("(Will be saved in the current working directory)");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
String tmpText = et.getText().toString();
try {
File tempfile = new File(currentDirectory, value);
FileWriter writer = new FileWriter(tempfile);
writer.write(tmpText);
writer.flush();
writer.close();
changed=false;
//itla.notifyDataSetChanged();
fill(currentDirectory.listFiles());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
/**
* This function browses up one level
* according to the field: currentDirectory
*/
private void upOneLevel(){
if(this.currentDirectory.getParent() != null && !this.currentDirectory.getPath().equals("/sdcard/My Webs")){
this.browseTo(this.currentDirectory.getParentFile());
}else{
//Do nothing
}
}
private void browseTo(final File aDirectory){
// On relative we display the full path in the title.
if(this.displayMode == DISPLAYMODE.RELATIVE)
this.setTitle(aDirectory.getAbsolutePath() + " :: " +
getString(R.string.app_name));
if (aDirectory.isDirectory()){
this.currentDirectory = aDirectory;
fill(aDirectory.listFiles());
}else{
openFile(aDirectory);
}
changed=false;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String selectedFileString = this.directoryEntries.get(position)
.getText();
if (selectedFileString.equals(getString(R.string.current_dir))) {
// Refresh
this.browseTo(this.currentDirectory);
} else if (selectedFileString.equals(getString(R.string.up_one_level))) {
this.upOneLevel();
} else {
File clickedFile = null;
switch (this.displayMode) {
case RELATIVE:
clickedFile = new File(this.currentDirectory
.getAbsolutePath()
+ this.directoryEntries.get(position)
.getText());
break;
case ABSOLUTE:
clickedFile = new File(this.directoryEntries.get(
position).getText());
break;
}
if (clickedFile != null)
currentFile=clickedFile;
this.browseTo(clickedFile);
}
}
}

Third line of openFile(): you change currentFile before you conditionally ask the user if he wants to save currentFile before opening the new file. Change currentFile when you actually open another file, rather than before, and you won't have this problem even accidentally.

Related

passing file name to intent

I'm new to android and trying to create an app which has a file picker and plays a particular file. I have been able to create the intent to open files; however I'm not able to pass the file path from the file picker to the intent to open that same particular file. Code given below. Appreciate any help. thanks.
EDIT Adding lines I missed___
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
public String root = "/mnt/usbhost0";
public TextView myPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView) findViewById(R.id.path);
getDir(root);
}
public void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
File file;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory())
{
if (file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
} else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select")
.setMessage("Select " + file.getName() + " to play ?") //Send fileurl from here //
.setPositiveButton("Select", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new DecryptTask().execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
void decrypt() throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
File videoFile2Play = new File(//to here);
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "video/m4v");
startActivity(i);
}
public class DecryptTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
decrypt();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
EDIT July 27, 2018
Updated my code as per #miguelarc's suggestion, but still unable to pass the name. Any suggestions or mistakes pointed out?
public class MainActivity extends ListActivity {
private List<String> item = null;
private List<String> path = null;
public String root = "/mnt/usbhost0";
public TextView myPath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myPath = (TextView) findViewById(R.id.path);
getDir(root);
}
public void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
File file;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final File file = new File(path.get(position));
if (file.isDirectory())
{
if (file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
} else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("Select")
.setMessage("Select " + file.getName() + " to play ?")
.setPositiveButton("Select", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new DecryptTask(file.getAbsolutePath()).execute();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
void decrypt(String filePath) throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException {
File extStore = Environment.getExternalStorageDirectory();
File videoFile2Play = new File(file.getAbsolutePath());
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "video/*");
startActivity(i);
}
public class DecryptTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
String filePath;
public DecryptTask(String filePath){
this.filePath = filePath;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Loading your video");
pd.show();
}
#Override
protected String doInBackground(String... params) {
try {
decrypt(this.filePath);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
}
}
}
You should pass the filePath to your DecryptTask. Add a constructor to it, and add the filePath, so you can initialize your videoFile2Play with the valid path. At the moment, your file is not initializing anything, that's why the intent is not starting/showing anything.
Add a constructor like so:
public class DecryptTask extends AsyncTask<String, String, String> {
String filePath;
public DecryptTask(String filePath){
this.filePath = filePath;
}
#Override
protected String doInBackground(String... params) {
try {
decrypt(this.filePath); //<--- Add filePath as param of decrypt method
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
then, use the filePath you got inside the decrypt() method.

Trouble in opening front camera in android 6.0

See i have permissions for camera.Opening front camera returns null, Even though i have permissions for using camera, searched a lot of answers but nothing helped
This is how i am trying to open front camera
Camera cam = null;
try{
cam = Camera.open(1);
}catch (Exception e){
Log.e("Manojjjj", "Camera failed to open: " + e.getMessage());
e.printStackTrace();
}
return cam;
The code is working fine in android 5,But in android 6,it is returning null for front camera(Back camera is working fine), and when i change the id to 0(cam = Camera.open(0)), it opens back camera without any problem.
Thanks in advance.
the exception is:
09-01 16:52:29.228 24480-24480/com.magostech.dualcamera E/Manojjjj: Camera failed to open: Fail to connect to camera service
Every question that i have searched is saying to add run time permission, but i am already giving run time permission, So i am doing it right, i think my problem is not to add run time permission.
Full Code:
private Camera mCamera = null;
private Camera mCamera1 = null;
private Handler mBackgroundHandler;
private CameraActivity mPreview;
private CameraPreview mPreview1;
FrameLayout preview;
FrameLayout preview1;
private static final int REQUEST_CAMERA_PERMISSION = 1;
public boolean safeToTakePicture = false;
String front,back;
Bitmap bitmap1;
Bitmap bitmap2;
private static final int PERMISSION_CALLBACK_CONSTANT = 100;
private static final int REQUEST_PERMISSION_SETTING = 101;
String[] permissionsRequired = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private SharedPreferences permissionStatus;
private boolean sentToSettings = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
permissionStatus = getSharedPreferences("permissionStatus",MODE_PRIVATE);
checkForPermissions();
// Create an instance of Camera
}
public void checkForPermissions(){
if(ActivityCompat.checkSelfPermission(Main2Activity.this,permissionsRequired[0]) != PackageManager.PERMISSION_GRANTED
||ActivityCompat.checkSelfPermission(Main2Activity.this,permissionsRequired[1]) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(Main2Activity.this,permissionsRequired[0])
||ActivityCompat.shouldShowRequestPermissionRationale(Main2Activity.this,permissionsRequired[1])){
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("Need Multiple Permissions");
builder.setMessage("This app needs Camera and Location permissions.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
ActivityCompat.requestPermissions(Main2Activity.this,permissionsRequired,PERMISSION_CALLBACK_CONSTANT);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
else if (permissionStatus.getBoolean(permissionsRequired[0],false)) {
//Previously Permission Request was cancelled with 'Dont Ask Again',
// Redirect to Settings after showing Information about why you need the permission
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("Need Multiple Permissions");
builder.setMessage("This app needs Camera and Location permissions.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
sentToSettings = true;
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
Toast.makeText(getBaseContext(), "Go to Permissions to Grant Camera and Location", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
//just request the permission
ActivityCompat.requestPermissions(Main2Activity.this,permissionsRequired,PERMISSION_CALLBACK_CONSTANT);
}
SharedPreferences.Editor editor = permissionStatus.edit();
editor.putBoolean(permissionsRequired[0],true);
editor.commit();
} else {
//You already have the permission, just go ahead.
proceedAfterPermission();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == PERMISSION_CALLBACK_CONSTANT){
//check if all permissions are granted
boolean allgranted = false;
for(int i=0;i<grantResults.length;i++){
if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
allgranted = true;
} else {
allgranted = false;
break;
}
}
if(allgranted){
proceedAfterPermission();
} else if(ActivityCompat.shouldShowRequestPermissionRationale(Main2Activity.this,permissionsRequired[0])
|| ActivityCompat.shouldShowRequestPermissionRationale(Main2Activity.this,permissionsRequired[1])
|| ActivityCompat.shouldShowRequestPermissionRationale(Main2Activity.this,permissionsRequired[2])){
AlertDialog.Builder builder = new AlertDialog.Builder(Main2Activity.this);
builder.setTitle("Need Multiple Permissions");
builder.setMessage("This app needs Camera and Location permissions.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
ActivityCompat.requestPermissions(Main2Activity.this,permissionsRequired,PERMISSION_CALLBACK_CONSTANT);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
Toast.makeText(getBaseContext(),"Unable to get Permission",Toast.LENGTH_LONG).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_PERMISSION_SETTING) {
if (ActivityCompat.checkSelfPermission(Main2Activity.this, permissionsRequired[0]) == PackageManager.PERMISSION_GRANTED) {
//Got Permission
proceedAfterPermission();
}
}
}
private void proceedAfterPermission() {
mCamera = getCameraInstance();
mCamera1 = openFrontFacingCamera();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraActivity(this, mCamera);
mPreview1 = new CameraPreview(this,mCamera1);
preview = (FrameLayout) findViewById(R.id.camera_preview);
preview1 =(FrameLayout) findViewById(R.id.camera_preview1);
preview.addView(mPreview);
preview1.addView(mPreview1);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.take_picture);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (safeToTakePicture) {
mCamera.takePicture(null,null,backCamera);
mCamera1.takePicture(null, null, frontCamera);
safeToTakePicture = false;
}
}
});
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(0); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
private Camera openFrontFacingCamera(){
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camIdx = 0; camIdx < cameraCount; camIdx++ ) {
Camera.getCameraInfo( camIdx, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
Log.e("Cam Id",String.valueOf(camIdx));
cam = Camera.open( camIdx );
} catch (RuntimeException e) {
e.printStackTrace();
Log.e("Manoj", "Camera failed to open: " );
}
}
}
return cam;
}
#Override
protected void onPostResume() {
super.onPostResume();
if (sentToSettings) {
if (ActivityCompat.checkSelfPermission(Main2Activity.this, permissionsRequired[0]) == PackageManager.PERMISSION_GRANTED) {
//Got Permission
proceedAfterPermission();
}
}
}
private Camera.PictureCallback frontCamera = new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
camera.startPreview();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Dual Camera");
if (myDir.exists()) {
myDir.delete();
}
myDir.mkdirs();
String fname = "Image" + new Date().getTime() + ".jpg";
File file = new File(myDir, fname);
try{
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
MediaScannerConnection.scanFile(Main2Activity.this, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
front = String.valueOf(file);
bitmap1 = BitmapFactory.decodeFile(front);
Log.e("Front",front);
if(bitmap1!=null&&bitmap2!=null){
mergeBitmap(bitmap1,bitmap2);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
safeToTakePicture = true;
}
};
public Bitmap mergeBitmap(Bitmap bitmap1, Bitmap bitmap2) {
Bitmap mergedBitmap = null;
int w, h = 0;
h = bitmap1.getHeight() + bitmap2.getHeight();
if (bitmap1.getWidth() > bitmap2.getWidth()) {
w = bitmap1.getWidth();
} else {
w = bitmap2.getWidth();
}
mergedBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mergedBitmap);
canvas.drawBitmap(bitmap1, 0f, 0f, null);
canvas.drawBitmap(bitmap2, 0f, bitmap1.getHeight(), null);
saveBitmap(mergedBitmap);
return mergedBitmap;
}
private Camera.PictureCallback backCamera = new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
camera.startPreview();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Dual Camera");
if (myDir.exists()) {
myDir.delete();
}
myDir.mkdirs();
String fname = "Image" + new Date().getTime() + ".jpg";
File file = new File(myDir, fname);
try{
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
MediaScannerConnection.scanFile(Main2Activity.this, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
back = String.valueOf(file);
bitmap2 = BitmapFactory.decodeFile(String.valueOf(file));
Log.e("Back",back);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
safeToTakePicture = true;
}
};
private void saveBitmap(Bitmap finalBitmap){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Dual Camera");
if (myDir.exists()) {
myDir.delete();
}
myDir.mkdirs();
String fname = "Merged" + new Date().getTime() + ".jpg";
File file = new File(myDir, fname);
try{
FileOutputStream fos = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
MediaScannerConnection.scanFile(Main2Activity.this, new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
Toast.makeText(getApplicationContext(),
"Image Saved to:" + file, Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
try {
mCamera = Camera.open(0);
mCamera.setPreviewCallback(null);
mPreview = new CameraActivity(Main2Activity.this, mCamera);
preview.addView(mPreview);
mCamera.startPreview();
}catch (Exception e) {
Log.d("Manoj", "Error starting camera preview: " + e.getMessage());
}try{
if (mCamera1 == null){
mCamera1 = openFrontFacingCamera();
//mCamera1 = Camera.open(1);
mCamera1.setPreviewCallback(null);
mPreview1 = new CameraPreview(Main2Activity.this,mCamera1);
preview1.addView(mPreview1);
mCamera1.startPreview();
}
}catch (Exception e){
Log.d("Manoj", "Error starting camera preview: " + e.getMessage());
}
safeToTakePicture = true;
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
}
#Override
protected void onPause() {
try {
// release the camera immediately on pause event
// releaseCamera();
mCamera1.stopPreview();
mCamera1.setPreviewCallback(null);
mPreview1.getHolder().removeCallback(mPreview1);
mCamera1.release();
mCamera1 = null;
} catch (Exception e) {
e.printStackTrace();
}
try{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mPreview.getHolder().removeCallback(mPreview);
mCamera.release();
mCamera = null;
}catch (Exception e){
e.printStackTrace();
}
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBackgroundHandler != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
mBackgroundHandler.getLooper().quitSafely();
} else {
mBackgroundHandler.getLooper().quit();
}
mBackgroundHandler = null;
}
}
#Override
public void onBackPressed(){
super.onBackPressed();
}
As per the Android Doc, Android app operates in a process sandbox.
For Android 6.0 or above OS, user can not access the additional capabilities not provided by the basic sandbox. You need to request for that PERMISSION first. Here are those critical PERMISSIONS
If the device is running Android 5.1 (API level 22) or lower, or the app's targetSdkVersion is 22 or lower, the system asks the user to grant the permissions at install time and you can access any sensitive tool.
Check the DOC for more detail.
Try this:
if( ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA}, 5);
}
}
And override the following method using Ctrl + O copying, pasting would might result in an error
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 5) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
}
else {
// Your app will not have this permission. Turn off all functions
// that require this permission or it will force close like your
// original question
}
}
}

why do i get th java.lang.RuntimeException: Unable to start activity ComponentInfo

Hi guys im making a auto update after following a tutorial online then editing the code to suit my needs.. but im getting this error in my logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.Homescreen}: android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.harrops.h20droidapp/com.example.harrops.h20droidapp.UpdateService}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
can some one please help me
this is my service class
public class UpdateService extends Service {
public UpdateService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url = "<MY Link for version>";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response != null) {
boolean resp = response.contains("<div class='post-body entry-content' id='post-body-6791062644900393367' itemprop='description articleBody'>\n" +
"1.1.8\n" +
"<div style='clear: both;'></div>");
if (!resp) {
//Dialog to show update
Intent intent1 = new Intent(UpdateService.this, UpdateDialog.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
} else {
Toast.makeText(UpdateService.this, "No New Update Found..", Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(stringRequest);
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
then this is my dialog class
public static Button btn;
public static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Update";
public static File Dir = new File(path);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidAuthSession session = buildSession();
dropboxAPI = new DropboxAPI<AndroidAuthSession>(session);
Dir.mkdir();
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setTitle("update");
alertDialog.setMessage("New update Available...");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DownloadFromDropboxFromPath(path + "downloadFileFromDropbox", "Update/Myupdate.apk");
}
});
alertDialog.show();
}
static DropboxAPI<AndroidAuthSession> dropboxAPI;
private static final String APP_KEY = "********* **** ** **";
private static final String APP_SECRET = "XXX XX X X XX X";
private static final String ACCESSTOKEN = "xx x x xxx x x x x";
private DropboxAPI.UploadRequest request;
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeyPair);
session.setOAuth2AccessToken(ACCESSTOKEN);
return session;
}
static final int UploadFromSelectApp = 9501;
static final int UploadFromFilemanager = 9502;
public static String DropboxUploadPathFrom = "";
public static String DropboxUploadName = "";
public static String DropboxDownloadPathFrom = "";
public static String DropboxDownloadPathTo = "";
private void UploadToDropboxFromPath(String uploadPathFrom, String uploadPathTo) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final String uploadPathF = uploadPathFrom;
final String uploadPathT = uploadPathTo;
Thread th = new Thread(new Runnable() {
public void run() {
File tmpFile = null;
try {
tmpFile = new File(uploadPathF);
} catch (Exception e) {
e.printStackTrace();
}
FileInputStream fis = null;
try {
fis = new FileInputStream(tmpFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
dropboxAPI.putFileOverwrite(uploadPathT, fis, tmpFile.length(), null);
} catch (Exception e) {
}
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
private void UploadToDropboxFromSelectedApp(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Upload from ..."), UploadFromSelectApp);
}
private void UploadToDropboxFromFilemanager(String uploadName) {
DropboxUploadName = uploadName;
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, UploadFromFilemanager);
}
private void DownloadFromDropboxFromPath(String downloadPathTo, String downloadPathFrom) {
DropboxDownloadPathTo = downloadPathTo;
DropboxDownloadPathFrom = downloadPathFrom;
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Download file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
File file = new File(DropboxDownloadPathTo + DropboxDownloadPathFrom.substring(DropboxDownloadPathFrom.lastIndexOf('.')));
if (file.exists()) file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
UpdateDialog.dropboxAPI.getFile(DropboxDownloadPathFrom, null, outputStream, null);
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully downloaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == UploadFromFilemanager) {
final Uri currFileURI = intent.getData();
final String pathFrom = currFileURI.getPath();
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
Thread th = new Thread(new Runnable() {
public void run() {
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
UploadToDropboxFromPath(pathFrom, "/db-test/" + DropboxUploadName + pathFrom.substring(pathFrom.lastIndexOf('.')));
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
}
});
th.start();
}
if (requestCode == UploadFromSelectApp) {
Toast.makeText(getApplicationContext(), "Upload file ...", Toast.LENGTH_SHORT).show();
final Uri uri = intent.getData();
DropboxUploadPathFrom = getPath(getApplicationContext(), uri);
if (DropboxUploadPathFrom == null) {
DropboxUploadPathFrom = uri.getPath();
}
Thread th = new Thread(new Runnable() {
public void run() {
try {
final File file = new File(DropboxUploadPathFrom);
InputStream inputStream = getContentResolver().openInputStream(uri);
dropboxAPI.putFile("/db-test/" + DropboxUploadName + file.getName().substring(file.getName().lastIndexOf("."),
file.getName().length()), inputStream, file.length(), null, new ProgressListener() {
#Override
public long progressInterval() {
return 100;
}
#Override
public void onProgress(long arg0, long arg1) {
}
});
getMain().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File successfully uploaded.", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
th.start();
}
super.onActivityResult(requestCode, resultCode, intent);
}
public String getPath(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA, MediaStore.Video.Media.DATA, MediaStore.Audio.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
if (s != null) {
cursor.close();
return s;
}
} catch (Exception e) {
}
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public UpdateDialog getMain() {
return this;
}
}
then finally i call it in my homescreen class. with an intent
Intent intent = new Intent(Homescreen.this, UpdateService.class);
startActivity(intent);
UpdateService is a Service. It is not an Activity. To start a service, you call startService(), not startActivity().
As UpdateService is a service you have to start it by startService() method like #CommonsWare mentioned above. Also don't forget to add your service in Manifest file.
UpdateService is not an activity, It's a class that is extending services.
I think u r a very beginner.
Please go to Udacity and learn the concepts before tingling with android, otherwise, u will waste lot of your time in finding a copy-paste solution.

How can I alter ths code to correctly save a file if it exists?

Currently I can load a text file into an EditText. If the text is changed and the user attempts to open a new file a "save first?" dialog is displayed. The problem I'm having is instead of saving the working file (currentFile) it saves over the file to be opened.
Where am I going wrong?
File currentFile;
public boolean changed;
public boolean exists;
...
private void openFile(final File aFile){
String nullChk = et.getText().toString();
exists = true;
if(!changed || nullChk.matches("")){
try {
et.setText(new Scanner(aFile).useDelimiter("\\Z").next());
changed=false;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save first?");
alert.setMessage("(Will be saved in the current working directory)");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String temptxt = et.getText().toString();
if(exists){
saveFile(aFile.getPath(), temptxt);
}else{
saveAs();
}
}
});
final File tempFile = aFile;
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
et.setText(new Scanner(tempFile).useDelimiter("\\Z").next());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
changed=false;
}
});
alert.show();
//currentFile = aFile;
}
}
private void saveFile(String sFileName, String sBody){
//Toast.makeText(this, exists +"", Toast.LENGTH_SHORT).show();
if (exists) {
try {
File tempfile = new File(sFileName);
FileWriter writer = new FileWriter(tempfile);
writer.write(sBody);
writer.flush();
writer.close();
changed=false;
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
}
}else{
Toast.makeText(this, "Save as", Toast.LENGTH_SHORT).show();
saveAs();
}
}
private void saveAs(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Save as");
alert.setMessage("(Will be saved in the current working directory)");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
String tmpText = et.getText().toString();
try {
File tempfile = new File(currentDirectory, value);
FileWriter writer = new FileWriter(tempfile);
writer.write(tmpText);
writer.flush();
writer.close();
changed=false;
fill(currentDirectory.listFiles());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
startActivityForResult(new Intent(MainActivity.this, NewFile.class),1);
dialog.dismiss();
}
});
alert.show();
}
I think you use same file to open and save files.
When you open file you use aFile as parameter openFile(final File aFile) and use aFile in
et.setText(new Scanner(aFile).useDelimiter("\\Z").next());
and
saveFile(aFile.getPath(), temptxt);.

How to show ProgressDialog after AlertDialog

I am having trouble with an alert dialog that I cannot hide.
when the user press a button I show a dialog that is created with this code :
new AlertDialog.Builder(this)
.setTitle(R.string.enterPassword)
.setView(textEntryView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = pwdText.getText().toString();
dialog.dismiss();
processUserAction(password,targetUri);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.
create();
There are some heavy operations performed in the 'processUserAction' method, and inside it I am using an AysncTask that displays a ProgressDialog.
The problem I am having is that the dialog prompting for the password never goes of the screen (I have tried with dismiss(), cancel()).
I guess it stays there until the onClick method is finished.
So, my question is how to close that AlertDialog, so I can show the ProgressDialog?
Another approach I have been trying is to set a DismissListener in the AlertDialog and calling the heavy operations from there, but I have had no luck ( it didn't get called ).
EDIT: Adding AsyncTask code
public class BkgCryptOperations extends AsyncTask<File,Void,Integer>{
#Override
protected Integer doInBackground(File... files) {
if (files!=null && files.length > 0){
File source = files[0];
File target = files[1];
return cryptAction.process(source,password, target);
}
return Constants.RetCodeKO;
}
CryptAction cryptAction;
String password;
ProgressDialog progressDialog;
public BkgCryptOperations (CryptAction cryptAction,String password,ProgressDialog progressDialog){
this.cryptAction=cryptAction;
this.password=password;
this.progressDialog=progressDialog;
}
#Override
protected void onPreExecute() {
if (progressDialog!=null){
progressDialog.show();
}
}
protected void onPostExecute(Integer i) {
if (progressDialog!=null){
progressDialog.dismiss();
}
}
}
Thanks in advance
Here is a excample how I do it:
public void daten_remove_on_click(View button) {
// Nachfragen
if (spinadapter.getCount() > 0) {
AlertDialog Result = new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(getString(R.string.dialog_data_remove_titel))
.setMessage(getString(R.string.dialog_data_remove_text))
.setNegativeButton(getString(R.string.dialog_no),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
// Nicht löschen
dialogInterface.cancel();
}
})
.setPositiveButton(getString(R.string.dialog_yes),
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialogInterface, int i) {
String _quellenName = myCursor.getString(1);
deleteQuellenRecord(_quellenName);
zuletztGelöscht = _quellenName;
}
}).show();
} else {
// Keine Daten mehr vorhanden
Toast toast = Toast.makeText(Daten.this,
getString(R.string.dialog_data_remove_empty),
Toast.LENGTH_SHORT);
toast.show();
}
}
Here is the code of deleteQuellenRecord:
private void deleteQuellenRecord(String _quellenName) {
String DialogTitel = getString(R.string.daten_delete_titel);
String DialogText = getString(R.string.daten_delete_text);
// Dialogdefinition Prograssbar
dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
// set the progress to be horizontal
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// reset the bar to the default value of 0
dialog.setProgress(0);
// set the maximum value
dialog.setMax(4);
// display the progressbar
increment = 1;
dialog.show();
// Thread starten
new Thread(new MyDeleteDataThread(_quellenName)) {
#Override
public void run() {
try {
// Datensatz löschen
myDB.execSQL("DELETE ... ');");
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...);");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
myDB.execSQL("DELETE ...;");
// active the update handler
progressHandler
.sendMessage(progressHandler.obtainMessage());
// Einstellung speichern
try {
settings.edit().putString("LetzteQuelle", "-1")
.commit();
} catch (Exception ex) {
settings.edit().putString("LetzteQuelle", "").commit();
}
} catch (Exception ex) {
// Wait dialog beenden
dialog.dismiss();
Log.e("Glutenfrei Viewer",
"Error in activity MAIN - remove data", ex); // log
// the
// error
}
// Wait dialog beenden
dialog.dismiss();
}
}.start();
this.onCreate(null);
}
Wiht Async Task I do it this way:
private class RunningAlternativSearch extends
AsyncTask<Integer, Integer, Void> {
final ProgressDialog dialog = new ProgressDialog(SearchResult.this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
#Override
protected void onPreExecute() {
alternativeSucheBeendet = false;
String DialogTitel = getString(R.string.daten_wait_titel);
DialogText = getString(R.string.dialog_alternativ_text);
DialogZweiteChance = getString(R.string.dialog_zweite_chance);
DialogDritteChance = getString(R.string.dialog_dritte_chance);
sucheNach = getString(R.string.dialog_suche_nach);
dialog.setCancelable(true);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface arg0) {
// TODO Auto-generated method stub
cancleBarcodeWorker();
if (alternativeSucheBeendet==false){
// Activity nur beenden wenn die Suche
// nicht beendet wurde, also vom User abgebrochen
Toast toast = Toast.makeText(SearchResult.this, SearchResult.this
.getString(R.string.toast_suche_abgebrochen),
Toast.LENGTH_LONG);
toast.show();
myDB.close();
SearchResult.this.finish();
}
}
});
dialog.show();
}
...
Can you show the code for processUserAction(..)? There is no need to include the dismiss.
I did something very similar and had no problems...
Here's the code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Export data.\nContinue?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String file = getObra().getNome();
d = new ProgressDialog(MenuActivity.this);
d.setTitle("Exporting...");
d.setMessage("please wait...");
d.setIndeterminate(true);
d.setCancelable(false);
d.show();
export(file);
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In export(file) I open the thread:
private void export(final String file) {
new Thread() {
public void run() {
try {
ExportData ede = new ExportData(
getApplicationContext(), getPmo().getId(),
file);
ede.export();
handlerMessage("Done!!");
} catch (Exception e) {
handlerMessage(e.getMessage());
System.out.println("ERROR!!!" + e.getMessage());
}
}
}.start();
}
In handlerMessage I dismiss the progressDialog and show the final message.
Hope it helps you.
You could create a listener outside of the AlertDialog, to abstract out the logic within the OnClickListener for the positive button. That way, the listener can be notified, and the AlertDialog will be dismissed immediately. Then, whatever processing of the user's input from the AlertDialog can take place independently of the AlertDialog. I'm not sure if this is the best way to accomplish this or not, but it's worked well for me in the past.
As far as I can tell, I don't see any obvious problems with your AsyncTask code.
public interface IPasswordListener {
public void onReceivePassword(String password);
}
IPasswordListener m_passwordListener = new IPasswordListener {
#Override
public void onReceivePassword(String password) {
processUserAction(password,targetUri);
}
}
public void showPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.enterPassword);
builder.setView(textEntryView);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
m_passwordListener.onReceivePassword(pwdText.getText().toString());
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
}

Categories

Resources