How add setText in input view AlertDialog - android

I write an algorithm to rename a file, how can I print the current name in the input field?
final EditText input = new EditText(MainActivity.this);
new AlertDialog.Builder(MainActivity.this)
.setTitle("Rename")
.setMessage("Add new name:")
.setView(input)
.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
if (directory.isDirectory()) {
File from = new File(directory.getAbsolutePath());
File to = new File(directory.getParent() + "/" + value);
from.renameTo(to);
} else {
File from = new File(directory.getAbsolutePath());
File to = new File(directory.getParent() + "/" + value + "." + checkFormat);
from.renameTo(to);
}
go(currentDirectory);
}
}).setNegativeButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
I would greatly appreciate the help

If I understand correctly, this should work to put the old name in the input box.
File old = null;
if (directory.isDirectory()) {
old = new File(directory.getAbsolutePath());
}
final EditText input = new EditText(MainActivity.this);
input.setText(old.toString());
...
//the rest of your code

Related

android studio edittext force enter | keydown event

I have an edittext that performs an action and if the result of that actions returns an int greater than 1 a dialog box pops up for user input, how can I after the user has inputted data to force enter on the edittext (from_loc_code) again?
from_loc_code being my edittext that already has data
int total_tickets_to_loc = Integer.valueOf(VALUES.total_tickets_to_loc);
if (total_tickets_to_loc > 1) {
// force user to scan product id
AlertDialog.Builder aBuilder = new AlertDialog.Builder(transfer.this);
aBuilder.setTitle("Scan Product");
final EditText input = new EditText(transfer.this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
aBuilder.setView(input);
aBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String sText = input.getText().toString().toUpperCase();
VALUES.ticket_product_id = " and p.PRODUCT_ID = '" + sText + "' ";
handler.postDelayed(new Runnable() {
#Override
public void run() {
from_loc_code.requestFocus();
from_loc_code.performClick();
}
}, 200);
}
});
aBuilder.show();
}

AlertDialog with LinearLayout should not dismiss on button click

I only want my AlertDialog to be dismissed when certain conditions are met (when name and surname given are valid) - else it should always be on top of the parent view. My code is this:
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final TextView instructions = new TextView(this);
instructions.setText(R.string.alert_enter_data);
final EditText name = new EditText(this);
name.setHint(R.string.name);
final EditText surname = new EditText(this);
surname.setHint(R.string.surname);
LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(instructions);
ll.addView(name);
ll.addView(surname);
alert.setView(ll);
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1)) {
dialog.dismiss();
}
}
});
final AlertDialog alert_dialog = alert.create();
alert_dialog.setCanceledOnTouchOutside(false);
alert_dialog.show();
With this code the AlertDialog disappears when the button is pressed, regardless of the input text. I then tried this:
alert_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name_txt = name.getText().toString();
String surname_txt = surname.getText().toString();
String email_txt = email.getText().toString();
String cellphone_txt = cellphone.getText().toString();
String postcode_txt = postcode.getText().toString();
if ((name_txt.length() > 1) && (surname_txt.length() > 1) && (email_txt.length() > 4)) {
if (debug_mode) {Log.i(TAG,"clause 1");}
String data_to_upload = name_txt + ", " + surname_txt + ", " + email_txt + ", "+ cellphone_txt + ", " + postcode_txt + "\n";
// upload_to_github(data_to_upload);
alert_dialog.dismiss();
}
}
});
}
});
But this way I get not Button at all. The Alert Dialog only contains the EditText fields.
alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
and
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
both are different buttons.
try
Button b = alert.getButton(AlertDialog.BUTTON_NEUTRAL);

How to get selected value from alert dialog?

I'm using alert dialog to show some records.those records are comming from db and display in Alertdialog.when user click on item i want to get item name to Log.this is my code.it show item as [test] but i want it showing as test
ArrayList arrayList and String [] categoryStrings initialized on top
List<Video> vd=Video.findWithQuery(Video.class, "select * from Video");
if (vd.size()>0) {
for (Video v : vd) {
arrayList.add(v.getTitle());
}
final List<String> list = Arrays.asList(arrayList.toString());
categoryStrings=new String[list.size()];
categoryStrings=list.toArray(categoryStrings);
AlertDialog.Builder alert = new AlertDialog.Builder(Editmedia.this);
alert.setTitle("Media List");
alert.setCancelable(false);
final int selected = 0; // or whatever you want
alert.setSingleChoiceItems(categoryStrings, selected, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//onclick
String categoryString = categoryStrings[item];
Log.d("sel", " " + item+" "+categoryString);
edit();
}
});
alert.show();
log value showing
0 [test] i want it as test
Log
Try this, it should help
String categoryString = categoryStrings[item];
categoryString = categoryString.replaceAll("[\\p{Ps}\\p{Pe}]","");
Log.d("sel", " " +" "+categoryString);
[EDIT]
String categoryString = categoryStrings[item];
categoryString = categoryString.replace("[","");
categoryString = categoryString.replace("]","");
Log.d("sel", " " +" "+categoryString);
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Media List");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
arrayAdapter.clear();
for (int i = 0; i < list.size(); i++) {
Log.i(LOG_TAG, list.get(i));
arrayAdapter.add(list.get(i));
}
builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), list.get(which),
Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();

trying to save a file with the current date and the name that the user choose but i get ERROR: open failed :EACCES (Permission denied )

i am trying to save a file in the emulator with the name that choose it the user and the current date .
but i get an error message that say :open failed :EACCES (Permission denied )
how to fix this error i will appreciate any help
SingInSActivity.java
public class SignSoldgerActivity extends Activity {
EditText edit_txt_note;
final Context context = this;
// attribute for the date picker
public String fileName;
Button btn_save_soldger;
TextView txtatePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_soldger);
edit_txt_note = (EditText) findViewById(R.id.editTxtNote);
txtatePicker = (TextView) findViewById(R.id.txtDate);
btn_save_soldger = (Button) findViewById(R.id.btnSaveSoldger);
btn_save_soldger.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// / for creating a dialog
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// get user input and set it to result
// edit text
String userinputResult = userInput
.getText().toString();
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy/MM/dd_HH:mm:ss");
Date now = new Date();
fileName = formatter.format(now) + "__"
+ userinputResult;
txtatePicker.setText(fileName);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// / for saving the file on the SD
try {
String sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + fileName + ".txt";
File myFile = new File(sdPath);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
// append or write
myOutWriter.append(edit_txt_note.getText());
myOutWriter.close();
fOut.close();
edit_txt_note.setText("");
Toast.makeText(getBaseContext(),
"Done Writing SD" + fileName, Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
the permission is added in the
manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Emulator SD Card size should be defined
You need to edit your AVD to allot an SD card size to it. You need to launch the AVD Manager dor it of course.
Here's the screen where you add it:
Updating after to include your comments
You're mostly missing the path seperator.
String sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + fileName + ".txt";
must be changed to
String sdPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() +"/"+ fileName + ".txt";
Please add following in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Most likely you need to read as well so this is needed for that:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Also note that most likely SD card has different allowed characters so you might need to replace all "|\\?*<\":>+[]/'"; with wanted character like _

Rename/Delete audio file from gallery in android programatically

Listed all audio files from gallery ,This is my code to rename and delete list of audio files.By using this code i can able to perform rename and delete operations on list only those are not effecting audio file,How to perform rename and delete operations on audio file in gallery based on my code ,i tried like this by using Filebut didn't work,id there any wrong in my code ,correct me plz
here is my code
Variables
ListView myList;
List values;
ArrayAdapter adapter;
MediaPlayerActivity mp = new MediaPlayerActivity();
Code to rename and delete by using contextmenu
case CONTEXT_MENU_DELETE:
Toast.makeText(
this,
"You selected item " + context_menu_number
+ " from the context menu", Toast.LENGTH_SHORT)
.show();
Toast.makeText(
this,
"You removed item " + number_of_item_in_listview
+ " from the list", Toast.LENGTH_SHORT).show();
values.remove(number_of_item_in_listview);
// myadapter.notifyDataSetChanged(); //if this does not work,
// reinitialize the adapter:
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
values);
myList.setAdapter(adapter);
File f = new File(path + filename);
if (f != null && f.exists()) {
// delete it
f.delete();
}
return (true);
case CONTEXT_MENU_RENAME:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("öğeyi yeniden adlandırmak");
alert.setMessage("Seçili öğe için yeni bir isim girin");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("tamam",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
values.set(number_of_item_in_listview, value
+ ".3gp");
adapter.notifyDataSetChanged();
/*
* File sdcard =
* Environment.getExternalStorageDirectory(); File
* from = new File(sdcard,"from.txt"); File to = new
* File(sdcard,"to.txt"); from.renameTo(to);
*/
File f = new File(path + filename);
if (f != null && f.exists()) {
File from = new File(f, f.getName());
File to = new File(f, value);
from.renameTo(to);
}
}
});
alert.setNegativeButton("iptal",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
Rename the files:
Its working fine:Put this code where you want to change the name.
File sdcard = new File(Environment.getExternalStorageDirectory(), "sample");
String fromFullPath = "/username556596268.mp3";
String toFullPath = "/username.mp3";
File from = new File(sdcard,fromFullPath);
File to = new File(sdcard,toFullPath);
from.renameTo(to);
here "sample" is my sdcard main directory name,"fromFullPath" is my filename it is in inside the sample directory, "toFullPath" is my changed name.
Delete the files:
Its working fine:Put this code where you want to delete file.
File sdcard = new File(Environment.getExternalStorageDirectory(), "sample");
String fromFullPath = "/username556596268.mp3";
File from = new File(sdcard,fromFullPath);
from.delete();
from.deleteOnExit();

Categories

Resources