Generate PDF file and attach to e-mail - android

first post here.
I have read all similar posts without finding any answer, i'm a newbie at dev in general.
Here is what i'm looking for:
On button click, the code generates a PDF with some info, and i just want to send the created pdf by mail.
First problem is when i choose an email app to send the mail, i got a message "Impossible to attach file".
Second problem is that the created file is not readable on the phone while it's readable on PC.
By searching i found out that it may be in relation with permission. I tried setReadablemethod without result. Android studio makes a hint (result of setReadable is ignored).
Code :
public class VerifList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verif_list);
//Variables
//Strings
final String name;
final String myFormat;
//Others
final Calendar calendar;
final SimpleDateFormat sdf;
final String datePdf;
//Buttons
Button endControlButton;
//TextView
TextView title;
TextView date;
//Edit Text
final EditText oil_TV;
final EditText engine_liquid_TV;
EditText wipers_liquid_TV;
EditText breaks_liquid_TV;
EditText windows_TV;
EditText wipers_TV;
EditText mirrors_TV;
EditText numberplate_TV;
EditText frontTires_TV;
EditText rearTires_TV;
EditText tiresState_TV;
EditText light1_TV;
EditText light2_TV;
EditText light3_TV;
EditText light4_TV;
EditText light5_TV;
EditText light6_TV;
EditText light7_TV;
EditText interiorClean_TV;
EditText exteriorClean_TV;
EditText jacket_TV;
EditText triangle_TV;
EditText strap_TV;
EditText extinguisher_TV;
//Set title text
title = findViewById(R.id.title_TV);
Bundle extras = getIntent().getExtras();
assert extras != null;
name = extras.getString("name");
title.setText(name);
//Display date
date = findViewById(R.id.date_TV);
calendar = Calendar.getInstance();
myFormat = "dd/MM/yy";
sdf = new SimpleDateFormat(myFormat, Locale.FRANCE);
date.setText("Date du contrôle : " + sdf.format(calendar.getTime()));
datePdf = calendar.getTime().toString();
//Variables declaration
oil_TV = findViewById(R.id.oil_TV);
engine_liquid_TV = findViewById(R.id.engine_liquid_TV);
wipers_liquid_TV = findViewById(R.id.wipers_liquid_TV);
breaks_liquid_TV = findViewById(R.id.breaks_liquid_TV);
windows_TV = findViewById(R.id.windows_TV);
wipers_TV = findViewById(R.id.wipers_TV);
mirrors_TV = findViewById(R.id.mirrors_TV);
numberplate_TV = findViewById(R.id.numberplate_TV);
frontTires_TV = findViewById(R.id.frontTires_TV);
rearTires_TV = findViewById(R.id.rearTires_TV);
tiresState_TV = findViewById(R.id.tiresState_TV);
light1_TV = findViewById(R.id.light1_TV);
light2_TV = findViewById(R.id.light2_TV);
light3_TV = findViewById(R.id.light3_TV);
light4_TV = findViewById(R.id.light4_TV);
light5_TV = findViewById(R.id.light5_TV);
light6_TV = findViewById(R.id.light6_TV);
light7_TV = findViewById(R.id.light7_TV);
interiorClean_TV = findViewById(R.id.interiorClean_TV);
exteriorClean_TV = findViewById(R.id.exteriorClean_TV);
jacket_TV = findViewById(R.id.jacket_TV);
triangle_TV = findViewById(R.id.triangle_TV);
strap_TV = findViewById(R.id.strap_TV);
extinguisher_TV = findViewById(R.id.extinguisher_TV);
//Création de listes
final ArrayList textViewArray = new ArrayList(24);
//TextViews
textViewArray.add(oil_TV);
textViewArray.add(engine_liquid_TV);
textViewArray.add(wipers_liquid_TV);
textViewArray.add(breaks_liquid_TV);
textViewArray.add(windows_TV);
textViewArray.add(wipers_TV);
textViewArray.add(mirrors_TV);
textViewArray.add(numberplate_TV);
textViewArray.add(frontTires_TV);
textViewArray.add(rearTires_TV);
textViewArray.add(tiresState_TV);
textViewArray.add(light1_TV);
textViewArray.add(light2_TV);
textViewArray.add(light3_TV);
textViewArray.add(light4_TV);
textViewArray.add(light5_TV);
textViewArray.add(light6_TV);
textViewArray.add(light7_TV);
textViewArray.add(interiorClean_TV);
textViewArray.add(exteriorClean_TV);
textViewArray.add(jacket_TV);
textViewArray.add(triangle_TV);
textViewArray.add(strap_TV);
textViewArray.add(extinguisher_TV);
//Déclaration du bouton Fin de controle
endControlButton = findViewById(R.id.end_control_button);
endControlButton.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetWorldReadable")
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View view) {
//Création du pdf
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(300,600,1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setTextSize(30);
canvas.drawText(name,50,30,paint);
for (int i = 0 ; i<textViewArray.size();i++){
EditText editText = (EditText) textViewArray.get(i);
String editTextDesc = (String) editText.getContentDescription();
String content = editText.getText().toString();
Boolean isEmpty = content.isEmpty();
if (!isEmpty) {
paint.setTextSize(10);
paint.setColor(Color.RED);
canvas.drawText(editTextDesc + " : " + content, 50 , 50 + (20 * i),paint);
} else {
paint.setTextSize(10);
paint.setColor(Color.BLACK);
canvas.drawText(editTextDesc + " : OK",50, 50 + (20 * i),paint);
}
}
document.finishPage(page);
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/ATTM
Vehicules/";
File file = new File(directory_path);
if (!file.exists()){
file.mkdirs();
}
String targetPdf = directory_path + name + datePdf +".pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
Toast.makeText(getApplicationContext(), "Envoyé", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("main", "error "+e.toString());
Toast.makeText(getApplicationContext(), "Erreur" + e.toString(), Toast.LENGTH_LONG).show();
}
document.close();
//Mail
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
shareIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "email#hotmail.fr" });
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "test ");
shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(targetPdf));
startActivity(shareIntent);
}
});
}
}
Any help would be appreciated. Thanks for reading!

Try the below code in your Activity..
package com.example.pdfshare;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.FileProvider;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.Page;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintAttributes.Margins;
import android.print.PrintAttributes.Resolution;
import android.print.pdf.PrintedPdfDocument;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity implements Runnable {
private Intent mShareIntent;
private OutputStream os;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** PDF Gen should run in own thread to not slow the GUI */
public void makeAndSharePDF(View buttonSource) {
new Thread(this).start();
}
public void run() {
// Create a shiny new (but blank) PDF document in memory
// We want it to optionally be printable, so add PrintAttributes
// and use a PrintedPdfDocument. Simpler: new PdfDocument().
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new Resolution("zooey", PRINT_SERVICE, 300, 300)).
setMinMargins(Margins.NO_MARGINS).
build();
PdfDocument document = new PrintedPdfDocument(this, printAttrs);
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(300, 300, 1).create();
// create a new page from the PageInfo
Page page = document.startPage(pageInfo);
// repaint the user's text into the page
View content = findViewById(R.id.textArea);
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
// Here you could add more pages in a longer doc app, but you'd have
// to handle page-breaking yourself in e.g., write your own word processor...
// Now write the PDF document to a file; it actually needs to be a file
// since the Share mechanism can't accept a byte[]. though it can
// accept a String/CharSequence. Meh.
try {
File pdfDirPath = new File(getFilesDir(), "pdfs");
pdfDirPath.mkdirs();
File file = new File(pdfDirPath, "pdfsend.pdf");
Uri contentUri = FileProvider.getUriForFile(this, "com.example.fileprovider", file);
os = new FileOutputStream(file);
document.writeTo(os);
document.close();
os.close();
shareDocument(contentUri);
} catch (IOException e) {
throw new RuntimeException("Error generating file", e);
}
}
private void shareDocument(Uri uri) {
mShareIntent = new Intent();
mShareIntent.setAction(Intent.ACTION_SEND);
mShareIntent.setType("application/pdf");
// Assuming it may go via eMail:
mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "Here is a PDF from PdfSend");
// Attach the PDf as a Uri, since Android can't take it as bytes yet.
mShareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(mShareIntent);
return;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
The above code is self explanatory with comments.. All the Best..

Related

On broadcast receiver, check for write permission android M

I use broadcastreceiver of media folder android.hardware.action.NEW_PICTURE service to rename and move image using this code and it was running:
CameraReciver
package perim.ebrahimi.ir.perim;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
public class CameraReciver extends BroadcastReceiver {
private States states;
private SessionManager session;
private WriteService main;
#Override
public void onReceive(Context context, Intent intent) {
getStates(context);
if(states.getAPP()){
Cursor cursor = context.getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
if(cursor!=null){
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
main = new WriteService();
main.writeFolder(image_path, states, context);
}
cursor.close();
} else abortBroadcast();
}
// OK
private void getStates(Context context){
session = new SessionManager(context.getApplicationContext());
states = new States();
states = session.getSession();
}
}
and here is WriteService:
package perim.ebrahimi.ir.perim;
import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class WriteService extends Activity {
private States states;
private Context context;
private static CalendarJalalian cal;
private static int day ;
private static int month ;
private static int year ;
private static int saat ;
private static int minut ;
private static int secnd ;
private int orientation = -1;
private static final int REQUEST_EXTERNAL_STORAGE = 100;
private static final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS=200;
private boolean mExternalStorageAvailable = false;
private boolean mExternalStorageWriteable = false;
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// //setContentView(R.layout.activity_main);
//
// // A simple check of whether runtime permissions need to be managed
// if (Build.VERSION.SDK_INT >= 23) {
// checkMultiplePermissions();
// }
// }
public void writeFolder(String image_path, States _states, Context _context){
states = _states;
context= _context;
cal = new CalendarJalalian();
long fileSize = new File(image_path).length();
Cursor mediaCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.MediaColumns.SIZE },
MediaStore.MediaColumns.DATE_ADDED + ">=?",
new String[]{String.valueOf(cal.getTimeInMillis()/1000 - 1)},
MediaStore.MediaColumns.DATE_ADDED + " desc");
if (mediaCursor != null && mediaCursor.getCount() !=0 ) {
while(mediaCursor.moveToNext()){
long size = mediaCursor.getLong(1);
if(size == fileSize){
orientation = mediaCursor.getInt(0);
break;
}
}
}
orientation = (orientation<0)?0:orientation;
image_path = changeName(image_path);
if(image_path.length()==0) return;
String image_jadid = copyFile(image_path);
if(states.getMain() && image_jadid.length()>0){
removeMain(image_path);
removeMedia(context, new File(image_path));
}
if(states.getPayam()) Toast.makeText(this, getText(R.string.imageSaved)+": "+states.getKhas(), 500).show();
}
private void checkExternalStorage(){
String[] aaa = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, aaa , REQUEST_EXTERNAL_STORAGE);
if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
} else {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
}
private static void removeMedia(Context context, File f) {
ContentResolver resolver = context.getContentResolver();
resolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[] { f.getAbsolutePath() });
}
// OK
private String changeName(String image_path){
String result = "";
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
File from = new File(image_path);
if(from.exists()){
if(states.getOnimage()){
addTextToImage(image_path, persianDateName);
}
File to = new File(from.getParentFile(),persianDateName);
try
{
boolean b = from.renameTo(to);
if (!b) {
copy(from, to);
from.delete();
}
removeMedia(context, from);
sendToMedia(to, persianDateName);
result = to.getAbsolutePath();
}
catch(Exception ex){
ex.printStackTrace();
}
}
return result;
}
private void addTextToImage(String from, String persianDateName) {
Log.i("info","Draw "+persianDateName+" on image");
try
{
Log.i("info","1");
FileOutputStream fos = new FileOutputStream(from);
if(fos==null) Log.i("info","fos = null");
Log.i("info","2 = "+from);
Bitmap bitmap = BitmapFactory.decodeFile(from);
if(bitmap==null) Log.i("info","bitmap = null");
// Log.i("info","3");
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig==null) Log.i("info","bitmapConfig = null");
// Log.i("info","4");
// if (bitmapConfig == null) {
// bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
// }
Log.i("info","5");
bitmap = bitmap.copy(bitmapConfig, true);
Log.i("info","6");
Canvas canvas = new Canvas(bitmap);
Log.i("info","7");
Resources resources = this.getResources();
float scale = resources.getDisplayMetrics().density;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(61, 61, 61));
paint.setTextSize((int) (14 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
Rect qab = new Rect();
paint.getTextBounds(persianDateName, 0, persianDateName.length(), qab);
int x = (bitmap.getWidth() - qab.width()) / 2;
int y = (bitmap.getHeight() + qab.height()) / 2;
canvas.drawText(persianDateName, x, y, paint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
catch (IOException e)
{
e.printStackTrace();
}
Log.i("info","Text added on image");
}
private void copy(final File f1, final File f2) throws IOException {
if(f2.exists()) f2.delete();
//checkExternalStorage();
checkMultiplePermissions();
if(mExternalStorageAvailable && mExternalStorageWriteable) {
f2.createNewFile();
final RandomAccessFile file1 = new RandomAccessFile(f1, "r");
final RandomAccessFile file2 = new RandomAccessFile(f2, "rw");
file2.getChannel().write(file1.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f1.length()));
file1.close();
file2.close();
}
}
private boolean canRename(final File f1, final File f2) {
final String p1 = f1.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
final String p2 = f2.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
return p1.replaceAll("\\/\\w+", "").equals(p2.replaceAll("\\/\\w+", ""));
}
// OK
private void removeMain(String image_path){
File f = new File(image_path);
if(f.exists()) f.delete();
}
// OK
private File createFileName(){
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
String masirFolder = "";
if(states.getSal()) masirFolder += year;
if(states.getMah()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month);
if(states.getRuz()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day);
if(states.getSaat()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat);
if(states.getMinut()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat)+"_"+((minut<10)?"0"+minut:minut);
if(states.getKhas().length()>0) masirFolder += File.separator+states.getKhas();
File directTime = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), masirFolder);
if (!directTime.mkdir()) makeDir(directTime);
directTime = new File(directTime, persianDateName);
return directTime;
}
// OK
private void makeDir(File direct){
direct.mkdirs();
}
// OK
private String copyFile(String image_path){
String masir = "";
File sourceFile = new File(image_path);
if (!sourceFile.exists()) {return masir;}
File destinationFile = createFileName();
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destinationFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
masir = destinationFile.getName();
sendToMedia(destinationFile, masir);
masir = destinationFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return masir;
}
// OK
private void sendToMedia(File imageFile, String imageTitle){
ContentValues image = new ContentValues();
Date dateTaken = new Date();
File parent = imageFile.getParentFile();
String path = parent.toString().toLowerCase();
String name = parent.getName().toLowerCase();
image.put(MediaStore.Images.Media.TITLE, imageTitle);
image.put(MediaStore.Images.Media.DISPLAY_NAME, String.format(this.getText(R.string.imageDisplayName).toString(),states.getKhas()));
image.put(MediaStore.Images.Media.DESCRIPTION, String.format(this.getText(R.string.imageDescription).toString(),name));
image.put(MediaStore.Images.Media.DATE_ADDED, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_MODIFIED, dateTaken.toString());
image.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
image.put(MediaStore.Images.Media.ORIENTATION, orientation);//getImageOrientation(imageFile.getAbsolutePath()));
image.put(MediaStore.Images.ImageColumns.BUCKET_ID, path.hashCode());
image.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
image.put(MediaStore.Images.Media.SIZE, imageFile.length());
image.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
}
private void checkMultiplePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
List<String> permissionsNeeded = new ArrayList<String>();
List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
permissionsNeeded.add("GPS");
}
if (!addPermission(permissionsList, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
permissionsNeeded.add("Read Storage");
}
if (permissionsList.size() > 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
try {
if (Build.VERSION.SDK_INT >= 23)
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
} catch(Exception ex){
ex.printStackTrace();
}
return true;
}
}
But class addPermission raise error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
android.content.Context.checkSelfPermission(java.lang.String)' on a
null object reference
I think the way I call activity is not correct, but I have no idea how to do it, please help.
Edit:
I have found this difference in returned path:
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
The changed part is obvious:
old but correct path: /storage/emulated/0/DCIM/Camera/IMG_20161215_173334.jpg
new but incorrect path: /storage/3466-033/DCIM/Camera/IMG_20161215_173334.jpg
I think since new devices permit user to select where to save Images, then returning address is changed accordingly.
How to get correct address out of cursor?
You can't do that with a broadcast receiver. You can check if you have a permission via ContextCompat.checkSelfPermission, but in order to request the permission, you need to call ActivityCompat.requestPermissions. It needs an activity, and the result will also arrive to that activity.
Given that, the best solution for you is to implement some activity which will explain the user what is going on and request the permission. If the broadcast receiver detects that it doesn't have the necessary permission, it would launch this activity. When the permission is granted, the normal operation would be resumed.
I have to say that as a user it would be very weird to me if a dialog with a permission request suddenly popped up out of the blue, so I think it's for the best that you need to have an activity to request permissions.
Judging by your path, however, it is definitely somewhere on the SD card. This means that the SD card write restrictions apply. That means that requesting permissions for writing won't help. Take a look at this question: How to avoid the “EACCES permission denied” on SD card?

How to get the file extension in Android?

I am a newbie.
I have an EditText and a Browse Button to explore Folders and select files only.
From the Browse Button, when a file is clicked it stores the folder path in which that file is in one string and the file name without extension in other string, which I am using to store, either of these two, in the EditText.
I want to make the file name with the exactly file extension (whether one or two dots), but I don't have any idea how to get the file extension also.
All answers will be appreciated.
FileChooser.java
package com.threefriends.filecrypto;
/**
* Created by hp on 01-06-2016.
*/
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir=new File("/sdcard/");
fill(currentDir);
}
private void fill(File f)
{
File[]dirs=f.listFiles();
this.setTitle("Current Dir: "+f.getName());
List<Item>dir=new ArrayList<Item>();
List<Item>fls=new ArrayList<Item>();
try{
for(File ff: dirs)
{
Date lastModDate=new Date(ff.lastModified());
DateFormat formater=DateFormat.getDateTimeInstance();
String date_modify=formater.format(lastModDate);
if(ff.isDirectory()){
File[] fbuf=ff.listFiles();
int buf=0;
if(fbuf != null){
buf=fbuf.length;
}
else
buf=0;
String num_item=String.valueOf(buf);
if(buf == 0)
num_item=num_item+" item";
else
num_item = num_item+" items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(), num_item, date_modify, ff.getAbsolutePath(), "directory_icon"));
}
else
{
fls.add(new Item(ff.getName(), ff.length()+" Byte", date_modify, ff.getAbsolutePath(), "file_icon"));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0, new Item("..", "Parent Directory", "", f.getParent(), "directory_up"));
adapter=new FileArrayAdapter(FileChooser.this, R.layout.file_view, dir);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon") || o.getImage().equalsIgnoreCase("directory_up")){
currentDir=new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o);
}
}
private void onFileClick(Item o)
{
//Toast.makeText(this, "Folder Clicked: "+ currentDir, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("GetPath", currentDir.toString());
intent.putExtra("GetFileName", o.getName());
setResult(RESULT_OK, intent);
finish();
}
}
Part of MainActivity.java
//Defined for file edittext.
EditText editText2;
private static String TAG = MainFragment.class.getSimpleName(); //For File Exploring.
private static final int REQUEST_PATH = 1;
String curFileName;
String filePath;
EditText edittext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_main, container, false);
edittext = (EditText) view.findViewById(R.id.editText); //Done for File Exploring, EditText, Browse Button.
Button b1 = (Button) view.findViewById(R.id.skipButton);
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent1 = new Intent(v.getContext(), FileChooser.class);
startActivityForResult(intent1, REQUEST_PATH);
}
}
);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// See which child activity is calling us back.
if (requestCode == REQUEST_PATH)
{
if (resultCode == Activity.RESULT_OK)
{
curFileName = data.getStringExtra("GetFileName");
filePath=data.getStringExtra("GetPath");
edittext.setText(filePath);
}
}
}
lots of ways . here are 2 sample-
String someFilepath = "image.fromyesterday.test.jpg";
String extension = someFilepath.substring(someFilepath.lastIndexOf("."));
So in you case, it should be something like that
String extension = ff.getAbsolutePath().substring(ff.getAbsolutePath().lastIndexOf("."));
In case if you don't want to do it yourself-
use FilenameUtils.getExtension from Apache Commons IO-
String extension = FilenameUtils.getExtension("/path/to/file/mytext.txt");
or in your case -
String extension = FilenameUtils.getExtension(ff.getAbsolutePath());
You could just do it with one line of code using MIME Type Map.
First grab the file:
Uri file = Uri.fromFile(new File(filePath));
Then
String fileExt = MimeTypeMap.getFileExtensionFromUrl(file.toString());
You can put your code in your activity like this:
private String getfileExtension(Uri uri)
{
String extension;
ContentResolver contentResolver = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
extension= mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
return extension;
}
"uri" is the file uri from the result of "Browse button" selected file
Kotlin Approach:
val fileExtention: String = file.extension
Check this: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/java.io.-file/extension.html
Function:
public String getExt(String filePath){
int strLength = filePath.lastIndexOf(".");
if(strLength > 0)
return filePath.substring(strLength + 1).toLowerCase();
return null;
}
Usage:
String ext = getExt(path);
if(ext != null && ext.equals("txt")){
// do anything
}
PS: If you don't use toLowerCase(), possible the function returns upper and lower cases (dependent the exists file).
In Kotlin
You can read the MimeTypeMap documentation here
This is example if you are using startActivityForResult and you get data from it. Then you define Content Resolver to get mime type from the uri.
val uri: Uri? = it.data?.data
val contentResolver = requireContext().contentResolver
val stringMimeType = contentResolver.getType(uri!!)
Using that code, if you choose pdf file you will get something like
"application/pdf"
After that, using the MimeTypeMap you'll get the extensions. Don't forget that you should add getSingleton() because it's only available in singleton.
val stringFileType = MimeTypeMap.getSingleton().getExtensionFromMimeType(stringMimeType)
I used DocumentFile to get the file name and extension
DocumentFile documentFile = DocumentFile.fromSingleUri(YourActivity.this, fileUri);
String fileName = documentFile.getName();
String extension = fileName.substring(fileName.lastIndexOf("."));
For example, if your file name is 'your_image.jpg' then the extension will be '.jpg'
In Java
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
In Kotlin
fun getFileExt(fileName: String): String? {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length)
}
Kotlin
import android.webkit.MimeTypeMap
MimeTypeMap.getFileExtensionFromUrl("my.xlsx") // xlsx
MimeTypeMap.getFileExtensionFromUrl("my.pdf") // pdf
MimeTypeMap.getFileExtensionFromUrl("http://www.google.com/my.docx") // docx
MimeTypeMap.getFileExtensionFromUrl(File.createTempFile("aaa", ".txt").absolutePath) // txt
Getting extension of file in Kotlin:
fun getExtension(fileName: String): String {
return fileName.substring(if (fileName.lastIndexOf(".") > 0) fileName
.lastIndexOf(".") + 1 else return "",fileName.length)
}
getContentResolver().getType(theReceivedUri); // return "media/format"

Read Images From Emulator sdcard folder -Android

I attempt in my app to read images from sdcard folder. However, In tablet device the task done with no errors, it lists all images on folder in Gridview, BUT in Emulator, just empty Gridview list appear, although the folder and pictures exist on Emulator sdcard as you see in picture below?!
Class that used to create folder and read pictures:
Utils Code:
package com.example.imageslider.helper;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
import com.example.classes.DBItems;
import com.example.classes.ProjectEngine;
import com.example.diwansalesorder.MainScreen;
import com.example.diwansalesorder.R;
import com.example.imageslider.GridViewActivity;
public class Utils {
private final Context _context;
ArrayList<String> allData = new ArrayList<String>();
// Progress Dialog
private ProgressDialog pDialog;
ArrayList<String> filePaths;
File sdCard, directory;
File[] listFiles;
// constructor
public Utils(Context context) {
this._context = context;
}
/*
* Reading file paths from SDCard
*/
public ArrayList<String> getFilePaths() {
filePaths = new ArrayList<String>();
boolean success = true; // to check if directory created ot not
readAllItems();
sdCard = Environment.getExternalStorageDirectory();
directory = new File(sdCard.getAbsolutePath() + "/DiwanAppPictures");
if (!directory.exists()) {
success = directory.mkdirs();
}
if (success) {
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
new LoadAllPictures().execute();
} else {
new LoadAllPictures2().execute();
}
} else {
AlertDialog.Builder alert = new AlertDialog.Builder(_context);
alert.setTitle("Error!");
alert.setMessage(AppConstant.PHOTO_ALBUM
+ " directory path is not valid! Please set the image directory name AppConstant.java class");
alert.setPositiveButton("OK", null);
alert.show();
}
} else {
Toast.makeText(_context,
" can't create " + AppConstant.PHOTO_ALBUM + " folder !!",
Toast.LENGTH_LONG).show();
Intent prevIntent = new Intent(_context, MainScreen.class);
_context.startActivity(prevIntent);
}
return filePaths;
}
/*
* Check supported file extensions
*
* #returns boolean
*/
private boolean IsSupportedFile(String filePath) {
String ext = filePath.substring((filePath.lastIndexOf(".") + 1),
filePath.length());
if (AppConstant.FILE_EXTN
.contains(ext.toLowerCase(Locale.getDefault())))
return true;
else
return false;
}
/*
* getting screen width
*/
#SuppressLint("NewApi")
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) _context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
// Function to read all items from data base
private void readAllItems() {
final DBItems dbI = new DBItems(_context);
try {
dbI.open();
Cursor allTitles = dbI.getAllAccounts();
allTitles.moveToFirst();
do {
String Item = allTitles.getString(1);
String Name = allTitles.getString(2);
String Cprice = allTitles.getString(3);
String Ccurr = allTitles.getString(4);
String Sprice = allTitles.getString(5);
String Scurr = allTitles.getString(6);
String Qnty = allTitles.getString(7);
String IncVat = allTitles.getString(8);
String StQnty = allTitles.getString(9);
String MinQnty = allTitles.getString(10);
String MaxQnty = allTitles.getString(11);
String Class = allTitles.getString(12);
String StkLoc = allTitles.getString(13);
String currQnty = allTitles.getString(14);
String VatDate = allTitles.getString(15);
String Ttime = allTitles.getString(16);
allData.add(Item + "!" + Name + "!" + Cprice + "!" + Ccurr
+ "!" + Sprice + "!" + Scurr + "!" + Qnty + "!"
+ IncVat + "!" + StQnty + "!" + MinQnty + "!" + MaxQnty
+ "!" + Class + "!" + StkLoc + "!" + currQnty + "!"
+ VatDate + "!" + Ttime + "");
} while (allTitles.moveToNext());
dbI.close();
} catch (Exception e) {
e.printStackTrace();
dbI.close();
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllPictures2 extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(_context);
pDialog.setMessage(ProjectEngine.fillDataMsg);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
#Override
protected String doInBackground(String... args) {
// Load Image from res
try {
for (int i = 0; i < allData.size(); i++) {
OutputStream fOut = null;
File file = new File(directory,
allData.get(i).split("!")[0].toString() + ".jpeg");
if (file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
Drawable ditemp = _context.getResources().getDrawable(
R.drawable.nopicture);
Bitmap image = ((BitmapDrawable) ditemp).getBitmap();
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
}
} catch (Exception e) {
// Log.e("saveToExternalStorage()", e.getMessage());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent prevIntent = new Intent(_context, GridViewActivity.class);
_context.startActivity(prevIntent);
pDialog.dismiss();
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllPictures extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(_context);
pDialog.setMessage(ProjectEngine.fillDataMsg);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
#Override
protected String doInBackground(String... args) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
// check for supported file extension
if (IsSupportedFile(filePath)) {
// Add image path to array list
filePaths.add(filePath);
}
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
please any help will be appropriated,
Most likely it's a problem with the path to the directory holding your pictures. Please compare the value returned by Environment.getExternalStorageDirectory() method on your phone with the one returned on the emulator. They may be different, thus you may need to move your images accordingly.

How do I write to a .txt file in Android?

I have an app that needs to read and write to a text file. I have it reading, but I don't have it writing. The idea is that when I click the save button on the screen, its going to save all the info that has been put into the textviews into an array and the write each segment of the array into the text file. This is my code for the writing portion:
public class AddOrModify extends Activity {
private Button Savebtn;
private Button Cancelbtn;
private EditText NameofRoute;
private EditText Address1;
private EditText City1;
private EditText State1;
private EditText Zip1;
private EditText Address2;
private EditText City2;
private EditText State2;
private EditText zip2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_or_modify);
Savebtn = (Button)findViewById(R.id.savebtn);
Savebtn.setOnClickListener(new btnlistenersave());
Cancelbtn = (Button)findViewById(R.id.cancelbtn);
Cancelbtn.setOnClickListener(new btnlistenercancel());
}
private class btnlistenersave implements View.OnClickListener{
public void onClick(View v) {
NameofRoute = (EditText)findViewById(R.id.NameofRoute);
Address1 = (EditText)findViewById(R.id.editAddress1);
City1 = (EditText)findViewById(R.id.City1);
State1= (EditText)findViewById(R.id.State1);
Zip1 = (EditText)findViewById(R.id.Zip1);
Address2= (EditText)findViewById(R.id.Address2);
City2 = (EditText)findViewById(R.id.City2);
State2 = (EditText)findViewById(R.id.State2);
zip2 = (EditText)findViewById(R.id.Zip2);
//String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};
// if(mySettings != null){
try{
String NameofRouteinput = NameofRoute.getText().toString();
String Address1input = Address1.getText().toString();
String City1input = City1.getText().toString();
String State1input=State1.getText().toString();
String Zip1input = Zip1.getText().toString();
String Address2input =Address2.getText().toString();
String City2input = City2.getText().toString();
String State2input = State2.getText().toString();
String Zip2input= zip2.getText().toString();
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("myaddress.txt",0));
String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};
for(int i =0; i < mySettings.length; i++)
out.write(mySettings[i]);
out.close();
}
catch (java.io.IOException e){
}
Intent i = new Intent(AddOrModify.this, Frontpage.class);
startActivity(i);
}
}
private class btnlistenercancel implements View.OnClickListener{
public void onClick(View v) {
Intent i = new Intent(AddOrModify.this, Frontpage.class);
startActivity(i);
}
}
}
with mari's solution i was getting
java.lang.IllegalArgumentException: contains a path separator
then i tried following and it worked for me
File root = new File(DIRECTORY_PATH);
File gpxfile = new File(root, "samples.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append("First string is here to be written.");
writer.flush();
writer.close();
you can loop it to write multiple lines
You can use FileOutputStream instead of OutputStreamWriter, something like this:
File file = getFileStreamPath("test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE);
for (String string: data){
writer.write(string.getBytes());
writer.flush();
}
writer.close();
Check the android docs.

Android OutputStreamWriter not creating file

I am trying to write data from EditText fields to a text file. I have verified that the data is being captured for output in an EditText field that I populate after clicking the Add button. The program runs successfully in the Emulator, but no output file is created. I have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" to the Android Manifest xml file. LogCat & Console do not show any errors. I have tried several different methods after reseaching examples here, but no luck. Can anyone point out my issue? Thanks in advance for your help.
package john.BRprogram;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
//import android.graphics.Color;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class BRprogramActivity extends Activity implements OnItemSelectedListener {
private static final String TAG = null;
//
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
Button addButton;
Button editButton;
Button sendButton;
//
Spinner array_spinner;
//
// activate soft Keyboard
this.getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
//
// .csv comma separated values file
//
try {
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.brdata));
//
List<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
String data = (scanner.next()); //read data record
String [] values = data.split(","); //parse data to fields
// String [] values = data.split(",(?=([^\"]\"[^\"]\")[^\"]$)");
if(values.length != 3)
Log.v("Example", "Malformed row: " + data);
else
list.add(values[0] + " " + values[1] + " $" + values[2]);
}
//
array_spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
array_spinner.setAdapter(adapter);
array_spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
//
scanner.close();
//
} catch (Exception e) {
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
//
addButton = (Button) findViewById(R.id.addbutton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
// get customer number,itemnumber,quantity,price
//
String writeCustomer = ((EditText) findViewById(R.id.editText1)).getText().toString().trim();
// itemNumber from list selection
String writeQuantity = ((EditText) findViewById(R.id.editText2)).getText().toString().trim();
String writePrice = ((EditText) findViewById(R.id.editText3)).getText().toString().trim();
//
String newRecord = writeCustomer + "," + writeQuantity + "," + writePrice;
EditText myString = (EditText)findViewById(R.id.editText4);
myString.setText(newRecord);
//
// write seq to output file
//
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("broutput.txt",0));
out.write(newRecord);
out.close();
}catch (Exception e){
Log.v("test", "record written");
}
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "ADD button clicked");
}
});
//
editButton = (Button) findViewById(R.id.editbutton);
editButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Log.v("test", "EDIT button clicked");
}
});
//
sendButton = (Button) findViewById(R.id.sendbutton);
sendButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "SEND button clicked");
}
});
}
// *** http://www.youtube.com/watch?v=Pfasw0bbe_4 ***
//
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//
String selection = parent.getItemAtPosition(position).toString();
String [] priceField = selection.split("\\$"); //parse price field
String [] item = selection.split("_"); //parse item number
String itemNumber = item[0];
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText(priceField[1]);
}
//
public void onNothingSelected(AdapterView<?> arg0) {
//nothing here
}
}
Looks like you need to create and/or specify the directory where you wish to save the file. I didn't see that anywhere in your code. It might look something like this:
if (Environment.getExternalStorageState() == null) {
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}
When you save data from your app, you have to remember that it is running on the Android, and not your computer, so all data is going to be written to your Android, not your comp. You have to pull the data after it is written to view it. Make sure you that you created a local directory on your device and make sure you check for an SD card. The code I listed will show you how to do everything you need.
Hope this helps!
I've actually experienced a problem like this; everything seemed fine, but my code wasn't working. My problem was the characters in the file name I was writing. For example, I tried writing the file name my_file - date 07/11/2012. This caused problems because it treated each / as a cue to begin a new directory! For this reason, I discovered I could not have any / (or :, for some reason) in my file names. Would this be your problem?
If this is your problem, then you could do what I did: perform a newRecord.replace('/', '-'); to replace all / in your file name with a - (if you are fine with having -'s instead).
On a side note, why are you logging "record written" in your the catch of your try/catch statement? If it catches a problem, doesn't that mean it wasn't written?

Categories

Resources