GVKun编程网logo

android – 如何在按钮的点击事件中在sqlite数据库中存储图像?

29

针对android–如何在按钮的点击事件中在sqlite数据库中存储图像?这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展3种方法实现Android按钮的点击事件,建议收藏!、AndroidS

针对android – 如何在按钮的点击事件中在sqlite数据库中存储图像?这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展3种方法实现Android按钮的点击事件,建议收藏!、Android SQLite数据库中的表详解、android – 从sqlite数据库中删除所有表、android – 从sqlite数据库中获取最后一行等相关知识,希望可以帮助到你。

本文目录一览:

android – 如何在按钮的点击事件中在sqlite数据库中存储图像?

android – 如何在按钮的点击事件中在sqlite数据库中存储图像?

如何在按钮的点击事件中将图像存储在sqlite数据库中?

解决方法:

package com.examples.aMysqL2;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.sqliteCursor;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


//Reading lines from a file
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;


public class aMysqL2Activity extends Activity implements OnClickListener
{
    protected static TextView textView;
    protected static ImageView bmImage;
    protected Button start;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        bmImage = (ImageView)findViewById(R.id.imageView1);
        textView = (TextView) findViewById(R.id.textView1);

        start = (Button) findViewById(R.id.button1);
        start.setonClickListener(this); 

    DownloadFile();


    }
    // /data/data/<package_name>/databases  -путь к базе данных по умолчанию
    // "/data/data/com.examples.aMysqL2/databases/MyDB.db" //-путь к базе данных по умолчанию
    //  "/sdcard/Nick/MyDB.db"
    //  "/mnt/sdcard/Nick/MyDB.db"
    /// Android/data/<package_name>/files/
    public void onClick(View v) 
    {
     sqliteDatabase myDb;       
     String MysqL;
     int icount;
     byte[] byteImage1 = null;
     byte[] byteImage2 = null;
       MysqL="create table emp1(_id INTEGER primary key autoincrement, fio TEXT not null, picture BLOB);";
       myDb = openorCreateDatabase("/sdcard/Nick/MyWeatherDB.db", Context.MODE_PRIVATE, null);
  //     myDb.execsql(MysqL);
  String s=myDb.getPath();
  textView.append("\r\n" + s+"\r\n");       
       myDb.execsql("delete from emp1");
       ContentValues newValues = new ContentValues();
    newValues.put("fio", "Иванов Петр Сергеевич");

 /////////// insert picture to blob field ///////////////////// 
    try
    {
    FileInputStream instream = new FileInputStream("/sdcard/Nick/weather.png"); 
    BufferedInputStream bif = new BufferedInputStream(instream); 
    byteImage1 = new byte[bif.available()]; 
    bif.read(byteImage1); 
textView.append("\r\n" + byteImage1.length+"\r\n"); 
    newValues.put("picture", byteImage1); 

    long ret = myDb.insert("emp1", null, newValues); 
    if(ret<0) textView.append("\r\n!!! Error add blob filed!!!\r\n");
    } catch (IOException e) 
    {
        textView.append("\r\n!!! Error: " + e+"!!!\r\n");   
    }

////////////Read data ////////////////////////////  
Cursor cur = myDb.query("emp1",null, null, null, null, null, null);
    cur.movetoFirst();
    while (cur.isAfterLast() == false)
    {
        textView.append("\r\n" + cur.getString(1)+"\r\n");
        cur.movetoNext();
    }
///////Read data from blob field////////////////////
    cur.movetoFirst();
    byteImage2=cur.getBlob(cur.getColumnIndex("picture")); // ИМЕННО ТАК!!!
bmImage.setimageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0, byteImage2.length));
    textView.append("\r\n" + byteImage2.length+"\r\n"); 
//////////////////////////    
    cur.close();
    myDb.close();
  }

    public void DownloadFile() 
    {   
      Bitmap bitmap1 = null;                    
      bitmap1 = BitmapFactory.decodeFile("/sdcard/Nick/Saranka.jpg"); //weather.png");
      bmImage.setimageBitmap(bitmap1);
    }


}

3种方法实现Android按钮的点击事件,建议收藏!

3种方法实现Android按钮的点击事件,建议收藏!

Button是程序用于和用户进行交互的一个重要控件,相信大家对这个控件已经非常熟悉了,我们平时用的最多的控件之一。既然有Button,那肯定有onClick方法,下面就教大家三种实现点击事件的方法,大家选择一种自己喜欢的方式写就可以了。

我们先在layout文件里面放置一个Button控件,很简单,让它水平和垂直都居中,Button里面的文字也居中对齐,字体大小15sp,内容为“我是按钮”,具体代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ButtonActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:text="我是按钮"
        android:textSize="15sp" />

</RelativeLayout>

运行一下模拟器,显示如下:

image.png

下面,我们来实现按钮点击事件:只要我们点击按钮,就会弹出Toast提示信息,内容为“按钮被点击了”。

| 一、匿名内部类实现 | |--|--|

在onCreate()方法里面声明并绑定控件,然后注册监听器,重写onClick()方法,只要在onClick()方法中加入待处理的逻辑就行。 这里我们只用Toast显示了一条消息。所有代码如下:

public class ButtonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button);
        Button button=findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(ButtonActivity.this,"按钮被点击了",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

这样,只要我们点击按钮,就会执行监听器中的onClick()方法,效果如下:

image.png

| 二、接口实现 | |--|--|

第二种方法只要引用View.OnClickListener这个接口就行,接着Button button=findViewById(R.id.button);用来声明和绑定button控件,button.setOnClickListener(this);设置button的监听器,这两者缺一不可。下面就是重写onClick()方法,一般使用switch语句,参数是view,可以根据不同id来赋予不同的点击事件,不用像上面匿名内部类那样每一个按钮都要单独设置一下点击事件。所有代码如下:

public class ButtonActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button);
        Button button=findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button:
                Toast.makeText(this,"按钮被点击了",Toast.LENGTH_SHORT).show();
            default:
                break;
        }
    }
}

我们运行看下效果:
image.png

| 三、布局实现 | |--|--| 上面两种点击事件都很简单,相信大家已经掌握了,那么接下来的方法更加简单。

我们在layout文件中,给每一个用到的Button设置属性android:onClick="onClick",其他不需要改变。 然后我们在ButtonActivity里面写一个onClick()方法,这里就不是重写了,因为我们没有任何继承父类和引用接口,这里的方法名可以随意取。然后写上代码逻辑。完整代码如下:

public class ButtonActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button);
    }

    public void onClick(View view) {
        Toast.makeText(this,"按钮被点击了",Toast.LENGTH_SHORT).show();
    }
}

我们来运行一下程序,发现点击按钮之后一样有响应。

好了,以上就是3种实现Android按钮的点击事件,是不是已经学会了呢。如果学会的话点个三连支持下博主吧。

Android SQLite数据库中的表详解

Android SQLite数据库中的表详解

Android sqlite数据库

前言

以前写PHP的时候,内置了print_r()和var_dump()两个函数用于打印输出任意类型的数据内部结构,现在做Android的开发,发现并没有这种类似的函数,对于数据库的查看很不方便,于是就写了一下查看数据库表的方法代码。

代码实现

import java.util.Arrays;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class SecondActivity extends Activity {

  public static final String TAG = "Debug Info";

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

    ((Button)findViewById(R.id.btnQue)).setonClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        MyDatabaseHelper dbhelper = new MyDatabaseHelper(SecondActivity.this,"BookStore.db",null,1);
        sqliteDatabase db = dbhelper.getWritableDatabase();

        //核心区
        //读取系统表 sqlite_master
        String sql = "select * from sqlite_master";
        Cursor cursor = db.rawQuery(sql,null);

        //打印表的所有列名
        Log.i(TAG,Arrays.toString(cursor.getColumnNames()));

        //打印当前数据库中的所有表
        if (cursor.movetoFirst()) {
          do {
            String str = "";

            for (String item : cursor.getColumnNames()) {
              str += item + ": " + cursor.getString(cursor.getColumnIndex(item)) + "\n";
            }

            Log.i(TAG,str);

          } while (cursor.movetoNext());
        }
      }
    });
  }

}

功能扩展

查看表是否存在

public Boolean tableIsExist(sqliteDatabase db,String tableName){
  boolean result = false;
  Cursor cursor = null;

  if(tableName == null){
    return result;
  }

  String sql = "select count(*) from sqlite_master where type ='table' and name ='"+tableName.trim()+"'";
  cursor = db.rawQuery(sql,null);

  if(cursor.movetoNext()){
    if(cursor.getInt(0) > 0){
      result = true;
    }
  }

  return result;
}  

查看数据库中有哪些表

public ArrayList<String> tablesInDB(sqliteDatabase db){
  ArrayList<String> list = new ArrayList<String>();
  String sql = "select name from sqlite_master where type='table'";
  Cursor cursor = db.rawQuery(sql,null);

  if (cursor.movetoFirst()) {
      do {
        list.add(cursor.getString(0));
      } while (cursor.movetoNext());
    }

  return list;

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

android – 从sqlite数据库中删除所有表

android – 从sqlite数据库中删除所有表

我做了很多研究,无法找到合适的方法来删除sqlite数据库中的所有表.最后,我做了一个代码来从数据库中获取所有表名,我尝试逐个使用检索到的表名删除表.它没有用.

请建议我从数据库中删除所有表的方法.

这是我使用的代码:

public void deleteall(){
    sqliteDatabase db = this.getWritableDatabase();
    Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
    do
    {
        db.delete(c.getString(0),null,null);
    }while (c.movetoNext());
}

按钮单击时调用函数deleteall(),其代码如下:

public void ButtonClick(View view)
{
    String Button_text;
    Button_text = ((Button) view).getText().toString();

    if(Button_text.equals("Delete Database"))
    {
        DatabaseHelper a = new DatabaseHelper(this);
        a.deleteall();
        Toast.makeText(getApplicationContext(), "Database Deleted Succesfully!", Toast.LENGTH_SHORT).show();
    }}

解决方法:

使用DROP TABLE:

// query to obtain the names of all tables in your database
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();

// iterate over the result set, adding every table name to a list
while (c.movetoNext()) {
    tables.add(c.getString(0));
}

// call DROP TABLE on every table name
for (String table : tables) {
    String dropQuery = "DROP TABLE IF EXISTS " + table;
    db.execsql(dropQuery);
}

android – 从sqlite数据库中获取最后一行

android – 从sqlite数据库中获取最后一行

我试图从我的sqlite数据库中获取最后一行.直到现在我已经尝试过max,sql_sequence但似乎没有任何效果.我必须获取行值并将其分配给类变量.
感谢任何帮助,因为我是sqlite和Android的新手.
谢谢..

解决方法:

如果您已经获得了光标,那么这就是您从光标获取最后一条记录的方法:

cursor.movetoPosition(cursor.getCount() – 1);

//然后使用cursor来读取值

要么

像这样做

Cursor cursor = db.rawQuery(selectQuery, null);
cursor.movetoLast();

要么

SELECT * FROM TABLE WHERE ID = (SELECT MAX(ID) FROM TABLE);

今天的关于android – 如何在按钮的点击事件中在sqlite数据库中存储图像?的分享已经结束,谢谢您的关注,如果想了解更多关于3种方法实现Android按钮的点击事件,建议收藏!、Android SQLite数据库中的表详解、android – 从sqlite数据库中删除所有表、android – 从sqlite数据库中获取最后一行的相关知识,请在本站进行查询。

本文标签: