Theme images by Storman. Powered by Blogger.

Monday 6 March 2017

Android SQLite Database Tutorial | SQLite step by step Tutorial

- 16 comments
Hello warriors what going on guys hope you all are doing well , Today I am going to share with you a topic which is Backbone of any app called SQLite Database.






No doubt you can save small and simple data in SharedPrefrences but when you need to save complex and repeated data SQLite play a big role in that situation.So like every post i will make module of steps and we will follow all step to complete this tutorial. In this post we are going to
make a sample project in which we will save user data in First Activity and will show it in Recycler view of Second Activity,we will also add a delete button in Recyclerview of second Activity to delete that row you can see preview in above picture.


  • Create a new project in your Android Studio Go to File-> New ->New project and select Empty Activity from template and leave every thing as default.
  • Add Five EditText for username,college,place,userId and number, also add a button to activity_main.xml.
  • Create one more activity  and add Recyclerview to its xml.
  • Create a new Java class and name it DbHelper.
  • Extend SQLiteOpenHelper in DbHelper class.
  • Create a new Java class name it UserData and implement Serializable Interface to it and declare Five String varriable name,college,place,user_id and number in this class.
  • Write method in DbHelper class to insert user data in to Database and to delete from Database.
  • Write one more method to fetch all data from Database to show into Recyclerview 
  • Create a new Java class for Recyclerview  Adapter and complete all the code for Recyclerview Adapter.
  • Save user data in MainActivity on Button click and call second Activity.
  • Show all the inserted data in Recyclerview of Second Activity.
Time to start coding with our First step.

1.Create a new project in your Android Studio Go to File-> New ->New project and select Empty Activity from template and leave every thing as default. like below picture.





2.Add Five EditText for username,college,place,userId and number, also add a button to activity_main.xml. here is my activity_main.xml.

3.Create one more activity  and add Recyclerview to its xml. To add Recyclerview you also need to add Library for Recyclerview in my case I added Design Support Library to build.gradle of app module. you can use either Support Library for Recyclerview or Design Support Library Simply copy and Paste one library from below code.

compile 'com.android.support:recyclerview-v7:23.1.0'
  compile 'com.android.support:design:23.1.1'

Now Add Recyclerview to xml of Second Activity here is my xml of Second Activity.


4.Create a new Java class and name it DbHelper. Now we are going to play with SQLite.

5.Extend SQLiteOpenHelper in DbHelper class. when you will extend this class it will ask you to implement its methods onCreate(SQLiteDatabase db) and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersionit will also ask you to create a constructor matching super. after messing with all these your class will be like this.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class DbHelper extends SQLiteOpenHelper {
    
    
    public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

Now I will add some variables for Database name,Table name,Database version and all the column name like this.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
    private static final String TAG = "DbHelper";
    // Database Info
    private static final String DATABASE_NAME = "UserDatabase";
    private static final int DATABASE_VERSION = 1;

    //Table Names
    private static final String TABLE_USERdETAIL = "userdetail";


    //userdetail Table Columns
    private static final String _ID = "_id";
    private static final String NAME = "name";
    private static final String COLLEGE = "college";
    private static final String PLACE = "place";
    private static final String USER_ID = "userId";
    private static final String NUMBER = "number";

Now i will add SQL query to create Table inside onCreate(),for that i am making a string of query to create Table and here is that String.



1
2
3
4
5
6
7
8
9
String CREATE_USERDETAIL_TABLE = "CREATE TABLE " + TABLE_USERdETAIL +
                "(" +
                _ID + " INTEGER PRIMARY KEY ," +
                USER_ID + " TEXT," +
                NAME + " TEXT," +
                COLLEGE + " TEXT," +
                PLACE + " TEXT," +
                NUMBER + " TEXT" +
                ")";

you can see i am making _id as primary key and it will auto increase. Now  use execSQL() method to execute query. here is my onCreate() method .


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
  /*
    Called when the database is created for the FIRST time.
    If a database already exists on disk with the same DATABASE_NAME, this method will NOT be called.
    */

    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_USERDETAIL_TABLE = "CREATE TABLE " + TABLE_USERdETAIL +
                "(" +
                _ID + " INTEGER PRIMARY KEY ," +
                USER_ID + " TEXT," +
                NAME + " TEXT," +
                COLLEGE + " TEXT," +
                PLACE + " TEXT," +
                NUMBER + " TEXT" +
                ")";
        db.execSQL(CREATE_USERDETAIL_TABLE);
    }

Since onUpgrade()  method is use to update your Database But i will refer you to Drop complete table and call onCreate() method inside onUpgrade() and add updation code inside onCreate(),here is my onUpgrade() method.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 /*
    Called when the database needs to be upgraded.
    This method will only be called if a database already exists on disk with the same DATABASE_NAME,
    but the DATABASE_VERSION is different than the version of the database that exists on disk.
    */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion != newVersion) {
            // Simplest implementation is to drop all old tables and recreate them
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERdETAIL);

            onCreate(db);
        }
    }

Now i am updating existing constructor and also adding a method which will return instance of DbHelper I will use this method in complete code where i need instance of DbHelper to insert,update or delete data. here is my constructor and getInstance() method.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 private static DbHelper mDbHelper;


    public static synchronized DbHelper getInstance(Context context) {
        // Use the application context, which will ensure that you
        // don't accidentally leak an Activity's context.

        if (mDbHelper == null) {
            mDbHelper = new DbHelper(context.getApplicationContext());
        }
        return mDbHelper;
    }


    /**
     * Constructor should be private to prevent direct instantiation.
     * Make a call to the static method "getInstance()" instead.
     */
    private DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

5.Create a new Java class name it UserData and implement Serializable Interface to it and declare Five String varriable name,college,place,user_id and number in this class.
here is my UserData class.

6.Write method in DbHelper class to insert user data in to Database and to delete from Database.
In this step we will make three method one for Insert data,one for delete data and one for fetch all data. steps are simple.
  • Call getWritableDatabase()/getReadableDatabase() according to need.
  • Begin Transaction
  • Execute query
  • End Transaction
Here is all three method..


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
 /*
   Insert a  user detail into database
   */

    public void insertUserDetail(UserData userData) {

        SQLiteDatabase db = getWritableDatabase();

        db.beginTransaction();

        try {
            ContentValues values = new ContentValues();
            values.put(NAME, userData.name);
            values.put(COLLEGE, userData.college);
            values.put(PLACE, userData.place);
            values.put(USER_ID, userData.user_id);
            values.put(NUMBER, userData.number);

            db.insertOrThrow(TABLE_USERdETAIL, null, values);
            db.setTransactionSuccessful();
        } catch (SQLException e) {
            e.printStackTrace();
            Log.d(TAG, "Error while trying to add post to database");
        } finally {

            db.endTransaction();
        }


    }
    
   /* 
   fetch all data from UserTable
    */

    public List<UserData> getAllUser() {

        List<UserData> usersdetail = new ArrayList<>();

        String USER_DETAIL_SELECT_QUERY = "SELECT * FROM " + TABLE_USERdETAIL;

        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(USER_DETAIL_SELECT_QUERY, null);

        try {
            if (cursor.moveToFirst()) {
                do {
                    UserData userData = new UserData();
                    userData.name = cursor.getString(cursor.getColumnIndex(NAME));
                    userData.college = cursor.getString(cursor.getColumnIndex(COLLEGE));
                    userData.place = cursor.getString(cursor.getColumnIndex(PLACE));
                    userData.user_id = cursor.getString(cursor.getColumnIndex(USER_ID));
                    userData.number = cursor.getString(cursor.getColumnIndex(NUMBER));


                    usersdetail.add(userData);

                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Log.d(TAG, "Error while trying to get posts from database");
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
            }
        }

        return usersdetail;

    }

    /*
   Delete single row from UserTable 
     */
    void deleteRow(String name) {
        SQLiteDatabase db = getWritableDatabase();


        try {
            db.beginTransaction();
            db.execSQL("delete from " + TABLE_USERdETAIL + " where name ='" + name + "'");
            db.setTransactionSuccessful();
        } catch (SQLException e) {
            Log.d(TAG, "Error while trying to delete  users detail");
        } finally {
            db.endTransaction();
        }


    }

7.Create a new Java class for Recyclerview  Adapter and complete all the code for Recyclerview Adapter.
In this step I am creating a new java class name as ListAdapter and extend Recyclerview.Adapter ,If you are not familiar with Recyclerview check our Recyclerview tutorial . So  first make a layout for single row of Recyclerview ,I am making a simple layout with one TextView and one ImageView. TextView to show user name and ImageView for delete icon. here is xml for single row



Now i am creating a Interface for callback to get position of item to delete. and then we will call delete  method of SQLite to delete that row from Activity. Here is My Interface.
Now here is complete code for ListAdapter class.
8.Save user data in MainActivity on Button click and call second Activity. Now open your MainActivity and Register all your EditText and Button and save all data in SQLite by using Insert method of DbHelper on Button click. here is my MainActivity.java.
Don't be confused because code is very simple. onClick of button I am checking Text of all EditText  for null and Empty in that case I am saving empty string. I am saving Text of Every EditText into UserData object and calling insertUserDetail() method to save data into SQLite.

9.Show all the inserted data in Recyclerview of Second Activity. Open your Second Activity and Register Recyclerview.  get all user data by calling getAllUser() method of DbHelper and pass List of type UserData type to ListAdapter. here is code of  Second Activity .

Hey finally we have completed this tutorial, I know it was a lengthy tutorial but trust me If you follow all the steps it will help you a lot. Still having any problem feel free to comment below.

Sunday 5 March 2017

Android Recyclerview Example Tutorial | Recyclerview and Cardview Android

- 8 comments
Hello warriors whats up guys today i am going to share with you another two  great member of Material family called Recyclerview and Cardview.




If you are not familiar with these widgets then you are wondering about this. so  First of all i am going to give some intro of these two widget.


Recyclerview : 

The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. for more go to this link...

 CardView : 

CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the platform. CardView widgets can have shadows and rounded corners. for more go to this link...

 I hope now you are not wondering. you can say Recyclerview is an advance version of Listview but its not a Replacement of Listview. Time to start with coding so like each post First of all i will make a module of steps and then we will follow all the step to complete this tutorial.


  1. Create a new project using your android studio File>>New>>New Project. My project name is RecyclerviewDemo you can use your own.
  2. Add Recylerview and CardView dependencies to build.gradle(Module:app).
  3. Add Recylerview to our activity_main.xml and complete this layout.
  4. Create a new layout for single row of Recyclerview using Cardview.
  5. Create an RecylerAdapter java class for Recyclerview by extending RecyclerView.Adapter.
  6. Create a RecylerViewHolder java class for Recyclerview by extending RecyclerView.ViewHolder.
  7. Set Recylerview in MainActivity and complete everything.



1.Create new project :

Open your Android studio and create a new project Go to File>>New>>New project and name it what you want in my case project name is RecyclerViewDemo like below picture.

Leave everything as default and Select Empty Activity from template like below image.


and finish it.

2. Add Recylerview and CardView dependencies to build.gradle(Module:app).

 Go to GradleScripts>>build.gradle(Module:app) and add below libraries to this file under dependencies block like below image.
         compile 'com.android.support:cardview-v7:23.0.1'
         compile 'com.android.support:recyclerview-v7:23.0.1'




after adding dependencies sync your project.

3. Add Recylerview to our activity_main.xml and complete this layout.

Open your activity_main.xml file and add Recyclerview to it . here is my complete activity_main.xml file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?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"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="16dp"
        android:paddingTop="16dp"
        android:scrollbars="vertical"
         />

</RelativeLayout>


4. Create a new layout for single row of Recyclerview using Cardview:

For single row of Recyclerview i am going to make a simple layout with one imageview and two text for title and description. and complete layout is wrapped inside cardview to give it some good look. here is my item_list.xml 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:background="#C5CAE9"
    android:foreground="?attr/selectableItemBackground"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/list_avatar"
        android:layout_width="40dp"
        android:layout_height="40dp"
       android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="10dp"
        android:scaleType="centerCrop"
        android:src="@drawable/icon" />

    <TextView
        android:id="@+id/list_title"
        android:layout_centerVertical="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/list_avatar"
        android:text="Androidwarriors "
        android:textColor="#000000"
        android:textAppearance="?attr/textAppearanceListItem"
        android:textSize="16sp" />

    <TextView
        android:id="@+id/list_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/list_title"
        android:layout_marginLeft="16dp"
        android:layout_toRightOf="@+id/list_avatar"
        android:textColor="#000000"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Place to dive into android programming"
        android:textAppearance="?attr/textAppearanceListItem"
        android:textSize="14sp" />
</RelativeLayout>
</android.support.v7.widget.CardView>


5. Create an RecylerAdapter java class for Recyclerview by extending RecyclerView.Adapter.

So  we have completed all layout stuff now need to do some java code. to connect data set and view we need an adapter as you have  already used adapter in Listview. but in case of Recyclerview we are not going to extend any base adapter or array adapter like Listview. For Recyclerview we are going to extend RecyclerView.Adapter in our Adapter class like below code.Create an new java class by Right click on your package and name it RecyclerAdapter and extend RecyclerView.Adapter it will ask you to implement three method 
  • onCreateViewHolder()
  • onBindViewHolder()
  • getItemCount()
like below code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class RecyclerAdapter extends RecyclerView.Adapter{

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }
}

Now we will complete some small things like we will make an array for title text . we will also make a context variable a LayoutInflater  object and a constructor of Adapter class just copy and paste below code in your adapter class above all the methods.



1
2
3
4
5
6
7
8
9
 String[] name = {"Androidwarriors", "Stackoverflow", "Developer Android", "AndroidHive",
            "Slidenerd", "TheNewBoston", "Truiton", "HmkCode", "JavaTpoint", "Javapeper"};
    Context context;
    LayoutInflater inflater;

    public RecyclerAdapter(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
    }


6.Create a RecylerViewHolder java class for Recyclerview by extending RecyclerView.ViewHolder. 

Right click on your package and create a new java class name it RecyclerViewHolder and extends RecyclerView.ViewHolder. in this define two textview and an imageview of item_list.xml file. copy and paste below code to your RecyclerViewHolder class. here is my complete code of RecyclerViewHolder.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by androidwarriros on 10/26/2015.
 */
public class RecyclerViewHolder extends RecyclerView.ViewHolder {

    TextView tv1, tv2;
    ImageView imageView;

    public RecyclerViewHolder(View itemView) {
        super(itemView);

        tv1 = (TextView) itemView.findViewById(R.id.list_title);
        tv2 = (TextView) itemView.findViewById(R.id.list_desc);
        imageView = (ImageView) itemView.findViewById(R.id.list_avatar);

    }
}

Now open your RecyclerAdapter and Replace RecyclerView.ViewHolder with RecyclerViewHolder in onCreateViewHolder() and onBindViewHolder(). and inflate item_list.xml file inside onCreateViewHolder(). also make object of RecyclerViewHolder inside onCreateViewHolder and return this object like below code. or simply Replace your onCreateViewHolder() with below code.



1
2
3
4
5
6
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = inflater.inflate(R.layout.item_list, parent, false);

        RecyclerViewHolder viewHolder = new RecyclerViewHolder(v);
        return viewHolder;
    }

Now inside onBindViewHolder() method set text to TextView from name array and we will also make onClickListener for click on ImageView of row of RecyclerView. So just copy and Replace your onBindViewHolder() with below code.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public void onBindViewHolder(RecyclerViewHolder holder, int position) {

        holder.tv1.setText(name[position]);
        holder.imageView.setOnClickListener(clickListener);
        holder.imageView.setTag(holder);
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            RecyclerViewHolder vholder = (RecyclerViewHolder) v.getTag();
            int position = vholder.getPosition();

            Toast.makeText(context, "This is position " + position, Toast.LENGTH_LONG).show();

        }
    };

One last thing to do in Adapter class is to set number of item or row of RecyclerView so inside getItemCount() method return number of row you want in my case this is length of name array.like below code.


1
2
3
4
@Override
    public int getItemCount() {
        return name.length;
    }

7.Set Recylerview in MainActivity and complete everything.

Open your MainActivity.java and we will complete following steps 
  • Define Recyclerview and register.
  • Make an object of RecyclerAdapter class and set Adapter to Recyclerview.
  • Set Layout Manager to Recyclerview in my case i am using LinearLayoutManager.
 here is my complete code of MainActivity.java just copy and paste this inside your MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);

        RecyclerAdapter adapter=new RecyclerAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setHasFixedSize(true);

        //Layout manager for Recycler view
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

Yo man we have completed this tutorial run your code and you can see a smart beautifull looking Recyclerview. you can download complete code from below button. If you are facing any problem feel free to comment.


https://github.com/androidwarriors/Recyclerviewdemo

Android Studio Drawable Folders | Drawable Folder in Android studio

- 31 comments
Hello warrios what's up guys....Today I am going to share with you how to use drawable folder in Android Studio. Since Google declared Android Studio as official IDE and Eclipse is deprecated by google.

Time to change our IDE from Eclipse to Android Studio. Android Studio is much more better than Eclipse for android app development according to my experience. You can download it from android developer website.

Now Let's come to our topic as we know that Eclipse gives subfolder of drawable folder by default for different screen size..

Drawable folder in Eclipse
  • Drawable-ldpi
  • Drawable-mdpi
  • Drawable-hdpi
  • Drawable-xhdpi
  • Drawable-xxhdpi
But in case of android studio things is little complicated.  Its little tricky you will see only single drawable folder in Android studio like this..


 


So now question is that how to add image for different screen. Follow my steps:
  • Copy an image for highest screen size or for xxhdpi folder 
  • Paste it in drawable folder you will see a popup like below

 
  • Add folder name after drawable according to your image. I will suggest to you to add image of xxhdpi resolution as you can see in below image and  you are done.

 
  • After this you can see your folder inside project structure but not under android you will see it under project. like below image seems confusing just look at right top corner of your editor you will see Android  just click on android you can see structure like below image and then select project.
 
  • After slecting Project Go to app-->src-->main-->res--> here is your xxhdpi drwable folder dude. for all different resolution repeat same steps  


After creating all folder when you will go to paste your image to drawable you will see a popup with all folder you just need to choose your folder.

I hope this tutorial will help you to solve drawable folder problem of android studio. if you like this dont forget to comment..njoy