dimanche 20 septembre 2015

Realm database - how do I structure my Android application

I have an application where I want to search for a book using ISBN and display it on the screen. The Book objects are stored in a Realm database with ISBN as primary key. If they are not stored in the database, they are retrieved asynchronously (ASyncTask) from a server and then stored in the database.

Now, I am unfamiliar with Realm and how to use it.

In the code below, would ViewBookActivity and MainController run on the same thread, and therefore use the same database instance? Would returning a Realm object from a "static class" be a problem?

How can I guarantee that calling MainController.getBook() always returns a book? The way it works now, is that when getBook is called and the book is not in the database, it returns null.

Is a changelisteners in each Activity that uses the MainController the only way? I want to avoid, if possible, to use/reference Realm at all in the activities and make them get objects through the MainController instead.

public class RealmActivity extends Activity {
    private Realm realm;

    @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();
        Realm.deleteRealm(realmConfiguration); // Clean slate
        Realm.setDefaultConfiguration(realmConfiguration); // Make this Realm the default
    }

    @Override
     protected void onDestroy() {
        super.onDestroy();
    }
}

public class ViewBookActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        ISBN = intent.getStringExtra("ISBN");
        setContentView(R.layout.activity_scan_result);
        setBook(ISBN);
    }

    public void setBook(String ISBN) {
        Book b = MainController.getBook(ISBN);
        // Display book on screen
    }
}

public class MainController {
    static Realm realm = Realm.getDefaultInstance();

    public static Book getBook(String isbn) {
        Book book = realm.where(Book.class)
                .equalTo("isbn", isbn)
                .findFirst();
        if (book == null) {
            NetworkController.getBook(bookId);
        } else {
            return book;
        }
        return null;
    }
}

public class NetworkController {
    public static void getBook(String isbn) {
        NetworkHelper.sendRequest(HTTPRequestMethod.GET,
                "/books/" + isbn, bookHandler);
    }
}


public class NetworkHelper {
    private static String host = "http://ift.tt/1V44PC9";
    public static void sendRequest(final HTTPRequestMethod requestMethod, final String route, final ResponseHandler responseHandler) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void doInBackground(Void... params) {
                try {
                    URL url = new URL(host + "/api" + route);
                    Log.d("NETDBTEST", "NetworkHelper request: " + requestMethod.toString() + " URL: " + url.toString());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.connect();

                    BufferedReader bReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    StringBuilder builder = new StringBuilder();
                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        builder.append(line).append("\n");
                    }
                    String jsonString = builder.toString();
                    responseHandler.handleJsonResponse(jsonString);
                return null;
                }
            }
        }.execute();
    }
}

public class BookHandler implements ResponseHandler {
    @Override
    public void handleJsonResponse(String jsonString) {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.createOrUpdateObjectFromJson(Book.class, jsonString);
        realm.commitTransaction();
        realm.close();
    }
}

Aucun commentaire:

Enregistrer un commentaire