File not found Exception in Android but File Exists - android

I am trying to get the address of any file on android and then read its content.
I am getting the location of file as :
uri2.toString() gives string "file:///storage/emulated/0/download/user.txt"
uri2.getEndodedPath() gives string "/storage/emulated/0/download/user.txt"
when passing these value to file it gives file not found exception
Note : I am not reading file from sdcard or asset folder or raw folder and i am testing my app on mobile one plus cyanogen mod
here is my android code
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.nfc.Tag;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
public class MainSpeechActivity extends Activity {
TextToSpeech tts;
Button btn;
private String uri;
private Uri uri2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_speech);
final Intent intent = getIntent();
final String action = intent.getAction();
if(Intent.ACTION_VIEW.equals(action)){
//uri = intent.getStringExtra("URI");
uri2 = intent.getData();
uri = uri2.getEncodedPath() + " complete: " + uri2.toString();
TextView textView = (TextView)findViewById(R.id.textView);
TextView textView2 = (TextView)findViewById(R.id.textView2);
textView.setText(uri);
// now you call whatever function your app uses
String str = uri2.toString();// value is mentioned above
File f = new File(str);
BufferedReader br = null;
String line;
StringBuilder sbr = new StringBuilder();
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
while((line = br.readLine()) != null) {
sbr.append(line);
sbr.append("\n");
}
br.close();
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"FileNotFound",Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),"InputError",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if(sbr.toString().isEmpty())
textView2.setText("Blah blah");
else
textView2.setText(sbr.toString());
} else {
Log.d("know", "intent was something else: " + action);
}
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if( i != TextToSpeech.ERROR) {
tts.setLanguage(Locale.ENGLISH);
}
}
});
btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String toSpeak = "My friend is very good programmer do you aggree";
Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
tts.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_speech, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If reading file from android is not possible then how to copy that file to sdcard or at location where reading and writing is possible

I am trying to get the address of any file on android and then read its content.
I am not reading file from sdcard
Then your options are fairly limited. The only way you can read a file from internal storage is if your app is allowed to access that part of internal storage.
However, seeing that you're trying to read from downloads, it should be fine. I think the problem is your file path is badly formatted:
file:///storage/emulated/0/download/user.txt
Should just be
/storage/emulated/0/download/user.txt
which you have the value of, you just need to set your str variable to getEncodedPath instead of toString

Related

Android open another application from EditText

Can we open other app through this code by executing command given through the Edittext view. If yes then how it can be done?
package com.example.honey.shell;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
TextView op;
EditText ip;
Button exec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
op = (TextView) findViewById(R.id.textView);
ip = (EditText) findViewById(R.id.editText);
exec = (Button) findViewById(R.id.button);
}
public void execute(View view) {
String input = ip.getText().toString();
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(input);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {}
op.setText(output.toString());
}
}
Actually i wish to open some other application from my app by executing the command but it's not working,as I tried commands such as cd but it didn't work only the ls command is working in it...
to open an application from another app , you can use Intents
Intent launchNewApp = getPackageManager().getLaunchIntentForPackage("com.example.name");//specify the package name of other application which you intended to launch
if (launchNewApp != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}

How to write (and append) data to text files externally? (test using real device vs emulator)

First, I used the code below that I wrote with the help from:
How to save parsed text file in internal/external storage in android
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
#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;
}
#Override
public void onClick(View v) {
String string = "nooooon";
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");
directory.mkdirs();
File file = new File(directory, "mysdfile.txt");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(string);
osw.flush();
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Then, I used emulator to test it, and it worked fine. I can see the new directory and the new file has been created. Now, I am not sure how I can append data to the current file, meaning that each time I press the button the data need to be appended in the next line.
Second, when I use a real device to test it, I cannot figure out where the new directory and file are created. I actually debugged the app and found that the new file is created under /storage/emulated/0/MyFiles/mysdfile.txt , but I cannot actually see the file in the file explorer or on the device. (Also, I gave permission to write) how can I see the newly generated files/directories?
I appreciate your time.

Finish an activity,get string typed result from a class and use that result to another activity

I'm new in android environment and started a Software development project, so my knowledge is too few in it. I need help in detail.
Problem details:
Project is on ANDROID OCR code source from github Robert m.theis
currently it's outcome is - while i take an image of any written text,it retrieves quite exact output using tesseract engine as text and search in internet.
my work is -
use the text string (digits ) and call to a phone operator.
my project name is automated mobile card recharging system.
so that i took result text from a method getText() class named OcrResult.java and put into my own activity. But i don't know why this don't working in real device.
it builds, run in emulator, but in real device at least it should show messages! But it doesn't.
i also added in manifest.xml file as (angel braces are remover here)
under activity
activity android:name="edu.sfsu.cs.orange.ocr.call.CallManager"
under application
uses-permission android:name="android.permission.CALL_PHONE"
here my code is
package edu.sfsu.cs.orange.ocr.call;
import edu.sfsu.cs.orange.ocr.OcrResult;
import edu.sfsu.cs.orange.ocr.CaptureActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class CallManager extends Activity
{
public static final String preString = "*111*";
public static final String postString = "#";
//to store retrieved digits
String finalString;
//to get text result from ocr result
OcrResult getStringResult = new OcrResult();
String middleString = getStringResult.getText();
//if it fails to scan desired digit,call the process again
CaptureActivity tryProcessAgain = new CaptureActivity();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void setString(String x)
{
middleString = x;
}
public String getString( String toBeInserted)
{
if(toBeInserted.length() == 16)
{
int counter = 0;
char [] insertHere = new char[16];
for(int verifier = 0; verifier < 16; verifier ++)
{
insertHere[verifier] = toBeInserted.charAt(verifier);
if(!Character.isDigit(insertHere[verifier]))
{
break;
}
counter ++;
}
if(counter == 16)
{
finalString = preString + toBeInserted + postString;
return finalString;
}
else
{
// #SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scan invalid.....OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
else
{
//#SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scannin invalid...OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
public void CallToOperator(String callMe)
{
Toast toast = Toast.makeText(this,finalString,Toast.LENGTH_SHORT);
toast.show();
//Toast toast1 = Toast.makeText(this,middleString,Toast.LENGTH_SHORT);
//toast1.show();
if(callMe == finalString)
{
try
{
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + finalString)));
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
tryProcessAgain.onShutterButtonPressContinuous();
}
}
}

How to read a selected text file from sdcard on android

i am new at android development and i need your help. I was locking at topics that are similar for my development but non of then help me.
So far i create functions that gets me the files from my sdcard and shows me the list of then.
That is working
this is the code for getting the paths on sdcard:
package com.seminarskirad;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class LoadActivity extends ListActivity{
private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }
private final DISPLAYMODE displayMode = DISPLAYMODE.ABSOLUTE;
private List<String> directoryEntries = new ArrayList<String>();
private File currentDirectory = new File("/");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Browse(Environment.getExternalStorageDirectory());
}
private void upOneLevel(){
if(this.currentDirectory.getParent() != null)
this.Browse(this.currentDirectory.getParentFile());
}
private void Browse(final File aDirectory){
if (aDirectory.isDirectory()){
this.currentDirectory = aDirectory;
fill(aDirectory.listFiles());
}
}
private void fill(File[] files) {
this.directoryEntries.clear();
if(this.currentDirectory.getParent() != null)
this.directoryEntries.add("..");
switch(this.displayMode){
case ABSOLUTE:
for (File file : files){
this.directoryEntries.add(file.getPath());
}
break;
case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
for (File file : files){
this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
}
break;
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, R.layout.load, this.directoryEntries);
this.setListAdapter(directoryList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
int selectionRowID = position;
String selectedFileString = this.directoryEntries.get(selectionRowID);
if(selectedFileString.equals("..")){
this.upOneLevel();
}else if(selectedFileString.equals()){ /// what to write here ???
this.readFile(); ///what to write here???
} else {
File clickedFile = null;
switch(this.displayMode){
case RELATIVE:
clickedFile = new File(this.currentDirectory.getAbsolutePath()
+ this.directoryEntries.get(selectionRowID));
break;
case ABSOLUTE:
clickedFile = new File(this.directoryEntries.get(selectionRowID));
break;
}
if(clickedFile.isFile())
this.Browse(clickedFile);
}
}
private void readFile() {
// what to write here???
}
Sorry i cant put the image because i dont have reputation, but when i run it on my emulator a get something like this:
/mnt/sdcard/kuzmanic.c
/mnt/sdcard/text.txt
/mnt/sdcard/DCIM
/mnt/sdcard/LOST.DIR
So what I want to do is when i click on the text.txt or kuzmanic.c file I want to open then in the same layout file, that is my load.xml file:
This is the code for the xml file:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="18sp">
</TextView>
What i need to write in my code and do I have to write anything in the manifest???
Try this code:
package com.javasamples;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
public class FileDemo2 extends Activity {
// GUI controls
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnWriteSDFile
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
finish();
}
}); // btnClose
}// onCreate
}// AndSDcard
the layout file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText
android:id="#+id/txtData"
android:layout_width="fill_parent"
android:layout_height="180px"
android:textSize="18sp" />
<Button
android:id="#+id/btnWriteSDFile"
android:layout_width="143px"
android:layout_height="44px"
android:text="1. Write SD File" />
<Button
android:id="#+id/btnClearScreen"
android:layout_width="141px"
android:layout_height="42px"
android:text="2. Clear Screen" />
<Button
android:id="#+id/btnReadSDFile"
android:layout_width="140px"
android:layout_height="42px"
android:text="3. Read SD File" />
<Button
android:id="#+id/btnClose"
android:layout_width="141px"
android:layout_height="43px"
android:text="4. Close" />
</LinearLayout>
I used this code to read a text file in SD card,
public class ReadFileSDCardActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.fileContent);
File dir = Environment.getExternalStorageDirectory();
//File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
//Get the text file
File file = new File(dir,"text.txt");
// i have kept text.txt in the sd-card
if(file.exists()) // check if file exist
{
//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
}
//Set the text
tv.setText(text);
}
else
{
tv.setText("Sorry file doesn't exist!!");
}
}
}
first you have to give an id to your textview into the load.xml file and define the textview inside a linear layout. like this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
<TextView android:id="#+id/tv1
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="18sp"/>
now you have to set the layout of your activity.you can do this in the onCreate() method only.
setContentView(R.layout.load);
now make a TextVew object like this.
TextView tview = (TextView) findViewById(R.id.tv1);
now you have to read the text file using FileInputStream and keep it into a string variable.
after that you can assign the string to the text view.
tview.setText(string variable name);

connection to a NFC-tag in an android app

I'm trying to write an android app for may Nexus S that is able to write a simple Text Record on a NFC-Tag. My problem is the connection-establishment to the NFC-Tag.
I've implemented two activities called "TagWriter" & "TagWriterStartPage".
Here ist the "TagWriter"-activity:
package nfc.example.writer;
import java.util.Locale;
import com.google.common.base.Charsets;
import com.google.common.primitives.Bytes;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class TagWriter extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tagwriter);
Intent intent = this.getIntent();
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeTag(tag);
}
private void writeTag(Tag t)
{
Ndef tag = Ndef.get(t);
Locale locale = Locale.US;
final byte[] langBytes = locale.getLanguage().getBytes(Charsets.US_ASCII);
String text = "Tag, you're it!";
final byte[] textBytes = text.getBytes(Charsets.UTF_8);
final int utfBit = 0;
final char status = (char) (utfBit + langBytes.length);
final byte[] data = Bytes.concat(new byte[] {(byte) status}, langBytes, textBytes);
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
try
{
NdefRecord[] records = {record};
NdefMessage message = new NdefMessage(records);
tag.connect();
boolean connected = tag.isConnected();
boolean writeable = tag.isWritable();
if( connected && writeable)
{
tag.writeNdefMessage(message);
}
tag.close();
}
catch (Exception e)
{
//do error handling
}
}
}
The activity "TagWriter" is called when I put my device on the NFC-tag. Everytime the method "tag.connect()" is called, there occures an exception.
Can anyone help me to solve the problem???
Thanks,
Dennis
this might work better:
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
ndef.writeNdefMessage(message);
} else {
NdefFormatable format = NdefFormatable.get(tag);
if (format != null) {
format.connect();
format.format(message);
}
}
need other checks in there for real use (capacity, writable etc) - but that is bare bones..

Categories

Resources