【问题标题】:How to load serialized data into an ArrayList when no connection?无连接时如何将序列化数据加载到 ArrayList 中?
【发布时间】:2017-03-08 03:18:30
【问题描述】:

美好的一天! 我是我的应用程序有一个下拉的微调器,在选择时您会在列表视图中获得该帖子的标题和作者。哪个工作正常。我也试图通过序列化来保存。我相信这是有效的。

我的问题: 保存后我想在没有连接时将数据加载回 ArrayList 并在我的 ListView 中显示。

我已经看到了几个类似的问题,如下面的问题,但仍然无法解决我的问题。

How to load a serialized file back to an arrayList

onCreate:我在哪里获得连接状态

    // onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.i(TAG, "onCreate: RAN");
    Context context = this;
    final Spinner spinner = (Spinner) findViewById(R.id.querySpinner);

    listView = (ListView) findViewById(R.id.resultsListView);
    ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

    if (manager != null) {
        NetworkInfo info = manager.getActiveNetworkInfo();

        if (info != null) {
            boolean isConnected = info.isConnected();

            // Network Operations
            if (isConnected) {
                Log.i(TAG, "onCreate: CONNECTED TO A NETWORK");

                spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
                        DataTask task = new DataTask();

                        if (pos == 0) {
                            Log.i(TAG, "onItemSelected: Pandas");
                            task.execute("https://api.reddit.com/r/pandas");
                        } else if (pos == 1) {
                            Log.i(TAG, "onItemSelected: Koalas");
                            task.execute("https://api.reddit.com/r/koalas");
                        } else if (pos == 2) {
                            Log.i(TAG, "onItemSelected: Chimpanzees");
                            task.execute("https://api.reddit.com/r/chimpanzees");
                        } else if (pos == 3) {
                            Log.i(TAG, "onItemSelected: Emus");
                            task.execute("https://api.reddit.com/r/emus");
                        } else if (pos == 4) {
                            Log.i(TAG, "onItemSelected: Zebras");
                            task.execute("https://api.reddit.com/r/zebras");
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {
                        Log.i(TAG, "onNothingSelected: NOTHING SELECTED");
                    }
                });

            } else {
                Log.i(TAG, "onCreate: NO CONNECTION");
                Toast.makeText(context, R.string.toast_notConnected, Toast.LENGTH_LONG).show();
            }
        }
    }
} // End onCreate

AsyncTask:我在哪里调用 saveSerialization()

// DataTask Class
private class DataTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.i(TAG, "onPreExecute: RAN");
    }

    @Override
    protected String doInBackground(String... url) {
        Log.i(TAG, "doInBackground: RAN");
        return getNetworkData(url[0]);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.i(TAG, "onPostExecute: RAN");

        try {
            JSONObject outerObject = new JSONObject(s);
            JSONObject dataObject = outerObject.optJSONObject("data");
            JSONArray childrenArray = dataObject.optJSONArray("children");

            ArrayList<Post> postList = new ArrayList<>();

            for (int i = 0; i <childrenArray.length() ; i++) {
                Post post = new Post("","");
                JSONObject data = childrenArray.optJSONObject(i).optJSONObject("data");

                postTitle = MainActivity.this.getString(R.string.string_title) + " " + data.getString("title");
                post.setmTitle(postTitle);
                postAuthor = MainActivity.this.getString(R.string.string_author) + " " + data.getString("author");
                post.setmAuthor(postAuthor);

                postList.add(post);
                saveSerializable(postList);
            }
            setupBaseAdapter(postList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} // End DataTask

saveSerialization() 和 loadSerialization() 方法:我尝试加载回数组列表。

 // saveSerializable
private void saveSerializable(ArrayList<Post> arrposts) {
    Log.i(TAG, "saveSerializable: RAN");

    try {
        FileOutputStream fileOutputStream = openFileOutput("post.txt", MODE_PRIVATE);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
        objectOutputStream.writeObject(arrposts);
        objectOutputStream.close();
    } catch(IOException e) {
        e.printStackTrace();
    }
} // End saveSerializable

private void loadSerializable() {
    Post post = null;
    try {
        FileInputStream fileInputStream = openFileInput("post.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
        post = (Post) objectInputStream.readObject();
        objectInputStream.close();

    } catch(IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }

    if(post != null) {

    }

}

岗位类别:

public class Post implements Serializable {

private String mTitle;
private String mAuthor;

public Post(String mTitle, String mAuthor) {
    this.mTitle = mTitle;
    this.mAuthor = mAuthor;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

public String getmAuthor() {
    return mAuthor;
}

public void setmAuthor(String mAuthor) {
    this.mAuthor = mAuthor;
}

}

后适配器:

class PostAdapter extends BaseAdapter {

private final Random rand = new Random();
private final int ID = rand.nextInt(Integer.MAX_VALUE);

private final Context context;
private List<Post> posts = new ArrayList<>();

public PostAdapter(Context context, List<Post> posts) {
    this.context = context;
    this.posts = posts;
}

@Override
public int getCount() {
    return (posts != null) ? posts.size() :0;
}

@Override
public Post getItem(int pos) {
    return (posts != null && pos < posts.size() && pos >= 0) ? posts.get(pos) : null;
}

@Override
public long getItemId(int pos) {
    return ID + pos;
}

@Override
public View getView(int pos, View view, ViewGroup viewGroup) {
    ViewHolder holder;

    if (view == null) {
        view = LayoutInflater.from(context).inflate(R.layout.lv_redditposts, viewGroup, false);
        holder = new ViewHolder(view);
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }

    Post post = getItem(pos);
    holder.postTitle.setText(post.getmTitle());
    holder.postAuthor.setText(post.getmAuthor());

    return view;
}

// ViewHolder
static class ViewHolder {
    public final TextView postTitle;
    public final TextView postAuthor;

    public ViewHolder(View v){
        postTitle = (TextView) v.findViewById(R.id.postTitleTextView);
        postAuthor = (TextView) v.findViewById(R.id.postAuthorTextView);
    }
} // End ViewHolder

}

【问题讨论】:

    标签: java android serialization arraylist android-asynctask


    【解决方案1】:

    这是我在文件中保存数组列表的方法。

             if (MyArrayList.size() > 0) {
                            FileOutputStream lObject = new FileOutputStream(new File("YOUR FILE PATH"));
                            ObjectOutputStream lco = new ObjectOutputStream(lObject);
                            lco.writeObject(MyArrayList);
                            lco.flush();
                            lObject.close();
                            return true;
                        } else {
                            return false;
                        }
    

    要返回该列表,请使用以下代码:

                    try {
                       MyArrayList=new ArrayList<>();
                        if (file.exists()) {
                            int nn;
                            FileInputStream localFileInputStream = new FileInputStream(new File("YOUR FILE PATH"));
                            byte[] arr=new byte[1024];
                            ByteArrayOutputStream by=new ByteArrayOutputStream();
                            while ((nn=localFileInputStream.read(arr)) != -1){
                                by.write(arr,0,nn);
                            }
                            List list=(List)new ObjectInputStream((InputStream)new ByteArrayInputStream(by.toByteArray())).readObject();
                            MyArrayList.clear();
                            MyArrayList.addAll(list);
                        }
                      }catch (Exception e){
                        e.printStackTrace();
          }
    

    【讨论】:

      猜你喜欢
      • 2013-03-19
      • 2011-08-22
      • 2017-06-23
      • 1970-01-01
      • 2013-12-29
      • 2013-01-02
      • 2015-06-23
      • 1970-01-01
      • 2016-03-21
      相关资源
      最近更新 更多