EditText.getText() cannot be resolved, making a file protection app - android

I am making a file protection application that asks users to enter a password, this password is stored and next time to view the file they have to enter the same password.
I am able to ask users to set password, and protect the file, and I am able to ask users to enter password for viewing. the issue I have is with the input field.
The code for setting password is:
public static void protect(final File file, final FileListActivity mContext, final OperationCallback<Void> callback)
{
LinearLayout layout = new LinearLayout(mContext);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText input = new EditText(mContext);
input.setHint(mContext.getString(R.string.enter_new_name));
input.setSingleLine();
layout.addView(input);
final EditText confirm = new EditText(mContext);
confirm.setHint(mContext.getString(R.string.confirm_new_name));
confirm.setSingleLine();
layout.addView(confirm);
new Builder(mContext)
.setTitle(mContext.getString(R.string.rename_dialog_title, file.getName()))
.setView(layout)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String newName = confirm.getText().toString();
String password=input.getText().toString();
try
{
//File parentFolder = file.getParentFile();
if (newName.equals(input.getText().toString())){
pass=newName;
pe=true;
filename=file.getName();
Toast.makeText(mContext,"password match", Toast.LENGTH_LONG).show();
}
else if (!newName.equals(password)) {
pe=false;
Toast.makeText(mContext,"password doesnot match", Toast.LENGTH_LONG).show();
}
else
{
if(callback!=null)
{
callback.onFailure(new Exception());
}
if(mContext!=null)
new Builder(mContext)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.rename_failed, file.getName()))
.show();
}
}
catch (Exception e) {
if(callback!=null)
{
callback.onFailure(e);
}
Log.e(TAG, "Error occured while renaming path", e);
if(mContext!=null)
new Builder(mContext)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(mContext.getString(R.string.error))
.setMessage(mContext.getString(R.string.rename_failed, file.getName()))
.show();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
The code for asking users for the password to view the file is:
private void checkpass(final File file,FileListActivity mContext){
if(FileActionsHelper.pe==true && file.getName().equals(FileActionsHelper.filename)){
final EditText input = new EditText(FileListActivity.this);
input.setHint(mContext.getString(R.string.password_add));
input.setSingleLine();
new Builder( mContext)
.setTitle(mContext.getString(R.string.rename_dialog_title, file.getName()))
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try
{
if ((FileActionsHelper.pass).equals("1")){
openFile(file);
Toast.makeText( FileListActivity.this,"password matched", Toast.LENGTH_LONG).show();
}
else if (!(FileActionsHelper.pass).equals("1")) {
Toast.makeText( FileListActivity.this,"you entered wrong password", Toast.LENGTH_LONG).show();
}
else if (FileActionsHelper.pe!=true){
openFile(file);
}
}
catch (Exception e) {
Log.e(TAG, "Error occured while renaming path", e);
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.show();
}
}
the code for opening of file is:
void openFile(File file) {
//if(FileActionsHelper.pe==true && file.getName().equals(FileActionsHelper.filename)){
checkpass(file,FileListActivity.this);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(uri.toString()));
intent.setDataAndType(uri, type == null ? "*/*" : type);
startActivity((Intent.createChooser(intent,getString(R.string.open_using))));}
//else {
// }
//}
The error i am getting is in the function check pass, at input.getText.toString(); it says getText cannot be resolved into a type or field.
How can I fix this ?

Related

Picasso image error java.lang.BootstrapMethodError: Exception from call site #4 bootstrap method

so im making a chat app and my pictures are not showing now im using Picasso and android studio.
with i comment the code where the pictures are suppose to go everything works but if i leave the code in there i get this error java.lang.BootstrapMethodError: Exception from call site #4 bootstrap method
and the app crashes. i"m also connected to a firebase storage.
the logcat is here
java.lang.BootstrapMethodError: Exception from call site #4 bootstrap method
at okhttp3.internal.Util.<clinit>(Util.java:87)
at okhttp3.internal.Util.immutableList(Util.java:234)
at okhttp3.OkHttpClient.<clinit>(OkHttpClient.java:124)
at okhttp3.OkHttpClient$Builder.<init>(OkHttpClient.java:449)
at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:71)
at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:50)
at com.squareup.picasso.OkHttp3Downloader.<init>(OkHttp3Downloader.java:40)
at com.squareup.picasso.Picasso$Builder.build(Picasso.java:848)
at com.squareup.picasso.Picasso.get(Picasso.java:683)
at com.example.room.ProfileFragment$1.onDataChange(ProfileFragment.java:146)
avatarIv = view.findViewById(R.id.avatarIv);
nameTv = view.findViewById(R.id.nameTv);
emailTv =view.findViewById(R.id.emailTv);
phoneTv = view.findViewById(R.id.phoneTv);
coverIv = view.findViewById(R.id.coverIv);
fab = view.findViewById(R.id.fab);
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// until required data get
for (DataSnapshot ds : dataSnapshot.getChildren()){
//get data
String name = "" + ds.child("name").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String image = "" + ds.child("image").getValue();
String cover = "" + ds.child("cover").getValue();
//set data
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
try {
Picasso.get().load(image).into(avatarIv);
}
catch (Exception e){
Picasso.get().load(R.drawable.ic_default_img_white).into(avatarIv);
}
try {
Picasso.get().load(cover).into(coverIv);
}
catch (Exception e){
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private void showEditProfileDialog() {
/* show dialog containg options
edit profile
cover photo
name
phone
* */
//options to show in dialog
String options [] = {"Edit Profile Picture ", "Edit Cover Photo ", "Edit Name ", "Edit Phone"};
// alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Action");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
profileorCoverPhoto = "image";
showImagePicDialog();
}else if (which==1){
// Edit cover click
profileorCoverPhoto = "cover";
showImagePicDialog();
}else if (which==2){
// Edit name click
showNamePhoneUpdateDialog("name");
}else if (which==3){
// Edit Phone click
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showImagePicDialog() {
String options [] = {"Camera", "Gallery"};
// alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Pick Image From ");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// camera clicked
if(!checkCameraPermission()){
reqCameraPermission();
}
else {
pickFromCamera();
}
showImagePicDialog();
} else if (which == 1) {
// Gallery cliked
if (!checkStoragePermission()){
reqStoragePermission();
}
else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(final String key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Update" + key);
LinearLayout linearLayout =new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
final EditText editText= new EditText(getActivity());
editText.setHint("Enter" + key);
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//input text
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)){
HashMap<String, Object> result = new HashMap<>();
result.put(key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getActivity(), "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "" +e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(getActivity(), "please enter "+key, Toast.LENGTH_SHORT).show();
}
}
});
//add button to cancel
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST_CODE:{
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0]== PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1]== PackageManager.PERMISSION_GRANTED;
if(cameraAccepted && writeStorageAccepted){
pickFromCamera();
}
else {
Toast.makeText(getActivity(), "Please enable camera & storage permission ", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
if (grantResults.length>0){
boolean writeStorageAccepted = grantResults[1]== PackageManager.PERMISSION_GRANTED;
if(writeStorageAccepted){
pickFromGallery();
}
else {
Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//this method will be called after picking image from cam or gallery
if (resultCode== RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE){
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverPhoto(final Uri uri){
String filePathAndName = storagePath+ ""+ profileorCoverPhoto + "_" + user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask= taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
// check if image is uploaded or not
if (uriTask.isSuccessful()){
HashMap<String,Object> results = new HashMap<>();
results.put(profileorCoverPhoto,downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getActivity(), "Image Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), "Error updating Image", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "some error occured", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//intent of picking image from device
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// intet to start camera
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
Intent galleryIntent= new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,IMAGE_PICK_GALLERY_CODE);
}
}

Android java : How to write string text and save it into txt.file [duplicate]

This question already has answers here:
Android Writing Logs to text File
(15 answers)
Closed 8 years ago.
Okay so far i have successfully create the folder. in CreateFolderActivity.java
The following bellow is the create folder code:
btn_cFolder.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
String dateN = edit_date.getText().toString();
new AlertDialog.Builder(DatePickerActivity.this, AlertDialog.THEME_HOLO_DARK)
.setTitle("Create Folder")
.setMessage("Confirm to create " + dateN +" folder ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Environment.getExternalStorageDirectory();
String dateN = edit_date.getText().toString();
edit_date.setTypeface(edit_date.getTypeface(), Typeface.BOLD_ITALIC);
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/CalendarNote/" + dateN);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Toast.makeText(getBaseContext(), "You have successfully created." , Toast.LENGTH_LONG ).show();
Intent w = new Intent(DatePickerActivity.this, SelectTypeActivity.class);
startActivity(w);
} else {
Toast.makeText(getBaseContext(), "You have Failed to create." , Toast.LENGTH_LONG ).show();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
});
And also i have successfully to create the txt file.
But now the only problem is the path location I try many of way to connect this two to
save file into the folder. So far i wish the txt file is save like this /CalendarNote/TheDateIPick/hello.txt.
Now i only can save to the same folder as CalendarNote.
The following code is the code i modified but not successful. Please help me.
public void SaveListener() {
imb_savefile = (ImageButton) findViewById(R.id.imb_savefile);
imb_savefile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
edit_date = (EditText) findViewById(R.id.edit_date);
String t = edit_title.getText().toString();
new AlertDialog.Builder(WriteNoteActivity.this, AlertDialog.THEME_HOLO_DARK)
.setTitle("Save Note")
.setMessage("Confirm to save " + t +"?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String content = edit_content.getText().toString();
String title = edit_title.getText().toString();
String dateN = edit_date.getText().toString();
boolean success = true;
try {
File sdCardDir = Environment.getExternalStorageDirectory();
File targetFile;
targetFile = new File(sdCardDir.getCanonicalPath()
+ "/CalendarNote/"+ dateN);
File file=new File(targetFile + "/"+title+".txt");
if(!targetFile.exists()){
success = targetFile.mkdir();
}
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(file.length());
raf.write(content.getBytes());
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getBaseContext(), "You have successfully created." , Toast.LENGTH_LONG ).show();
} else {
Toast.makeText(getBaseContext(), "You have Failed to create." , Toast.LENGTH_LONG ).show();
}
//Toast.makeText(getBaseContext(), "Note have successfully saved." , Toast.LENGTH_LONG ).show();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "Note Cancelled." , Toast.LENGTH_LONG ).show();
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
});
}
Yes, it is possible. See this for details: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

How to "Save as" via Button programmatically

In my android app, I'm producing a lot of data which I store at the moment in a .txt file simply called "logData". Now my boss wants me to give him the possibility to save it as an extra file, like the Save As Button in various windows programms.
At the moment I have a method for generating a logFile and write first data to it and one for writing all coming data to it. But how can I implement a "Save as" functionality?
Here the code of both methods and the used variables:
private String logData = "logData.txt";
private String logText = "";
private File extStorageDir = Environment.getExternalStorageDirectory();
private File mLogFile = new File(extStorageDir, "DCULogData/logData.txt");
generating:
public void generateLogFileOnSD(String sFilename, String sBody) {
try {
File logFile = new File(extStorageDir, sFilename);
FileWriter writer = new FileWriter(logFile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
writing:
public void writeLogFileOnSD(String sFilename, String sBody) {
if (mLogFile.exists()) {
try {
FileOutputStream fOut = new FileOutputStream(mLogFile);
OutputStreamWriter mOutWriter = new OutputStreamWriter(fOut);
mOutWriter.append(sBody);
mOutWriter.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
generateLogFileOnSD(logData, logText);
}
}
EDIT : This is my solution based on Simple Plan's answer. Thanks for this!
I also tested some scenarios with filenames like "/blabla", "m/m/m/m/m/". No failure found until now :)
public Button.OnClickListener saveLogFileOnClickListener = new Button.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
DiagnosisActivity.this);
builder.setTitle(R.string.save_file_dialog);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final EditText input = new EditText(
DiagnosisActivity.this);
input.setSingleLine();
AlertDialog.Builder ad = new Builder(
DiagnosisActivity.this);
ad.setTitle("Enter save as File Name");
ad.setView(input);
ad.setCancelable(true);
ad.setPositiveButton("Save as",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
int len = input.length();
if (len != 0) {
final_filename = input
.getText().toString()
.trim();
generateLogFileOnSD(
"DCULogData/"
+ final_filename
+ ".txt",
ReceiverThread
.getLogText());
Toast.makeText(
getApplicationContext(),
"Saved!",
Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(
getApplicationContext(),
"Enter a proper name",
Toast.LENGTH_LONG)
.show();
}
}
});
ad.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = ad.create();
alert.show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert1 = builder.create();
alert1.show();
}
};
First add Button into your Layout as a text Save as and implement OnClickListner()
String final_filename;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
annual_crop.setTextColor(Color.BLUE);
AlertDialog.Builder al1 = new Builder(youractivity);
al1.setMessage("Do you want to save a file?");
al1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
final EditText input = new EditText(
youractivity.this);
input.setSingleLine();
AlertDialog.Builder al = new Builder(
AgriListView.this);
al.setTitle("Enter save as File Name");
al.setView(input);
al.setCancelable(true);
al.setIcon(R.drawable.bt);
al.setPositiveButton(
"Save as",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
int len = input
.length();
if (!(len == 0)) {
final_filename=input.getText().toString.trim();
);
} else {
Toast.makeText(
getApplicationContext(),
"Enter Name Properly",
Toast.LENGTH_LONG)
.show();
}
}
});
al.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert = al.create();
alert.show();
}
});
al1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
AlertDialog alert1 = al1.create();
alert1.show();
}
});
}
});
And used final_filename like below:
File folder = new File(Environment.getExternalStorageDirectory(), "DCULogData");
File mLogFile = new File(folder.getPath(), final_filename);
And add permission in your manifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to get the context in the marked position?

I am trying to use parse.com in an android application of mine, how to get the context at the place of *** in the code AlertDialog.Builder(*******)? I tried using getApplicationcontext which doesn't work.Can anyone with experience in the android help me with respect to this?
mSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mVibrator.vibrate(100);
//Checking for internet connection...
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//internet connection inactive... show alert...
if (!(netInfo != null && netInfo.isConnectedOrConnecting())) {
AlertDialog.Builder adb = new AlertDialog.Builder(arg0.getContext());
adb.setTitle("ALERT");
adb.setMessage("Please turn on Internet.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}else{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Admin");
query.whereEqualTo("password", mUserNameEditText.getText().toString());
query.whereEqualTo("userName", mPasswordEditText.getText().toString());
query.countInBackground(new CountCallback() {
public void done(int count, ParseException e) {
if (e == null) {
// The count request succeeded. Log the count
Log.d("test", "Sean has played " + count + " games");
if(count>0){
// save the login status... loggedIn/notloggedIn...
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginScreenActivity.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
// if user name password is correct, navigate to next activity...
Intent intent = new Intent(LoginScreenActivity.this,OptionScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 0);
overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
}else{
AlertDialog.Builder adb = new AlertDialog.Builder(*********************);
adb.setTitle("ALERT");
adb.setMessage("Wrong username or password.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
} else {
// The request failed
}
}
});
Try out as below:
AlertDialog.Builder adb = new AlertDialog.Builder(getApplicationContext());
OR
AlertDialog.Builder adb = new AlertDialog.Builder(<YourActivity>.this);

Android: How to show a dialog after user clicks "Okay" on a previous dialog

How come the AlertDialog that has the title "Location was saved to file" doesn't show up? It is the one that should be displayed after the user presses Okay on the first dialog.
I think it has something to do with threads, but I'm not sure.
SimpleDateFormat timeStampFormat = new SimpleDateFormat("MMMMM-dd-yyyy");
final EditText input = new EditText(EncounterActivity.this);
input.setWidth(75);
input.setText("Bear-Encounter-GPS-" + timeStampFormat.format(new Date()) + ".txt");
new AlertDialog.Builder(EncounterActivity.this)
.setTitle("Save GPS Location")
.setMessage("Please enter a filename")
.setView(input)
.setIcon(R.drawable.gps)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File fn = new File(root, input.getText().toString());
FileWriter gpxwriter = new FileWriter(fn);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write(ll.toUTMRef().toString());
out.close();
AlertDialog.Builder builder = new AlertDialog.Builder(EncounterActivity.this);
builder.setIcon(R.drawable.gps);
builder.setTitle("Location was saved to file");
builder.setMessage("Your GPS coordinates were saved to " + fn.getAbsolutePath())
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (IOException e) {
//ProfitBandit.alert(Shipment.this, "Couldn't write the file.");
Log.v("IOException", "Could not write file " + e.getMessage());
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
You CAN display an alert dialog from an alert dialog if you use the pattern showDialog(int) getInstanceSomeDialog and onCreateDialog(int) for both dialogs. So in my aboutAlertDialog I have:
builder.setPositiveButton("View EULA", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { //cancels itself?
showDialog(DIALOG_EULA_SHOW);
}
});
which in turn displays an EULA in yet another AlertDialog. OR you could just toss up a Toast as in:
Toast.makeText(Main.this,"Location Saved.", Toast.LENGTH_SHORT).show();
where Main is the activity class.

Categories

Resources