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

Zoom Image - Android Tutorial

Here we are going to see how to zoom an image in Imageview Will see it through a sample 1. Create xml with an ImageView <? xml version="1.0" encoding="utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout       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=".MainActivity" >     < LinearLayout         android:layout_width="200dp"         android:layout_height="200dp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintLeft_toLeftOf="parent"         app:layout_constraintRight_toRightOf="parent"    ...

Add custom font in Android using Calligraphy library

Are you fed up of Custom Views to set fonts? Or traversing the ViewTree to find TextViews? Sometime we want some other font for our Android application then you can add custom font in Android using Calligraphy library . Dependency Include the dependency Download (.aar) dependencies { compile ‘uk.co.chrisjenx:calligraphy:2.2.0’ } Add Fonts Add your custom fonts to assets/ . All font definitions are relative to this path. On Assets you should right-click New Directory, call it "fonts". In the finder put the .ttf  or .otf  font files in there. Create Class Create a class that extends Application and write this code public class App extends Application { @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("your font path") .setFontAttrId(...

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 ...