unable to locate file in DDMS view - android

I am generating a notification for classes according to my timetable. In the notification i am providing action button if the user clicks this button a file for that class opens where attendance is marked for the corresponding class. I have written the following code
public class Record extends BroadcastReceiver
{public void onReceive(Context context, Intent intent)
{
String f = intent.getStringExtra("class");
String fname= f+".txt";
System.out.println("File Name :" + fname);
try
{ File name = new File(f+".txt");
if(!name.exists())
{
System.out.println("Creating file" + fname);
name.createNewFile();
FileOutputStream fos = context.openFileOutput(fname,Context.MODE_PRIVATE);
String str1= "1";
fos.write(str1.getBytes());
fos.close();
if(!name.exists())
{
System.out.println("FILE NOT CREATED");
}
}
else
{ String inputString;
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
context.openFileInput(fname)));
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null)
{
stringBuffer.append(inputString + "\n");
}
int number = Integer.parseInt(inputString);
number=number+1;
String str1 = String.valueOf(number);
FileOutputStream fos = context.openFileOutput(fname,Context.MODE_PRIVATE);
fos.write(str1.getBytes());
fos.close();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
So what i did is check if the file exists . if not then create one else increment the contents by one.
when i run this and click on the action button, i get
1) File Name
2) Creating File
but don't get FILE NOT CREATED. this means the file is being created. But i cannot find the file in DDMS view.
I dont know where i am going wrong. Please help.

It is probably already created. Context.MODE_PRIVATE automatically creates the file in your internal app directory if not already there. The complete path to your internal app files directory is /data/data/com.example.yourpackage/files.
Is your phone rooted? Because you shouldn't be able to see the root folders in DDMS without it being rooted. If so, another way you can check is use a File Manager program on your phone. I use ES File Manager.

Try to put fname on the disk as I doubt that you are creating file in a non authorized area on the disk
Use
String fname= getFilesDir() +"/" + f+".txt";

Related

When accessing a text file on my android device through my PC, part of it doesn't come through

In my android app, I am putting values to a text file and I have confirmed that it works. I can open the text file on my android device and see ALL of the data in there as it should be. However, when I plug the device into my PC via USB, some of the data in the text file gets cut off.
Here's the data I see on my android device when I open the text file:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,false,4,1,
Here's the data I see when I access the text file on my computer:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,f
As you can see, the last few pieces of data get cut off. I've tried with different data and it still gets cut off there.
I'm not sure if this will help as the following code seemingly does get all the data to the text file (if looking on my android device), but here's the code for writing to the text file. I'm getting two lists of data from SharedPreferences files I've previously created and writing them to a file when a button is pressed.
SharedPreferences auto = getSharedPreferences("Auto", MODE_PRIVATE);
SharedPreferences teleop = getSharedPreferences("Teleop", MODE_PRIVATE);
autoValues = auto.getAll();
teleopValues = teleop.getAll();
public void writeToFile(View view){
try {
FileOutputStream stream = new FileOutputStream(myFile);
for (Map.Entry<String, ?> entry : autoValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
for (Map.Entry<String, ?> entry : teleopValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
stream.close();
System.out.println("SUCCESS: MAY HAVE WRITTEN TO FILE IN EXPORT");
} catch (Exception e){
e.printStackTrace();
System.out.println("ERROR: DID NOT WRITE TO FILE");
}
}
Use following function to efficiently write to your file. You must have permission to access external storage.
public static void logToFile(String message) {
String formattedData = String.format("%s", (new SimpleDateFormat("dd-MM HH:mm:ss", Locale.getDefault())
.format(new Date())) + "\t\t\t" + message + "\n");
FileOutputStream stream = null;
String path = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOWNLOADS;
try {
File file = new File(path + "/Logger.txt");
if (!file.exists()) {
file.createNewFile();
}
stream = new FileOutputStream(file, true);
stream.write(formattedData.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}

Reading data from downloaded .txt file downloaded multiple times in Android app

I'm developing an app in which I'm sending a .txt file from one end by attaching it with gmail. Everytime this file is sent, its name is data.txt. When this file is downloaded at the other end, on the first download its name is the same, i.e. data.txt. However, when another file is sent with the same name, the name of the file at the receiveing end becomes data-1.txt, data-2.txt etc. And because of this, I'm not able to read the proper file. Please could someone give me some suggestions to solve this problem? The sending and receiving code is given below: SEND
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
String toWrite = enterText.getText().toString();
FileOutputStream fos;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.v("path", path);
File myFile = new File("" + path + "/" + fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(toWrite);
Log.v("file written", toWrite);
myOutWriter.close();
fOut.close();
Uri u1 = null;
u1 = Uri.fromFile(myFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "MPPT Configuration Data");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
READ:
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/storage/sdcard0/download/" + fileName + ".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
Log.v("read data", "" + aBuffer);
tvData.setText(aBuffer);
}catch (IOException e2) {
e2.printStackTrace();
}
}
});
I found a possible solution. I can link the file manager (external app) from where the user can pick out whichever file he wants to be read.
Thanks #greenapps fir the idea of displaying a list of files.
You can get all the file by using regex ,then process the file by following way:
1.if only one file found,read it;
2.if more than one file found, compare and read the file which last number is biggest
but this solution still has one problem,if has file data.txt and data-3.txt ,the file we want to read may become data-2.txt,but what we really read is data-3.txt.
Or,maybe you can get the file you want by judging file established time.

Opening a textfle and pushing it to parse cloud (android)

I have a textfile in /sdcard/applit/mytext.txt
I want to push it to parse cloud.Googled a lot but No profit.Please explain completely.Thanx.
private void txtPusher(File dir) throws IOException {
File outputFile;
outputFile=newFile(dir,"MyText\t"+ParseUser.getCurrentUser().getUsername()+".txt");
byte [] b;
b=FileUtils.readFileToByteArray(outputFile);
file=new ParseFile("MyText\t"+ParseUser.getCurrentUser().getUsername()+".txt",b);
file.saveInBackground();
TextPusher Tpusher=new TextPusher(file);
Tpusher.execute();
}
Here dir is the directory I am passing to txtPusher function.I want to know wether output file is that file which I am going to push or another directory or it is creating a new file.but my file is not getting pushed.If i am wrong please share the right way to push the textfile
You can read the contents of a text (.txt) file using the following:
private String readFile(String fileName) {
//Find the directory for the SD Card using the API
File sdcard = new File(Environment.getExternalStorageDirectory() + File.separator + "Inventory_Files/Version/");
// Get the text file
File file = new File(sdcard, fileName);
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}
As for sending this data to the cloud, this looks to be very well documented on their site.

read from text file in android

I am new in android development, and I'm trying to create a simple application which reads some data from a text file and displays it in a ListView. The problem is my reader doesn't find my file. I've debugged my application and that is the conclusion I've come up with. So, where does the text file have to placed in order for the reader to find it?
Heres some code:
try
{
FileInputStream fstream = new FileInputStream("movies.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
filme.add(strLine);
Log.d(LOG_TAG,"movie name:" + strLine);
}
in.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
Thanks!
Put the file named movies.txt in res/raw, then use the following code
String displayText = "";
try {
InputStream fileStream = getResources().openRawResource(
R.raw.movies);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
} catch (IOException e) {
// exception handling
}
FileInputStream fstream = new FileInputStream("movies.txt");
where is the path for movies.txt ?? You must need to give the path as sd card or internal storage wherever you have stored.
As if, it is in sd card
FileInputStream fstream = new FileInputStream("/sdcard/movies.txt");
Usually when you want to open a file you put it into the res folder of your project.
When you want to open a text file, you can put it into the res/raw directory. Your Android eclipse plugin will generate a Resource class for you containing a handle to your textfile.
To access your file you can use this in your activity:
InputStream ins = getResources().openRawResource(R.raw.movies);
where "movies" is the name of your file without the filetype.
If you store your files on the SD card, then you can get the root of the SD card with Environment.getExternalStorageDirectory().
Note, that you might not be able to access the SD card, if it is mounted to the computer for example.
You can check the state of the external storage like this:
boolean externalStorageAvailable = false;
boolean externalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
externalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
externalStorageAvailable = true;
externalStorageWriteable = false;
} else {
externalStorageAvailable = mExternalStorageWriteable = false;
}
if(externalStorageAvailable && externalStorageWriteable){
File sdRoot = Environment.getExternalStorageDirectory();
File myFile = new File(sdRoot, "path/to/my/file.txt");
}

I need to be able to store sound files for my application on sdcard

I've read a lot of topics but none seem to cover what I need.
I basically have a load of sound files and I want to be able to play them in the application from the sdcard.
I also want to be able to install them there in the first place when the application is installed.
I am using Eclipse with the android SDK and currently my Target project is v1.6
Can anyone help?
Thanks
OK so I found the answer!
First we need to get the external Storage Directory to a variable called baseDir.
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
Then Create the directory mysounds on the SDcard
File folder = new File(Environment.getExternalStorageDirectory() + "/mysounds");
boolean success = false;
if(!folder.exists())
{
success = folder.mkdir();
}
if (!success)
{
// Do something on success
}
else
{
// Do something else on failure
}
Then This following bit of code will copy all the files with sound at the beginning of the name from the assets directory to the mysounds directory you have already created.
try {
AssetManager am = getAssets();
String[] list = am.list("");
for (String s:list) {
if (s.startsWith("sound")) {
Log.d("Notice", "Copying asset file " + s);
InputStream inStream = am.open(s);
int size = inStream.available();
byte[] buffer = new byte[size];
inStream.read(buffer);
inStream.close();
FileOutputStream fos = new FileOutputStream(baseDir + "/mysounds/" + s);
fos.write(buffer);
fos.close();
}
}
}
Hope this helps someone!

Categories

Resources