Android: Saving one entry in file instead of more data - android

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.

Related

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

Bitmap : Set Wallpaper and Save on Sdcard in Menu Item

i almost finished my app, im working on menu items now,
The problem is to set a bitmap as wallpaper and save it on sdcard from menu item.
i tried to things, 1st was to create a second intent which was taking -again- same data from previous activity , -I have failed-
2nd was using the same intent -i ve failed-
here is my code.
thank you
public class Fullpic extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// menu
getMenuInflater().inflate(R.layout.menu_pics, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_set:
// setting as wallpaper
return true;
case R.id.menu_save:
// save the image on sdcard
return true;
case R.id.menu_back:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//menu end
// XML node keys
static final String KEY_THUMB_URL = "source";
static final String HEIGHT_MAX = "600";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_pic);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent dude
String bid = in.getStringExtra(KEY_THUMB_URL);
int hoppa= Integer.parseInt(in.getStringExtra(HEIGHT_MAX));
// Displaying all values on the screen
ImageView balls = (ImageView) findViewById(R.id.bals_label);
balls.getLayoutParams().height = hoppa-30;
URL url = null;
try {
url = new URL(bid);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
balls.setImageBitmap(bmp);
}
public Object fetch(String address) throws MalformedURLException,
IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "source");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
}
new Thread(new Runnable(){
#Override
public void run(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/blabla");
myDir.mkdirs();
String fname = "name_here.jpg";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file); //create stream to output the contents of the image
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out); //compress and write bitmap data to output file stream
out.flush();
out.close(); //closes stream important to avoid memory leaks
} catch (Exception e) {
//exception handling
}
}}).start();
This should help you write the bitmap file to where you need it to be on the SD card of the device, and done in a thread to keep heavy actions off the main UI Thread. Cheers.

Error in adding text to existing txt file

Firstly, i know there are same questions in this web site but i couldn't add text to my existing txt file. maybe i miss out something but where ? anyway here are my codes.
i have translate.txt file. it is /raw folder.and When i click the button, the words which are written in the editTexts(w1,w2) must be added to the existing translate.txt file.But it is not working..
public class Add extends Activity {
EditText w1,w2;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
w1=(EditText)findViewById(R.id.idText1);
w2=(EditText)findViewById(R.id.idText2);
save=(Button) findViewById(R.id.idSave);
save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String word1=w1.getText().toString();
String word2=w2.getText().toString();
writefile(word1,word2);
}
});
}
public void writefile(String word1,String word2)
{
try
{
String finalstring=new String(word1 + " " + word2);
FileOutputStream fOut = openFileOutput("translate.txt",MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(finalstring);
osw.flush();
osw.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
} catch(Exception e)
{
Toast.makeText(this, "ERROR!!!", Toast.LENGTH_SHORT).show();
}
}
}
A) Code to write APPEND file in Android
public void writefile(String word1,String word2)
try {
String path = sdCard.getAbsolutePath() + "/";
File logFile = new File(path + "translate.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append(word1 + " " + word2);
buf.newLine();
buf.flush();
}
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
B) Rule/ Permission
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT For user
You cannot write a file to raw folder. Its read-only. Precisely you can't modify anything contained within "Res" folder on the fly.
Check this out, https://stackoverflow.com/a/3374149
Just in case you don't want to store the data in sd card and want to use the previous method
the way you was creating a file and stroing data to it was not actually editing the file in res/ raw folder ( because it can not be edited )
but the data you was writing was actually stored in a private file associated with this Context's application package for reading.
hence it was there and the file can be read as follow:
private void readFile() {
// TODO Auto-generated method stub
try {
FileInputStream fin = openFileInput("translate.txt");
InputStreamReader isr = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder str2 = new StringBuilder();
while ((str = br.readLine()) != null) {
str2 = str2.append(str);
}
isr.close();
editText.setText(str2.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you can follow this method incase you dont want to store file in sd card because files in sd crad can be read by anyone.

Concatenate two audio files and play resulting file

I am really facing problem from last couple of days but I am not able to find the exact solution please help me.
I want to merge two .mp3 or any audio file and play final single one mp3 file. But when I am combine two file the final file size is ok but when I am trying to play it just play first file, I have tried this with SequenceInputStream or byte array but I am not able to get exact result please help me.
My code is the following:
public class MerginFileHere extends Activity {
public ArrayList<String> audNames;
byte fileContent[];
byte fileContent1[];
FileInputStream ins,ins1;
FileOutputStream fos = null;
String combined_file_stored_path = Environment
.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/final.mp3";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audNames = new ArrayList<String>();
String file1 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/one.mp3";
String file2 = Environment.getExternalStorageDirectory().getPath()
+ "/AudioRecorder/two.mp3";
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/AudioRecorder/" + "final.mp3");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
audNames.add(file1);
audNames.add(file2);
Button btn = (Button) findViewById(R.id.clickme);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
createCombineRecFile();
}
});
}
public void createCombineRecFile() {
// String combined_file_stored_path = // File path in String to store
// recorded audio
try {
fos = new FileOutputStream(combined_file_stored_path, true);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
File f = new File(audNames.get(0));
File f1 = new File(audNames.get(1));
Log.i("Record Message", "File Length=========>>>" + f.length()+"------------->"+f1.length());
fileContent = new byte[(int) f.length()];
ins = new FileInputStream(audNames.get(0));
int r = ins.read(fileContent);// Reads the file content as byte
fileContent1 = new byte[(int) f1.length()];
ins1 = new FileInputStream(audNames.get(1));
int r1 = ins1.read(fileContent1);// Reads the file content as byte
// from the list.
Log.i("Record Message", "Number Of Bytes Readed=====>>>" + r);
//fos.write(fileContent1);// Write the byte into the combine file.
byte[] combined = new byte[fileContent.length + fileContent1.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < fileContent.length ? fileContent[i] : fileContent1[i - fileContent.length];
}
fos.write(combined);
//fos.write(fileContent1);*
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fos.close();
Log.v("Record Message", "===== Combine File Closed =====");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I already published an app with this function... try my method using SequenceInputStream, in my app I just merge 17 MP3 files in one and play it using the JNI Library MPG123, but I tested the file using MediaPlayer without problems.
This code isn't the best, but it works...
private void mergeSongs(File mergedFile,File...mp3Files){
FileInputStream fisToFinal = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mergedFile);
fisToFinal = new FileInputStream(mergedFile);
for(File mp3File:mp3Files){
if(!mp3File.exists())
continue;
FileInputStream fisSong = new FileInputStream(mp3File);
SequenceInputStream sis = new SequenceInputStream(fisToFinal, fisSong);
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fisSong.read(buf)) != -1;)
fos.write(buf, 0, readNum);
} finally {
if(fisSong!=null){
fisSong.close();
}
if(sis!=null){
sis.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fos!=null){
fos.flush();
fos.close();
}
if(fisToFinal!=null){
fisToFinal.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mp3 files are some frames.
You can concatenate these files by appending the streams to each other if and only if the bit rate and sample rate of your files are same.
If not, the first file plays because it has truly true encoding but the second file can not decode to an true mp3 file.
Suggestion: convert your files with some specific bit rate and sample rate, then use your function.

Save mobile number in a file 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;
}

Categories

Resources