sqlite 如何在应用程序运行时只解析一次JSON数据

k97glaaz  于 2023-03-23  发布在  SQLite
关注(0)|答案(1)|浏览(135)

我不知道如何在我的应用程序运行时只解析一次JSON数据。目前JSON解析是在每个用户交互(如横向/纵向)上完成的,页面刷新和页面重建(来自子活动)。这使得我的应用程序每次实际显示数据都很慢。甚至当提供大量用户交互(如多次方向更改)时,应用程序会崩溃。有人能帮助我如何限制JSON解析不超过一次吗?
JSON在数据库和ArrayList中的解析和保存

public void parseApiData () {

            RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

            JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                        if (response != null) {

                            if(!books.isEmpty())
                            {
                                books.removeAll(books);
                                dbHandler.removeAll();
                            }

                            for (int i = 0; i < response.length(); i++) {

                                try {

                                    JSONObject obj = response.getJSONObject(i);

                                    int bookId = obj.getInt("id");

                                    String bookName = obj.getString("title");

                                    String bookDescription = obj.getString("description");

                                    int bookPage = obj.getInt("pageCount");

                                    String bookExcerpt = obj.getString("excerpt");

                                    String bookPublishDate = obj.getString("publishDate");

                                    books.add(new Books(bookId, bookName, bookDescription, bookPage, bookExcerpt, bookPublishDate));

                                    dbHandler.addNewCourse(bookId, bookName, bookDescription, bookPage, bookExcerpt, bookPublishDate);

                                    // books ?
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            //Books[] b=books.toArray(new Books[books.size()]);
                            //System.out.println(b[184].getmBookName());
                            //System.out.println(books.get(198).getmBookPage());
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                               for(int j=0;j<books.size();j++)
                               {
                                   Books note=books.get(j);
                                   dbHandler.addNewCourse(note.getmBookId(),note.getmBookName(),note.getmBookDescription(),note.getmBookPage(),note.getmBookExcerpt(),note.getmBookPublishDate());
                               }
                                }
                            });

                            // books = dbHandler.readCourses();
                            progressBar.setVisibility(View.GONE);
                            onConfigurationChanged(getApplicationContext().getResources().getConfiguration());
                            BookAdapter adapter = new BookAdapter(MainActivity.this, books);
                            recyclerView.setAdapter(adapter);

                        } else {
                            Toast.makeText(MainActivity.this, "Array is empty", Toast.LENGTH_SHORT).show();
                        }
                    }

            }, new com.android.volley.Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
                }
            });

            queue.add(jsonArrayRequest);

        };

在后台解析以减少主线程的负载

private class AsyncTaskRunner extends AsyncTask<Void,Void,Void>{

        @Override
        protected Void doInBackground(Void... voids) {

            try {

                if(!run) {
                    parseApiData();
                    run=true;

                }
            }
            catch (Exception e){

                e.printStackTrace();

            }

            return null;
        }
    }
woobm2wo

woobm2wo1#

我假设你在一个班(活动)(这已经很混乱)。
这个案例我相信你已经具备了这个2出的功能

List<Book> books = new ArrayList<>();
boolean run = false;

对于parseApiData,您正在做重复的事情,这就是应该查看的内容

public void parseApiData() {

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "url", null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            if (response != null) {

                if (!books.isEmpty()) {
                    books.clear();
                   dbHandler.removeAll();
                }

                for (int i = 0; i < response.length(); i++) {

                    try {

                        JSONObject obj = response.getJSONObject(i);

                        int bookId = obj.getInt("id");

                        String bookName = obj.getString("title");

                        String bookDescription = obj.getString("description");

                        int bookPage = obj.getInt("pageCount");

                        String bookExcerpt = obj.getString("excerpt");

                        String bookPublishDate = obj.getString("publishDate");
                        Book note = new Book( bookId, bookName, bookDescription, bookPage, bookExcerpt, bookPublishDate);
                        books.add(note);

                        dbHandler.addNewCourse(note.getmBookId(), note.getmBookName(), note.getmBookDescription(), note.getmBookPage(), note.getmBookExcerpt(), note.getmBookPublishDate());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            } else {
                Toast.makeText(MainActivity.this, "Array is empty", Toast.LENGTH_SHORT).show();
            }
        }

    }, new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_SHORT).show();

        }
    });
    Volley.newRequestQueue(this).add(jsonArrayRequest);
}

对于AsyncTaskRunner

private class AsyncTaskRunner extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(Void... voids) {

            if (!run) {
                parseApiData();
                run = true;

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {
            super.onPostExecute(unused);

            progressBar.setVisibility(View.GONE);
            onConfigurationChanged(getApplicationContext().getResources().getConfiguration());
            BookAdapter adapter = new BookAdapter(MainActivity.this, books);
            recyclerView.setAdapter(adapter);

        }
    }

此处重复:

dbHandler.addNewCourse(bookId,bookName,bookDescription,bookPage,bookExcerpt,bookPublishDate);
有了这个:

new Thread(new Runnable() {
                                @Override
                                public void run() {
                               for(int j=0;j<books.size();j++)
                               {
                                   Books note=books.get(j);
                                   dbHandler.addNewCourse(note.getmBookId(),note.getmBookName(),note.getmBookDescription(),note.getmBookPage(),note.getmBookExcerpt(),note.getmBookPublishDate());
                               }
                                }
                            });

我也建议修改一下:

onConfigurationChanged(getApplicationContext().getResources().getConfiguration());
BookAdapter adapter = new BookAdapter(MainActivity.this, books);
recyclerView.setAdapter(adapter);

如果您请求API 3时间,它保持这一点,并重建为新的一次又一次
请考虑在适配器中创建函数,类似于以下内容:

void updateList(List<Book> books){
        your_list_in_adapter = books;
        notifyDataSetChanged();
    }

onPostExecute时,您只调用:

youradapter.updateList(books);

这样会更好。注意:AsyncTask,它已经过时了。请考虑更改它here

相关问题