I'm trying a way to save a picture when I'll click in button save using upload component of vaadin7.
The upload component has one button to send image but I wanna that save when I click button save of my Window with name that I define.
I'm trying this.
//upload image
Upload upload = new Upload("Choose your picture");
upload.setButtonCaption(null);
mainLayout.addComponent(upload);
Button btnSave = new Button("Save");
btnSave.addClickListener(new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
//click to save all fields and picture choosed in upload
}
});
/** upload image picture */
public class ImageUpload implements Receiver{
private File file;
private String cpf; // image's name example 222.333.444-55
/** save image picture */
#Override
public OutputStream receiveUpload(String filename, String mimeType) {
FileOutputStream fos = null;
try{
if(new File(filename).getName().endsWith("jpg")){
String cpfFormato = this.cpf.replaceAll("\\.", "").replace("-", "");
String[] imagem = filename.split("\\.");
String novaImagem = cpfFormato + ".jpg"; //22233344455.jpg
file = new File(novaImagem);
fos = new FileOutputStream("/tmp/" + file);
}else{
new Notification("Erro de arquivo \n",
"Only jpg",
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
}
}catch(FileNotFoundException ex){
new Notification("File not found \n",
ex.getLocalizedMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos;
}
}
Any idea ?
Use the upload.submitUpload(); method.
Hint: As you can see in the API description you can hide the upload internal submit button by setting upload.setButtonCaption(null);
Link to the API: https://vaadin.com/api/com/vaadin/ui/Upload.html#submitUpload()
Related
There's a problem i'm fighting with for two days. Using FileWriter I try to save data into txt file. File is saved by an application but it's always empty.
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
boolean usunieto = true;
boolean stworzono = false;
String t_magazyn = e_magazyn.getText().toString();
String nazwa = e_nazwa.getText().toString();
if(!t_magazyn.trim().equals("")){
#SuppressLint("SdCardPath") File plik = new File("/sdcard/"+nazwa+".txt");
// jeśli plik nie istnieje, stwórz go
if(plik.exists()){
usunieto = plik.delete();
Toast.makeText(getApplicationContext(),"Plik został usunięty!",Toast
.LENGTH_SHORT).show();
}
if(usunieto){
stworzono = plik.createNewFile();
Toast.makeText(getApplicationContext(),"Plik utworzony!",Toast
.LENGTH_SHORT).show();
}
if(!usunieto||!stworzono){
Toast.makeText(getApplicationContext(),"Apka dalej cie olewa xD",Toast
.LENGTH_SHORT).show();
}
//THIS PART DOESN'T WORK AS INTENDED
FileWriter wpis = new FileWriter(plik.getName(),true);
BufferedWriter bufor = new BufferedWriter(wpis);
bufor.write(e_magazyn.getText().toString());
i_e_magazyn.setText(e_magazyn.getText().toString());
bufor.close();
}
}
catch(IOException e) {
e.printStackTrace();
}
}
});
e_magazyn,e_nazwa are EditText fields and i_e_magazyn is TextView field
In b2 button which isn't visible here this line of code works.
i_e_magazyn.setText(e_magazyn.getText().toString());
I tried a lot of actions to update data into file but it looks like after creating a new FileWriter variables are made empty
How do i make it work?
You just need to write this line
FileWriter wpis = new FileWriter(plik,true);
Instead of
FileWriter wpis = new FileWriter(plik.getName(),true);
I have and activity where on click of menu item save I want to save the image of the screen to my device inside a a specific folder. how can I do it. ?
The image which is displayed in the background is a ImageView and the text is textview. I have to merge them and save them as a single image.
Try with below code on menu item click event....
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
// give path of external directory to save image
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "test.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
where view v is root layout...
I created application of write and read file. when i click button ,my file is write and also read the file on the same button click.I want as and when my file is write , that file is save it into SQLite.I'm surfing lot of on the net but can't find proper source or ideas how to do this.And that file is compare with input String something like "code" . If this input_String is match with that file which is store in the SQLite database , if match user can't go ahead for the further process.I would appreciate if anybody out there is capable of giving me some advice on this one and I hope other people find this helpful too.Here is my code.Thanks in Advanced.
The Activity class
public class Write extends Activity {
/** Called when the activity is first created. */
EditText myText;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
myText = (EditText) findViewById(R.id.myText);
Button createButton = (Button) findViewById(R.id.btnCreate);
Button readButton = (Button) findViewById(R.id.btnRead);
createButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
createFile(myText.getText().toString());
myText.setText("");
readFile();
}
});
}
private void createFile(String Text)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(Text.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
catch (IOException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
And the DataBase_Adapter code
//Table Name
public static final String TABLE_NAME_CODE="code_table";
//Colum,n Names
public static final String KEY_CODE_ID="ID";
public static final String KEY_CODE_NAME="USERNAME";
//Table Create Statement
public static final String DATABASE_CREATE_CODE = "CREATE TABLE "+TABLE_NAME_CODE+" ("+KEY_CODE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_CODE_NAME+"TEXT)";
//Insert Code in Database code_table
public void saveCode(String strKey_Code)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_CODE_NAME , strKey_Code);
// Insert the row into your table
db.insert(TABLE_NAME_CODE, null, newValues);
}
The approach you have taken could be improved a little bit, consider storing in the database only the name of the files, you already have the files saved, right? why store their content again in the database?
I'm still new to development, and I was wondering if someone can guide me towards the right direction in my situation because I'm not sure where to begin:
Scheme:
After pressing a capture_button to capture an image (capture_button and imagePreview is in same activity), I would like to remove the capture_buttonand have an ACCEPT or DECLINE button. These buttons are supposed to be accept the image and then save, or decline the image and go back to the imagePreview.
Now, I'm not sure if I'm supposed to create another activity when capture_button is pressed,
PhotoActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
mCamera = getCameraInstant();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
preview.addView(mCameraPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
PictureCallback mPicture = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.e("photo","pictureCallback");
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if(pictureFile==null){
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e){
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Photo");
if (!mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("Photo", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
Now, am I supposed to do some kind of Intent after the capture_button click, or after
PictureCallback mPicture = new PictureCallback(){
and then have the onPictureTaken at the other activity? Or is my thinking all wrong?
Please help?
Thank you in advance.
try this it will help you
final LinearLayout accept_deciline = new LinearLayout(getApplicationContext());
LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
accept_deciline.setOrientation(LinearLayout.HORIZONTAL);
Button accept = new Button(getApplicationContext());
accept.setText("Accept");
Button decline = new Button(getApplicationContext());
decline.setText("Decline");
accept_deciline.addView(accept);
accept_deciline.addView(decline);
addContentView(accept_deciline, lp);
accept_deciline.setVisibility(View.INVISIBLE);
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// SAVE YOUR IMAGE.
}
});
decline.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
//KEEP THIS LINE IN YOUR PICTURE CALLBACK NOT HERE.
accept_deciline.setVisibility(View.VISIBLE);
IT WILL BE BETTER IF YOU WILL CREATE YOUR ACCEPT DECLINE LAYOUT IN XML FILE AND MAKE IT INVISIBLE WHEN YOUR ON PICTURE TAKEN WILL BE CALLED JUST MAKE IT VISIBLE.
One thing that I have done is to use an alertdialog that pops up after you take a picture. You can set the onclick listeners to perform any actions you need depending on what you want to happen(accept or decline). This would avoid the need to make any changes to your layouts and add buttons and take them away. You could launch the alertdialog by placing the alertdialog.show() method at the end of your onPictureTaken method.
If you do this youll have to have the filepath of the image you just took so you can allow a user to destroy it if they decline it and on some devices it may take the mediaservice a couple of seconds to update the images filepath so if you go to destroy an image it doesnt see you can get a force close. There are a couple ways to do this and I cant remember at the moment but one of them is way faster than the rest.
You wouldnt need an intent unless you plan on launching some other kind of action, activity, service, ect. For instance if you want to pass the filepath of the image to another activity where you can make changes to it, upload it, or what have you, you can add the filepath of the image to an intent like this:
intent.putExtra("imagepath",imagepath);
I am building an android application that reads text files.
Now,i have multiple text files in the sdcard .
Location of files is /sdcard/textfile/
filenames: abc.txt
def.txt
ghi.txt
i want that when users select any one of the file,the selected file should be read.
i know the code to read a single file
i.e
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,pathtofile);
BufferedReader br = new BufferedReader(new FileReader(file));
pathtofile stores the path to file abc.txt that is defined .
Is there any way i can pass the filepath to file object for the file that user selected
currently,it works for abc.txt as i have defined its path in pathtofile
You can also make a list of all the items in your textfile folder and save it in a list where the user can choose from.
public class DirectoryBrowser extends ListActivity {
private List<String> items = null;
private File currentDirectory;
private ArrayAdapter<String> fileList;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
currentDirectory = new File("/sdcard/textfile");
getFiles(currentDirectory.listFiles());
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
int selectedRow = (int)id;
currentDirectory = new File(items.get(selectedRow));
if(currentDirectory.isDirectory()){
getFiles(currentDirectory.listFiles());
}else{
//if the selected file is not a directory. get the filename
currentDirectory.getPath();
}
}
private void getFiles(File[] files){
items = new ArrayList<String>();
for(File file : files){
items.add(file.getPath());
}
fileList = new ArrayAdapter<String>(this,R.layout.list_text, items);
setListAdapter(fileList);
}
}
You can use a AlertDialog with a list.
final CharSequence[] items = {"abc.txt", "def.txt", "ghi.txt"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a file");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,items[item]);
BufferedReader br = new BufferedReader(new FileReader(file));
}
});
AlertDialog alert = builder.create();