简体   繁体   中英

Error when I run the app on my smartphone, but its correct If I run the app on Android Studio

when I run my app in Android Studio, everything run correctly. The ListView in drawer is correctly populated by run a RushSearch() query. But when I have created the apk and I installed on my smartphone to try run the app, the ListView in Drawer at the first run doesn't populated. If I close the app and run it again, everything is correct.

Why this anomaly?

The code for onCreate method on MainActivity.java class is this

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    callWebservice();

    // Layout principale col drawer
    setContentView(R.layout.activity_main_drawer);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    leftArrow = (ImageView) findViewById(R.id.left_arrow);
    titolo = (TextView) findViewById(R.id.titolo_id);

    ActionBarDrawerToggle actionBarDrawerToggle =
            new ActionBarDrawerToggle(this, drawerLayout, toolbar,
                    R.string.navigation_drawer_open, R.string.navigation_drawer_close);

    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();

    drawerListView = (ListView) findViewById(R.id.drawer_listView);

    // SELECT * FROM Sections where Fk == 0;
    sectionsList = new RushSearch().whereEqual("Fk", 0).find(Sections.class);
    Log.d("ELEMENTI",""+sectionsList.size());
    drawerListViewAdapter = new DrawerListViewAdapter(sectionsList, getApplicationContext());

    // Adapter che si occupa di popolare il drawer
    drawerListView.setAdapter(drawerListViewAdapter);


    // Listner per il click su un elemento del drawer
    drawerListView.setOnItemClickListener(click);
}

The method callWebservice() is responsabile to take a JSON file from an url and its code is this

private void callWebservice() {

    String tag_json_obj = "GetItem";
    String url = String.format("http://digitalbox.getsandbox.com/item");
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {
                saveSections(response.getJSONArray("Sections"));

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Settings", "Error: " + error.getMessage());
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");
            return headers;
        }
    };
    NetworkController.getInstance().addToRequestQueue(jsonObjectRequest, tag_json_obj);
}

private void saveSections(final JSONArray section) {

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {


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

                try {
                    JSONObject obj = section.getJSONObject(i);

                    Sections s = new RushSearch().whereEqual("ID", obj.getInt("ID")).findSingle(Sections.class);
                    if (s == null) {
                        s = new Sections();
                        s.setID(obj.getInt("ID"));
                    }

                    if (!obj.isNull("Fk"))
                        s.setFk(obj.getInt("Fk"));

                    s.setTitle(obj.getString("Title"));

                    if (!obj.isNull("CategoryColor"))
                        s.setCategoryColor(obj.getString("CategoryColor"));

                    s.setPos(obj.getInt("Pos"));
                    s.setLanguageId(obj.getInt("LanguageId"));
                    s.setUnavailableForSend(obj.getBoolean("UnavailableForSend"));

                    s.save();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            Log.d("sections", "DB updated");


        }
    });
    t.setPriority(Thread.MIN_PRIORITY);
    t.start();
}

If I run the app with Android Studio, in an AVD smartphone, I have this log

    11-30 15:21:53.520 2170-2170/? I/art: Not late-enabling -Xcheck:jni (already on)
11-30 15:21:53.520 2170-2170/? I/art: Late-enabling JIT
11-30 15:21:53.558 2170-2170/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-30 15:21:53.685 2170-2170/rawpepper.it.digitalbox W/System: ClassLoader referenced unknown path: /data/app/rawpepper.it.digitalbox-2/lib/x86
11-30 15:21:54.099 2170-2170/rawpepper.it.digitalbox W/art: Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
11-30 15:21:54.469 2170-2170/rawpepper.it.digitalbox D/ELEMENT: 13
11-30 15:21:54.486 2170-2210/rawpepper.it.digitalbox D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-30 15:21:54.592 2170-2210/rawpepper.it.digitalbox I/OpenGLRenderer: Initialized EGL, version 1.4
11-30 15:21:54.719 2170-2210/rawpepper.it.digitalbox W/EGL_emulation: eglSurfaceAttrib not implemented
11-30 15:21:54.719 2170-2210/rawpepper.it.digitalbox W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad6fc2e0, error=EGL_SUCCESS
11-30 15:21:57.542 2170-2204/rawpepper.it.digitalbox D/Volley: [117] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://digitalbox.getsandbox.com/item 0x95b78f5f NORMAL 1> [lifetime=3034], [size=196862], [rc=200], [retryCount=0]
11-30 15:21:57.691 2170-2180/rawpepper.it.digitalbox W/art: Suspending all threads took: 25.964ms
11-30 15:21:57.909 2170-2405/rawpepper.it.digitalbox D/sections: DB updated

that tells me that the number of elements in sectionList array are 13 (sixth row), that is correct. app run with Android Studio If I create the apk and I install it on my smartphone, and I plug this on pc to check the log when I run the app, I have this log

    11-30 15:35:01.765 17183-17183/rawpepper.it.digitalbox I/art: Late-enabling -Xcheck:jni
11-30 15:35:01.883 17183-17183/rawpepper.it.digitalbox W/System: ClassLoader referenced unknown path: /data/app/rawpepper.it.digitalbox-2/lib/arm
11-30 15:35:02.357 17183-17183/rawpepper.it.digitalbox W/art: Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
11-30 15:35:03.235 17183-17183/rawpepper.it.digitalbox D/ELEMENT: 0
11-30 15:35:03.249 17183-17260/rawpepper.it.digitalbox D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-30 15:35:03.304 17183-17260/rawpepper.it.digitalbox I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 09/02/15, 76f806e, Ibddc658e36
11-30 15:35:03.306 17183-17260/rawpepper.it.digitalbox I/OpenGLRenderer: Initialized EGL, version 1.4
11-30 15:35:05.976 17183-17321/rawpepper.it.digitalbox D/sections: DB updated

that tells me that the elements in sectionList array are 0, but if I close and run it again, everything is correct.

You need to set up the drawer after the data is downloaded. For example by calling saveDate() when downloading a new section and setUpDraw() in onCreate().

private void saveData(Sections newSections) {
    newSections.save()
    setUpDraw()
}

private void setUpDraw() {

    drawerListView = (ListView) findViewById(R.id.drawer_listView);
    sectionsList = new RushSearch().whereEqual("Fk", 0).find(Sections.class);
    drawerListViewAdapter = new DrawerListViewAdapter(sectionsList, context); // You don't want application context
    drawerListView.setAdapter(drawerListViewAdapter);
    drawerListView.setOnItemClickListener(click);
}

I think you should call this part of your code:

// SELECT * FROM Sections where Fk == 0;
sectionsList = new RushSearch().whereEqual("Fk", 0).find(Sections.class);
Log.d("ELEMENTI",""+sectionsList.size());
drawerListViewAdapter = new DrawerListViewAdapter(sectionsList, getApplicationContext());

// Adapter che si occupa di popolare il drawer
drawerListView.setAdapter(drawerListViewAdapter);

After the saveSections() method completes. Something like this:

private void callWebservice() {

String tag_json_obj = "GetItem";
String url = String.format("http://digitalbox.getsandbox.com/item");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        try {
            saveSections(response.getJSONArray("Sections"));
// SELECT * FROM Sections where Fk == 0;
sectionsList = new RushSearch().whereEqual("Fk", 0).find(Sections.class);
Log.d("ELEMENTI",""+sectionsList.size());
drawerListViewAdapter = new DrawerListViewAdapter(sectionsList, getApplicationContext());

// Adapter che si occupa di popolare il drawer
drawerListView.setAdapter(drawerListViewAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}, new Response.ErrorListener() {
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d("Settings", "Error: " + error.getMessage());
    }
}) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        HashMap<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");
        return headers;
    }
};
NetworkController.getInstance().addToRequestQueue(jsonObjectRequest, tag_json_obj);

}

I have modified my code, now I have this code for the onCreate() method

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        callWebservice();

//        setContentView(R.layout.activity_main);

        // Layout principale col drawer
        setContentView(R.layout.activity_main_drawer);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        leftArrow = (ImageView) findViewById(R.id.left_arrow);
        titolo = (TextView) findViewById(R.id.titolo_id);

        ActionBarDrawerToggle actionBarDrawerToggle =
                new ActionBarDrawerToggle(this, drawerLayout, toolbar,
                        R.string.navigation_drawer_open, R.string.navigation_drawer_close);

        drawerLayout.setDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();

        drawerListView = (ListView) findViewById(R.id.drawer_listView);
        setupDrawer();

    }

where the setupDrawer() method is

private void setupDrawer() {
        // SELECT * FROM Sections where Fk == 0;
        sectionsList = new RushSearch().whereEqual("Fk", 0).find(Sections.class);
        Log.d("ELEMENT", "" + sectionsList.size());
        drawerListViewAdapter = new DrawerListViewAdapter(sectionsList, getApplicationContext());

        // Adapter che si occupa di popolare il drawer
        drawerListView.setAdapter(drawerListViewAdapter);

        // Listner per il click su un elemento del drawer
        drawerListView.setOnItemClickListener(click);
    }

If I call this method from onCreate() or from callWebservice() after saveSections(response.getJSONArray("Sections")); in try-catch, I have the same problem.

Ok Man. Try this:

private void callWebservice() {
    String tag_json_obj = "GetItem";
    String url = String.format("http://digitalbox.getsandbox.com/item");
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {
                new SaveData().execute(response.getJSONArray("Sections"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("Settings", "Error: " + error.getMessage());
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Accept", "application/json");
            return headers;
        }
    };
    NetworkController.getInstance().addToRequestQueue(jsonObjectRequest, tag_json_obj);
}

Then add this inner class inside your activity:

private final class SaveData extends AsyncTask<JSONArray, Void, Void> {
    protected Void doInBackground(JSONArray... params) {
        int c = section.length();
        for (int i = 0; i < c; i++) {

            try {
                JSONObject obj = section.getJSONObject(i);

                Sections s = new RushSearch().whereEqual("ID", obj.getInt("ID")).findSingle(Sections.class);
                if (s == null) {
                    s = new Sections();
                    s.setID(obj.getInt("ID"));
                }

                if (!obj.isNull("Fk"))
                    s.setFk(obj.getInt("Fk"));

                s.setTitle(obj.getString("Title"));

                if (!obj.isNull("CategoryColor"))
                    s.setCategoryColor(obj.getString("CategoryColor"));

                s.setPos(obj.getInt("Pos"));
                s.setLanguageId(obj.getInt("LanguageId"));
                s.setUnavailableForSend(obj.getBoolean("UnavailableForSend"));

                s.save();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        Log.d("sections", "DB updated");
        return null;
    }

    public void onPostExecute(Void result) {
        sectionsList = new RushSearch().whereEqual("Fk", 0).find(Sections.class);
        Log.d("ELEMENTI",""+sectionsList.size());
        drawerListViewAdapter = new DrawerListViewAdapter(sectionsList, getApplicationContext());
    }
}

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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