数据库

//创建数据库

public class Sql extends SQLiteOpenHelper {
    public Sql(Context context) {
        super(context, "User.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table user(id integer primary key      autoincrement,"+"name text,"+"img text)");
    }

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

    }

}
//UserDao里面

package ningjiaxin1.bwie.com.lian;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

    public class UserDao {
        private Sql sql;
        private SQLiteDatabase database;
        public UserDao(Context context){
            sql=new Sql(context);
           database=sql.getReadableDatabase();
        }
        //添加到数据库
        public void add(String name,String img){
            ContentValues values = new ContentValues();
            values.put("name",name);
            values.put("img",img);
            database.insert("user", null, values);
        }
        //查询数据库
        public List select(){
            Cursor query = database.query("user", null, null, null, null, null, null);
            ArrayList list=new ArrayList<>();
            while(query.moveToNext()){
                String name = query.getString(query.getColumnIndex("name"));
                String img = query.getString(query.getColumnIndex("img"));
                User user = new User(name, img);
                list.add(user);
            }
            return list;
        }
    }

//在那个页面添加

dao = new UserDao(getActivity());
                    for (int i = 0; i < data.size(); i++) {
                        String news_summary = data.get(i).getNews_summary();
                        String pic_url = data.get(i).getPic_url();
                        dao.add(news_summary, pic_url);
                    }

你可能感兴趣的:(数据库)