无法将数据从会议室数据库获取到Spinner

时间:2019-08-19 07:30:53

标签: java android android-volley android-spinner android-room

该应用程序将从api.github.com/users中获取数据并反映在微调器上

我正在Splash.java上的日志中获取数据,但无法反映Home.java上的数据

MyAppDatabase.java

@Database(entities = {Users.class}, version = 1, exportSchema = false)
public abstract class MyAppDatabase extends RoomDatabase {
        public abstract MyDao myDao();
    }

MyDao.java

@Dao
    public interface MyDao {

        @Insert(onConflict = OnConflictStrategy.REPLACE)
        void addUsers(Users users);

        @Query("SELECT * FROM Users")
        List<Users> getUsers();

        @Query("SELECT node_id FROM Users")
        List<String> getNodeId();

    }

getData() on Splash.java

   public class Splash extends AppCompatActivity {

    MyAppDatabase myAppDatabase;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class, "MyDao").allowMainThreadQueries().build();


                //get data from webservice and store locally

                getData();
            }
        }, 500);
    }

    private void getData() {
        //Creating a string request
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                Log.e("response", response.toString());
                response.length();
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        Users users = new Users();

                        //Set fields in Users object.

                        users.setLogin(jsonObject.getString(Config.TAG_Login));
                        users.setId(jsonObject.getString(Config.TAG_Id));
                        users.setNode_id(jsonObject.getString(Config.TAG_Node));
                        users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
                        users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
                        users.setUrl(jsonObject.getString(Config.TAG_url));
                        users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
                        users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
                        users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
                        users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
                        users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
                        users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
                        users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
                        users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
                        users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
                        users.setType(jsonObject.getString(Config.TAG_Type));
                        users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
                        users.setEvents_url(jsonObject.getString(Config.TAG_events_url));

                        myAppDatabase.myDao().addUsers(users);

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

                Intent intent = new Intent(Splash.this, Home.class);
                // intent.putExtra("remember", "true");
                startActivity(intent);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley", error.toString());
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(jsonArrayRequest);
    }
}

putData() on Home.java

  public class Home extends AppCompatActivity {

    MyAppDatabase myAppDatabase;

    //To add into spinner
    private ArrayList<String> userType;

    //List of users from Db
    List<Users> users;

    private  Spinner spinner;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        userType = new ArrayList<>();

        spinner = findViewById(R.id.sp_user_type);

        myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class,"UsersDb").allowMainThreadQueries().build();
        //get data from Db and put into arrayList for spinner

        putData();
    }

    private void putData() {

        users =myAppDatabase.myDao().getUsers();
        userType.add("Select UserType"); //Dummy addition

        for(int i = 0; i < users.size(); i++){
            userType.add(users.get(i).getType());
            Log.e("DistNames",users.get(i).getType());
        }

        users.size();
        spinner.setAdapter(new ArrayAdapter<>(Home.this, android.R.layout.simple_spinner_dropdown_item, userType));
    }
}

1 个答案:

答案 0 :(得分:0)

因为您是在循环本身中开始活动,所以实际上应该在循环之外。

实际上,您所犯的错误是它将在第一次迭代中启动Home活动,因此您不会从API响应中获取所有数据。为了解决这个问题,让循环遍历每个条目并添加到数据库中,并在完成时开始活动,如此循环之外。

错误:

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                Log.e("response", response.toString());
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        Users users = new Users();

                        //Set fields in Users object.

                        users.setLogin(jsonObject.getString(Config.TAG_Login));
                        users.setId(jsonObject.getString(Config.TAG_Id));
                        users.setNode_id(jsonObject.getString(Config.TAG_Node));
                        users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
                        users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
                        users.setUrl(jsonObject.getString(Config.TAG_url));
                        users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
                        users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
                        users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
                        users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
                        users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
                        users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
                        users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
                        users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
                        users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
                        users.setType(jsonObject.getString(Config.TAG_Type));
                        users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
                        users.setEvents_url(jsonObject.getString(Config.TAG_events_url));

                        myAppDatabase.myDao().addUsers(users);

                      Intent intent = new Intent(Splash.this, Home.class);
//                        intent.putExtra("remember", "true");
                        startActivity(intent);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley", error.toString());
            }
        });

正确:

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                Log.e("response", response.toString());
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        Users users = new Users();

                        //Set fields in Users object.

                        users.setLogin(jsonObject.getString(Config.TAG_Login));
                        users.setId(jsonObject.getString(Config.TAG_Id));
                        users.setNode_id(jsonObject.getString(Config.TAG_Node));
                        users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
                        users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
                        users.setUrl(jsonObject.getString(Config.TAG_url));
                        users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
                        users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
                        users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
                        users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
                        users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
                        users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
                        users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
                        users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
                        users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
                        users.setType(jsonObject.getString(Config.TAG_Type));
                        users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
                        users.setEvents_url(jsonObject.getString(Config.TAG_events_url));

                        myAppDatabase.myDao().addUsers(users);

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

                Intent intent = new Intent(Splash.this, Home.class);
                // intent.putExtra("remember", "true");
                startActivity(intent);

            }               
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley", error.toString());
            }
        });