Save mobile number in a file android - android

I have developed an android app that enable the user to register by his/her mobile phone number. I want my app to save the phone number so that next time the user open the app, there will be no need to enter the phone number again, analogous to Whatsapp..
Here is my code, but it doesn't work and I still have to enter the phone number each time I open the app, besides, after adding this code to my app, the app became so heavy and slow.
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
TelephonyManager tMgr = (TelephonyManager) getApplicationContext()
.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = tMgr.getLine1Number().toString();
} catch (Exception e) {
String EE = e.getMessage();
}
if (mPhoneNumber == null) {
try {
fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);
fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[50];
if (isr.read(inputBuffer) == 0) {
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Warrning");
alert.setMessage("Please Set Your Phone number");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mPhoneNumber = input.getText().toString();
try {
fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[50];
if (isr.read(inputBuffer) == 0) {
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// ---write the string to the file---
osw.write(mPhoneNumber);
osw.flush();
osw.close();
// ---display file saved message---
Toast.makeText(getBaseContext(),
"Phone number saved successfully!",
Toast.LENGTH_SHORT).show();
// ---clears the EditText---
input.setText("");
} else {
int charRead;
while ((charRead = isr.read(inputBuffer)) > 0) {
// ---convert the chars to a String---
String readString = String.copyValueOf(inputBuffer,
0, charRead);
mPhoneNumber = readString;
inputBuffer = new char[50];
}
// ---set the EditText to the text that has been
// read---
Toast.makeText(getBaseContext(),
"Phone number read successfully!",
Toast.LENGTH_SHORT).show();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
int UserServiceId = CallLogin(mPhoneNumber);
if (UserServiceId > 0) {
Intent Service = new Intent(MainScreeen.this,
RecipeService.class);
Service.putExtra("UserId", UserServiceId);
startService(Service);
} else {
Intent Reg = new Intent(MainScreeen.this,
Regsteration.class);
Reg.putExtra("PhoneNumber", mPhoneNumber);
startActivity(Reg);
}
}
});
alert.show();
} else {
int UserServiceId = CallLogin(mPhoneNumber);
if (UserServiceId > 0) {
Intent Service = new Intent(MainScreeen.this,
RecipeService.class);
Service.putExtra("UserId", UserServiceId);
startService(Service);
} else {
Intent Reg = new Intent(MainScreeen.this, Regsteration.class);
Reg.putExtra("PhoneNumber", mPhoneNumber);
startActivity(Reg);
}
}
Please help me to figure it out !!

Well, in this block of code:
if (mPhoneNumber == null) {
try {
fOut = openFileOutput("textfile.txt", MODE_WORLD_READABLE);
fIn = openFileInput("textfile.txt");
you open the file for output, which will destroy anything that you've already written to it. Later, when you try to read from this file, it is all too late.
Also, you've got way too much code here. Don't reinvent the wheel. You don't need to read files a character at a time. If all you want to do is to write a string into the file and later read it back out again, use DataInputStream and DataOutputStream and you can read/write strings directly using readUTF() and writeUTF(). Here's a simple example to r ead the file:
DataInputStream in = new DataInputStream(openFileInput("textfile.txt"));
String contents = in.readUTF();
to write the file use:
DataOuputStream out = new DataOutputStream(openFileOutput("textfile.txt", 0));
out.writeUTF(phoneNumber);
Obviously you need to add the try/catch blocks and deal with exceptions and make sure you close the streams in a finally block, but you will end up with a lot less code if you do it like this.

To help you I give you my activity example in order to read and write data in a file:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class StoreDataActivity extends Activity {
private static final String TAG = "ExerciceActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
writeFileOnDisk("toto.txt", "Bienvenue chez Android");
String content = readFileOnDisk("toto.txt");
Log.v(TAG, "content=" + content);
}
private void writeFileOnDisk(String filename, String data) {
try {
FileOutputStream fos = openFileOutput(filename, this.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String readFileOnDisk(String filename) {
int inChar;
StringBuffer buffer = new StringBuffer();
try {
FileInputStream fis = this.openFileInput(filename);
while ((inChar = fis.read()) != -1) {
buffer.append((char) inChar);
}
fis.close();
String content = buffer.toString();
return content;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

Related

Writing to a file, but file is empty when I read it in [duplicate]

I want to save a file to the internal storage by getting the text inputted from EditText. Then I want the same file to return the inputted text in String form and save it to another String which is to be used later.
Here's the code:
package com.omm.easybalancerecharge;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num = (EditText) findViewById(R.id.sNum);
Button ch = (Button) findViewById(R.id.rButton);
TelephonyManager operator = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String opname = operator.getNetworkOperatorName();
TextView status = (TextView) findViewById(R.id.setStatus);
final EditText ID = (EditText) findViewById(R.id.IQID);
Button save = (Button) findViewById(R.id.sButton);
final String myID = ""; //When Reading The File Back, I Need To Store It In This String For Later Use
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Get Text From EditText "ID" And Save It To Internal Memory
}
});
if (opname.contentEquals("zain SA")) {
status.setText("Your Network Is: " + opname);
} else {
status.setText("No Network");
}
ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Read From The Saved File Here And Append It To String "myID"
String hash = Uri.encode("#");
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:*141*" + /*Use The String With Data Retrieved Here*/ num.getText()
+ hash));
startActivity(intent);
}
});
}
I have included comments to help you further analyze my points as to where I want the operations to be done/variables to be used.
Hope this might be useful to you.
Write File:
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Read File:
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append("\n").append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
For those looking for a general strategy for reading and writing a string to file:
First, get a file object
You'll need the storage path. For the internal storage, use:
File path = context.getFilesDir();
For the external storage (SD card), use:
File path = context.getExternalFilesDir(null);
Then create your file object:
File file = new File(path, "my-file-name.txt");
Write a string to the file
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("text-to-write".getBytes());
} finally {
stream.close();
}
Or with Google Guava
String contents = Files.toString(file, StandardCharsets.UTF_8);
Read the file to a string
int length = (int) file.length();
byte[] bytes = new byte[length];
FileInputStream in = new FileInputStream(file);
try {
in.read(bytes);
} finally {
in.close();
}
String contents = new String(bytes);
Or if you are using Google Guava
String contents = Files.toString(file,"UTF-8");
For completeness I'll mention
String contents = new Scanner(file).useDelimiter("\\A").next();
which requires no libraries, but benchmarks 50% - 400% slower than the other options (in various tests on my Nexus 5).
Notes
For each of these strategies, you'll be asked to catch an IOException.
The default character encoding on Android is UTF-8.
If you are using external storage, you'll need to add to your manifest either:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
or
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Write permission implies read permission, so you don't need both.
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
Just a a bit modifications on reading string from a file method for more performance
private String readFromFile(Context context, String fileName) {
if (context == null) {
return null;
}
String ret = "";
try {
InputStream inputStream = context.openFileInput(fileName);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int size = inputStream.available();
char[] buffer = new char[size];
inputStreamReader.read(buffer);
inputStream.close();
ret = new String(buffer);
}
}catch (Exception e) {
e.printStackTrace();
}
return ret;
}
The Kotlin way by using builtin Extension function on File
Write: yourFile.writeText(textFromEditText)
Read: yourFile.readText()
check the below code.
Reading from a file in the filesystem.
FileInputStream fis = null;
try {
fis = context.openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
// READ STRING OF UNKNOWN LENGTH
StringBuilder sb = new StringBuilder();
char[] inputBuffer = new char[2048];
int l;
// FILL BUFFER WITH DATA
while ((l = isr.read(inputBuffer)) != -1) {
sb.append(inputBuffer, 0, l);
}
// CONVERT BYTES TO STRING
String readString = sb.toString();
fis.close();
catch (Exception e) {
} finally {
if (fis != null) {
fis = null;
}
}
below code is to write the file in to internal filesystem.
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(stringdatatobestoredinfile.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
I think this will help you.
I'm a bit of a beginner and struggled getting this to work today.
Below is the class that I ended up with. It works but I was wondering how imperfect my solution is. Anyway, I was hoping some of you more experienced folk might be willing to have a look at my IO class and give me some tips. Cheers!
public class HighScore {
File data = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
File file = new File(data, "highscore.txt");
private int highScore = 0;
public int readHighScore() {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
try {
highScore = Integer.parseInt(br.readLine());
br.close();
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
try {
file.createNewFile();
} catch (IOException ioe) {
ioe.printStackTrace();
}
e.printStackTrace();
}
return highScore;
}
public void writeHighScore(int highestScore) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(String.valueOf(highestScore));
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Kotlin
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
We can use this code to write String to a file
public static void writeTextToFile(final String filename, final String data) {
File file = new File(filename);
try {
FileOutputStream stream = new FileOutputStream(file);
stream.write(data.getBytes());
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then in the Main code, we use this, for example
writeTextToFile(getExternalFilesDir("/").getAbsolutePath() + "/output.txt", "my-example-text");
After that, check the file at Android/data/<package-name>/files.
The easiest way to append to a text file in kotlin:
val directory = File(context.filesDir, "LogsToSendToNextMunich").apply {
mkdirs()
}
val file = File(directory,"Logs.txt")
file.appendText("You new text")
If you want to just write to the file:
yourFile.writeText("You new text")
writing anything to the files, using bytes:
FileOutputStream(file).use {
it.write("Some text for example".encodeToByteArray())
}

Retrieve the saved WiFi passwords from Android devices

I am developing an Android application in which I need to show the saved WiFi passwords in the mobile or tablet. Like for example, if my mobile is connected to any network that n/w password is saved in my mobile. I want to get it.
Unless you are rooted, I don't know of any way to do it. If you are rooted, or are willing to root your Galaxy for those nice guy points, you should be able to use a file manager (ASTRO, Root Browser, etc.) to find it.
Use the file manager to locate your data/misc/file folder, then look for wpa_supplicant.conf, or I assume it could be wep_supplicant.conf if his/her network is using WEP instead of WPA. Open the .conf file using a text editor (which is probably built into your file manager application, if not, add that to your shopping list). You should be able to read the password in plain text at that point.
Your Comments helped me to some extent to find out the solution to my question. Especially #Namik Kalavadia I am talking about you Thanks for that.
Finally here is the solution.
public class MainActivity extends Activity {
File file;
public StringBuffer ab;
public File savefile;
public InputStream in = null;
public String filename = "wpa_supplicant.conf";
public File ot_path;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
ot_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Log.d("aaa", ""+ot_path.toString());
}
public void path(View v){
getPath();
}
private void getPath(){
file = Environment.getRootDirectory();
String ext = ".conf";
File list[] = file.listFiles();
ab = new StringBuffer();
if(list!=null){
fileNameSearch(list);
}
}
public void fileNameSearch(File list[]){
if(list!=null){
for(int f = 0;f<list.length;f++){
ab.append(list[f].getName()+"\n");
File fi = list[f];
String path = fi.getPath();
if(fi.isDirectory()){
fileNameSearch(fi.listFiles());
}
else if(path.endsWith(".conf")){
if(path.contains(filename)){
try{
File fileForParse = copyFile(path,ot_path);
in = new FileInputStream(fileForParse);
getStringFromInputStream(in);
Log.d("aaa", "conf I got it"+path);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
else{
Log.d("aaa", "List is null in method");
}
}
private File copyFile(String inputPath, File outputPath) {
InputStream input = null;
OutputStream out = null;
try {
if (!outputPath.exists())
{
outputPath.mkdirs();
}
savefile = new File(outputPath,filename);
if (!savefile.exists()) {
savefile.createNewFile();
File f = new File(inputPath);
Log.d("aaa",""+f.length());
input = new FileInputStream(inputPath);
out = new FileOutputStream(savefile);
byte[] buffer = new byte[1024];
int read;
while ((read = input.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
Log.d("aaa",""+savefile.length());
input.close();
input = null;
out.flush();
out.close();
out = null;
}
} catch (FileNotFoundException fnfe1) {
Log.e("aaa", fnfe1.getMessage());
return null;
}
catch (Exception e) {
Log.e("aaa", e.getMessage());
return null;
}
return savefile;
}
#SuppressWarnings("deprecation")
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
if(line.contains("ssid")||line.contains("psk")){
sb.append(line+"\n");
}
if(line.contains("}")){
sb.append("-----------------\n");
}
AlertDialog ad = new AlertDialog.Builder(MainActivity.this).create();
ad.setTitle("Lis of WiFi Passwords Saved in your Mobile");
ad.setMessage(sb);
ad.setButton("OK",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
ad.show();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
It is not possible as far as I know . It will be a security problem if sdk tools allows to do so .
Retrieving saved Wifi password programatically is not possible due to security issue.If you root your phone you may able to get it,but that too in an encrypted form.

Android save to file.txt appending

I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).
public void saveText(View view){
try {
//open file for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
//write information to file
EditText text = (EditText)findViewById(R.id.editText1);
String text2 = text.getText().toString();
out.write(text2);
out.write('\n');
//close file
out.close();
Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
//if caught
Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
}
}
Change this,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
to,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
This will append your new contents to the already existing file.
I Hope it helps!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
try {
String filename = Environment.getExternalStorageDirectory()
.getAbsolutePath() + mFileName;
FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
fw.write(mValue + "\n\n");
fw.close();
} catch (IOException ioe) {
}
}
To display the content of the saved file with the line breaks with a button click use:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(fileTitle);
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
To Delete content of existing file whist retaining the filename you can use:
deleteOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_PRIVATE);
// fOut.write(data.getBytes());
dataTitle = "";
fOut.write(data.getBytes());
fOut.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This worked for me. Takes content of a TextEdit called textTitle. Writes it to file called dataTitle. Then writes a new line with fOut.write("\n"). The next text entered into TextEdit is added to the file with a line break.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Android: Saving one entry in file instead of more data

I need to save the barcode with timestamp and save that in a .csv file and send it to another device via Bluetooth. I am taking the barcode through SerialMagic Gear Keyboard option which take the barcode as an input
Problem: When the application run and i enter data, when the file is received by another device the file only contains the last entry.
I am sure that I am making some mistake in the structure of the program. If so kindly indicate where.
And sorry for the long code.
package com.android.app;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Timestamp for file name e.g. Data_7-19-2012
SimpleDateFormat s1 = new SimpleDateFormat("MM-dd-yyyy_hh:mm:ss");
final String format1 = s1.format(new Date());
//Creating file name
final String FileName = "Data_"+format1+".csv";
final EditText addbarcode = (EditText) findViewById(R.id.editText1);
//getting file directory
final File dir = getFilesDir();
final File shareFile = new File(dir, FileName);
addbarcode.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
switch (keyCode)
{
//case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
//to get Timestamp
SimpleDateFormat s = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
String format = s.format(new Date());
//get barcode in a variable
Editable barcode = addbarcode.getText();
final String DATASTRING = new String(""+barcode+","+format+"\n");
FileOutputStream fOut = null;
try {
fOut = openFileOutput(FileName , MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
try {
osw.write(DATASTRING);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
osw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* ensure that everything is
* really written out and close */
//For showing data recived on screen
FileInputStream fIn = null;
try {
fIn = openFileInput(FileName);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(fIn);
//Prepare a char-Array that will
//* hold the chars we read back in.
char[] inputBuffer = new char[DATASTRING.length()];
// Fill the Buffer with data from the file
try {
isr.read(inputBuffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Transform the chars to a String
String readString = new String(inputBuffer);
TextView etData= (TextView)findViewById(R.id.textView3);
etData.setText(readString);
//Clear the editview for new entries
addbarcode.setText("");
return true;
default:
break;
}
}
return false;
}
});
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri u1 = null;
u1 = Uri.fromFile(shareFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Person Details");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/csv");
startActivity(sendIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You need to use the MODE_APPEND flag in openFileOutput, otherwise the old file contents gets overwritten by default.

IO Exception in FileInputStream.read. Android

I'm writting an Android's app. Two activities, one has TextEdit to type 'hello message', and button to save message in Internal Storage. Second is main activity. Hello mesage should appear after app's start.
Second activity:
String s = ((EditText) findViewById(R.id.message_act_editText_hello)).getText().toString();
FileOutputStream fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_PRIVATE);
fos.write(s.getBytes());
fos.close();
first (main) activity:
static String FILENAME = "message_file.zip";
FileOutputStream fos;
try {
//piece of code to guarantee that file exists
fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_APPEND);
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis = openFileInput(FILENAME);
messageString = new StringBuffer("");
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast t = Toast.makeText(this, messageString, 3000);
t.show();
I'm getting IO Exception in logcat at line:
while ((length = fis.read(buffer)) != -1)
but app seems to work correctly (defined message appears after app's start). I tried to find explanation, I found several topics, but all was according to large files, or files in assets, or compressed files.
I tried to name my file like
static String FILENAME = "message_file.zip",
static String FILENAME = "message_file.txt",
to try different extensions, but always i'm getting the same IO Exception.
Thanks for suggestions.
of course you will get an IO Exception your file doesn't exit and you request to open it
You forget this peice of code
File myFile = new File("/sdcard/mysdfile.txt");
In your first activity you can use this code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
EditText txtData;
Button btnWriteSDFile;
#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();
Intent i = new Intent(getApplicationContext(),SecondActivity.class);
startActivity(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
});
}
}
in the second one you can use this:
public class SecondActivity extends Activity {
private TextView txtData2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
txtData2 = (TextView) findViewById(R.id.textView2);
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";
}
txtData2.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();
}
}
}
The first latout uses a linearlayout that contain an edittext and a button
The second a linearLayout with only a textview
Try it works fine if you find problem let me know!!
Ah i forget you have to add in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I found reason. Problem was in fragment:
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
What's the catch?
fis.close();
should be after while. I didn't notice that yesterday...

Categories

Resources