使用背景线程Android中的Realm一次存储所有信息

时间:2017-09-12 08:25:04

标签: android multithreading realm realm-mobile-platform background-thread

我正在开发一个Android应用程序,我使用Relam作为本地数据库。我有一个用于所有用户信息的api,另一个用于新闻信息。我有两个按钮。一个用于显示用户信息,另一个用于显示新闻信息。现在,用我的代码做了什么,登录后,我首先需要点击按钮获取用户信息和新闻信息然后我可以看到那些图像和新闻。但如果我在登录后关闭,则数据不会显示在视图中。我正在详细解释我的代码。我也在图像加载方面遇到问题。如何实现功能,以便用户可以在登录后获取所有信息。我非常抱歉这么长的代码。如果有人告诉我如何修改我的代码以将所有数据存储在后台线程中,那么对我来说真的很有用,这样用户只需在登录后获取所有信息。

我要开始的登录页面部分

private void loginUser(final String mEmail, final String mPassword) {

    final GlobalClass globalClass = new GlobalClass();
    globalClass.setEmail_info( mEmail );

    setFilePath();

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

    StringRequest strReq = new StringRequest( Request.Method.POST,
            LOGIN_URL, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d( TAG, "Register Response: " + response.toString() );

            //parse your response here
            if (response.contains( "overview" )) {
                showProgress( true );

                globalClass.setImage_urlpath( Constants.HTTP.PHOTO_URL + mEmail);
                String str = globalClass.readDatafromStorage();
                Log.d("----After Login---",str);

               if ( !str.contains("ACTIVATE") ) {
                   Log.d( "----After Login---", "After Login" );

                }

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(KEY_EMAIL, mEmail);
                editor.putString(KEY_PASSWORD, mPassword);
                editor.commit();

                showProgress(false);
                Intent loginIntent = new Intent(LoginPage.this, MainOptionPage.class);
                loginIntent.putExtra(KEY_EMAIL, mEmail);
                startActivity(loginIntent);

            } else {
                userEmail.setError(getString(R.string.error_incorrect_login));
                userEmail.requestFocus();

            }
        }

    }, new Response.ErrorListener() {
        @Override
       ....

这是我的用户页面代码

    public class MyColleaguesPage extends AppCompatActivity implements ColleagueController.UserCallbackListener {

     private List<MyColleagueModel> myColleagueList = new ArrayList<>();

    private Realm colleagueRealm;
    private RealmResults<MyColleagueModel> colleagueResult;

    private List<MyColleagueModel> filteredModelList;
    private RealmChangeListener realmListener;
    private static final String DIALOG_TAG = "EmployeeDialog";

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



        configViews();

    }

    private void configViews() {
        recyclerView = this.findViewById(R.id.colleagues_recycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
        recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());

        colleagueRealm = Realm.getDefaultInstance();

        RealmResults<MyColleagueModel> results = colleagueRealm.where(MyColleagueModel.class).findAll();

        for (int i = 0; i < results.size(); i++) {

            myColleagueList.add(results.get(i));
        }
        adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
        //adapter = new MyColleaguesAdapter(myColleagueList,getApplicationContext());
        Log.d( "adapter value is"+"", String.valueOf( adapter ) );
        recyclerView.setAdapter(adapter);
    }


    //successful
    @Override
    public void onFetchStart() {

    }

    @Override
    public void onFetchProgress(ColleagueModel colleague) {
        //adapter.addColleague(colleague);
    }

    @Override
    public void onFetchProgress(List<ColleagueModel> colleagueList) {

    }

    @Override
    public void onFetchComplete() {

    }

    @Override
    public void onFetchFailed() {

    }
   }

这是我的同事页面的控制器类

    public class ColleagueController {

    private static final String TAG = ColleagueController.class.getSimpleName();
    private UserCallbackListener mListener;
    private ColleagueResApiManager mApiManager;


    Realm myColleague_realm;    
    public ColleagueController() {
        mApiManager = new ColleagueResApiManager();
    }


public void startFetching(){
    myColleague_realm = Realm.getDefaultInstance();

    mApiManager.getColleagueApi().getColleague(new Callback<String>() {
        @Override
        public void success(String s, Response response) {
            Log.d(TAG, "JSON :: " + s);
            try {
                JSONArray array = new JSONArray(s);

                for(int i = 0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    Log.d("-----Start Fetching---", object.optString( "name" ));

                        myColleague_realm.beginTransaction();
                        MyColleagueModel mycolleague = myColleague_realm.createObject( MyColleagueModel.class );

                       mycolleague.setName( object.optString( "name" ) );
                       .... data  ) );



                    myColleague_realm.commitTransaction();

                }

            } catch (JSONException e) {
                mListener.onFetchFailed();
            }

           // mListener.onFetchComplete();
        }
        @Override
        public void failure(RetrofitError error) {
            Log.d(TAG, "Error :: " + error.getMessage());
            if (mListener != null) {
                mListener.onFetchComplete();
            }
        }
    });

}




    public interface UserCallbackListener{

        void onFetchComplete();
        void onFetchFailed();
    }
}

以同样的方式,我有其他页面新闻选项页面,我正在显示新闻数据。这是我的新闻页面。

    public class NewsPage extends AppCompatActivity{

    private RecyclerView recyclerView;
    private NewsAdapter adapter;
    private Realm newsRealm;


    private List<NewsRealmModel> mNewsList;
    private List<NewsRealmModel> filteredModelList;

    private NewsController mController;

    Constant constant;
    SharedPreferences app_preferences;
    int appTheme;
    int themeColor;
    int appColor;

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



        configViews();

    }

    private void configViews() {
        recyclerView = this.findViewById(R.id.news_recycler);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(NewsPage.this));
        recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());

        Realm newsRealm = Realm.getDefaultInstance();
        RealmResults<NewsRealmModel> temp = newsRealm.where(NewsRealmModel.class).findAll();
        mNewsList = new ArrayList<>();
        for (int i = 0; i < temp.size(); i++) {

            mNewsList.add(temp.get(i));
        }

        adapter = new NewsAdapter(mNewsList,getApplicationContext());
        Log.d( "adapter value is"+"", String.valueOf( adapter ) );
        recyclerView.setAdapter(adapter);
     }


   } 

新的控制器类

public class NewsController {
private static final String TAG = NewsController.class.getSimpleName();
private UserCallbackListener mListener;
private NewsRestApiManager mApiManager;
private AppImage appImages;

Realm myNews_realm;
ArrayList<String> title_list = new ArrayList<>();
GlobalClass globalClass = new GlobalClass();

public NewsController(UserCallbackListener listener) {
    mListener = listener;
    mApiManager = new NewsRestApiManager();
}


public void startFetching() {
    myNews_realm = Realm.getDefaultInstance();
    mApiManager.getNewsApi().getNews(new Callback<String>() {

        @Override
        public void success(String s, Response response) {
            Log.d(TAG, "JSON :: " + s);

            try {
                JSONArray array = new JSONArray(s);

                for (int i = 0; i < array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);
                    Log.d("-----Start Fetching---", jsonObject.optString("title"));

                    if (!myNews_realm.isInTransaction()) {

                        myNews_realm.beginTransaction();

                        NewsRealmModel news = new NewsRealmModel();
                       ....... data 
                        }

                        myNews_realm.copyToRealm(news);
                        myNews_realm.commitTransaction();

                        mListener.onFetchProgressNews(news);

                    } else {
                        myNews_realm.commitTransaction();
                    }


                }
            } catch (JSONException e) {
                mListener.onFetchFailed();
            }

            mListener.onFetchComplete();
        }

        @Override
        public void failure(RetrofitError error) {
            Log.d(TAG, "Error :: " + error.getMessage());
            mListener.onFetchComplete();
        }
    });

}
public interface UserCallbackListener {


    void onFetchProgressNews(NewsRealmModel news);



    void onFetchComplete();

    void onFetchFailed();
}

}

1 个答案:

答案 0 :(得分:0)

要使用Volley在后台线程上进行数据库处理,您需要扩展Request<T>并使用parseNetworkResponse方法编写Realm。

public class RealmGsonObjectRequest<T, M extends RealmModel> extends Response<Void> {
  ...
  @Override
  protected Response<Void> parseNetworkResponse(
                            NetworkResponse response) {
    try {
      String json = new String(response.data,
          HttpHeaderParser.parseCharset(response.headers));
      T data = gson.fromJson(json, clazz);

      // write the downloaded data into the Realm on bg thread
      try(Realm r = Realm.getDefaultInstance()) {
        M model = mapper.toModel(data);
        r.executeTransaction((realm) -> {
          realm.insertOrUpdate(model);
        });
      }

      return Response.success(null,
         HttpHeaderParser.parseCacheHeaders(response)
      );
    } // handle errors
}

您可能还需要RealmGsonListRequest

public class RealmGsonListRequest<T, M extends RealmModel> extends Response<Void> {
  ...
  @Override
  protected Response<Void> parseNetworkResponse(
                            NetworkResponse response) {
    try {
      String json = new String(response.data,
          HttpHeaderParser.parseCharset(response.headers));
      List<T> data = gson.fromJson(json, new TypeToken<ArrayList<T>>() {}.getType());

      // write the downloaded data into the Realm on bg thread
      try(Realm r = Realm.getDefaultInstance()) {
        M model = mapper.toModel(data);
        r.executeTransaction((realm) -> {
          realm.insertOrUpdate(model);
        });
      }

      return Response.success(null,
         HttpHeaderParser.parseCacheHeaders(response)
      );
    } // handle errors
}

有关详细信息,请参阅official Volley tutorial on how to create a custom Volley request type