Save listview state (rows)? - java

So I'm making an app that records sounds and then adds them to listview in another activity. After the sound is recorded, a user is asked to rename the file and then it is added directly to listview.
Adding items to listview code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recorded_library);
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, fileNames);
}
public void setFileName(final Editable filename) {
Log.d("2", "Set filename from first activity " + filename);
TextView emptyLibText = (TextView) findViewById (R.id.textView1);
emptyLibText.setVisibility(TextView.INVISIBLE);
//LISTVIEW
fileNames.add(filename.toString());
listView = (ListView) findViewById (R.id.mainListView);
listView.setAdapter(listAdapter);
//ALERT DIALOG
final AlertDialog.Builder deleteAlert = new AlertDialog.Builder(this);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
player = new MediaPlayer();
try {
player.setDataSource(externalStoragePath + File.separator + "Android/data/com.whizzappseasyvoicenotepad/" + fileNames.get(arg2) + ".mp3");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast toast = Toast.makeText(getApplicationContext(), "Now playing: " + fileNames.get(arg2), Toast.LENGTH_SHORT);
toast.show();
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
deleteAlert.setTitle("Warning");
deleteAlert.setMessage("Are you sure you want to delete this?");
toDelete = arg2;
deleteAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File directory = new File (externalStoragePath + File.separator + "Android/data/com.whizzappseasyvoicenotepad/");
File deleteFile = new File (directory, fileNames.get(toDelete) + ".mp3");
deleteFile.delete();
Log.i("TAG", "Deleting file: " + directory + fileNames.get(toDelete) + ".mp3");
listAdapter.remove(listAdapter.getItem(toDelete));
listAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
I've done a lot of research but I can't find anywhere how to save listview state. I also tried using Shared Preferences but I was very unsuccessful with it. I didn't even come close to working so I deleted the code (else I'd put it there). I'd appreciate it a lot if someone could give me some pointers on how I could save added rows to listview.

It looks like you're trying to persist the list data on the device (rather than fetching it from a server). You should check out the Storage Options section in the guide.
The easiest (but not necessarily the proper) way to do this is to dumped the serialized ArrayList into Internal Storage. Here's a snippet of what it may look like (not tested):
ArrayList<String> filenames = ...
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(filenames);
oos.close();
PS. Several recommendations for your code:
Setup the ListView (setAdapters, setOnItemClickListener) in onCreate instead of in setFileName().
Try using setEmptyView() instead of emptyLibText

Related

Edit activity-shared ArrayList to be saved in SharedPreferences

I have an ArrayList<String> that I save in shared preference in Activity A. I access the list from a second activity (ListActivity). Activity A starts ListActivity for a result. When an item is clicked the ListActivity sends the string at that position to Activity A for use. A long click allows you to delete.
When I delete from the list, I want to save the new (the latest) list in sharedpreferences. PLEASE! How can I do this? I just need the List to popup, you do your thing, and it goes away after saving the newest list.
I tried so many ways (code is patchwork at this point) but the deleted item persists when I open ListActivity again after deleting the item.
My code is below...
Activity A:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
...
lyricTitle = (AutoCompleteTextView) findViewById(R.id.lyricTitle);
...
lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// load in song when selected from auto-complete list
lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
}
});
lyricHolder = (EditText) findViewById(R.id.lyricHolder);
newSongBtn = (ImageView) findViewById(R.id.newSongBtn);
newSongBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (areFieldsNull(lyricTitle.getText().toString(),
lyricHolder.getText().toString()))
alertEmpty.show();
else {
/** There is some redundancy within performSave() here */
performSave();
lyricTitle.setText("");
lyricHolder.setText("");
}
}
});
...
findBtn = (Button) findViewById(R.id.findBtn);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showListIntent = new Intent(getApplicationContext(), pickActivity.class);
startActivityForResult(showListIntent, GET_SONG_CODE);
Log.i("TAG1", "Starting pickActivity.class for result");
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
...
// init sharedPreferences
colorPref = getSharedPreferences(COLOR_PREF, MODE_PRIVATE);
titlePref = getSharedPreferences(TITLE_PREF, MODE_PRIVATE);
externalSDPref = getSharedPreferences(EXTERNAL_SD_PREF, MODE_PRIVATE);
// load defaults of sharedPreferences
titleList = new ArrayList<>();
try {
titleList = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetTitleListAdapter(titleList);
...
} //end onCreate
private void mSetTitleListAdapter(ArrayList<String> List) {
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
List
);
lyricTitle.setAdapter(autoCompleteAdapter);
}
...
private boolean areFieldsNull(String title, String song) {
// check if the text fields are empty
return (
title.isEmpty()||
title.equals(" ")||
title.equals(" ")||
song.isEmpty()||
song.equals(" ")||
song.equals(" ")
);
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
alertSave.show();
}
else
alertEmpty.show();
}
private void saveTitleArray() {
// save string array list in shared prefs
try {
prefEditor = titlePref.edit();
prefEditor.putString(TITLE_PREF, ObjectSerializer.serialize(titleList));
} catch (IOException e) {
e.printStackTrace();
}
prefEditor.apply();
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isExternalStoragePresent()&&externalSD_box.isChecked()){
// save to the SD card IF SD is found AND enableSD_box is checked
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File songFile = new File (path, title + ".txt");
try {
OutputStream os = new FileOutputStream(songFile);
byte[] data = song.getBytes();
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
// new songs (but not updated songs) go to top
if (!titleList.contains(title))
titleList.add(0, title);
mSetTitleListAdapter(titleList);
saveTitleArray();
}
private String openSongFile(String title){
BufferedReader bufferReader = null;
StringBuilder builder = new StringBuilder();
try {
FileInputStream fis = openFileInput(title);
bufferReader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = bufferReader.readLine()) != null) {
builder.append(line + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// when pickActivity ListView returns result
Log.i("TAG1", "Activity data returned from pickActivity.class");
if (requestCode == GET_SONG_CODE && resultCode == RESULT_OK) {
String title = data.getData().toString();
lyricTitle.setText(title);
lyricHolder.setText(openSongFile(title));
Log.i("TAG1", "Result success\nSong loaded into edittext");
Toast.makeText(this, "\""+title+"\""+" selected", Toast.LENGTH_SHORT).show();
}
}
ListActivity:
public class pickActivity extends ListActivity {
ArrayList<String> songListArray;
SharedPreferences titlePref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_song);
Log.i("TAG2", "pickActivity.class created");
// init string array from blank list or sharedPref saved data
titlePref = getSharedPreferences(writeActivity.TITLE_PREF, MODE_PRIVATE);
songListArray = new ArrayList<>();
try {
songListArray = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(writeActivity.TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetListAdapter(songListArray);
Log.i("TAG2", "Extra received and set");
mSetListAdapter(songListArray);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Log.i("TAG2", "onItemLongClick()");
final AlertDialog.Builder confirmDel = new AlertDialog.Builder(pickActivity.this);
confirmDel.setTitle("Delete Song")
.setIcon(R.mipmap.ic_keeper)
.setMessage("Are you sure you want " +
"\"" + songListArray.get(position) +
"\"" + " gone?")
.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// system default is dismiss()
}
})
.setNegativeButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// delete song, title, then update title list
getApplicationContext().deleteFile(songListArray.get(position));
songListArray.remove(position);
Log.i("TAG2", "Item deleted from list");
updateSharedPref(titlePref, writeActivity.TITLE_PREF, songListArray);
mSetListAdapter(songListArray);
Toast.makeText(
getApplicationContext(),
"Deleted",
Toast.LENGTH_SHORT).show();
}
});
confirmDel.create().show();
return true;
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("TAG2", "onListItemClick()");
Intent resultIntent = new Intent(EXTRA_NAME, Uri.parse(songListArray.get(position)));
setResult(RESULT_OK, resultIntent);
finish();
}
private void mSetListAdapter(ArrayList<String> list) {
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);
setListAdapter(arrayAdapter);
Log.i("TAG2", "ArrayList adapter set");
}
private void updateSharedPref(SharedPreferences sharedPref,
String prefFileName,
ArrayList<String> list) {
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString(prefFileName, ObjectSerializer.serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Log.i("TAG2", "SharedPref updated!");
}
}
Honestly, source code would help a lot in this case...
My best guess (without any code) would be, please make sure that you call
editor.apply();
and not
editor.commit();

How to add Alertdialog to my Android app?

I want to add a Yes/No dialog box to my Android app, I tried the solution in this answer but I couldn't manage to make it work with my code, any help please?
This is my code in which I want to write a text from EditText.
public void buttonSelect( View v ) {
View view = null;
String mac1 = "mac1";
String mac2 = "mac2";
TextView tv1, tv2;
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
switch (v.getId()) {
case (R.id.Write_MAC1):
writeData(view, mac1); //I need to confirm writing the data
break;
case (R.id.Write_MAC2):
writeData(view, mac2); //I need to confirm writing the data
break;
}
}
//---------------------------- Writing MACs addresses Function --------------------------------------------
public void writeData(View view, String macNum)
{
BufferedWriter bufferWriter =null;
try {
FileOutputStream fileOutputStream = openFileOutput(macNum, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
if (macNum.equals("mac1")){
bufferWriter.write(((EditText)this.findViewById(R.id.editText1)).getText().toString());}
if (macNum.equals("mac2")){
bufferWriter.write(((EditText)this.findViewById(R.id.editText2)).getText().toString());}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
bufferWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try to use this:
AlertDialog.Builder alertbox = new AlertDialog.Builder(LauncherActivity.this);
alertbox.setTitle("Are you sure?");
alertbox.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(LauncherActivity.this, "You Choose Yes!!", Toast.LENGTH_LONG).show();
}
});
alertbox.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(LauncherActivity.this, "You Choose Nooo!!", Toast.LENGTH_LONG).show();
}
});
alertbox.show();
See this git repo
Also a custom alertdialog example is exist in this repo.

I jsut try to implement mp3 cutter in android...but its not working [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am just trying to develop an mp3 cutter application on android. I just done some thing to do this. But it is not working . I am bale to play mp3 and i store the hole mp3 in input stream and then i use output stream to write the mp3 . But it is not working...
public class second extends Activity {
SeekBar bar;
String path;
Runnable r;
MediaPlayer mp = new MediaPlayer();
Handler handler = new Handler();
public static final String MEDIA_PATH = new String(Environment
.getExternalStorageDirectory().getPath() + "/Music/");
int length;
TextView time, time1, time2;
int i = 0;
int start, end;
Button cutMp3;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
bar = (SeekBar) findViewById(R.id.seekBar1);
Bundle b = getIntent().getExtras();
path = b.getString("path");
time = (TextView) findViewById(R.id.time);
time1 = (TextView) findViewById(R.id.textView1);
time2 = (TextView) findViewById(R.id.textView2);
cutMp3 = (Button) findViewById(R.id.button1);
try {
mp.reset();
mp.setDataSource(MEDIA_PATH + path);
mp.prepare();
mp.start();
File mp3 = new File(MEDIA_PATH + path);
InputStream is = new FileInputStream(mp3);
final BufferedInputStream bis = new BufferedInputStream(is);
int numBytes = bis.available();
final byte[] buf = new byte[numBytes];
Toast.makeText(getApplicationContext(),
"num of bytes: " + numBytes, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "" + mp3.length(),
Toast.LENGTH_SHORT).show();
final File file = new File(MEDIA_PATH + path);
Toast.makeText(getApplicationContext(), "mjmj" + file.length(),
Toast.LENGTH_SHORT).show();
length = mp.getDuration();
bar.setMax(length);
bar.setClickable(true);
bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
++i;
if (i == 1) {
time1.setText("" + mp.getCurrentPosition() / 1000);
start = mp.getCurrentPosition();
}
if (i == 2) {
time2.setText("" + mp.getCurrentPosition() / 1000);
end = mp.getCurrentPosition();
i = 0;
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1,
boolean arg2) {
// TODO Auto-generated method stub
mp.seekTo(arg1);
}
});
r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
updateSeekbar();
}
};
r.run();
cutMp3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Log.d("chk", "read bytes");
bis.read(buf, start, end - start);
Log.d("chk", "end of read");
Log.d("chk", "toast start");
// Toast.makeText(getApplicationContext(),"" + bis.read(buf, start, end - start),
Toast.LENGTH_SHORT).show();
Log.d("chk", "toast end");
final byte[] buf1 = new byte[end - start];
ByteArrayBuffer baf = new ByteArrayBuffer(end - start);
try {
File file = new File("new.mp3");
if (file.createNewFile()) {
Toast.makeText(getApplicationContext(),
"file created", Toast.LENGTH_SHORT)
.show();
}
}
catch (Exception e) {
}
for (byte b : buf1) {
FileOutputStream fos = new FileOutputStream(file);
fos.write(buf1);
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Toast.makeText(getApplicationContext(), ""+length,
// Toast.LENGTH_SHORT).show();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void updateSeekbar() {
// TODO Auto-generated method stub
bar.setProgress(mp.getCurrentPosition());
handler.postDelayed(r, 1000);
time.setText("" + mp.getCurrentPosition() / 1000);
}
}
While there are likely even more bugs in your code, the most critical is the misunderstanding of the MP3 file format.
An MP3 file does not just contain the audio data, but actually multiple MP3 frames that each come with their own header and data sections. Thus, you cannot just cut an existing MP3 file in the middle and expect the result to be two playable MP3 files.
Have a look at the MP3 specification here: http://en.wikipedia.org/wiki/MP3

android- setAdapter on AlertDialog not working

I am making a list of the user's tumblr blogs in a pop-box. All of this happens within a Handler. Here is the code:
private class PicHandler extends Handler{
Context c;
String name;
JumblrClient client;
public PicHandler(Context context, String n, JumblrClient cl){
c=context;
name = n;
client = cl;
}
public void handleMessage(Message msg)
{
final String[] cs = preferences.getString("allBlogs", "").split(",");
for (String s : cs){
Log.d("DrawLog", s); //logs the blogs correctly
}
ListAdapter adapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_selectable_list_item, cs);
Log.d("DrawLog", (String) adapter.getItem(0)); //logs the first blog correctlys
new AlertDialog.Builder(c)
.setTitle("Choose blog")
.setMessage("Choose the blog to publish the .gif")
.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String root_sd = Environment.getExternalStorageDirectory().toString();
File file = new File( root_sd + "/Flippy/" + name) ;
if(file.exists()){
Log.d("DrawLog", "file exists"); //file exists
Log.d("DrawLog", file.getPath());
}
PhotoPost post;
try {
post = client.newPost(cs[which], PhotoPost.class);
//Photo p = new Photo();
post.setData(file);
Log.d("DrawLog" , post.toString()+"");
post.save();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(NullPointerException e){
Log.d("DrawLog", "null pointer wtf");
}
}
}).create().show();
}
}
All the logs log the right things... It's just when the alert displays there is no list. Any ideas why?
You can either use setMessage() or setAdapter(). They are mutually exclusive. If you use both, the message wins. A solution would be to remove setMessage() and use setTitle() instead.

Saving a file in Android

I have the following code:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/tc/strip.tcl");
try {
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
}
else {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in try", Toast.LENGTH_SHORT).show();
}
finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}
else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
What I am looking to do is:
When the button is clicked:
1) Check to make the data is not null or empty (Working fine):
if (showLog != null && showLog.getText().toString().length() > 0) {
2) Check to make sure the folder exists, if not create the folder (Working fine):
File folder = new File(Environment.getExternalStorageDirectory() + "/tc");
if (!folder.exists()) {
folder.mkdir();
}
3) Before writing the data to the file, ensure it doesn't already exist. If it does exist, prompt the user to see if it can be overwritten. If the user chooses YES then overwrite the file but if the user chooses NO then add a "1" at the end of the filename and save it. (NOT WORKING and need help)
I am getting an error for the following line:
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Error:
Unhandled exception type FileNotFoundException
--> (Surround with try/catch)
1)
File tcDir = new File(Environment.getExternalStorageDirectory(),"tc");
tcDir.mkdirs();
File file = new File(tcdir, "strip.tcl");
The first line creates a file object called tc in the external storage directoy. The second line creates it on disk, with any missing parents. The third line creates a file object inside that directory
2)You seem to be doing that- you create a file output stream and write to it like you're doing.
3)Before writing the file, cal file.exists(). If it exists, you need to pop up a AlertDialog. If they hit the yes button of the dialog you write a file. If they choose the no button, you do nothing. It would be best to put all of the writing code into a separate function so it can be called in both the dialog click code and in the !exists code here.
In answer to part 3), I've edited your code to work properly for you. Most of the code you had was correctly written there was just a couple of issues. I also moved the code to write a new file into a new method writeFile() in order to avoid replicating code and to make it easier to keep track of what's going on:
btnSaveTrip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (showLog != null && showLog.getText().toString().length() > 0) {
File folder = new File(Environment.getExternalStorageDirectory() + "/TollCulator");
if (!folder.exists()) {
folder.mkdir();
}
String externalStoragePath = Environment.getExternalStorageDirectory().toString();
final File file = new File(externalStoragePath + "/TollCulator/strip.tcl");
if (file.exists()) {
new AlertDialog.Builder(getActivity())
.setTitle("File Already Exist")
.setMessage("Do you want to overwrite the existing file?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
writeFile(file);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
} else {
writeFile(file);
}
} else {
Toast.makeText (getActivity(), "empty", Toast.LENGTH_SHORT).show();
}
}
});
// ...
private void writeFile(File file){
try {
outputStream = new FileOutputStream(file);
outputStream.write(showLog.getText().toString().getBytes());
Toast.makeText (getActivity(), file.toString(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream!=null) {
try {
outputStream.close();
Toast.makeText (getActivity(), "file closed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText (getActivity(), "error in finally catch", Toast.LENGTH_SHORT).show();
}
}
}
}

Categories