Yog Yog - 12 days ago 6
Android Question

How to retrieve value from server and save it in sqlite and to display it instantly?

I am having one doubt am fetching records from server using volley and saving it in sqlite and setting adapter by querying getlist but it is not displaying the result instantaneously I need to go back and come again to see the newly updated data how to display that record instantly after inserting it in sqlite let me post my code:

Here is the volley code for fetching records from server:

JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, params[0], new JSONObject(),
new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
String server_response = response.toString();
try {
JSONObject json_object = new JSONObject(server_response);
JSONArray json_array = new JSONArray(json_object.getString("AccountPageLoadAccountListResult"));
for (int i = 0; i < json_array.length(); i++) {
Model_Account modelobjs = new Model_Account();
JSONObject json_arrayJSONObject = json_array.getJSONObject(i);
modelobjs.setCompany_group(json_arrayJSONObject.getString("CompanyName"));
modelobjs.setState(json_arrayJSONObject.getString("Region"));
account_sf_db.InsertorUpdate(modelobjs);


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

}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), error.toString(), Toast.LENGTH_SHORT).show();

}
});
queue.add(jsonObjRequest);


Here is the adapter where am setting adapter from sqlite android:

List<ModelClass>listobj=new Arraylist<Modelclass>();
listobj=account_sf_db.list();
accountListAdapter = new AccountListAdapter(listobj, getApplicationContext());
recyclerView.setAdapter(accountListAdapter);


Purpose for this is to handle offline capability even during offline we must access it using sqlite

Answer

When creating your database table in Sqlite you need to add a notifyChange with the URI associated with the database table.

Here's an example how I did it in my code.

I had to declare a URI for my database table like this:

// These are just some constants
public static final String DB_NAME = "mydatabase";
private static final int DATABASE_VERSION = 1;
public static final String ApplicationPackage = "com.example.myapp";
public static final String DB_TABLE_ACCOUNTS = "accounts";

// This is the URI of the database table
public static final Uri DB_TABLE_ACCOUNTS_URI = Uri
            .parse("sqlite://" + Constants.ApplicationPackage + "/" + DB_TABLE_ACCOUNTS);

Now when I'm creating a database table entry with a function, the function looks like this.

public void createAccounts(Account mNewAccount) {
    SQLiteDatabase db = null;

    try {
        DataBaseOpenHelper dOpenHelper;
        dOpenHelper = new DataBaseOpenHelper(context,DB_NAME,DATABASE_VERSION);

        ContentValues values = new ContentValues();
        values.put("account_name", mNewAccount.getAccountName());
        values.put("account_number", mNewAccount.getAccountNumber());
        db = dOpenHelper.getWritableDatabase();
        db.insert(DBConstants.DB_TABLE_ACCOUNTS, null, values);

        // Here you notify the change when the database is updated
        context.getContentResolver().notifyChange(DB_TABLE_ACCOUNTS_URI, null);

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

Now here's the DataBaseOpenHelper.java

public class DataBaseOpenHelper extends SQLiteOpenHelper {

    private int newVersion;
    private String name;

    public DataBaseOpenHelper(Context context, String name, int version) {
        super(context, name, null, version);
        this.newVersion = version;
        this.name = name;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table if not exists "
                + DBConstants.DB_TABLE_ACCOUNTS
                + "(_id integer primary key autoincrement, account_number text not null, "
                + "account_name text)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

Now when you query your database table from your Activity or Fragment you need to registerContentOberver in your onCreateLoader if you're using LoaderManager.LoaderCallBacks<Cursor> like this:

Cursor cursor = DataHelper.getInstance(getActivity()).getAccounts();
this.registerContentObserver(cursor, DB_TABLE_ACCOUNTS_URI);

So you need to load the data again from your Sqlite database to reinitialize your listobj when response returned from the server. And then call accountListAdapter.notifyDataSetChanged().

Comments