我有一个应用程序,我希望有离线功能,我使用改造,目前通过Dataadapter处理列表视图中的json显示的网络,我已经创建了一个数据库处理程序来创建sqlitedata来存储数据。
两个问题: 1.在我的改装服务调用成功获取数据后如何保存数据?
我看了很多,但看到没有教程或任何有用的答案用sqlite进行改造?
POJO班
public class Datum implements Serializable
{
@SerializedName("id")
@Expose
private String id;
@SerializedName("sku")
@Expose
private String sku;
@SerializedName("title")
@Expose
private String title;
@SerializedName("description")
@Expose
private String description;
@SerializedName("list_price")
@Expose
private String listPrice;
}
SQLDATABASE
public class SQLLiteDatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Gousto Products";
private static final String TABLE_PRODUCTS = "Products";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_DESCRIPTION = "description";
private static final String KEY_LIST_PRICE = "listPrice";
public SQLLiteDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "("
+ KEY_ID + " STRING PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_LIST_PRICE + " TEXT," + KEY_DESCRIPTION + " TEXT" + ")";
db.execSQL(CREATE_PRODUCTS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new
public void addProduct(Datum product) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, product.getTitle()); // title
values.put(KEY_DESCRIPTION, product.getDescription()); // description
values.put(KEY_LIST_PRICE, product.getListPrice()); //listprice
// Inserting Row
db.insert(TABLE_PRODUCTS, null, values);
db.close(); // Closing database connection
}
// Getting single
Datum getProduct(String id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PRODUCTS, new String[] { KEY_ID,
KEY_TITLE, KEY_DESCRIPTION, KEY_LIST_PRICE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
assert cursor != null;
Datum product = new Datum(cursor.getString(0),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return
return product;
}
// Getting All
public List<Datum> getAllProducts() {
List<Datum> productList = new ArrayList<Datum>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_PRODUCTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.close();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Datum product = new Datum();
product.setId(cursor.getString(0));
product.setTitle(cursor.getString(1));
product.setDescription(cursor.getString(2));
product.setListPrice(cursor.getString(3));
// Adding to list
productList.add(product);
} while (cursor.moveToNext());
}
// return list
return productList;
}
// Updating single
public int updateProduct(Datum product) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, product.getTitle()); // title
values.put(KEY_DESCRIPTION, product.getDescription()); // description
values.put(KEY_LIST_PRICE, product.getListPrice()); //listprice
// updating row
return db.update(TABLE_PRODUCTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(product.getId()) });
}
// Getting Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_PRODUCTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
MainActivty
public class MainActivity extends AppCompatActivity {
private ListView listView;
private List<Datum> productList;
private DataAdapter dataAdapter;
SQLLiteDatabaseHandler db = new SQLLiteDatabaseHandler(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
loadJson();
}
private void initViews(){
productList = new ArrayList<>();
/**
* Getting List and then set Adapter
*/
listView = (ListView) findViewById(R.id.productListView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Convert Image to byte Array
String strImage = productList.get(position).getImages().get500().getSrc();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("imageView", strImage);
intent.putExtra("description", productList.get(position).getDescription());
intent.putExtra("price", "£ " + productList.get(position).getListPrice());
intent.putExtra("title", productList.get(position).getTitle());
try {
intent.putExtra("category", "Category: " + productList.get(position).getCategories().get(position).getTitle());
} catch (Exception e) {
e.printStackTrace();
}
startActivity(intent);
}
});
}
private void loadJson() {
final ProgressDialog dialog;
/**
* Progress Dialog for User Interaction
*/
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle(getString(R.string.dialogTitle));
dialog.setMessage(getString(R.string.dialogMessage));
dialog.show();
ApiInterface api = RetroClient.getApiService();
Call<GustoProducts> call = api.getProductList();
call.enqueue(new Callback<GustoProducts>() {
@Override
public void onResponse(Call<GustoProducts> call, Response<GustoProducts> response) {
dialog.dismiss();
if (response.isSuccessful()){
/**
* Got Data successfully
*/
productList = response.body().getData();
dataAdapter = new DataAdapter(MainActivity.this, productList);
listView.setAdapter(dataAdapter);
}
}
@Override
public void onFailure(Call<GustoProducts> call, Throwable t) {
}
});
}
}