您的位置:首页 > 数据库

请求下来的数据放到数据库中 操作

2015-07-29 22:30 232 查看
1.数据库类DBDao

/**
* 数据库管理
*/
public class DBDao {
// 数据库管理
private DbOpenHelper dbHelper = null;
private Context context = null;

public DBDao(Context context) {
this.context = context;
dbHelper = DbOpenHelper.getInstance(context);
}

/**
* 保存地区到数据库中

* @param Regionlist
*/
public void saveCategoryList(List<Category> categorylist) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
if (db.isOpen()) {
db.delete("category", null, null);
for (Category region : categorylist) {
ContentValues values = new ContentValues();
values.put("category_id", region.getCategory_id());
values.put("category_name", region.getCategory_name());
values.put("category_call_name", region.getCategory_call_name());
values.put("parent_id", region.getParent_id());
values.put("icon", region.getIcon());
values.put("bg_img", region.getBg_img());
values.put("width", region.getWidth());
values.put("height", region.getHeight());
values.put("is_show_index", region.getIs_show_index());
values.put("sort_id", region.getSort_id());
db.replace("category", null, values);
}
}

}

/**
* 获取地区列表

* @return
*/
public List<Category> getAllCategoryList() {
List<Category> list = new ArrayList<Category>();
SQLiteDatabase db = dbHelper.getReadableDatabase();
if (db.isOpen()) {
Cursor cursor = db.rawQuery("select * from  category", null);
while (cursor.moveToNext()) {
String category_id = cursor.getString(cursor
.getColumnIndex("category_id"));
String category_name = cursor.getString(cursor
.getColumnIndex("category_name"));
String category_call_name = cursor.getString(cursor
.getColumnIndex("category_call_name"));
String parent_id = cursor.getString(cursor
.getColumnIndex("parent_id"));
String icon = cursor.getString(cursor
.getColumnIndex("icon"));
String bg_img = cursor.getString(cursor
.getColumnIndex("bg_img"));
String width = cursor.getString(cursor
.getColumnIndex("width"));
String height = cursor.getString(cursor
.getColumnIndex("height"));
String is_show_index = cursor.getString(cursor
.getColumnIndex("is_show_index"));
String sort_id = cursor.getString(cursor
.getColumnIndex("sort_id"));
Category category = new Category();
category.setBg_img(bg_img);
category.setCategory_call_name(category_call_name);
category.setCategory_id(category_id);
category.setCategory_name(category_name);
category.setHeight(height);
category.setIcon(icon);
category.setIs_show_index(is_show_index);
category.setParent_id(parent_id);
category.setSort_id(sort_id);
category.setWidth(width);
list.add(category);
}
cursor.close();
}
return list;
}

/**
* 分页显示,默认每页5条数据
* @param page
* @return
*/
public List<Category> getAllCategoryListByPage(int page) {
List<Category> list = new ArrayList<Category>();
SQLiteDatabase db = dbHelper.getReadableDatabase();
if (db.isOpen()) {
Cursor cursor = db.rawQuery(
"select * from  category limit " + (page*5)+ " 5", null);
while (cursor.moveToNext()) {
String category_id = cursor.getString(cursor
.getColumnIndex("category_id"));
String category_name = cursor.getString(cursor
.getColumnIndex("category_name"));
String category_call_name = cursor.getString(cursor
.getColumnIndex("category_call_name"));
String parent_id = cursor.getString(cursor
.getColumnIndex("parent_id"));
String icon = cursor.getString(cursor
.getColumnIndex("icon"));
String bg_img = cursor.getString(cursor
.getColumnIndex("bg_img"));
String width = cursor.getString(cursor
.getColumnIndex("width"));
String height = cursor.getString(cursor
.getColumnIndex("height"));
String is_show_index = cursor.getSt
4000
ring(cursor
.getColumnIndex("is_show_index"));
String sort_id = cursor.getString(cursor
.getColumnIndex("sort_id"));
Category category = new Category();
category.setBg_img(bg_img);
category.setCategory_call_name(category_call_name);
category.setCategory_id(category_id);
category.setCategory_name(category_name);
category.setHeight(height);
category.setIcon(icon);
category.setIs_show_index(is_show_index);
category.setParent_id(parent_id);
category.setSort_id(sort_id);
category.setWidth(width);
list.add(category);
}
cursor.close();
}
return list;
}

/**
* 数据库的帮助类

*/
private static class DbOpenHelper extends SQLiteOpenHelper
{

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydb.db";
private static DbOpenHelper instance;
// 地区SQL
private static final String REGION_TABLE_CREATE = "CREATE TABLE category (id INTEGER PRIMARY KEY AUTOINCREMENT, category_id text, category_name text,category_call_name text,parent_id TEXT,icon text,bg_img text,width text
,height text,is_show_index text,sort_id text);";

private DbOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public static DbOpenHelper getInstance(Context context) {
if (instance == null) {
instance = new DbOpenHelper(context.getApplicationContext());
}
return instance;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(REGION_TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table  if exists  category");
onCreate(db);
}

public void closeDB() {
if (instance != null) {
try {
SQLiteDatabase db = instance.getWritableDatabase();
db.close();
} catch (Exception e) {
e.printStackTrace();
}
instance = null;
}
}
}
}

2.网络请求

DBDao db=new DBDao(MainActivity.this);
//取所有数据
List<Category> getPagelistData=db.getAllCategoryListByPage(1);
Log.e("数据库分页查询数据", getPagelistData.toString());

// DBDao db=new DBDao(MainActivity.this);

// //取所有数据

// List<Category> getlistData=db.getAllCategoryList();

//

//       Log.e("解析全部数据", getlistData.toString());

       

AsyncTask<String, Integer, String> asyncTask = new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... params) {
return httpService4GetString(params[0]);
}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result!=null) {//返回数据存在,解析数据
Log.e("返回数据", result);
try {
JSONObject objResult=new JSONObject(result);
String status=objResult.optString("status");
String tip=objResult.optString("tip");
JSONObject info=objResult.optJSONObject("info");
Log.e("返回数据解析数据 tip", tip);
if ("T".equals(status)) {//表示请求成功
if (info!=null) {//请求下来数据了
JSONArray category_list=info.optJSONArray("category_list");
if (category_list!=null) {//有数据
List<Category> listData=new ArrayList<Category>();
int num=category_list.length();
for (int i = 0; i < num; i++) {
JSONObject item=category_list.getJSONObject(i);
if (item!=null) {
Category category=new  Category();
category.setBg_img(item.optString("bg_img"));
category.setCategory_call_name(item.optString("category_call_name"));
category.setCategory_id(item.optString("category_id"));
category.setCategory_name(item.optString("category_name"));
category.setHeight(item.optString("height"));
category.setIcon(item.optString("icon"));
category.setIs_show_index(item.optString("is_show_index"));
category.setParent_id(item.optString("parent_id"));
category.setSort_id(item.optString("sort_id"));
category.setWidth(item.optString("width"));
listData.add(category);
}
}
if (listData.size()>0) {//解析到数据,保持到数据库
DBDao db=new DBDao(MainActivity.this);
db.saveCategoryList(listData);
//取所有数据
//List<Category> getlistData=db.getAllCategoryList();
//List<Category> getPagelistData=db.getAllCategoryListByPage(1);
}
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
};

asyncTask.execute("http://192.168.0.23:9305/webapi/shopping/goods.ashx?action=get_category&parent_id=0");

/**
* Get请求
* @param url
* @return
*/
public static String httpService4GetString(String url) {
int i = 8 * 1024;
HttpGet httpPost = new HttpGet(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
InputStream inputStream = httpEntity.getContent();
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(inputStream), i);
String returnStr = "";
String readLine = null;
while ((readLine = bufferReader.readLine()) != null) {
returnStr = returnStr + readLine;
}
inputStream.close();
bufferReader.close();
return returnStr;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}

/**
* post请求

* @param url
* @param pairs
* @return
*/
public static String postHttpService(String url,
List<BasicNameValuePair> pairs) {
DefaultHttpClient httpClient = null;
    int i = 8 * 1024;
// 请求必须参数
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type",
"application/x-www-form-urlencoded; charset=utf-8");
// DefaultHttpClient httpClient = new DefaultHttpClient();
if (httpClient == null) {
httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300000);  
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
InputStream inputStream = httpEntity.getContent();
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(inputStream), i);
String returnStr = "";
String readLine = null;
while ((readLine = bufferReader.readLine()) != null) {
returnStr = returnStr + readLine;
}
inputStream.close();
bufferReader.close();
return returnStr;
}
} else {
String errorNet = "{\"status\":{\"succeed\":\"0\",\"error_code\":\"1\",\"error_desc\":\"网络异常\"}}";
return errorNet;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: