如何从内部存储中读取ArrayList

时间:2014-03-11 06:53:00

标签: java android arraylist internal-storage

我有一个ArrayList,它有大约1000个联系人详细信息。打开需要30秒。 所以我把这个列表存储在android的内部存储中。我在安装数据后检查应用程序的详细信息显示16 kb,这是之前的0.因此数据正在存储但是当我尝试从列表中读取数据时,应用程序将使用nullpointerexception关闭。

我的主要课程是

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);
    listcontact = (GridView)findViewById(R.id.listapp);
    ImageView img=(ImageView)findViewById(R.id.imageView1);
    listcontact.setEmptyView(img);
    try {
        aa = readFromInternalStorage();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if(aa.isEmpty()){
        getnumber(this.getContentResolver());
    }
    else{
        adapt=new ContactAdapter(MainActivity.this, aa);
        listcontact.setAdapter(adapt);
    }
    edittext = (EditText)findViewById(R.id.edit_search);
    edittext.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int start, int before, int count) {
            // TODO Auto-generated method stub
            //MainActivity.this.adapt.getFilter().filter(s);
            int textlength = cs.length();
               ArrayList<ContactStock> tempArrayList = new ArrayList<ContactStock>();
               for(ContactStock c: aa){
                   String srch= c.getNumber().replaceAll(" ", "");
                  if (textlength <= c.getName().length() || textlength <= srch.length()) { 
                     if (c.getName().toLowerCase().contains(cs.toString().toLowerCase()) || srch.toLowerCase().contains(cs.toString().toLowerCase())) {
                        tempArrayList.add(c);
                     }
                  }
               }
               adapt = new ContactAdapter(MainActivity.this, tempArrayList);
               listcontact.setAdapter(adapt);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

class Info {
      public String name;
      public String phone;
      public String picture;

      @Override
      public String toString() {
        return name + " " + phone;
      } 
    }
public void getnumber(ContentResolver cr) {
    Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null,  ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
    while (phone.moveToNext()) {
        Info info = new Info();
        ids=phone.getInt(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID));
        info.phone=phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        info.name=phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        long id=Long.valueOf(ids);
        byte[] imagearray = queryContactImage(ids);
        System.out.println("...........name");
        aa.add(new ContactStock(info.name,info.phone,imagearray));
    }
    saveToInternalStorage(aa);
    phone.close();
    adapt=new ContactAdapter(MainActivity.this, aa);
    listcontact.setAdapter(adapt);
}


private byte[] queryContactImage(int imageDataRow) {
    Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {
        ContactsContract.CommonDataKinds.Photo.PHOTO
    }, ContactsContract.Data._ID + "=?", new String[] {
        Integer.toString(imageDataRow)
    }, null);
    byte[] imageBytes = null;
    if (c != null) {
        if (c.moveToFirst()) {
            imageBytes = c.getBlob(0);
        }
        c.close();
    }
    return imageBytes;
}

public void saveToInternalStorage(ArrayList<ContactStock> aList) {
    try {
        FileOutputStream fos = openFileOutput(NAME, Context.MODE_PRIVATE);
        ObjectOutputStream of = new ObjectOutputStream(fos);
        of.writeObject(aList);
        of.flush();
        of.close();
        fos.close();
    }
    catch (Exception e) {
        Log.e("InternalStorage", e.getMessage());
    }
}
@SuppressWarnings("unchecked")
public ArrayList<ContactStock> readFromInternalStorage() throws ClassNotFoundException {
    ArrayList<ContactStock> toReturn = null;
    FileInputStream fis;
    try {
        fis = openFileInput(NAME);
        ObjectInputStream oi = new ObjectInputStream(fis);
        toReturn = (ArrayList<ContactStock>) oi.readObject();
        oi.close();
    } catch (FileNotFoundException e) {
        Log.e("InternalStorage", e.getMessage());
    } catch (IOException e) {
        Log.e("InternalStorage", e.getMessage()); 
    }
    return toReturn;
}

任何帮助将不胜感激。 提前谢谢。

更新: -

我的堆栈跟踪是
enter image description here

logcat中的错误

03-11 12:47:52.037: E/InternalStorage(2919): Read an exception; java.io.NotSerializableException: com.webshine.quickdialplus.ContactStock
03-11 12:47:52.039: E/AndroidRuntime(2919): FATAL EXCEPTION: main
03-11 12:47:52.039: E/AndroidRuntime(2919): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.webshine.quickdialerwidget/com.webshine.quickdialplus.MainActivity}: java.lang.NullPointerException
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.ActivityThread.access$600(ActivityThread.java:162)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.os.Handler.dispatchMessage(Handler.java:107)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.os.Looper.loop(Looper.java:194)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.ActivityThread.main(ActivityThread.java:5371)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at java.lang.reflect.Method.invokeNative(Native Method)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at java.lang.reflect.Method.invoke(Method.java:525)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at dalvik.system.NativeStart.main(Native Method)
03-11 12:47:52.039: E/AndroidRuntime(2919): Caused by: java.lang.NullPointerException
03-11 12:47:52.039: E/AndroidRuntime(2919):     at com.webshine.quickdialplus.MainActivity.onCreate(MainActivity.java:62)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.Activity.performCreate(Activity.java:5122)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
03-11 12:47:52.039: E/AndroidRuntime(2919):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
03-11 12:47:52.039: E/AndroidRuntime(2919):     ... 11 more

1 个答案:

答案 0 :(得分:1)

让您的序列化类可序列化

   Class ContactStock implements Serializable
    {
         // your existing code
    }