In my application on clicking on button i'm showing alert dailog box to get file name.and getting name from user for a file.and saving it.
but what is happening is, after clicking on button alert dailog box is gets infront of screen and before that its try to save file.but its trying to save file befor user enters the name for file thats why file name is null in saving file.how to call use alert box so that i can get name from user and then save the file using that name.plase help me.
public void savebitmap(Bitmap bitmap)
{
str++;
AlertDialog.Builder alert = new AlertDialog.Builder(Work.this);
alert.setMessage("File name :");
input = new EditText(Work.this);
input.setLayoutParams(new LayoutParams(100,50));
alert.setView(input);
alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
NameValue = input.getText().toString();
System.out.println(" file name.---"+NameValue);
}
});
alert.show();
System.out.println("file is..."+NameValue);
try
{
System.out.println("in bitmap save...");
File fn=new File("/sdcard/"+" filename4"+".png");
FileOutputStream out=new FileOutputStream(fn);
System.out.println(",,,,,,,,,,,,,,,"+out);
Toast.makeText(getApplicationContext(), "In Save",Toast.LENGTH_SHORT).show();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "File is Saved in "+fn, Toast.LENGTH_SHORT).show();
}
catch(Exception e){
e.printStackTrace();
}
}
you will to move all file saving code inside onClick event of Button or wrap all code inside a method and then call it on Button click as :
public void savebitmap(Bitmap bitmap){
//....your code here
alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
NameValue = input.getText().toString();
System.out.println(" file name.---"+NameValue);
// put your code here to save file on Ok button click
saveFileOnSdCard(NameValue);
}
});
alert.show();
}
private void saveFileOnSdCard(String str_filename){
// move yor file saving code here..
}
You need to take input first then when user press OK on that you need to create file. So you need to write code in side onClick.
Try this,
public void savebitmap(Bitmap bitmap)
{
str++;
AlertDialog.Builder alert = new AlertDialog.Builder(Work.this);
alert.setMessage("File name :");
input = new EditText(Work.this);
input.setLayoutParams(new LayoutParams(100,50));
alert.setView(input);
alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
NameValue = input.getText().toString();
System.out.println(" file name.---"+NameValue);
try
{
System.out.println("in bitmap save...");
File fn=new File("/sdcard/"+" filename4"+".png");
FileOutputStream out=new FileOutputStream(fn);
System.out.println(",,,,,,,,,,,,,,,"+out);
Toast.makeText(getApplicationContext(), "In Save",Toast.LENGTH_SHORT).show();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,out);
out.flush();
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
});
alert.show();
System.out.println("file is..."+NameValue);
}
Related
I have connected my Android device to the wifi shared by my laptop. After I input the IP address and click "OK" in the Android app, I can not find any packets to/from the address in Wireshark (packet sniffer)
I have added this to the manifest of the Android Project:
<uses-permission android:name="android.permission.INTERNET"/>
Android Code:
private boolean attemptOpenDoor(){
// Store values at the time of the login attempt.
String studentId = mStudentIdView.getText().toString();
String password = mPasswordView.getText().toString();
final EditText et = new EditText(this);
new AlertDialog.Builder(this).setTitle("please input IP address")
.setIcon(android.R.drawable.ic_dialog_info).setView(et)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
IPAddr = et.getText().toString();
}
}).setNegativeButton("cancel", null).show();
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
OutputStream ou = socket.getOutputStream();
ou.write((studentId+password).getBytes("UTF-8"));
ou.close();
socket.close();
}catch (SocketTimeoutException aa) {
//连接超时 在UI界面显示消息
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setMessage("服务器连接失败!请检查网络是否打开");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
The program doesn't work because at the time that you're trying to open the socket using:
socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
the dialog is still up and value of IPAddr has not yet been set. Make sure that you only start connecting once the user has entered a valid input in the field.
Also, beware that the method above will block whichever thread it's running on until a connection is established or 5 seconds go by, meaning that it'd be unwise to call it directly inside of the OnClickListener. You should probably use an AsyncTask or similar to avoid blocking the UI thread while the connection is taking place.
You should move your connect codes after "onClick".
new AlertDialog.Builder(this).setTitle("please input IP address")
.setIcon(android.R.drawable.ic_dialog_info).setView(et)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
IPAddr = et.getText().toString();
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IPAddr, 8866), 5000);
OutputStream ou = socket.getOutputStream();
ou.write((studentId+password).getBytes("UTF-8"));
ou.close();
socket.close();
}catch (SocketTimeoutException aa) {
//连接超时 在UI界面显示消息
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setMessage("服务器连接失败!请检查网络是否打开");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}).setNegativeButton("cancel", null).show();
I have Android application which interacts with Web Server. When data is sent from phone to server, there is a bit of work with data (10-20 secs) and after that I get result back to phone. And i display that result in dialog with 2 choices. One choice is "OK" and it means that user is fine with result and dismiss the dialog. The other choice makes a screenshot of that results. And when I press this button I don't get picture of dialog, i get picture of layout which is behind that dialog.
My code behind this is
//this method is called on onPostExecute of async task
public void recieveResult (final Activity act,String result){
new AlertDialog.Builder(act)
.setTitle("Data - status")
.setMessage(result)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Save picture", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Bitmap bitmap = takeScreenshot(act);
saveBitmap(bitmap,act);
Toast.makeText(act,"Saved",Toast.LENGTH_LONG).show();
dialog.dismiss();
}
})
.show();
}
public Bitmap takeScreenshot(Activity act) {
View rootView = act.findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap,Activity act) {
String timeStamp = new SimpleDateFormat("MMyyyydd_HHmmss").format(new Date());
String imageFileName = "/screenshot_"+timeStamp+"_.png";
File storage = Environment.getExternalStoragePublicDirectory("Screens");
if (!storage.exists())
{
Toast.makeText(act, "Directory made", Toast.LENGTH_LONG).show();
storage.mkdirs();
}
File imagePath = new File(storage.getPath() + imageFileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
My result of picture is just screen without dialog. How to get picture of dialog in it?
Try obtaining the Windows's decor view
then get its drawing cache bitmap as you implemented.
Dialog has it's own window ( different form activity's window ), you can use dialog.getWindow() method to get dialog's window.
so here is the screenshot code:
private AlertDialog dialog;
public void showDialog(View view) {
dialog = new AlertDialog.Builder(this)
.setTitle("Titel")
.setMessage("some content")
.setPositiveButton("Screenshot", (d, which) -> {
Bitmap bitmap = screenshot(dialog);
// you can save the bitmap or display in an ImageView
}).create();
dialog.show();
}
private Bitmap screenshot(Dialog dialog) {
Window window = dialog.getWindow();
View decorView = window.getDecorView();
Bitmap bitmap = Bitmap.createBitmap(decorView.getWidth(), decorView.getHeight(), Bitmap.Config.ARGB_8888);
decorView.draw(new Canvas(bitmap));
return bitmap;
}
try this code
String picId=String.valueOf(nu);
String myfile="meter"+picId+".jpeg";
BitmapDrawable bitmapDrawable = null;
Toast.makeText(getActivity(),"success full store image gallery",Toast.LENGTH_SHORT).show();
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
File dir_image = new File(Environment.getExternalStorageDirectory()+//<---
File.separator+"SoundMeter"); //23-1-16 //<---
dir_image.mkdirs();
// image naming and path to include sd card appending name you choose for file
// String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = surfaceView.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
/* bitmapDrawable = new BitmapDrawable(bitmap);*/
v1.setDrawingCacheEnabled(false);
// File imageFile = new File(mPath); //file path 23-1-16
File imageFile = new File(dir_image,myfile);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
btnCaptured1.setVisibility(View.VISIBLE);
btnCaptured.setVisibility(View.VISIBLE);
//btnCaptured.setBackgroundDrawable(bitmapDrawable);
}
});
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "No Connection", Toast.LENGTH_LONG).show();
}
This question might have been asked several times (about returning value from alert dialog) but i just couldn't get this thing to work (the flow in android application was fine but it just couldn't save the data to the excel files), I've tried several methods posted in SO but still no luck and in a deep frustration atm.
I have some suspicion though. I think it's because i accessed both etOne and etTwo from within the inner class that makes it somewhat unreadable?
The snippet of my code:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Enter the data below");
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialog = inflater.inflate(R.layout.alertdialog, null);
//I think the problem comes from here?
final EditText etOne = (EditText) dialog.findViewById(R.id.etOne);
final EditText etTwo = (EditText) dialog.findViewById(R.id.etTwo);
//----------------------------------------------------------------
alertDialog.setView(dialog)
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Save One and Two to excel file
try {
FileInputStream file;
HSSFWorkbook workbook;
file = new FileInputStream(new File(fileName));
workbook = new HSSFWorkbook(file);
HSSFSheet sheet2 = workbook.getSheetAt(2);
int row;
Cell cell;
row = ((KaryawanActivity) getActivity()).position;
cell = sheet2.getRow(row).getCell(1);
cell.setCellValue(etOne.getText().toString());
cell = sheet2.getRow(row).getCell(2);
cell.setCellValue(etTwo.getText().toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Open Semasa Activity
Intent intent = new Intent(getActivity().getBaseContext(), SemasaActivity.class);
intent.putExtra("filepath", fileName);
intent.putExtra("evaluator", evaluator);
intent.putExtra(THEME, theme);
intent.putExtra("KaryawanNo", KaryawanNo);
intent.putExtra("KaryawanPos", ((KaryawanActivity) getActivity()).position);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialog.show();
Thanks in advance.
Ah forget it, it's my own mistake anyway. I forgot to set the write the workbook of course it'll never save. My bad -_-
For those who need it, the complete code goes this way, and accessing the EditText from within inner class is doable (although i doubt this is a good way of doing it).
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Enter the data below");
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialog = inflater.inflate(R.layout.alertdialog, null);
//I think the problem comes from here?
final EditText etOne = (EditText) dialog.findViewById(R.id.etOne);
final EditText etTwo = (EditText) dialog.findViewById(R.id.etTwo);
//----------------------------------------------------------------
alertDialog.setView(dialog)
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Save One and Two to excel file
try {
FileInputStream file;
HSSFWorkbook workbook;
file = new FileInputStream(new File(fileName));
workbook = new HSSFWorkbook(file);
HSSFSheet sheet2 = workbook.getSheetAt(2);
int row;
Cell cell;
row = ((KaryawanActivity) getActivity()).position;
cell = sheet2.getRow(row).getCell(1);
cell.setCellValue(etOne.getText().toString());
cell = sheet2.getRow(row).getCell(2);
cell.setCellValue(etTwo.getText().toString());
file.close();
FileOutputStream outFile = new FileOutputStream(new File(fileName));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Open Semasa Activity
Intent intent = new Intent(getActivity().getBaseContext(), SemasaActivity.class);
intent.putExtra("filepath", fileName);
intent.putExtra("evaluator", evaluator);
intent.putExtra(THEME, theme);
intent.putExtra("KaryawanNo", KaryawanNo);
intent.putExtra("KaryawanPos", ((KaryawanActivity) getActivity()).position);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
alertDialog.show();
I have a file list with a longclicklistener that brings up a context menu with delete and rename options. These launch either a deleteDialog() or renameDialog(). These call either delete() or rename(). The delete works but rename is giving:
05-05 10:26:44.105: W/System.err(19017884): java.io.FileNotFoundException: Failed to rename file: /sdcard/My Webs/new/index.php
Even thought I can see this file on the filesystem at this location.
Here is my code for the Alerts:
void delete(File f) throws IOException {
if (f.isDirectory()) {
for (File c : f.listFiles())
delete(c);
}
if (!f.delete())
throw new FileNotFoundException("Failed to delete file: " + f);
}
void rename(File f, String newName) throws IOException {
File newFile = new File(newName);
f.renameTo(newFile);
if (!f.renameTo(newFile))
throw new FileNotFoundException("Failed to rename file: " + f);
}
public void delDialog(int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.drawable.remove);
alertDialog.setTitle(getString(R.string.delete));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String selectedFileString = directoryEntries.get(pos).getText();
File tmpFile = new File(currentDirectory.toString()
+ selectedFileString);
try {
delete(tmpFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
directoryEntries.remove(pos);
itla.notifyDataSetChanged();
currentFile = null;
changed = false;
return;
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage("Are you sure you want to delete this file?");
alertDialog.show();
}
public void renameDialog(int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setIcon(R.drawable.renameicon);
alertDialog.setTitle(getString(R.string.rename));
alertDialog.setButton("Rename", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String selectedFileString = directoryEntries.get(pos).getText();
File tmpFile = new File(currentDirectory.toString()
+ selectedFileString);
try {
rename(tmpFile, "test.html");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
itla.notifyDataSetChanged();
return;
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage("Are you sure you want to rename this file?");
alertDialog.show();
}
public void Show_Context(Context context, String message, int position) {
final AlertDialog customDialog = new AlertDialog.Builder(this).create();
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.contextmenu, null);
final Button del = (Button) view.findViewById(R.id.delBtn);
final Button rename = (Button) view.findViewById(R.id.renameBtn);
final int pos = position;
customDialog.setView(del);
customDialog.setView(rename);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
delDialog(pos);
}
});
rename.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
customDialog.dismiss();
renameDialog(pos);
}
});
customDialog.setView(view);
customDialog.show();
}
As you can see the code for the deleteDialog() and renameDialog() is the same yet the renameDialog() throws the FileNotFoundException
Have you tried fully qualifying the filename of the destination? You're currently attempting to rename to "test.html" from currentDirectory.toString()+selectedFileString.
You probably want to try currentDirectory.toString()+"test.html" as you might be running into permissions issues otherwise.
You call f.renameTo(newFile) two times! One time normally, and a second time within the if() condition. I guess it already gets renamed the first time, so when you do it a second time, it fails (either because the file doesn't have the same name anymore or because it already has the new filename).
f.renameTo(newFile);
if (!f.renameTo(newFile)) {...}
Try and remove the first .f.renameTo().
Also note, that renameTo() returning false can have all kinds of reasons, not just that the file cannot be found. And of course you get the FileNotFoundException because you throw it yourself in your code :-)
I have an app that backs up data to the sd card. When the SD card is inserted, it works perfectly fine and will backup the data. When the SD card is not present, I programed it to create an alert that tells the user that the SD card wasnt found.
The problem I'm having is that if somebody tries to export data for the first time without an SD card present, it will force close. However, if they backup a set of data first and then have no SD card later when they try to backup more data, an alert message appears just how I want.
Somebody help please! Heres my code (modified from a tutorial):
InputStream myInput;
try {
myInput = new FileInputStream("/data/data/com.android.footprint/databases/MY_DATABASE");
File directory = new File("/sdcard/Footprint");
if (!directory.exists())
{
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(directory.getPath()+ "/MY_DATABASE.backup");
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
alertDialog2 = new AlertDialog.Builder(
settings.this).create();
alertDialog2.setTitle("Export Complete");
alertDialog2.setMessage("Data Backup successful");
alertDialog2.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog2.dismiss();
}
});
alertDialog2.show();
} catch (FileNotFoundException e) {
alertDialog2.dismiss();
alertDialog3 = new AlertDialog.Builder(
settings.this).create();
alertDialog3.setIcon(R.drawable.delete);
alertDialog3.setTitle("Export Failed");
alertDialog3.setMessage("Make sure SD card is inserted and unmounted");
alertDialog3.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog3.dismiss();
}
});
alertDialog3.show();
} catch (IOException e) {
alertDialog2.dismiss();
alertDialog3 = new AlertDialog.Builder(
settings.this).create();
alertDialog3.setIcon(R.drawable.delete);
alertDialog3.setTitle("Export Failed");
alertDialog3.setMessage("Make sure SD card is inserted and unmounted");
alertDialog3.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog3.dismiss();
}
});
alertDialog3.show();
} catch (Exception e) {
alertDialog2.dismiss();
alertDialog3 = new AlertDialog.Builder(
settings.this).create();
alertDialog3.setIcon(R.drawable.delete);
alertDialog3.setTitle("Export Failed");
alertDialog3.setMessage("Make sure SD card is inserted and unmounted");
alertDialog3.setButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog3.dismiss();
}
});
alertDialog3.show();
}
use this code for check SD card:
public static boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
I found this on this link. Hope this helps..
Not sure if that is your problem but it would be a good idea to review the way you're checking if the SD Card is present. Here's how I handled it in one of my most recent application:
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// Everything is fine, write away !
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// Card is in read mode, cannot write
Log.e("FileManager", "SD Card is in READ ONLY mode, impossible to write files.");
} else {
// Impossible to access SD Card
Log.e("FileManager", "Having trouble with SD card, can't write nor read from it.");
}
Also, may I suggest you get your path from the static method found in the Environement Class like so:
File root = Environment.getExternalStorageDirectory();
File directory = new File(root + "/Footprint");
Hope this helps you solve your problem!