can not display file content in text view - java

i am trying to select a file from the alert dialog and when i press OK i should display the content of the selected file in a text View by using the method display Content() that take the selected file read it and display the content line by line, but it does not display anything and i think the problem is with the call because i already use the method in another app and it work.
this is the code i have and how i call displayContent()
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Single Choice List")
.setSingleChoiceItems(files, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectionID = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//display the content of the selected file
displayContent();
Toast.makeText(View_Records.this, "You selected " + files[selectionID], Toast.LENGTH_SHORT).show();
}
})
this is the code for displayContent():
private void displayContent(){
try {
myFilesDirectory = new File(getFilesDir(), "MyFiles");
String fileName = files[selectionID] + ".txt";
File file = new File(myFilesDirectory, fileName);
String text;
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
txtViewRecords.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Replace
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Single Choice List")
.setSingleChoiceItems(files, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectionID = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//display the content of the selected file
displayContent();
Toast.makeText(View_Records.this, "You selected " + files[selectionID], Toast.LENGTH_SHORT).show();
}
})
with calling for another Activity (startActivityForResult()) with dialog style where you will pick a File and return it's path with Intent and then inside onActivityResult() you just use it to open File and then display it's content inside TextView.
Otherwise you can try to use create() first and add onDismissListener(). Like this:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// do you things with builder
AlertDialog ad = builder.create();
ad.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
// here you open file, read content and put it inside TextView`
}
});
ad.show()
I'm not sure, but this should do the job with AlertDialog without creating Activity for this.
This is for getting all files from directory:
public static ArrayList<File> listFiles(File folder) {
if (folder.isDirectory()) {
ArrayList<File> tempList = new ArrayList<>();
File[] files = folder.listFiles();
for (File inFile : files) {
if (!inFile.isDirectory()) {
tempList.add(inFile);
}
}
/*Collections.sort(tempList, new Comparator<File>() { //you can sort by name
#Override
public int compare(File file1, File file2) {
return file1.getName().compareTo(file2.getName());
}
});*/
return tempList;
}
return null;
}
And you just send myFilesDirectory as a parameter.
Also you can skip checking if(!inFile.isDirectory()) if you are 100% sure that all files are files, not directories and return Array.
And then you just get your file using list.get(selectionID) or array[selectionID] depending what you are going to return from method.
Also method doesn't need to be static. I've got it static for my project needs.

Related

I want to add condition if user already save the image than show toast image already saved

The current code works to save the photo but I want to implement the toast code below when the user saves the image already it show image save already. Any ideas how I would do this.
Below is the source code to take the photo:
holder.save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkFolder();
final String path = imagesList.get(position).getPath();
final File file=new File(path);
String destPath = Environment.getExternalStorageDirectory().getAbsolutePath()+Common.APP_DIR;
final File destFile =new File(destPath);
try {
FileUtils.copyFileToDirectory(file, destFile);
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[]{destPath + status.getTitle()},
new String[]{"*/*"}, new MediaScannerConnection.MediaScannerConnectionClient() {
#Override
public void onMediaScannerConnected() {
}
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
Toast.makeText(context, "Image Saved Successfully!", Toast.LENGTH_SHORT).show();
}
});

How to create a simple local backup and restore for an app?

I Have five sqlite databases and I want user to be able to have local backup in his phone and he can restore the backup file .
I don't know how to create these backups and restore them programatcally .
I used A github repo but it did not work at all,
I need your help to create this process of backup and restore .
Thank for your attention
In your Activity make backup and restore button and define local database variable like,
private MainDatabase localBackup = new MainDatabase(this);
Then perform backup and restore operation when it's just click
#Override
public void onClick(View v) {
final MainDatabase db = new MainDatabase(getApplicationContext());
switch (v.getId()) {
case R.id.tvBackUp:
String outFileName = Environment.getExternalStorageDirectory() +
File.separator + getResources().getString(R.string.app_name) + File.separator;
localBackup.performBackup(db, outFileName);
break;
case R.id.tvRestore:
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + getApplicationContext().getResources().getString(R.string.app_name));
if (folder.exists()) {
final File[] files = folder.listFiles();
if (files.length == 0) {
Toast.makeText(this, "No any Backup", Toast.LENGTH_SHORT).show();
} else {
localBackup.performRestore(db);
}
}
break;
}
}
Make a method for backup in your database file
public void performBackup(final MainDatabase db, final String outFileName) {
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ mContext.getResources().getString(R.string.app_name));
boolean success = true;
if (!folder.exists())
success = folder.mkdirs();
if (success) {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.backup_dialog);
dialog.getWindow().getAttributes().windowAnimations =
R.style.PauseDialogAnimation;
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
Button btnSave = dialog.findViewById(R.id.btnSave);
Button btnCancel = dialog.findViewById(R.id.btnCancel);
EditText etName = dialog.findViewById(R.id.etName);
etName.setInputType(InputType.TYPE_CLASS_TEXT);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String m_Text = etName.getText().toString();
String out = outFileName + m_Text + ".db";
db.backup(out);
dialog.dismiss();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
} else
Toast.makeText(mContext, "Unable to create directory. Retry",
Toast.LENGTH_SHORT).show();
}
public void backup(String outFileName) {
//database path
final String inFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Backup Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to backup database. Retry",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
As well as for restore do this thing,
ask to the user what backup to restore
public void performRestore(final MainDatabase db) {
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ mContext.getResources().getString(R.string.app_name));
if (folder.exists()) {
final File[] files = folder.listFiles();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item);
for (File file : files)
arrayAdapter.add(file.getName());
AlertDialog.Builder builderSingle = new AlertDialog.Builder(mContext);
builderSingle.setTitle("Select & Restore ");
builderSingle.setNegativeButton("cancle", (dialog, which) ->
dialog.dismiss());
builderSingle.setAdapter(arrayAdapter, (dialog, which) -> {
try {
db.importDB(files[which].getPath());
} catch (Exception e) {
Toast.makeText(mContext, "Unable to restore. Retry",
Toast.LENGTH_SHORT).show();
}
});
builderSingle.show();
} else
Toast.makeText(mContext, "Backup folder not present.\nDo a backup before a
restore!", Toast.LENGTH_SHORT).show();
}
public void importDB(String inFileName) {
final String outFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Restore Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to import database. Retry",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
Android already supports system automatic backups if you have android:allowBackup="true" at your manifest. If it isn't enough and you want to manage backups manually between app reinstalls than you have to copy database from context.getDatabasePath("<your-database-name>") to external storage somewhere, and then copy it back when you want

AlertDialog not refreshing data

public void setFileName(String inMake, String inModel) {
//sets spinner to get year
filename = filename.concat(inMake);
filename = filename.concat(inModel);
filename = filename.concat(".txt");
spinner3 = (Spinner) findViewById(R.id.spinner3);
BufferedReader reader;
AssetManager assetManager = MainActivity.getContext().getAssets();
List<String> testYears = new ArrayList<String>();
try {
InputStream istr = assetManager.open(filename);
reader = new BufferedReader(new InputStreamReader(istr));
String line;
while((line = reader.readLine()) != null) {
testYears.add(line);
}
}
catch (IOException e){
Log.e("message: ",e.getMessage());
}
AlertDialog.Builder yearDialog = new Builder(this);
yearDialog.setTitle("Select Year");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice, testYears);
adapter.notifyDataSetChanged();
yearDialog.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
year = Integer.parseInt(adapter.getItem(which));
Toast.makeText(getApplicationContext(),
"Year : " + year, Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = yearDialog.create();
alert.show();
}
I'm attempting to retrieve a user choice via an alertdialog. The array it uses for the arrayAdapter is based on the input of the function(string inmake, string inmodel) which are passed from outside the activity. This method seems to work perfectly - but only the first time. If I send in new string information to the method, it doesn't show any options in the alertdialog.
Any help would be much obliged.

Saving a file in Android

I have the following code:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/tc/strip.tcl");
try {
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
else {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in try", Toast.LENGTH_SHORT).show();
}
finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
What I am looking to do is:
When the button is clicked:
1) Check to make the data is not null or empty (Working fine):
if (showLog != null && showLog.getText().toString().length() > 0) {
2) Check to make sure the folder exists, if not create the folder (Working fine):
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
3) Before writing the data to the file, ensure it doesn't already exist. If it does exist, prompt the user to see if it can be overwritten. If the user chooses YES then overwrite the file but if the user chooses NO then add a "1" at the end of the filename and save it. (NOT WORKING and need help)
I am getting an error for the following line:
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Error:
Unhandled exception type FileNotFoundException
--> (Surround with try/catch)
1)
File tcDir = new File(Environment.getExternalStorageDirectory(),"tc");
tcDir.mkdirs();
File file = new File(tcdir, "strip.tcl");
The first line creates a file object called tc in the external storage directoy. The second line creates it on disk, with any missing parents. The third line creates a file object inside that directory
2)You seem to be doing that- you create a file output stream and write to it like you're doing.
3)Before writing the file, cal file.exists(). If it exists, you need to pop up a AlertDialog. If they hit the yes button of the dialog you write a file. If they choose the no button, you do nothing. It would be best to put all of the writing code into a separate function so it can be called in both the dialog click code and in the !exists code here.
In answer to part 3), I've edited your code to work properly for you. Most of the code you had was correctly written there was just a couple of issues. I also moved the code to write a new file into a new method writeFile() in order to avoid replicating code and to make it easier to keep track of what's going on:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/TollCulator");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/TollCulator/strip.tcl");
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the existing file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeFile(file);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
} else {
writeFile(file);
}
} else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
// ...
private void writeFile(File file){
try {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}

Reading files from a dir on the sdcard

I'm trying to read a dir and within this dir I have files for each contact. I want to to be able to read those contacts and then put them into the listview. I have tried but, I get a Java error and tried to research it more and found out when I try to do:
fileInputStream fi = fileInput(sdcard/contacts, 0);
fi.read();
//then the parse.
As I said I tried this and get an error which means I can't access a dir with the method above as that method is looking for app specific data.
My Code so far:
private void checkFosImprtCtacs() {
String FILENAME = "check";
String RND = "LewisR";
OutputStream out = null;
// TODO Auto-generated method stub
/*
* Check if the dir exists, if it does we'll load the contacts, if it
* doesn't the user will be presented with a dialog box and if they hit
* yes the contacts will be written to the SD card see the
* importcontacts theory file.
*/
File dir = new File(Environment.getExternalStorageDirectory()
+ "/chckcontacts");
if (dir.exists() && dir.isDirectory()) {
dir.exists();
dir.getPath().getBytes().toString(
//yes I KNOW THIS CODE IS WRONG, I JUST WANTED TO SHOW SOMETHING.
BufferedReader inputReader = null;
while (dir.getPath().getBytes() != null) {
}
} else {
if (dir.exists())
;
{
dir.mkdir();
// import contacts via dialog box.
new AlertDialog.Builder(this)
.setTitle("Import Contacts")
.setMessage("Do you want to import your contacts?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Cursor cursor = getContacts();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Log.e(displayName, displayName);
// create a File object for the
// parent directory
File Contacts = new File(
Environment
.getExternalStorageDirectory()
+ "/contacts");
// have the object build the
// directory structure, if needed.
Contacts.mkdirs();
// create a File object for the
// output file
File outputFile = new File(
Contacts,
displayName);
// now attach the OutputStream to
// the file object, instead of a
// String representation
try {
FileOutputStream fos = new FileOutputStream(
outputFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
}
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// do nothing
}
}).show();
}
}
}
private Cursor getContacts() {
// TODO Auto-generated method stub
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = 1";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}

Categories