Skip to main content
Sq-Lite and ListView(I) - Android Tutorial
This tutorial explain with the simple application which explains,
               - How to create sq-lite database
               - How to insert data into sq-lite database
               - How to retrieve the data from sq-lite and display it in ListView
               - Using SimpleCursorAdapter (Just to set list)


****screenshots uploaded shortly****


To create this simple application do the following:-
To create sq-lite database

Create the class with the name DBHelper with extends SQLiteOpenHelper and copy the following coding

public class DBHelper extends SQLiteOpenHelper {
   private static final int DATABASE_VERSION = 1;
   private static final String DATABASE_NAME = "todorecord.db";
   public static final String USER_NAME = "username";
   public static final String PASSWORD = "password";


   public static final String ROW_ID_FIELD = "_id";

   public static final String TASK_FIELD = "task_field";
   public static final String LOGIN_TABLE = "logintable";
   public static final String TODO_TABLE = "todotable";

   private static final String TODO_TABLE_QUERY = "CREATE TABLE "
         + TODO_TABLE +
         "(" + ROW_ID_FIELD + " integer primary key autoincrement, "
         + TASK_FIELD + " TEXT NOT NULL);";

   public DBHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }

   @Override
   public void onCreate(SQLiteDatabase db) {
      db.execSQL(TODO_TABLE_QUERY);

   }

   @Override
   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE_QUERY);

      onCreate(db);
   }
}

Create the class with the name DBUtil and copy the following coding

public class DBUtil {

   public static final String[] TODO_FIELDS = {
         DBHelper.ROW_ID_FIELD,
         DBHelper.TASK_FIELD
   };

   private DBHelper dbHelper;
   private SQLiteDatabase sqliteDb;
   private ContentValues contentValues;
   private Context context;

   public DBUtil(Context context) {
      this.context = context;
      contentValues = new ContentValues();
   }
   public SQLiteDatabase open() throws SQLException {
      if (dbHelper == null) {
         dbHelper = new DBHelper(context);
      }
      sqliteDb = dbHelper.getWritableDatabase();
      return sqliteDb;
   }

   public void close() {
      if (dbHelper != null) {
         dbHelper.close();
      }
   }

   public long addtask(String stredt) {
      contentValues.clear();
      contentValues.put(DBHelper.TASK_FIELD, stredt);

      return sqliteDb.insert(DBHelper.TODO_TABLE, null, contentValues);
   }

   public Cursor getalltask() {
      return sqliteDb.query(DBHelper.TODO_TABLE, TODO_FIELDS,
            null,
            null, null, null, null, null);
   }
}

Then create the activities

First Screen

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button btn1;
    ListView listview;
    private SimpleCursorAdapter dataAdapter;
    DBUtil dbUtil;

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


        btn1 = (Button) findViewById(R.id.btnid);
        listview = (ListView) findViewById(R.id.listid);
        btn1.setOnClickListener(this);

        dbUtil = new DBUtil(this);
        dbUtil.open();

        setlist();

    }

    private void setlist() {

        Cursor cur = dbUtil.getalltask();

        if (cur.moveToFirst() && cur != null) {
            cur.moveToLast();

            int c = cur.getCount();

            Log.e("COUNT9",""+c);

            final String[] from = new String[]{DBHelper.ROW_ID_FIELD,
                    DBHelper.TASK_FIELD};

            final int[] to = new int[]{R.id.textView1, R.id.textView2};


            dataAdapter = new SimpleCursorAdapter(
                    this, R.layout.list_text_two,
                    cur,
                    from,
                    to,
                    0);

            listview.setAdapter(dataAdapter);
        } else{
            Toast.makeText(this, "No To-Do entry", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btnid: /** Start a new Activity MyCards.java */
                Intent intent = new Intent(this, AddTodo.class);
                this.startActivity(intent);
                break ;
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mrbrown.todo.MainActivity">

   <LinearLayout
       android:id="@+id/lineid"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="#6666ff">

       <Button
           android:id="@+id/btnid"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="ADD"
           android:layout_marginLeft="270dp"
           />
   </LinearLayout>

    <ListView
        android:id="@+id/listid"
        android:layout_below="@+id/lineid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
</ListView>
</RelativeLayout>


list_text_two.xml for ListView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/textView1"
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:visibility="gone"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textView2"
            android:layout_weight="20"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

        <Button
            android:layout_weight="2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="X"/>

    </LinearLayout>

</RelativeLayout>


Second Screen

AddTodo.java

public class AddTodo extends Activity implements View.OnClickListener{

    DBUtil dbUtil;

    EditText edt;
    Button btn2;
    String stredt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Add Record");
        setContentView(R.layout.add_todo);

        edt = (EditText) findViewById(R.id.edtid);
        btn2 = (Button) findViewById(R.id.btn2id);
        btn2.setOnClickListener(this);

        dbUtil = new DBUtil(this);
        dbUtil.open();

    }

    @Override
    public void onClick(View v) {

        switch(v.getId()){
            case R.id.btn2id: /** Start a new Activity MyCards.java */

                stredt=edt.getText().toString();

                if(stredt.length()>0){

                    dbUtil.addtask(stredt);
                    edt.setText("");

                    Intent intent = new Intent(this, MainActivity.class);
                    this.startActivity(intent);
                }

                break;
        }
    }
}


add_todo.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mrbrown.todo.MainActivity">

    <LinearLayout
        android:id="@+id/lineid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#6666ff">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ADD"
            android:layout_marginLeft="150dp"
            android:textStyle="bold"
            android:textSize="30dp"/>

    </LinearLayout>

    <EditText
        android:id="@+id/edtid"
        android:layout_below="@+id/lineid"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter here..."/>

    <Button
        android:id="@+id/btn2id"
        android:layout_below="@+id/edtid"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="125dp"
        android:text="Submit"/>
</RelativeLayout>


Add WRITE_EXTERNAL_STORAGE to manifest

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>


Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mrbrown.todo">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


        <activity android:name=".AddTodo">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

________________________________________________________

Happy Coding...



Comments

Popular posts from this blog

Spinner with Search on DropDown - Android Tutorial

If you have more values on Dropdown of Spinner its hard to select the last item by making a long scroll. To overcome this issue Android introduced a component called  AutoCompleteTextView Yes it is!!! Then why Spinner with Search? There may be some requirement even though gave much knowledge about it. There is a simple and good library that helps us to achieve this -  SearchableSpinner Gradle dependencies {     ...     implementation 'com.toptoche.searchablespinner:searchablespinnerlibrary:1.3.1' } Usage Now replace your Normal Android Spinner on XML with the following < com.toptoche.searchablespinnerlibrary.SearchableSpinner     android:id="@+id/id_city"     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:background="@android:color/transparent"     android:padding="5dp" /> ______________________________________...

Get Phone Number from Contact List - Android Tutorial

When you create an application to send sms or an application to make calls, getting a destination number from the contacts list is a common task. In this Android tip, I am going to show the code to fetch a number from the contacts list. Now let me tell you how to achieve the goal. First, you need to create an Intent object for the PICK_ACTION action. To open the contacts list, the table that contains the contacts information must be specified as a parameter of the constructor of the Intent class. You can refer to the table using ContactsContract.Contacts.CONTENT_URI. Then call the startActivityForResult () method passing the Intent object and request code to open the contacts list. After a contact is selected from the contacts list, to get the result, you need to override the onActivityResult(int reqCode, int resultCode, Intent data) method of the activity. You can call the getData() method of the data parameter to get the table or uri that contains the selected contact. From the t...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...