Android Studio- Save custom class (with ArrayList) to a file - java

I've tried a few dozen tutorials and guides off stackoverflow and other sites to try and get this to work right. The app in question has a custom class that holds a list, with items that have a list within them. Ideally I'd like to be able to save from other activities when they close or are paused. The issue I run into is that when I close another activity (by pressing the back button), it shows a log of the save message. But when I open it back up instead of loading the info it should have saved it shows an blank list. Here's my code:
This is the main activity where the custom class is referenced and the save and load methods can be called:
public class ReminderList extends AppCompatActivity {
public static ListHolder Lholder;
public static ArrayList<ReminderType> AllReminders=new ArrayList<>();
public reminderCAdapter adapter;
public static ReminderType currentReminderType;
public static ItemType currentItemType;
public static TimeType currentTimesType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
//generate list
File file=new File("f.rem");
if(file.exists()) {
try {
LoadData();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
AllReminders=Lholder.Rlist;
}
adapter=new reminderCAdapter(AllReminders,this);
ReminderType r1=new ReminderType("Thing1");
//AllReminders.add(r1);
ReminderType r2=new ReminderType("Thing2");
//AllReminders.add(r2);
//instantiate custom adapter
//MyCustomAdapter adapter = new MyCustomAdapter(AllReminders, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.listView);
lView.setAdapter(adapter);
}
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
public static void SaveData() throws IOException {
Log.e("Saving Data", "trying");
FileOutputStream fos=new FileOutputStream("f.rem");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(Lholder);
oos.close();
}
public void LoadData() throws IOException, ClassNotFoundException {
Log.e("Loading Data", "trying");
FileInputStream fis=new FileInputStream("f.rem");
ObjectInputStream ois=new ObjectInputStream(fis);
Lholder=(ListHolder) ois.readObject();
ois.close();
}
public void AddToList(View view){
Intent intent = new Intent(this,ReminderSettings.class);
intent.putExtra("Type", "new");
startActivity(intent);
}
}
The other activity calls the save function like so:
#Override
protected void onStop() {
super.onStop(); // Always call the superclass method first
try {
ReminderList.SaveData();
} catch (IOException e) {
e.printStackTrace();
}
}
Here's a little list of the most recent posts Ive tried:
How to create a file on Android Internal Storage?
http://www.101apps.co.za/articles/using-android-s-file-system-for-saving-application-data-part-1-saving-files.html
If anyone can help me understand why this isn't working or what I need to do, I would greatly appreciate it.
Thanks much

I was unable to save it to a file without turning the arrays into a json string and nest the other arrays in it:
public class ReminderList extends AppCompatActivity {
public static ArrayList<ReminderType> AllReminders=new ArrayList<>();
public reminderCAdapter adapter;
public static ReminderType currentReminderType;
public static ItemType currentItemType;
public static TimeType currentTimesType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.context=this;
setContentView(R.layout.activity_reminder_list);
//generate list
try {
LoadData();
} catch (IOException | ClassNotFoundException | JSONException e) {
e.printStackTrace();
}
alarmMan=(AlarmManager) getSystemService(ALARM_SERVICE);
adapter=new reminderCAdapter(AllReminders,this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.listView);
lView.setAdapter(adapter);
}
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
public static void SaveData(Context context) throws IOException, JSONException {
Log.e("Saving Data", "trying");
JSONArray reminderData=new JSONArray();
JSONObject reminder;
JSONArray jItemData;
JSONObject jItem;
JSONArray jTimeData;
JSONObject jTime;
for(int i=0; i<AllReminders.size();i++){
//create the reminder item
reminder=new JSONObject();
jItemData=new JSONArray();
reminder.put("RemName",AllReminders.get(i).ReminderName);
//create each of the itemtype items
for(int j=0; j<AllReminders.get(i).Items.size();j++){
jItem=new JSONObject();
jTimeData=new JSONArray();
jItem.put("iName",AllReminders.get(i).Items.get(j).ItemName);
jItem.put("iNote",AllReminders.get(i).Items.get(j).AdditionalNote);
//create each time item
for(int h=0; h<AllReminders.get(i).Items.get(j).Times.size();h++){
jTime=new JSONObject();
jTime.put("hr",AllReminders.get(i).Items.get(j).Times.get(h).hour);
jTime.put("min",AllReminders.get(i).Items.get(j).Times.get(h).minute);
jTimeData.put(jTime);
}
//String tList=jTimeData.toString();
jItem.put("timeList",jTimeData);
jItemData.put(jItem);
}
//String iList=jItemData.toString();
reminder.put("itemList",jItemData);
Log.e("reminderItem", reminder.toString());
reminderData.put(reminder);
}
String remList=reminderData.toString();
FileOutputStream fos=context.openFileOutput("savedData",MODE_PRIVATE);
fos.write(remList.getBytes());
fos.close();
}
public void LoadData() throws IOException, ClassNotFoundException, JSONException {
Log.e("Loading Data", "trying");
FileInputStream fis=openFileInput("savedData");
BufferedInputStream bis= new BufferedInputStream(fis);
StringBuffer b=new StringBuffer();
while(bis.available() !=0){
char c=(char) bis.read();
b.append(c);
}
bis.close();
fis.close();
JSONArray reminderData= new JSONArray(b.toString());
//Log.e("b string", b.toString());
for(int i=0; i<reminderData.length();i++){
JSONObject remObj=reminderData.getJSONObject(i);
String rName=remObj.getString("RemName");
//Log.e("Rname",rName);
ReminderType remi=new ReminderType(rName);
JSONArray itemArray=remObj.getJSONArray("itemList");
for(int h=0; h<itemArray.length();h++){
JSONObject itemObj= itemArray.getJSONObject(h);
String iName=itemArray.getJSONObject(h).getString("iName");
//Log.e("iName",iName);
ItemType iTem= new ItemType(iName);
JSONArray timeArray=itemObj.getJSONArray("timeList");
for(int j=0; j<timeArray.length();j++){
JSONObject timeObj=timeArray.getJSONObject(j);
int hr=timeObj.getInt("hr");
int min=timeObj.getInt("min");
TimeType tIme=new TimeType(hr,min);
tIme.SetDisplayTime();
iTem.Times.add(tIme);
}
remi.Items.add(iTem);
}
AllReminders.add(remi);
}
}
public void AddToList(View view) throws IOException, JSONException {
Intent intent = new Intent(this,ReminderSettings.class);
intent.putExtra("Type", "new");
startActivity(intent);
}
}

Related

Get API data to RecyclerView in AsyncTask

I'm writing a simple Android app to get a JSON array into RecyclerView with AsyncTask. I know that I can use libraries as Retrofit or OKHTTP, but this time I tried to write the connection IO from scratch. The connection succeeded and data has been parsed and added to ArrayList. I do all of these in doInBackground(), and in onPostExecute() I just call notifyDataSetChanged() to the adapter, but it didn't work. I tried several ways such as move setAdapter() to onPostExecute(), or move all the AsyncTask to Adapter class and they didn't help anything. Can someone tell me what I miss, if I cannot fix it in 2 or 3 days, I think I will use Retrofit instead.
This is my Main class, I think the bug is only here, but if you need to see my adapter please leave a comment, thanks a lot.
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ProgressDialog progressDialog;
String apiUrl;
Gson gson;
List<User> userList;
UserAdapter userAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycle_view);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
apiUrl = "https://lebavui.github.io/jsons/users.json";
gson = new Gson();
userList = new ArrayList<>();
userAdapter = new UserAdapter(userList, MainActivity.this);
recyclerView.setAdapter(userAdapter);
DataGetter dataGetter = new DataGetter();
dataGetter.execute();
}
private class DataGetter extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
StringBuilder response = new StringBuilder();
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(apiUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
response.append((char) data);
data = isr.read();
}
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
userList.add(gson.fromJson(jsonArray.getJSONObject(i).toString(), User.class));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
progressDialog.dismiss();
userAdapter.notifyDataSetChanged();
}
}
}
As mentioned in comments you should be using something other than depreciated classes. Below is an example of using runnable, simply add your parser and adapter
This should be moved to android view model.
public class MainActivity extends AppCompatActivity {
private final String LOG_TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(LOG_TAG, "on Create");
String apiUrl = "https://lebavui.github.io/jsons/users.json";
getUsers(apiUrl);
}
//return interface
public interface Completion{
void onCompletion(List<String> list);
}
//calls a function which call Completion.onCompletion interface off of main thread
public void getUsers(String apiUrl){
getAsyncData(apiUrl, this::setListDataOnMain);
}
//bring back to main thread
//This should be in Android View model for application context instead of this.getMainLooper
private void setListDataOnMain(List<String> list){
Handler mainHandler = new Handler(this.getMainLooper());
Runnable myRunnable = () -> {
//Set local object "list" to your global variable
//Then notify adapter change
//only logging here as example
Log.v(LOG_TAG, "List: " + list);
};
mainHandler.post(myRunnable);
}
//make async
public void getAsyncData(String apiUrl, Completion completion) {
Runnable runnable = () -> {
List<String> userList = makeRequest(apiUrl);
completion.onCompletion(userList);
};
Thread thread = new Thread(runnable);
thread.start();
}
//This is not async calling this func from main thread will crash
public List<String> makeRequest(String apiUrl ) {
List<String> userList = new ArrayList<>();
StringBuilder response = new StringBuilder();
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(apiUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while (data != -1) {
response.append((char) data);
data = isr.read();
}
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
//your json parsing here
userList.add(String.valueOf(i));
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return userList;
}
}
I think the DataGetter class need to executed first than you can set adapter
i test this code and it works
#SuppressLint("NotifyDataSetChanged")
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
progressDialog.dismiss();
userAdapter = new UserAdapter(userList, MainActivity.this);
recyclerView.setAdapter(userAdapter);
}

Show image in ListView from JSON file in Android Studio

I want to display a list of member from a JSON file. Member information like Name, Location, Contact number, image etc. All information is showing fine but Member Image is not showing. Here is given the necessary file and coding for your checking.
JSON file
{"names":[
{
"serialno":"1. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy1",
"mobileno":"01942717067",
"address":"Digholia, Lohagara, Narial"
},
{
"serialno":"2. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy2",
"mobileno":"01823987654",
"address":"Kumri, Lohagara, Narial"
},
{
"serialno":"3. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy3",
"mobileno":"01782345678",
"address":"Baira, Lohagara, Narial"
},
{
"serialno":"4. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy4",
"mobileno":"01943876543",
"address":"Lutia, Lohagara, Narial"
}
]
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolBarId);
setSupportActionBar(toolbar);
listview=findViewById(R.id.listViewId);
try {
JSONObject jsonObject=new JSONObject(loadJsonFile());
JSONArray jsonArray=jsonObject.getJSONArray("names");
HashMap<String,String> listItem;
ArrayList<HashMap<String,String>> listItems=new ArrayList<>();
for(int i=0; i<jsonArray.length();i++)
{
JSONObject obj=jsonArray.getJSONObject(i);
String serialno=obj.getString("serialno");
String memberimage=obj.getString("memberimage");
String farmacyname=obj.getString("farmacyname");
String membername=obj.getString("membername");
String mobileno=obj.getString("mobileno");
String address=obj.getString("address");
listItem=new HashMap<>();
listItem.put("serialno",serialno);
listItem.put("memberimage",memberimage);
listItem.put("farmacyname",farmacyname);
listItem.put("membername",membername);
listItem.put("mobileno",mobileno);
listItem.put("address",address);
listItems.add(listItem);
}
ListAdapter adapter=new SimpleAdapter(this,listItems,R.layout.main_list_item_layout,
new String[]{"serialno","memberimage","membername","farmacyname","mobileno","address"},
new int[]{R.id.serialTextViewId,R.id.imageViewId,R.id.nameTextViewId,
R.id.shopNameTextViewId,R.id.mobileNoTextViewId,R.id.addressTextViewId});
listview.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String loadJsonFile() throws IOException {
String json=null;
InputStream inputStream=this.getAssets().open("member.json");
int size=inputStream.available();
byte[] byteArray=new byte[size];
inputStream.read(byteArray);
inputStream.close();
json=new String(byteArray, "UTF-8");
return json;
}
}
Problem: The image is not showing in list. Other information is showing good but Image is blank. Can anyone please help me if I do mistake anywhere.
When adding the image to the list you want to add the drawble id and not the drawable string i.e "#drawable/tojib" like below:
String memberImageDrawable = obj.getString("memberimage");
memberImageDrawable = memberImageDrawable.substring(memberImageDrawable.indexOf("/")); //extract the String after #drawable/
String memberimage = Integer.toString(getApplicationContext().getResources().getIdentifier(memberImageDrawable, "drawable", getApplicationContext().getPackageName()));

How to send values from an arraylist from AsyncTask class to another class in Android?

I have the next problem, I tried to send Arraylist<string> values from AsyncTask class to other class call graphics but I don’t know what I do wrong and how to get Arraylist<string> values in the other class, because I have a lot of sintaxis errors I my code
AsyncTask class
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//v funcional
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected ArrayList<String> doInBackground(Void... voids) {
String Id ="";
String Time ="";
String Pressure="";
ArrayList<String> IdArray = new ArrayList<String>();
ArrayList<String> TimeArray = new ArrayList<String>();
ArrayList<String> PressureArray = new ArrayList<String>();
String IdS=""+IdArray;
String TimeS=""+TimeArray;
String PresureS=""+PressureArray;
data.set(1,TimeS);
data.set(2,TimeS);
data.set(3,TimeS);
return data;
}
#Override
protected void onPostExecute(ArrayList<String> result){
super.onPostExecute(result);
Graphics.data.setText(data);
}}
The graphics class
public class Graphics extends AppCompatActivity {
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graphics);
Button firstButton = (Button) findViewById(R.id.json);
data = (TextView) findViewById(R.id.msgTxt);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetch process = new fetch();
ArrayList<String> data= process.execute();
data.get(1);
}
});
}
you can create an interface which your "Graphics" implements it , and pass it to your AsyncTask class.
like this
public interface BlaBlaBla {
void doBla(ArrayList<String> myBla);
}
and in your "Graphics" :
class Graphics extends AppCompatActivity implements BlaBlaBla {
fetch process = new fetch(this);
}
and for asyncClass :
public class fetch extends AsyncTask<Void,Void,ArrayList<String>> {
//constructor
BlaBlaBla bla;
public fetch(BlaBlaBla bla){
this.bla=bla;
}
//when your task is complete use bla.doBla(pass your array here);
}
my solution
Fetch class
public class Fetch extends AsyncTask<Void,Void,String[][]> {
public static int KEY = 0;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected String[][] doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http:xxxxxxx/xxx.json";
String jsonStr = sh.makeServiceCall(url);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
int nTiempos=jsonObj.length();
String[] IdKeyArray = new String[nTie];
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(String.valueOf(i));
IdKeyArray[i] = c.getString("Key");
String[][] valores={IdKeyArray};
return valores;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
And this is the "call" the other class where I get the values
private String[][] valores;
Fetch process = new Fetch();
process.execute();
try {
valores=process.get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
pm.setText(String.valueOf(valores[Fetch.Key][0]));
}
}
}

Reading and writing a serialized object in android

I've been searching on here but can't seem to find what works. I'm trying to write a simple object list to a serialized file and can't seem to locate the file in android. It's my first time building an app and I had this working in netbeans by pointing to src/list.ser, however, this doesn't work in android studio. I guess my question is where do I place the ser file and how do I point to it in the code? Here is my code:
ListActivity:
public class ListActivity extends Activity implements Serializable {
private ArrayList<Item> list;
public List() throws Exception {
list = new ArrayList<Item>();
}
public void addItem(String name) {
list.add(new Item(name));
}
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.separator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("NOPE NOPE NOPE NOPE");
}
}
public void addItem(String name, int price) {
list.add(new Item(name, price));
}
public ArrayList<Item> populate() {
return list;
}
public void record() {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("src/list.ser"));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private List tester;
private ListView lv;
private EditText gg;
private Button button;
private Button clearButton;
private ArrayList list;
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder + File.separator + "list.ser";
#Override
protected void onDestroy() {
try {
tester.addCurrentList();
} catch (Exception e) {
e.printStackTrace();
}
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create the list
lv = (ListView) findViewById(R.id.listDisplay);
ListView mine = lv;
list = new ArrayList<String>();
try {
tester = new List();
}
catch (Exception e) {
}
for (Item item : tester.populate()) {
list.add(item);
}
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
lv.setAdapter(arrayAdapter);
final TextView firstTextView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
clearButton = (Button) findViewById(R.id.clear);
gg = (EditText) findViewById(R.id.item);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String no = gg.getText().toString();
if (!no.isEmpty()) {
tester.addItem(no);
arrayAdapter.add(no);
arrayAdapter.notifyDataSetChanged();
gg.setText("");
}
}
});
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
arrayAdapter.clear();
arrayAdapter.notifyDataSetChanged();
}
});
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = lv.getItemAtPosition(position).toString();
arrayAdapter.remove(arrayAdapter.getItem(position));
arrayAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
First of all make sure that you have permission to write to the external storage.
as,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can use,
public void addCurrentList() throws Exception{
String pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
String filePath = pathToAppFolder +File.seperator + "list.ser";
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println("");
}
}
and the use create a file path from that as,
String filePath = pathToAppFolder +File.seperator + "Test.text";
and then where ever you want to read this file again, you can recreate the path. Because you have access to the context from the android code
EDIT
You can not access the context as you do in your code. You can do it in your onCreate method. I have added only the necessary parts.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pathToAppFolder = getExternalFilesDir(null).getAbsolutePath();
filePath = pathToAppFolder + File.separator + "list.ser";
//create the list
Oh my god, I had to go into great lengths to answer your question. Here it is, Your List class is not an Activity in your application. It is just a class. So I suggest you to remove those inheritance first. remove this extends Activity. And I suggest you to change the List class name to something else. Because, List is a defined keyword and its not a best practice to do so.
Change the method in List Activity as below.
public void addCurrentList(String filePath) throws Exception
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filePath));
os.writeObject(list);
os.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void record(String filePath) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath));
ArrayList<Item> list2 = (ArrayList<Item>) in.readObject();
System.out.println(list2);
list = list2;
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
In your MainActivity, onDestroy Method,
change the code to,
tester.addCurrentList(filePath);

Populate ArrayList in ListView

I'm trying to populate a simple listview using an array of strings in ArrayList. Every time I try though it force closes. I know I'm getting the correct strings in the array as I've seen with Logcat. I can't seem to figure out why it is force closing. Maybe I'm forgetting something in ArrayAdapter (it looks correct to me) or maybe I'm putting my populate method in the wrong place... Can someone help me with this?
public class SchedLayout extends Activity {
public ArrayList<String> titleArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sched_layout_layout);
new doParse().execute();
}
private class doParse extends AsyncTask<Void, Void, Void> {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/directory/");
File file = new File(dir, "file.html");
#Override
protected Void doInBackground(Void... params) {
try {
FileInputStream input = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(
input, "UTF-8"));
String line;
titleArray = new ArrayList<String>();
while ((line = br.readLine()) != null) {
String html = line;
Document doc = Jsoup.parse(html);
Elements rels = doc.select("a[rel]");
for (Element title : rels) {
String exclude = "Follow";
if (title.attr("title").contains(exclude)) {
continue;
}
titleArray.add(title.attr("title"));
// Log.v("", title.attr("title")); <--works
}
}
br.close();
input.close();
populate(titleArray); <--does not work
} catch (FileNotFoundException e) {
//Never happens
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void populate(ArrayList<String> array) {
ListView showList = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> shows = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1, array);
showList.setAdapter(shows);
}
}
}
Move your populate call to onPostExecute. You cannot modify the ListView in doInBackground or anything UI related.
#Override
protected void onPostExecute(Void v) {
populate(titleArray);
}

Categories