Android Sqlite Example

In this example, we are adding a lable on button click and displaying all the added labels on the spinner. As you have seen in the previous example, SQLiteOpenHelper  class need to be extended for performing oprations on the sqlite.
We have overridden the onCreate() and onUpgrade() method of SQLiteOpenHelper class in the DatabaseHandler class that provides additional methods to insert and display the lables or data.

Android Sqlite Spinner Example

Let's see the simple code to add and display the string content on spinner using sqlite database.
activity_main.xml
File: activity_main.xml
<RelativeLayout 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"
    tools:context=".MainActivity" >

     <!-- Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add New Label"
        android:padding="8dip" />

    <!-- Input Text -->
    <EditText android:id="@+id/input_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/btn_add"
        android:layout_marginTop="23dp" />

    <Button
        android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/input_label"
        android:layout_centerHorizontal="true"
        android:text="Add Item" />
   
</RelativeLayout>

Activity class
File: MainActivity.java
package com.example.sqlitespinner;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemSelectedListener{
    Spinner spinner;
    Button btnAdd;
    EditText inputLabel;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        spinner = (Spinner) findViewById(R.id.spinner);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
 
        spinner.setOnItemSelectedListener(this);
 
        // Loading spinner data from database
        loadSpinnerData();
 
        btnAdd.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();
 
                if (label.trim().length() > 0) {
                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    db.insertLabel(label);
 
                    // making input filed text to blank
                    inputLabel.setText("");
 
                    // Hiding the keyboard
                    InputMethodManager imm = (InputMethodManager) 
                          getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
 
                    // loading spinner with newly added data
                    loadSpinnerData();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }
 
            }
        });
    }
 
    /**
     * Function to load the spinner data from SQLite database
     * */
    private void loadSpinnerData() {
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        List<String> lables = db.getAllLabels();
 
        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
 
        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
 
        // attaching data adapter to spinner
        spinner.setAdapter(dataAdapter);
    }
 
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
        // On selecting a spinner item
        String label = parent.getItemAtPosition(position).toString();
 
        // Showing selected spinner item
        Toast.makeText(parent.getContext(), "You selected: " + label,
                Toast.LENGTH_LONG).show();
 
    }
 
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
 
    }
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

DatabaseHandler class
File: DatabaseHandler.java
package com.example.sqlitespinner2;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "spinnerExample";
    private static final String TABLE_NAME = "labels";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
 
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
 
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT)";
        db.execSQL(CREATE_ITEM_TABLE);
    }
 
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
 
        // Create tables again
        onCreate(db);
    }
 
    /**
     * Inserting new lable into lables table
     * */
    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, label);//column name, column value
 
        // Inserting Row
        db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, CotentValues
        db.close(); // Closing database connection
    }
 
    /**
     * Getting all labels
     * returns list of labels
     * */
    public List
   
   
    
     getAllLabels(){
        List
    
    
     
      list = new ArrayList
     
     
      
      ();
 
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;
 
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);//selectQuery,selectedArguments
 
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                list.add(cursor.getString(1));//adding 2nd column data
            } while (cursor.moveToNext());
        }
        // closing connection
        cursor.close();
        db.close();
 
        // returning lables
        return list;
    }
}

     
     
    
    
   
   



Output:






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 Android 应用程序中显示网络图片,可以使用 Picasso 或 Glide 这样的第三方库。而要将图片保存到 SQLite 数据库中,可以将图片转换为 Base64 字符串,然后将其保存到 TEXT 类型的列中。 以下是一个示例代码,用于从 SQLite 数据库中读取 Base64 编码的图片并将其显示在 ImageView 中: 1. 添加依赖库 在 app/build.gradle 文件中添加以下依赖库: ```groovy implementation 'com.squareup.picasso:picasso:2.71828' ``` 2. 读取 Base64 编码的图片 在 SQLite 数据库中保存图片时,可以将其转换为 Base64 编码的字符串,然后将其保存到 TEXT 类型的列中。例如: ```java String imageUrl = "https://example.com/image.png"; Bitmap bitmap = getBitmapFromUrl(imageUrl); String base64String = getBase64String(bitmap); // 将 base64String 保存到 SQLite 数据库中 ``` 其中,getBitmapFromUrl() 方法用于从 URL 中获取 Bitmap 对象,getBase64String() 方法用于将 Bitmap 对象转换为 Base64 编码的字符串。 在从 SQLite 数据库中读取图片时,可以使用以下代码: ```java String base64String = cursor.getString(cursor.getColumnIndexOrThrow("image_data")); byte[] decodedString = Base64.decode(base64String, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); imageView.setImageBitmap(bitmap); ``` 其中,cursor 是从 SQLite 数据库中查询得到的结果集对象,"image_data" 是保存 Base64 编码图片的列名。 3. 使用 Picasso 显示图片 使用 Picasso 显示网络图片非常简单,只需要调用以下方法即可: ```java String imageUrl = "https://example.com/image.png"; Picasso.get().load(imageUrl).into(imageView); ``` 其中,imageView 是要显示图片的 ImageView 对象。 因此,如果要将 Base64 编码的图片显示到 ImageView 中,可以使用以下代码: ```java String base64String = cursor.getString(cursor.getColumnIndexOrThrow("image_data")); byte[] decodedString = Base64.decode(base64String, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); imageView.setImageBitmap(bitmap); ``` 如果要显示网络图片,可以使用以下代码: ```java String imageUrl = "https://example.com/image.png"; Picasso.get().load(imageUrl).into(imageView); ``` 其中,imageView 是要显示图片的 ImageView 对象,imageUrl 是要显示的网络图片的 URL。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值