Java的:ArrayList的不德/序列化正确正确、序列化、Java、ArrayList

2023-09-05 05:20:34 作者:活着活着就死了

我想提出一个应用程序,你可以创建列表,将选择一个随机的选择。在这个程序我选择列表中的一个随机的条目。该应用程序序列化的ArrayList到一个txt文件。我正在那里反序列化ArrayList和打开与该信息的新活动的一部分。问题是,它forcloses上打开该活动。我beleive它是与它不序列正确。 Anyhelp将是真棒,谢谢!

I am making an App where you can create lists that will pick a random choice. In this app I pick a random entry in the list. The app serializes the ArrayList into a txt file. I am making the part where it deserializes the ArrayList and opens a new activity with that info. Problem is that it forcloses on opening that activity. I beleive it has something to do with it not serializing right. Anyhelp would be awesome, thanks!

BTW它对其关闭的原因是反序列化ArrayList中是空的。

BTW The reason it forecloses is the ArrayList that is deserialized is empty.

下面是第一个Java文件:

Here is the first Java file:

package com.frostbytedev.randomgenie;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Steven on 6/11/13.
 */
public class NewList extends Activity implements Serializable, View.OnClickListener{
    String ListName;
    String ItemText;
    int i = 0;

    List<String> List = new ArrayList<String>();
    Button save;
    EditText FileName, etItem1, etItem2, etItem3, etItem4, etItem5;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newlist);
        initilize();
    }

    private void IndexList() {
        List.add(FileName.getText().toString());
        List.add(etItem1.getText().toString());
        List.add(etItem2.getText().toString());
        List.add(etItem3.getText().toString());
        List.add(etItem4.getText().toString());
        List.add(etItem5.getText().toString());

        for(i=1;i<5;i++){
            ItemText = List.get(i);
            if(ItemText.contentEquals("")){
                List.remove(List.get(i));
            }
        }

    }

    private void initilize() {
        save = (Button)findViewById(R.id.bSave);
        FileName = (EditText)findViewById(R.id.etFileName);
        etItem1 = (EditText)findViewById(R.id.etItem1);
        etItem2 = (EditText)findViewById(R.id.etItem2);
        etItem3 = (EditText)findViewById(R.id.etItem3);
        etItem4 = (EditText)findViewById(R.id.etItem4);
        etItem5 = (EditText)findViewById(R.id.etItem5);
        save.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){

            case R.id.bSave:
                IndexList();
                try {
                    SaveList();
                } catch (IOException e) {
                    e.printStackTrace();
                }


        }
    }


    private void SaveList() throws IOException {
        String filename = FileName.getText().toString()+".txt";
        FileOutputStream fos;
        try {
            fos = openFileOutput(filename,Context.MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(List);
            out.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
    }
}

和第二个:

package com.frostbytedev.randomgenie;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Steven on 6/15/13.
 */
public class ListSelect extends ListActivity implements Serializable {
    List<String> List = new ArrayList<String>();
    List<String> textFiles = new ArrayList<String>();
    List<String> ListStrings = new ArrayList<String>();

    List<String> textFiles(String directory) {
        File dir = new File(directory);
        for (File file : dir.listFiles()) {
            if (file.getName().endsWith((".txt"))) {
                textFiles.add(file.getName().replace(".txt", ""));
            }
        }
        return textFiles;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, textFiles("data/data/com.frostbytedev.randomgenie/files")));
    }
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
            String FileName = textFiles.get(position);
        deserialize(FileName);
        Bundle b = new Bundle();
        Intent OpenList = new Intent(this, ListRandom.class);
        OpenList.putExtra("ListItem1",List.get(1));
        OpenList.putExtra("ListItem2", List.get(2));
        OpenList.putExtra("ListItem3", List.get(3));
        OpenList.putExtra("ListItem4",List.get(4));
        OpenList.putExtra("ListItem5", List.get(5));
        startActivity(OpenList);

    }

    private void deserialize(String filename) {
        FileInputStream fis = null;
        ObjectInputStream in = null;
        ObjectOutputStream out = null;
        try {
            fis = new FileInputStream(filename);
            in = new ObjectInputStream(fis);
            List = (ArrayList<String>) in.readObject();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}

LogCat中:

LogCat:

06-19 00:00:53.497    8447-8447/com.frostbytedev.randomgenie   E/AndroidRuntime: FATAL EXCEPTION: main
        java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
        at java.util.ArrayList.get(ArrayList.java:304)
        at com.frostbytedev.randomgenie.ListSelect.onListItemClick(ListSelect.java:44)
        at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
        at android.widget.AdapterView.performItemClick(AdapterView.java:298)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
        at android.widget.AbsListView$1.run(AbsListView.java:3423)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)

任何帮助将是真棒!

Any help would be awesome!

推荐答案

在从文件系统读取文件,你砍TXT扩展名:

When reading the files from the file system you cut the txt extension:

textFiles.add(file.getName().replace(".txt", ""))

当您单击该项目使用的文件名反序列化列表。原始文件是使用TXT扩展名,虽然写的,因此该文件将不被发现和反序列化失败,则列表为空,List.get(1)将抛出IndexOutOfBoundsException异常。 你可以做的是:

When you click the item you use that file name to deserialize the list. The original file was written using the txt extension though and so the file won't be found and the deserialization fails, the list is empty and List.get(1) will throw an IndexOutOfBoundsException. What you could do is:

fis = new FileInputStream(filename+".txt");

我是pretty的确保您的logcat输出也有IndexOutOfBoundsException异常上面出现FileNotFoundException。

I'm pretty sure you logcat output also has a FileNotFoundException above the IndexOutOfBoundsException.

顺便说一句这是一个非常糟糕的主意来命名的方法等变量。使用getTextFiles()的方法,如果变量称为TEXTFILES。

BTW it's a really bad idea to name a variable like a method. Use getTextFiles() for the method if the variable is called textFiles.