Skip to main content

Featured post

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND

SQLite Database Example

This is simple sqlite database tutorial without using External database. If you want to know how use external database in android then please click me!
To create and access a table in android using SQLite is very simple. The following method will show how to create a table and see column names of that table in android.
public void table1() {

  db = this.getWritableDatabase();

  db.execSQL("CREATE TABLE IF NOT EXISTS table1(id INTEGER PRIMARY KEY AUTOINCREMENT , description TEXT)");
  // to see colomn names in our table1
  Cursor t = db.rawQuery("PRAGMA TABLE_INFO(table1)", null);
  if (t.moveToFirst()) {
   do {
    Log.i("", t.getString(0) + " " + t.getString(1));
   } while (t.moveToNext());
  }
  t.close();
  db.close();

 }
And the following sample code is used to insert data into table.
public void inserIntoTable1(String desc) {

  db = this.getWritableDatabase();
  ContentValues cv = new ContentValues();
  try {
   db.beginTransaction();
   cv.put("description", desc);
   db.insert("table1", null, cv);
   db.setTransactionSuccessful();

  } catch (Exception ex) {

  } finally {
   db.endTransaction();
   db.close();
  }
 }
And the following code is used to access data from our table. The method will return data as list.
public List<String> getData() {
  db = this.getReadableDatabase();
  List<String> data = new ArrayList<String>();
  Cursor c = db.rawQuery("SELECT * FROM table1", null);
  while (c.moveToNext()) {
   data.add(c.getString(1));
  }
  c.close();
  db.close();
  return data;
 }
Now we can populate those data into our listview.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, list); 
  mylist = (ListView) findViewById(R.id.listView1);
  mylist.setAdapter(adapter);
Full code. main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Description" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Save" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

<LinearLayout>
DBHelper.java
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;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

 final static String dbname = "Sample";
 SQLiteDatabase db;

 public DBHelper(Context context) {
  super(context, dbname, null, 1);
  // TODO Auto-generated constructor stub
 }

 public void table1() {

  db = this.getWritableDatabase();

  db.execSQL("CREATE TABLE IF NOT EXISTS table1(id INTEGER PRIMARY KEY AUTOINCREMENT , description TEXT)");
  // to see colomn names in our table1
  Cursor t = db.rawQuery("PRAGMA TABLE_INFO(table1)", null);
  if (t.moveToFirst()) {
   do {
    Log.i("", t.getString(0) + " " + t.getString(1));
   } while (t.moveToNext());
  }
  t.close();
  db.close();

 }

 public void inserIntoTable1(String desc) {

  db = this.getWritableDatabase();
  ContentValues cv = new ContentValues();
  try {
   db.beginTransaction();
   cv.put("description", desc);
   db.insert("table1", null, cv);
   db.setTransactionSuccessful();

  } catch (Exception ex) {

  } finally {
   db.endTransaction();
   db.close();
  }
 }

 public List<String> getData() {
  db = this.getReadableDatabase();
  List<String> data = new ArrayList<String>();
  Cursor c = db.rawQuery("SELECT * FROM table1", null);
  while (c.moveToNext()) {
   data.add(c.getString(1));
  }
  c.close();
  db.close();
  return data;
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
 }

 @Override
 public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
  // TODO Auto-generated method stub

 }

}

SQLiteActivity.java
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class SQLiteActivity extends Activity {

 DBHelper dbhelper;
 Button save;
 EditText discription;
 ListView mylist;

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

  dbhelper = new DBHelper(this);

  accessTable1();
  loadMyList();
 }

 private void accessTable1() {
  dbhelper.table1();
  discription = (EditText) findViewById(R.id.editText1);
  save = (Button) findViewById(R.id.button1);
  save.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    dbhelper.inserIntoTable1(discription.getText().toString());
    loadMyList();
   }
  });
 }

 private void loadMyList() {
  List<String> list = dbhelper.getData();
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, list); 
  mylist = (ListView) findViewById(R.id.listView1);
  mylist.setAdapter(adapter);
 }
}


Reduce your work by using SQLiteHelper.jar

sample screen shot

 

Thank You

Comments

  1. Hi, i've found this exactly what i needed, but my java/android compiler says that List&ltString&gt doesn't exist (using 2.3.3 API, last version of Java), any clue about that or where to find the List&ltString&gt.java or something like that so i can make this code work?, thx ind advance :3

    ReplyDelete
    Replies
    1. Sorry friend :( It is my problem only. Just replace "&lt" with "<" symbol and "&gt" with ">" symbol. See my updates.

      Delete
    2. Thx u so much for that fast reply :3

      Delete

Post a Comment

Popular posts from this blog

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code. You can download the source code from OCRSample and import the library as a module into your project. Example usage : MainActivity.java public class MainActivity extends AppCompatActivity { private TextView textView; private final int CAMERA_SCAN_TEXT = 0; private final int LOAD_IMAGE_RESULTS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSele

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i

Set limit for fraction in decimal numbers in EditText

            Already we know that we can set which type of input the edittext should accept from user using android:inputType="numberDecimal" But there is no predefined function to set the limit for the edittext to How many digit it should accept after the decimal point from user . We can achieve this by using TextWatcher . Full code example. Following program creates a Decimal Filter. DecimalFilter.java import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class DecimalFilter implements TextWatcher { int count= -1 ; EditText et; Activity activity; public DecimalFilter(EditText edittext, Activity activity) { et = edittext; this.activity = activity; } public void afterTextChanged(Editable s) { if (s.length() > 0) { String str = et.getText().toString(); et.setOnKeyListener(new OnKeyL