Hey I have a Problem with my Android App. I'm a rookie in Android Development and try a little Android App. I want to save input in a file and load this. I want to save a object (or list of objects) serialize in the file. My Idea is to load this file if this exist and fill my ListView with them else I have a text message.
I debug my Application a look in LogCat and Android Monitor. I have a little Idea where is the Error.
The Problem is, if I start my App and the onStart Method begin. I execute a function that give me a list of records back. But for this I load the file in this list.(Here is the error I think).
Here is my Error in LogCat: (A part of this)
04-22 19:41:29.547 13928-13928/de.tarasov.wladimir.leistungen E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.tarasov.wladimir.leistungen, PID: 13928
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.tarasov.wladimir.leistungen/de.tarasov.wladimir.leistungen.persistence.RecordsActivity}: java.lang.ClassCastException: de.tarasov.wladimir.leistungen.models.Record cannot be cast to java.util.List
Here is my MainActivity:
@Override
protected void onStart(){
super.onStart();
List<Record> records = RecordDAO.findAll(this);
ArrayAdapter<Record> adapter =
new ArrayAdapter<Record>(this,
android.R.layout.simple_list_item_1,records);
mRecordsListView.setAdapter(adapter);
}
Here is the RecordDAO:
public static List<Record> findAll(Context ctx){
List<Record> result;
Object obj = null;
File f = ctx.getFileStreamPath("records.obj");
if(f.exists()){
try(FileInputStream in = ctx.openFileInput("records.obj")){
ObjectInputStream objIn = new ObjectInputStream(in);
obj = objIn.readObject();
}catch(Exception e){
e.printStackTrace();
}
}
if(obj != null){
result = (List<Record>) obj;
}else{
result = new ArrayList<>();
}
return result;
}
UPDATE : here is my method for saving the Object.
public static void persistAll(Context ctx, List<Record> records){
try(FileOutputStream out = ctx.openFileOutput("records.obj",Context.MODE_PRIVATE)){
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(records);
}catch(Exception e){
e.printStackTrace();
}
}
It would be great if you could attach the code where you write the objects into a file.
As the error message says, you are probably writing a Record in the file and trying to read it as a List. Instead you should have written it as an ArrayList and read it as a List.
It appears that your application is crashing on this line:
result = (List<Record>) obj;
Try checking the type of obj
. It looks like it may be of type Record
. If that is the case, try adding obj
to result
.
List<Record> result = new ArrayList();
if (obj instanceof Record) {
result.add(obj);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.