Android add sqlite data to spinner

If your application needs to use a Spinner to display data from a local SQLite database, this Android tutorial is useful to you. In the example app below, the database prodb is created. In the database, there is a table called tblprovinces that store names of provinces. Then the names of provinces are read from the database to populate a Spinner.
You create a new Android project. In the activity_main.xml file, you add a Spinner.







<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="com.example.myfirstprogram.MainActivity" >	
   <Spinner
     android:id="@+id/spinner"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      />    
</RelativeLayout>
You also have to create a layout file for the Spinner in the res/layout directory. The name of the layout file is spinner_layout.xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"   
      >
<TextView    android:id="@+id/text"      android:layout_width="match_parent"      android:layout_height="wrap_content"      android:paddingLeft="5sp"      android:paddingBottom="10sp"      android:paddingTop="10sp"   
>
</TextView>
</RelativeLayout>
In the src directory, you create a class called DataHelper. It is a convenient class used to create a database and a table, to insert data, and to get data from the table.


public class DataHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "prodb";
public static final String TABLE_PRO = "tblprovinces";
public static final int DATABASE_VERSION = 1;
public static final String CREATE_RPO = "CREATE TABLE IF NOT EXISTS "+ TABLE_PRO+ "(id INTEGER PRIMARY KEY AUTOINCREMENT, pname TEXT NULL UNIQUE)";
public static final String DELETE_PRO="DROP TABLE IF EXISTS " + TABLE_PRO;
public DataHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION);}
public void onCreate(SQLiteDatabase db) { // Create the table db.execSQL(CREATE_RPO); }
//Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older table if existed db.execSQL(DELETE_PRO); //Create tables again onCreate(db);
}
public void insertProvince(String pname) {
// Open the database for writing SQLiteDatabase db = this.getWritableDatabase(); // Start the transaction. db.beginTransaction(); ContentValues values;
try
{ values = new ContentValues(); values.put("pname", pname); // Insert Row db.insert(TABLE_PRO, null, values); // Insert into database successfully. db.setTransactionSuccessful();
} catch (Exception e) { e.printStackTrace();
}
finally
{ db.endTransaction(); // End the transaction. db.close(); // Close database } }
public ArrayList<String> getAllProvinces(){
ArrayList<String> list=new ArrayList<String>(); // Open the database for reading SQLiteDatabase db = this.getReadableDatabase(); // Start the transaction. db.beginTransaction();
try {
String selectQuery = "SELECT * FROM "+ TABLE_PRO; Cursor cursor = db.rawQuery(selectQuery, null); if(cursor.getCount() >0)
{ while (cursor.moveToNext()) { // Add province name to arraylist String pname= cursor.getString(cursor.getColumnIndex("pname")); list.add(pname);
}
} db.setTransactionSuccessful();
} catch (SQLiteException e) { e.printStackTrace();
} finally { db.endTransaction(); // End the transaction. db.close();
// Close database } return list;
}
}
In the MainActivity class that hosts the Spinner, you call the insertProvince() method of DataHelper to insert some sample data. Then call the getAllProvinces() method to read the sample data back to display in the Spinner.

public class MainActivity extends Activity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create DataHelper object and insert some sample data DataHelper datahelper=new DataHelper(this); datahelper.insertProvince("Kandal"); datahelper.insertProvince("Kep"); datahelper.insertProvince("Koh Kong"); datahelper.insertProvince("Takeo"); // Get sample data from the database and display them in the spinner Spinner spinner=(Spinner)findViewById(R.id.spinner); ArrayList<String> list=datahelper.getAllProvinces(); ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list); spinner.setAdapter(adapter);
}


Android-add-sqlite-data-to-spinner

Posted by: Dara | post date: 02-01-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.