例题数据库

来源:互联网 发布:无3c被淘宝下架了宝贝 编辑:程序博客网 时间:2024/05/16 10:35

package com.bawei;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import bean.Items;
import bean.Student;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.widget.ListView;

public class ShowMainActivity extends Activity {
private ListView lv;
private SQLiteDatabase database;
List list=new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_main);
lv=(ListView) findViewById(R.id.lv);
//得到解析文件
String str=Environment.getExternalStorageDirectory()+”/”+”cardata.json”;
try {
File file=new File(str);
FileReader reader=new FileReader(file);
//解析
Gson gson=new Gson();
Student student = gson.fromJson(reader, Student.class);
List items = student.getData().getItems();
//添加到数据库
MySQLiteDatabase mySQLiteDatabase = new MySQLiteDatabase(ShowMainActivity.this);
//得到数据库
database=mySQLiteDatabase.getReadableDatabase();
for (Items items2 : items) {
ContentValues values=new ContentValues();
values.put(“brand”, items2.getBrand());
values.put(“name”, items2.getName());
values.put(“price”, items2.getPrice());
database.insert(“student”, null, values);

        }        //关闭数据库        database.close();        reader.close();        //查找        database=mySQLiteDatabase.getReadableDatabase();        Cursor cursor=database.query("student", new String[]{"brand","name","price"}, null, null, null,null, null);        while (cursor.moveToNext()) {            String brand=cursor.getString(cursor.getColumnIndex("brand"));            String name=cursor.getString(cursor.getColumnIndex("name"));            String price=cursor.getString(cursor.getColumnIndex("price"));            Items tItems3=new Items();            tItems3.setBrand(brand);            tItems3.setName(name);            tItems3.setPrice(price);                list.add(tItems3);        }        //关闭数据库        database.close();        //适配器        lv.setAdapter(new Mydater(list,ShowMainActivity.this));    } catch (JsonSyntaxException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (JsonIOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (FileNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } }

}

0 0
原创粉丝点击