将图像和一些文本字段插入SQLite数据库 - Android [英] Insert image and some text fields into SQLite database - Android

查看:155
本文介绍了将图像和一些文本字段插入SQLite数据库 - Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android新开发的,我试图在Android中将数据插入SQLite数据库。我有一个问题找到解决方案,我在哪里可以看到代码,如何插入图像和文本到数据库。你知道一些文章/书籍或
他们帮助我的东西吗?



我写了一些代码,只插入文本,但我不能插在一起。
插入后,我想检索文本和图像的详细活动。



非常感谢您的帮助。



我可以上传代码。



我的DatabaseHelper:

  public class DatabaseHelpher extends SQLiteOpenHelper {
private static final String DATABASE_NAME =student;
private static final int DATABASE_VERSION = 1;
private static final String STUDENT_TABLE =stureg;
private static final String STU_TABLE =create table+ STUDENT_TABLE +(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT);

上下文上下文;

public DatabaseHelpher(final Context context){
super(context,Environment.getExternalStorageDirectory()
+ File.separator + DATABASE_NAME,null,DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db){

db.execSQL(STU_TABLE);
}

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

db.execSQL(DROP TABLE IF EXISTS + STUDENT_TABLE);

//再次创建表
onCreate(db);
}

public void insertIntoDB(String name,String email,String roll,String address,String branch){
Log.d(insert,before insert) ;

// 1.获取对可写DB的引用
SQLiteDatabase db = this.getWritableDatabase();

// 2.创建ContentValues以添加键column/ value
ContentValues values = new ContentValues();
values.put(name,name);
values.put(email,email);
values.put(roll,roll);
values.put(address,address);
values.put(branch,branch);

// 3. insert
db.insert(STUDENT_TABLE,null,values);
// 4. close
db.close();
Toast.makeText(context,insert value,Toast.LENGTH_LONG);
Log.i(insert into DB,After insert);



}

public List< DatabaseModel> getDataFromDB(){
List< DatabaseModel> modelList = new ArrayList< DatabaseModel>();
String query =select * from+ STUDENT_TABLE;

SQLiteDatabase DB = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do {
DatabaseModel model = new DatabaseModel();
model.setName(cursor.getString(0));
model.setEmail(cursor.getString(1));
model.setRoll(cursor.getString(2));
model.setAddress(cursor.getString(3));
model.setBranch(cursor.getString(4));

modelList.add(model);
} while(cursor.moveToNext());
}


Log.d(student data,modelList.toString());


return modelList;
}



public void deleteARow(String email){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(STUDENT_TABLE,email+=?,new String [] {email});
db.close();
}

DatabaseModel:

  public class DatabaseModel {
private String name;
private String roll;
private字符串地址;
private String branch;
private String email;
private String image;

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}

public String getRoll(){
return roll;
}

public void setRoll(String roll){
this.roll = roll;
}

public String getAddress(){
返回地址;
}

public void setAddress(String address){
this.address = address;
}

public String getBranch(){
return branch;
}

public void setBranch(String branch){
this.branch = branch;
}

public String getEmail(){
return email;
}

public void setEmail(String email){
this.email = email;
}

public String getImage(){
return image;
}

public void setImage(String image){
this.image = image;
}

DetailsActivity:

  public class DetailsActivity extends AppCompatActivity {
DatabaseHelpher helpher;
List< DatabaseModel> dbList;
int position;
TextView tvname,tvemail,tvroll,tvaddress,tvbranch;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_details);

工具栏工具栏=(工具栏)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar()。setDisplayHomeAsUpEnabled(true);


Intent intent = getIntent();
Bundle bundle = intent.getExtras();

// 5.从bundle中获取状态值
position = bundle.getInt(position);

tvname =(TextView)findViewById(R.id.name);
tvemail =(TextView)findViewById(R.id.email);
tvroll =(TextView)findViewById(R.id.roll);
tvaddress =(TextView)findViewById(R.id.address);
tvbranch =(TextView)findViewById(R.id.branch);
helpher = new DatabaseHelpher(this);
dbList = new ArrayList< DatabaseModel>();
dbList = helpher.getDataFromDB();

if(dbList.size()> 0){
String name = dbList.get(position).getName();
String email = dbList.get(position).getEmail();
String roll = dbList.get(position).getRoll();
String address = dbList.get(position).getAddress();
String branch = dbList.get(position).getBranch();
tvname.setText(name);
tvemail.setText(email);
tvroll.setText(roll);
tvaddress.setText(address);
tvbranch.setText(branch);
}

Toast.makeText(DetailsActivity.this,dbList.toString(),Toast.LENGTH_LONG);
}


public boolean onCreateOptionsMenu(菜单菜单){
//膨胀菜单;这会将条目添加到操作栏(如果存在)。
getMenuInflater()。inflate(R.menu.menu_details,menu);
return true;
}



@ Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}

MainActivity:

  public class MainActivity extends AppCompatActivity {
EditText etName,etRoll,etAddress,etBranch,etEmail;
Button btnSubmit,btngetdata,btndroptable;
DatabaseHelpher helpher;
List< DatabaseModel> dbList;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
工具栏toolbar =(工具栏)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dbList = new ArrayList< DatabaseModel>();
etName =(EditText)findViewById(R.id.etName);
etRoll =(EditText)findViewById(R.id.etRoll);
etAddress =(EditText)findViewById(R.id.etAddress);
etBranch =(EditText)findViewById(R.id.etBranch);
etEmail =(EditText)findViewById(R.id.etEmail);
btnSubmit =(Button)findViewById(R.id.btnSubmit);
btngetdata =(Button)findViewById(R.id.btngetdata);

btngetdata.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
startActivity(new Intent(MainActivity.this, SecondActivity.class));

// startActivity(new Intent(MainActivity.this,DetailsActivity.class));

}
}

btnSubmit.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){

String name = etName。 getText()。toString();
String email = etEmail.getText()。toString();
String roll = etRoll.getText .getText()。toString();
String branch = etBranch.getText()。toString();

if(name.equals()|| email.equals )|| roll.equals()|| address.equals()|| branch.equals()){
Toast.makeText(MainActivity.this,Please fill all the fields ,Toast.LENGTH_LONG).show();
} else {
helpher = new DatabaseHelpher(MainActivity.this);
helpher.insertIntoDB(name,email,roll,address,branch);
}
etName.setText();
etRoll.setText();
etAddress.setText();
etBranch.setText );
etEmail.setText();

Toast.makeText(MainActivity.this,insert value,Toast.LENGTH_LONG);

}
});

RecyclerAdapter:

  public class RecyclerAdapter extends RecyclerView.Adapter< RecyclerAdapter.ViewHolder> {

static List< DatabaseModel> dbList;
static上下文上下文;
RecyclerAdapter(Context context,List< DatabaseModel> dbList){
this.dbList = new ArrayList< DatabaseModel>();
this.context = context;
this.dbList = dbList;

}
@Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){

查看itemLayoutView = LayoutInflater.from(parent.getContext ())。inflate(
R.layout.item_row,null);


ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}

@Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder,int position){

holder.name.setText(dbList.get位置).getName());
holder.email.setText(dbList.get(position).getEmail());

}

@Override
public int getItemCount(){
return dbList.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

public TextView name,email;

public ViewHolder(查看itemLayoutView){
super(itemLayoutView);
name =(TextView)itemLayoutView.findViewById(R.id.rvname);
email =(TextView)itemLayoutView.findViewById(R.id.rvemail);
itemLayoutView.setOnClickListener(this);

}

@Override
public void onClick(View v){
Intent intent = new Intent(context,DetailsActivity.class);

Bundle extras = new Bundle();
extras.putInt(position,getAdapterPosition());
intent.putExtras(extras);

context.startActivity(intent);
Toast.makeText(RecyclerAdapter.context,你已经点击Row+ getAdapterPosition(),Toast.LENGTH_LONG).show();
}
}
}

SecondActivity:

  public class SecondActivity extends AppCompatActivity {
DatabaseHelpher helpher;
List< DatabaseModel> dbList;
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
工具栏toolbar =(工具栏)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar()。setDisplayHomeAsUpEnabled(true);


helpher = new DatabaseHelpher(this);
dbList = new ArrayList< DatabaseModel>();
dbList = helpher.getDataFromDB();


mRecyclerView =(RecyclerView)findViewById(R.id.recycleview);

mRecyclerView.setHasFixedSize(true);

//使用线性布局管理器
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

//指定适配器(参见下一个示例)
mAdapter = new RecyclerAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);

}

@Override
public boolean onCreateOptionsMenu(菜单菜单){
//膨胀菜单;这会将条目添加到操作栏(如果存在)。
getMenuInflater()。inflate(R.menu.menu_second,menu);
return true;
}



@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}

布局 >

ActivityDetails:

 < LinearLayout 
xmlns:android = http://schemas.android.com/apk/res/android
xmlns:app =http://schemas.android.com/apk/res-auto
android:layout_width = match_parent
android:layout_height =match_parent
android:orientation =vertical>

< android.support.design.widget.AppBarLayout
android:id =@ + id / appbar
android:layout_width =match_parent
:layout_height =wrap_content
android:theme =@ style / ThemeOverlay.AppCompat.Dark.ActionBar>

< android.support.v7.widget.Toolbar
android:id =@ + id / toolbar
android:layout_width =match_parent
android :layout_height =?attr / actionBarSize
android:background =?attr / colorPrimary
app:popupTheme =@ style / ThemeOverlay.AppCompat.Light
app:layout_scrollFlags = scroll | enterAlways/>
< /android.support.design.widget.AppBarLayout>

< TextView
android:id =@ + id / name
android:layout_width =match_parent
android:layout_height =wrap_content
android:text =name
android:paddingTop =15dp
android:paddingLeft =20dp
android:textSize =36sp/&

< TextView
android:id =@ + id / roll
android:layout_width =match_parent
android:layout_height =wrap_content
android:text =Roll/>
< TextView
android:id =@ + id / address
android:layout_width =match_parent
android:layout_height =wrap_content text =Address/>
< TextView
android:id =@ + id / branch
android:layout_width =match_parent
android:layout_height =wrap_content text =Branch/>
< TextView
android:id =@ + id / email
android:layout_width =match_parent
android:layout_height =wrap_content text =Email/>
< / LinearLayout>

ActivityMain:

 code>< LinearLayout xmlns:android =http://schemas.android.com/apk/res/android
xmlns:tools =http://schemas.android.com/tools
android:layout_width =match_parent
android:layout_height =match_parent
xmlns:app =http://schemas.android.com/apk/res-auto
android:orientation =vertical>
< android.support.design.widget.AppBarLayout
android:id =@ + id / appbar
android:layout_width =match_parent
android:layout_height = wrap_content
android:theme =@ style / ThemeOverlay.AppCompat.Dark.ActionBar>

< android.support.v7.widget.Toolbar
android:id =@ + id / toolbar
android:layout_width =match_parent
android :layout_height =?attr / actionBarSize
android:background =?attr / colorPrimary
app:popupTheme =@ style / ThemeOverlay.AppCompat.Light
app:layout_scrollFlags = scroll | enterAlways/>

< /android.support.design.widget.AppBarLayout>

< ScrollView
android:layout_width =match_parent
android:layout_height =match_parent>

< LinearLayout
android:layout_width =match_parent
android:layout_height =wrap_content
android:orientation =vertical>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:orientation =horizo​​ntal>
< TextView
android:layout_width =wrap_content
android:layout_height =wrap_content
android:text =Enter Email/&
< EditText
android:id =@ + id / etEmail
android:layout_width =fill_parent
android:layout_height =wrap_content/&

< / LinearLayout>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:orientation =horizo​​ntal>
< TextView
android:layout_width =wrap_content
android:layout_height =wrap_content
android:text =Enter Branch/>
< EditText
android:id =@ + id / etBranch
android:layout_width =fill_parent
android:layout_height =wrap_content/&

< / LinearLayout>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:orientation =horizo​​ntal>
< TextView
android:layout_width =wrap_content
android:layout_height =wrap_content
android:text =Enter Address/&
< EditText
android:id =@ + id / etAddress
android:layout_width =fill_parent
android:layout_height =wrap_content/>

< / LinearLayout>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:orientation =horizo​​ntal>
< TextView
android:layout_width =wrap_content
android:layout_height =wrap_content
android:text =Enter Roll/>
< EditText
android:id =@ + id / etRoll
android:layout_width =fill_parent
android:layout_height =wrap_content/&

< / LinearLayout>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:orientation =horizo​​ntal>
< TextView
android:layout_width =wrap_content
android:layout_height =wrap_content
android:text =Enter Name/>
< EditText
android:id =@ + id / etName
android:layout_width =fill_parent
android:layout_height =wrap_content/&

< / LinearLayout>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:orientation =horizo​​ntal>
< Button
android:id =@ + id / btnSubmit
android:layout_width =match_parent
android:layout_height =match_parent text =uložitdodatabáze
android:textColor =#ffffff
android:background =@ color / colorPrimary/&

< / LinearLayout>

< LinearLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:layout_marginTop =10dp
android: orientation =horizo​​ntal>
< Button
android:id =@ + id / btngetdata
android:layout_width =match_parent
android:layout_height =match_parent text =Zobrazit seznamrumů
android:textColor =#ffffff
android:background =@ color / colorPrimary/>

< / LinearLayout>

< / LinearLayout>
< / ScrollView>


< / LinearLayout>

活动秒:

 code>< LinearLayout xmlns:android =http://schemas.android.com/apk/res/android
xmlns:tools =http://schemas.android.com/tools
android:layout_width =match_parent
android:layout_height =match_parent
xmlns:app =http://schemas.android.com/apk/res-auto
android:orientation =vertical>
< android.support.design.widget.AppBarLayout
android:id =@ + id / appbar
android:layout_width =match_parent
android:layout_height = wrap_content
android:theme =@ style / ThemeOverlay.AppCompat.Dark.ActionBar>

< android.support.v7.widget.Toolbar
android:id =@ + id / toolbar
android:layout_width =match_parent
android :layout_height =?attr / actionBarSize
android:background =?attr / colorPrimary
app:popupTheme =@ style / ThemeOverlay.AppCompat.Light
app:layout_scrollFlags = scroll | enterAlways/>
< /android.support.design.widget.AppBarLayout>
< LinearLayout
android:layout_width =fill_parent
android:layout_height =wrap_content
android:orientation =horizo​​ntal>


< android.support.v7.widget.RecyclerView
android:id =@ + id / recycleview
android:layout_width =match_parent
android:layout_height =match_parent/>

< / LinearLayout>
< / LinearLayout>

item_row:

 code><?xml version =1.0encoding =utf-8?> 
< android.support.v7.widget.CardView xmlns:android =http://schemas.android.com/apk/res/android
xmlns:card_view =http:// schemas .android.com / apk / res-auto
android:layout_width =match_parent
android:layout_height =match_parent
android:layout_margin =5dp
android: orientation =horizo​​ntal
card_view:cardCornerRadius =5dp
card_view:cardUseCompatPadding =true>

< RelativeLayout
android:layout_width =match_parent
android:layout_height =match_parent
android:background =?android:selectableItemBackground>


< TextView
android:id =@ + id / rvemail
android:layout_width =fill_parent
android:layout_height = 45dp
android:textAlignment =center
android:padding =10dp
android:gravity =right
android:text =Email
android:textColor =@ android:color / black
android:layout_marginLeft =10dp
/>

< TextView
android:id =@ + id / rvname
android:layout_width =wrap_content
android:layout_height =45dp
android:gravity =left
android:padding =10dp
android:textAlignment =center
android:text =Name
android:textColor = @android:color / black
android:layout_alignParentTop =true
android:layout_alignParentLeft =true
android:layout_alignParentStart =true/&

< / RelativeLayout>

< /android.support.v7.widget.CardView>

非常非常感谢您的帮助,我不知道如何解决插入图像和文本到一个数据库的问题,然后将其存储在移动设备,然后单击行,然后应用程序显示图像和文本。
PS:对不起很多代码,但我不知道该怎么办:(

解决方案

  public class DatabaseHelpher extends SQLiteOpenHelper {
private static final String DATABASE_NAME =student;
private static final int DATABASE_VERSION = 1;
private static final String STUDENT_TABLE =stureg ;
private static final String STU_TABLE =create table+ STUDENT_TABLE +(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT ,, image BLOB);

context context;

public DatabaseHelpher(final Context context){
super(context,Environment.getExternalStorageDirectory()
+ File.separator + DATABASE_NAME,null,DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db){

db.execSQL(STU_TABLE );
}

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

db.execSQL(DROP TABLE IF EXISTS+ STUDENT_TABLE);

//再次创建表
onCreate(db);
}

public void insertIntoDB(String name,String email,String roll,String address,String branch,byte [] image_data){
Log.d before insert);

// 1.获取对可写DB的引用
SQLiteDatabase db = this.getWritableDatabase();

// 2.创建ContentValues以添加键column/ value
ContentValues values = new ContentValues();
values.put(name,name);
values.put(email,email);
values.put(roll,roll);
values.put(address,address);
values.put(branch,branch);
values.put(image,image_data);

// 3. insert
db.insert(STUDENT_TABLE,null,values);
// 4. close
db.close();
Toast.makeText(context,insert value,Toast.LENGTH_LONG);
Log.i(insert into DB,After insert);



}


public List< DatabaseModel> getDataFromDB(){
List< DatabaseModel> modelList = new ArrayList< DatabaseModel>();
String query =select * from+ STUDENT_TABLE;

SQLiteDatabase DB = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
do {
DatabaseModel model = new DatabaseModel();
model.setName(cursor.getString(0));
model.setEmail(cursor.getString(1));
model.setRoll(cursor.getString(2));
model.setAddress(cursor.getString(3));
model.setBranch(cursor.getString(4));
model.setImage(cursor.getBlob(5)); //在你的DatabaseModel中添加字节参数
modelList.add(model);
} while(cursor.moveToNext());
}


Log.d(student data,modelList.toString());


return modelList;
}



public void deleteARow(String email){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(STUDENT_TABLE,email+=?,new String [] {email});
db.close();
}
}


I am new in Android developing and I am trying to insert data into SQLite database in Android. I have a problem find the solution, where can I see code, how to insert Image and Text into database. Do you know some articles/books or something else which they help me ?

I write some code with inserting only text, but I cannot insert both together. After inserting, I want to retrieve text and image in detail activity.

Very thank you for help.

I can upload the code.

My DatabaseHelper:

 public class DatabaseHelpher extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="student";
    private static final int DATABASE_VERSION = 1;
    private static final String STUDENT_TABLE = "stureg";
    private static final String STU_TABLE = "create table "+STUDENT_TABLE +"(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT)";

    Context context;

    public DatabaseHelpher(final Context context) {
        super(context, Environment.getExternalStorageDirectory()
                + File.separator + DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(STU_TABLE);
    }

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

        db.execSQL("DROP TABLE IF EXISTS " + STUDENT_TABLE);

        // Create tables again
        onCreate(db);
    }

    public void insertIntoDB(String name,String email,String roll,String address,String branch){
        Log.d("insert", "before insert");

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("email", email);
        values.put("roll", roll);
         values.put("address", address);
        values.put("branch", branch);

        // 3. insert
        db.insert(STUDENT_TABLE, null, values);
        // 4. close
        db.close();
        Toast.makeText(context, "insert value", Toast.LENGTH_LONG);
        Log.i("insert into DB", "After insert");



    }

    public List<DatabaseModel> getDataFromDB(){
        List<DatabaseModel> modelList = new ArrayList<DatabaseModel>();
        String query = "select * from "+STUDENT_TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query,null);
        if (cursor.moveToFirst()){
            do {
                DatabaseModel model = new DatabaseModel();
                model.setName(cursor.getString(0));
                model.setEmail(cursor.getString(1));
                model.setRoll(cursor.getString(2));
                model.setAddress(cursor.getString(3));
                model.setBranch(cursor.getString(4));

                modelList.add(model);
            }while (cursor.moveToNext());
        }


        Log.d("student data", modelList.toString());


        return modelList;
    }



    public void deleteARow(String email){
        SQLiteDatabase db= this.getWritableDatabase();
        db.delete(STUDENT_TABLE, "email" + " = ?", new String[] { email });
        db.close();
    }

DatabaseModel:

public class DatabaseModel {
private String name;
private String roll;
private String address;
private String branch;
private String email;
private String image;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getRoll() {
    return roll;
}

public void setRoll(String roll) {
    this.roll = roll;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getBranch() {
    return branch;
}

public void setBranch(String branch) {
    this.branch = branch;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getImage() {
    return image;
}

public void setImage (String image) {
    this.image = image;
}

DetailsActivity:

 public class DetailsActivity extends AppCompatActivity {
    DatabaseHelpher helpher;
    List<DatabaseModel> dbList;
    int position;
    TextView tvname,tvemail,tvroll,tvaddress,tvbranch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_details);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();

        // 5. get status value from bundle
         position = bundle.getInt("position");

        tvname =(TextView)findViewById(R.id.name);
        tvemail =(TextView)findViewById(R.id.email);
        tvroll =(TextView)findViewById(R.id.roll);
        tvaddress =(TextView)findViewById(R.id.address);
        tvbranch =(TextView)findViewById(R.id.branch);
        helpher = new DatabaseHelpher(this);
        dbList= new ArrayList<DatabaseModel>();
        dbList = helpher.getDataFromDB();

        if(dbList.size()>0){
            String name= dbList.get(position).getName();
            String email=dbList.get(position).getEmail();
            String roll=dbList.get(position).getRoll();
            String address=dbList.get(position).getAddress();
            String branch=dbList.get(position).getBranch();
            tvname.setText(name);
            tvemail.setText(email);
            tvroll.setText(roll);
            tvaddress.setText(address);
            tvbranch.setText(branch);
        }

        Toast.makeText(DetailsActivity.this, dbList.toString(), Toast.LENGTH_LONG);
    }


    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_details, menu);
        return true;
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

MainActivity:

public class MainActivity extends AppCompatActivity {
EditText etName,etRoll,etAddress,etBranch,etEmail;
Button btnSubmit,btngetdata,btndroptable;
DatabaseHelpher helpher;
List<DatabaseModel> dbList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    dbList= new ArrayList<DatabaseModel>();
    etName = (EditText)findViewById(R.id.etName);
    etRoll = (EditText)findViewById(R.id.etRoll);
    etAddress =(EditText)findViewById(R.id.etAddress);
    etBranch = (EditText)findViewById(R.id.etBranch);
    etEmail = (EditText)findViewById(R.id.etEmail);
    btnSubmit  =(Button)findViewById(R.id.btnSubmit);
    btngetdata =(Button)findViewById(R.id.btngetdata);

    btngetdata.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, SecondActivity.class));

           // startActivity(new Intent(MainActivity.this, DetailsActivity.class));

        }
    });

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String name=etName.getText().toString();
            String email=etEmail.getText().toString();
            String roll=etRoll.getText().toString();
            String address=etAddress.getText().toString();
            String branch=etBranch.getText().toString();

        if(name.equals("") || email.equals("") || roll.equals("") ||address.equals("")||branch.equals("")){
            Toast.makeText(MainActivity.this,"Please fill all the fields",Toast.LENGTH_LONG).show();
        }else {
            helpher = new DatabaseHelpher(MainActivity.this);
            helpher.insertIntoDB(name, email, roll, address, branch);
        }
            etName.setText("");
            etRoll.setText("");
            etAddress.setText("");
            etBranch.setText("");
            etEmail.setText("");

            Toast.makeText(MainActivity.this, "insert value", Toast.LENGTH_LONG);

        }
    });

RecyclerAdapter:

 public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    static   List<DatabaseModel> dbList;
        static  Context context;
        RecyclerAdapter(Context context, List<DatabaseModel> dbList ){
            this.dbList = new ArrayList<DatabaseModel>();
            this.context = context;
            this.dbList = dbList;

        }
    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.item_row, null);


        ViewHolder viewHolder = new ViewHolder(itemLayoutView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {

        holder.name.setText(dbList.get(position).getName());
        holder.email.setText(dbList.get(position).getEmail());

    }

    @Override
    public int getItemCount() {
        return dbList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public TextView name,email;

        public ViewHolder(View itemLayoutView) {
            super(itemLayoutView);
            name = (TextView) itemLayoutView.findViewById(R.id.rvname);
            email = (TextView)itemLayoutView.findViewById(R.id.rvemail);
            itemLayoutView.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(context,DetailsActivity.class);

            Bundle extras = new Bundle();
            extras.putInt("position",getAdapterPosition());
            intent.putExtras(extras);

            context.startActivity(intent);
            Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_LONG).show();
        }
    }
}

SecondActivity:

  public class SecondActivity extends AppCompatActivity {
    DatabaseHelpher helpher;
    List<DatabaseModel> dbList;
    RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        helpher = new DatabaseHelpher(this);
        dbList= new ArrayList<DatabaseModel>();
        dbList = helpher.getDataFromDB();


        mRecyclerView = (RecyclerView)findViewById(R.id.recycleview);

        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // specify an adapter (see also next example)
        mAdapter = new RecyclerAdapter(this,dbList);
        mRecyclerView.setAdapter(mAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_second, menu);
        return true;
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Layouts

ActivityDetails:

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name"
        android:paddingTop="15dp"
        android:paddingLeft="20dp"
        android:textSize="36sp" />

    <TextView
        android:id="@+id/roll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Roll"/>
    <TextView
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Address"/>
    <TextView
        android:id="@+id/branch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Branch"/>
    <TextView
        android:id="@+id/email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Email"/>
    </LinearLayout>

ActivityMain:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways" />

    </android.support.design.widget.AppBarLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Enter Email"/>
                <EditText
                    android:id="@+id/etEmail"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Enter Branch"/>
                <EditText
                    android:id="@+id/etBranch"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Enter Address"/>
                <EditText
                    android:id="@+id/etAddress"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Enter Roll"/>
                <EditText
                    android:id="@+id/etRoll"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Enter Name"/>
                <EditText
                    android:id="@+id/etName"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">
                <Button
                    android:id="@+id/btnSubmit"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="uložit do databáze"
                    android:textColor="#ffffff"
                    android:background="@color/colorPrimary"/>

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="10dp"
                android:orientation="horizontal">
                <Button
                    android:id="@+id/btngetdata"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="Zobrazit seznam rumů"
                    android:textColor="#ffffff"
                    android:background="@color/colorPrimary"/>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>


</LinearLayout>

ActivitySecond:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">


        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycleview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </LinearLayout>
    </LinearLayout>

item_row:

  <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="5dp"
    android:orientation="horizontal"
    card_view:cardCornerRadius="5dp"
    card_view:cardUseCompatPadding="true" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?android:selectableItemBackground"  >


        <TextView
            android:id="@+id/rvemail"
            android:layout_width="fill_parent"
            android:layout_height="45dp"
            android:textAlignment="center"
            android:padding="10dp"
            android:gravity="right"
            android:text="Email"
            android:textColor="@android:color/black"
            android:layout_marginLeft="10dp"
             />

        <TextView
            android:id="@+id/rvname"
            android:layout_width="wrap_content"
            android:layout_height="45dp"
            android:gravity="left"
            android:padding="10dp"
            android:textAlignment="center"
            android:text="Name"
            android:textColor="@android:color/black"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

    </RelativeLayout>

</android.support.v7.widget.CardView>

Very Very thanks for help, I dont know how to resolve problem with insert image and text into one database, then store them in mobile and after click to row then app display image and texts. PS: sorry for a lot of code, but I dont know what to do :(

解决方案

    public class DatabaseHelpher extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="student";
    private static final int DATABASE_VERSION = 1;
    private static final String STUDENT_TABLE = "stureg";
    private static final String STU_TABLE = "create table "+STUDENT_TABLE +"(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT,,image BLOB)";

    Context context;

    public DatabaseHelpher(final Context context) {
        super(context, Environment.getExternalStorageDirectory()
                + File.separator + DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(STU_TABLE);
    }

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

        db.execSQL("DROP TABLE IF EXISTS " + STUDENT_TABLE);

        // Create tables again
        onCreate(db);
    }

    public void insertIntoDB(String name,String email,String roll,String address,String branch,byte[]image_data){
        Log.d("insert", "before insert");

        // 1. get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        // 2. create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("email", email);
        values.put("roll", roll);
         values.put("address", address);
        values.put("branch", branch);
        values.put("image", image_data);

        // 3. insert
        db.insert(STUDENT_TABLE, null, values);
        // 4. close
        db.close();
        Toast.makeText(context, "insert value", Toast.LENGTH_LONG);
        Log.i("insert into DB", "After insert");



    }


    public List<DatabaseModel> getDataFromDB(){
        List<DatabaseModel> modelList = new ArrayList<DatabaseModel>();
        String query = "select * from "+STUDENT_TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query,null);
        if (cursor.moveToFirst()){
            do {
                DatabaseModel model = new DatabaseModel();
                model.setName(cursor.getString(0));
                model.setEmail(cursor.getString(1));
                model.setRoll(cursor.getString(2));
                model.setAddress(cursor.getString(3));
                model.setBranch(cursor.getString(4));
                model.setImage(cursor.getBlob(5));  //Add byte paramter in your DatabaseModel
                modelList.add(model);
            }while (cursor.moveToNext());
        }


        Log.d("student data", modelList.toString());


        return modelList;
    }



    public void deleteARow(String email){
        SQLiteDatabase db= this.getWritableDatabase();
        db.delete(STUDENT_TABLE, "email" + " = ?", new String[] { email });
        db.close();
    }
    }

这篇关于将图像和一些文本字段插入SQLite数据库 - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆