在android

时间:2015-08-27 18:42:33

标签: java android serialization

我一直在这里搜索,但似乎无法找到有效的方法。我试图将一个简单的对象列表写入序列化文件,并且似乎无法在android中找到该文件。这是我第一次构建应用程序,我通过指向src / list.ser在netbeans中工作,但是,这在android studio中不起作用。我想我的问题是我在哪里放置ser文件,我如何在代码中指向它?这是我的代码:

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;
    }

}

1 个答案:

答案 0 :(得分:2)

首先确保您有权写入外部存储空间。

如,

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

你可以使用,

  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("");
            }
        }

并使用从中创建文件路径,

String filePath = pathToAppFolder +File.seperator + "Test.text";

然后您想要再次阅读此文件,您可以重新创建路径。因为您可以从Android代码

访问context

修改

您无法像在代码中那样访问上下文。您可以在onCreate方法中执行此操作。我只添加了必要的部分。

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

天啊,我不得不竭尽全力回答你的问题。在这里,您的List类不是应用程序中的Activity。这只是一堂课。所以我建议你先删除那些继承。删除此extends Activity。我建议你将List类名更改为其他名称。因为List是一个已定义的关键字,这不是最佳做法。

更改列表活动中的方法,如下所示。

    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());
        }
    }

在MainActivity中,onDestroy方法, 将代码更改为,

tester.addCurrentList(filePath);