Reading a text file dynamically on user selection in Android - java

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();

Related

Load a txt file -> open failed: ENOENT (No such file or directory). I'm pretty sure the problem is not the path, but i can't find the mistake

I'm trying to load a file and save what's wrote in it but I always get "open failed: ENOENT". The file is in the same folder of java files. Rest of code works nice, and if I run separately also the method read().
public class MainActivity extends AppCompatActivity {
ListView list;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intent = new Intent(this, Second_activity.class);
list = (ListView) findViewById(R.id.listView);
System.out.println(read());
String [] dati = {};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dati);
list.setAdapter(adapter);
list.setOnItemClickListener(listener);
}
private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
String itemValue = (String) list.getItemAtPosition(position);
intent.putExtra("listValue", itemValue);
startActivity(intent);
}
};
public String read(){
String data = null;
try {
File myObj = new File("com/example/myapplication2/calendario.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
}
myReader.close();
} catch (Exception e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
return data;
}
}
Your file is on your android studio project path, and then you need put it in the right place raw folder, second get it the right way. File("....") is for file in device path.
Get Started.
You need move your file to resource/raw folder, for create this folder just right click on res folder, select New> Directory, then studio will open a dialog box and it will ask you to enter the name.
and write “raw” and click OK. Open res folder and you will find your raw folder under it.
Then you can put your files like .txt, .mp3 in this folder, and to get one you can use this code or similar.
InputStreamReader inputStream = new InputStreamReader(getResources().openRawResource(R.raw.calendario))
BufferedReader reader = new BufferedReader();
String line = reader.readLine();
while (line != null) { ... }

renameTo() not working for renaming images and returns false

I have an image gallery app, I am trying to rename images using renameTo() method but it is not able to change the name of files and returns false. I read many questions on SO for renaming files and all of them suggest for only one method for renaming files - renameTo(). Strangely enough, many questions talk about how it is not a good method for renaming files in various conditions.
Is there any other way of renaming files in android? If I use this way only, how to make it work?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
alert = new AlertDialog.Builder(this);
etRenameFile = new EditText(getApplicationContext());
alert.setTitle("Do you want to rename the file?");
alert.setMessage(" ");
alert.setView(etRenameFile);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int whichButton) {
renameFileAlert();
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
private void renameFileAlert(){
String renameFile = etRenameFile.getText().toString();
Log.v(TAG, renameFile + " another");
String filename= al_images.get(int_position).getAl_imagepath().get(fileIndex);
File oldFilePath = new File(al_images.get(int_position).getAl_imagepath().get(fileIndex));
Log.v(TAG,oldFilePath.toString());
// Log.d("OLDFILEPATH", oldFilePath.toString()); // prints the correct path of the file being selected
x = al_images.get(int_position).getAl_imagepath().get(fileIndex);
File renamedFile = new File(x.replace(filename, renameFile));
Log.v(TAG, renamedFile.toString() + " new name"); //prints new name of the file being entered
// Log.d("NEWFILE", renamedFile.toString());
boolean renamed = oldFilePath.renameTo(renamedFile);
if(renamed){
Log.v(TAG, "rename done");
} else Log.v(TAG, "failed");
notifyMediaStoreScanner(renamedFile);
}
public final void notifyMediaStoreScanner(File file) {
// try {
// MediaStore.Images.Media.insertImage(getBaseContext().getContentResolver(),
// file.getAbsolutePath(), file.getName(), null);
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
getBaseContext().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
}
What are you trying to rename it to exactly? renameTo() will only return true if and only if the renaming succeeded; returning false otherwise.

Empty saved text file

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);

How to put AlertDialog in static method

How to show Alert Dialog in static method, i am trying to put a condition, in which i am checking for the folder inside the SD Card, if exist then listing Items, otherwise i want to show AlertDialog - with message no folder found with Church Name
public static List <String> fromSDCard()
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}else{
// here i want to put AlertDialog
}
return listChurchWall;
}
Pass your app context to the static method.
public static List <String> fromSDCard(Context context)
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}else{
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
.setTitle(R.string.dialog_title);
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
// 4. Show the dialog
dialog.show()
}
return listChurchWall;
}
If calling from your activity.
public MyActivity extends Activity
{
....
private void Method()
{
List<String> list = fromSdCard(this);
}
....
}
public static List<String> fromSDCard(Context mContext) {
List<String> listChurchWall = new ArrayList<String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File(string + name + "/");
if (f.exists()) {
files = f.listFiles();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
int imageResource = android.R.drawable.stat_sys_warning;
Drawable image = mContext.getResources().getDrawable(imageResource);
builder.setTitle("title").setMessage("your Message").setIcon(image).setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.setCancelable(false);
alert.show();
}
return listChurchWall;
}
Try the following way--
public static List <String> fromSDCard(Activity a, String title, String message)
{
List <String> listChurchWall = new ArrayList <String>();
// listing Wallpaper using church names
String string = "/mnt/sdcard/Church/Wallpaper/";
f = new File (string+name+"/");
if (f.exists())
{
files = f.listFiles ();
}
else
{
AlertDialog.Builder dialog = new AlertDialog.Builder(a);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setNeutralButton("OK", null);
dialog.create().show();
}
return listChurchWall;
}
Then in your class do---
public MyActivity extends Activity
{
....
private Method()
{
List<String> list = fromSdCard(this, "Your Title", "Your message");
}
....
}
UPDATE:
You get a NullPointerException because something is null that shouldn't be. It happens while sorting the array, so perhaps one of the array elements is null. Take a look at how you assign values to your array.
Perhaps at the top of it, see if any of the objects Object o1 or Object o2 themselves are null.

Getting Media Title from a File

I used import java.io.File; to import all music files from my sdcard,
Now i want the Title's of the files using Mediastore but how do I do that?
This is the code I Use now.
public class ListFiles extends ListActivity {
private List<String> directoryEntries = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
File directory = new File(i.getStringExtra("directory"));
if (directory.isDirectory()){
File[] files = directory.listFiles();
Arrays.sort(files, new Comparator<File>(){
public int compare(File f1, File f2) {
return -Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
this.directoryEntries.clear();
for (File file : files) {
this.directoryEntries.add(file.getName());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,R.layout.file_row, this.directoryEntries);
this.setListAdapter(directoryList);
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
File clickedFile = new File(this.directoryEntries.get(position));
Intent i = getIntent();
i.putExtra("clickedFile", clickedFile.toString());
setResult(RESULT_OK, i);
finish();
}
}
Thanks.
I have done that for Video files using MediaStore : Class Overview - The Media provider contains meta data for all available media on both internal and external storage devices.
You can refer these two example to understand the use of MediaStore
List Video and List Audio

Categories

Resources