My arrayList doesn't get successfully saved and restored? - java

I have an activity which contains a listview, the activity (MainActivity) launches another activity (HomeworkAddActivity), this retrieves a string from the user and adds it to the listview (all of the above works).
However in order that the listview 'remembers' its contents whilest the other activity is launched I try to save the list to a file, code:
public void saveHomework() {
try {
#SuppressWarnings("resource")
FileOutputStream fos = new FileOutputStream(homeworkFileName);
fos = openFileOutput(homeworkFileName,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(homeworkItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public void populateHomework() {
try {
#SuppressWarnings("resource")
FileInputStream fis = new FileInputStream(homeworkFileName);
fis = getParent().openFileInput(homeworkFileName);
ObjectInputStream is = new ObjectInputStream(fis);
homeworkItems = (ArrayList<String>) is.readObject();
is.close();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I then read it from the file.
saveHomework is called onPause
and populateHomework:
#Override
public void onResume() {
super.onResume();
homeworkItems = new ArrayList<String>();
activity = this;
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
populateHomework();
homeworkListAdapter.notifyDataSetChanged();
}
However it only ever shows the items added by addHomeworkActivity, not those 'saved' and 'restored' (they don't get saved/restored successfully), why is this?

It has 2 problems
your listview still connect with your old adapter
notifyDataSetChanged might not work in your case, it relate to this answer
notifyDataSetChanged example
you need to reorder your command in onResume()
#Override
public void onResume() {
super.onResume();
homeworkItems = new ArrayList<String>();
activity = this;
populateHomework(); // I move this line up
homeworkListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, homeworkItems);
//homeworkListAdapter.notifyDataSetChanged(); // this line might not work
yourListView.setAdapter(homeworkListAdapter); // because your listview still connect with your old ArrayAdapter
}

Related

Label the internal memory file At Run Time

I have an application that
takes data from the user and
creates a file in the internal memory based on the name entered by the user
and saves the user data.
But when the file is saved by that name, the fileInputStream does not respond to that name.
what should I do ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_food);
bundle = getIntent().getExtras();
Toolbar toolbar=(Toolbar)findViewById(R.id.food_lood_toolbar);
setSupportActionBar(toolbar);
file=bundle.getString("diname");
getSupportActionBar().setTitle(file);
String q=”123”;
if (bundle.getString("activity").equals(q)) {
String e1=editText1.getText().toString() +"/";
fileOutputStream=openFileOutput(file,Context.MODE_PRIVATE);
fileOutputStream.write(e1.getBytes());
}
String t="321";
if (bundle.getString("activity").equals(t)){
try {
fileInputStream= openFileInput(file);
int x;
StringBuffer y = new StringBuffer();
while((x=fileInputStream.read())!=-1){
y.append((char)x);
}
String c=y.toString();
txt=c.split("/");
editText1.setText(txt[0]);
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(),"file not found",Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getBaseContext(),"io",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

trying to write to read and write to a text file in eclipse

I am trying to write and read to a text file name students but I am having all kinds of hassles I am very new to android programming so I am trying this out for the first time. I have looked at code here and there to try and figure out what I am doing wrong but I cant find one specific thing to help, this question has probably been asked a couple of times, so I am sorry for asking it again. Please see my different .xml and .java files below. The actual question is to be able to write data to a textfile and from the main screen click on a textfield which will take you to the edit screen, where you get to edit that specific field and save it to a text file (this however has not been done yet as I am still struggling to figure out why my writing and reading to the textfile is not working, I hope my poor attempt at coding will shed some light on the matter.
Please don't crucify me for my bad coding I am super new to android
/////////////////////////////add screen.java///////////////////////////////
public class AddNew extends Activity {
private static final String newLine = System.getProperty("line.separator");
TextView txtText;
EditText Modules;
EditText Types;
#Override
protected void onCreate(Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.add);
txtText = (TextView)findViewById(R.id.textView1);
Modules = (EditText)findViewById(R.id.etMod);
Types = (EditText)findViewById(R.id.etType);
Button backMan = (Button)findViewById(R.id.btnBackMain);
backMan.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(AddNew.this, MainActivity.class));
}
}); //end back Button
//get the day, month & year from the Date picker
DatePicker myDPicker = (DatePicker)findViewById(R.id.dpDate);
Integer Year = myDPicker.getYear();
Integer Month = myDPicker.getMonth();
Integer Day = myDPicker.getDayOfMonth();
StringBuilder sb = new StringBuilder();
sb.append(Year.toString()).append("-").append(Month.toString()).append
("-").append(Day.toString());
final String dobStr=sb.toString();
txtText.setText("TEST");
Button Save = (Button)findViewById(R.id.btnSaveAdded);
Save.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
try {
writeToFile(Modules.getText().toString(),
Types.getText().toString(),dobStr);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void writeToFile(String Mod, String AsType, String dobDate) throws
IOException {
// TODO Auto-generated method stub
//String textTofile;
StringBuilder sbText = new StringBuilder();
sbText.append(Mod + "," + dobStr + "," + AsType);
//textTofile=sbText.toString();
String fileName = "student";
PrintWriter printWriter = null;
File file = new File(fileName);
try {
if (!file.exists()) file.createNewFile();
printWriter = new PrintWriter(new FileOutputStream(fileName,
true));
printWriter.write(newLine ); //+textTofile);
} catch (IOException ioex) {
ioex.printStackTrace();
} finally {
if (printWriter != null) {
printWriter.flush();
printWriter.close();
}
}
}
}); //end back Button
}
}
`public class MainActivity extends Activity {
TextView fDisplay;
TextView fTest;
int numItems=0; //use it later to keep track of the number of items.
String inText; //use this variable for the information read in from the textfile.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but1=(Button)findViewById(R.id.btnAdd);
but1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, AddNew.class));
}
}); //end but1
Button but2 = (Button)findViewById(R.id.btnEditCur);
but2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//This is where your code will go
startActivity(new Intent(MainActivity.this, EditCur.class));
}
}); //end of button 2
fDisplay = (TextView)findViewById(R.id.tvAssign1);
try {
readFromFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void readFromFile() throws IOException {
// TODO Auto-generated method stub
// String ret="";
BufferedReader br;
FileReader fr = null;
try {
fr = new FileReader("student");
br = new BufferedReader(fr);
String line = br.readLine();
while (null != line) {
fDisplay.append(line);
fDisplay.append("\n");
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != fr) {
try {
fr.close();
} catch (IOException e) {
// ignore
}
}
}
}
}
`
For writting on a file I have used this
String filename;
String content;
filename = "PATH_AND_FILE";
content = "CONTENT ON THE FILE"
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
out.write(myString.toString());
out.flush();
out.close();
And for reading I have this function:
public static String readFileAsString() {
String result = "";
String filename;
filename = "PATH_AND_FILE";
File file = new File(filename);
if ( file.exists() ) {
FileInputStream fis = null;
try { fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
result = result + String.valueOf(current);
}
} catch (Exception e) {
// System.out.println("DEBUG Exception String :"+ e.toString());
} finally {
if (fis != null)
{ try {
fis.close();
} catch (IOException ignored) {
}}
else {// System.out.println("DEBUG Exception String NULL");
}
}
return result;
}
else
{
return "DEFAULT CONTENT";
}
}
In Android, the file' directory is different then that on a PC, like :the files are stored in a directory related to your App, the accessing permissions are different.
This link might be helpful:
How To Read/Write String From A File In Android
Two simple functions (Java) to read and write:
private static void writeToFile(String path, String text) {
PrintWriter writer;
try {
writer = new PrintWriter(path, "UTF-8");
writer.print(text);
writer.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFileContent(String filename){
String everything = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
try {
line = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
everything = sb.toString();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return everything;
}

Object I/O Stream java android

I want to print an object to a file when my app is onStop and read it at onCreate. When I close the app and reopen it the object is not there. The objects acts ok while navigating trough the app, problem only on restart.
The object is an instance ("tl") of TList class - extends ArrayList
read:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
FileInputStream fis;
try {
fis = openFileInput("data_t");
ObjectInputStream ois = new ObjectInputStream(fis);
tl = (TList)ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
write:
#Override
protected void onStop() {
super.onStop();
FileOutputStream fos;
try {
fos = openFileOutput("data_t", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(tl);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}

Directory To Serialize/Deserialize Objects in Android?

I am trying to serialize an object onClick and then in a ListFragment, grab all the files in that directory and put them into the array. I have the code to serialize and put the filenames into an ArrayList, but it does not work.
What am I doing wrong? How can I make it so they both point to the same directory?
Here is my code for serialization:
WIFIQRCODE = "WIFI:T:"+PASSTYPE2+";S:"+SSID2+";P:"+PASS2;
OutputStream file = null;
try {
file = new FileOutputStream(SSID2+".ser");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = null;
try {
output = new ObjectOutputStream(buffer);
} catch (IOException e) {
e.printStackTrace();
}
assert output != null;
try {
output.writeObject(WIFIQRCODE);
} catch (IOException e) {
e.printStackTrace();
}
And my code for getting the filenames in the ListFragment:
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, filenames);
setListAdapter(adapter);
}
Any help would be appretitiated!

Read only the specific tag from RSS Feed

I'm trying to learn how to make RSS Reader for my android app by following this tutorial.
The feed is generated from a wordpress blog and I want to figure out a way to read by categories. It's currently reading the entire feed items but I'm trying to sort out specific categories from the list.
This is the Activity class to read the feed.
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, GridActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(http://mywordpressblog.com/feed/);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
before adding the items to your list you can check like this:
if(item.getCategory().contains("categorytoshow")){
add it to the list because it contains the category you want
}
then add it to the list

Categories