简体   繁体   English

如何从内部存储读取ArrayList

[英]How to read an ArrayList from internal storage

I have an ArrayList which has about 1000 contacts details. 我有一个包含大约1000个联系人详细信息的ArrayList。 It takes 30 seconds to open. 需要30秒才能打开。 So I store this list in internal storage of android. 所以我将此列表存储在android的内部存储中。 I check details of app after installing its data shows 16 kb, which was previously 0. So data is being stored but when I try to read data from list,the app is closed with nullpointerexception. 安装数据后,我检查了该应用程序的详细信息,该数据显示为16 kb,之前为0。因此正在存储数据,但是当我尝试从列表中读取数据时,该应用程序使用nullpointerexception关闭。

My main class is : 我的主要课程是

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

Any help will be appreciated. 任何帮助将不胜感激。 Thanks in advance. 提前致谢。

Update :- 更新:-

my stacktrace is 我的堆栈跟踪是
在此处输入图片说明

errors in logcat 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 

let your serialised class be serializable 让您的序列化类可序列化

   Class ContactStock implements Serializable
    {
         // your existing code
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM