Monday, June 12, 2017

Android Content Provider

June 12, 2017

Welcome to this post.
In this post we are going we learn about Content Provider.

Content Provider
Content Provider


In the previous post
, we work with the database. We learn how to create a database. How to use contract class. But we don't write any methods to access the database.

In this post, we learn about how to access the database. For access database, we use the content provider.
Let's start-

Before the start, we need contact class. please take a look

First, create a class and extend Content provider. In this case, my class name is DataProvider
public class DataProvider extends ContentProvider {
}
Now we have to override some methods.
1.query
2.insert
3.update
4.delete
5.getType
and Oncreate

let's do this one by one
OnCreate-
@Override
  public boolean onCreate() {
  return false;
  }
Query-
@Nullable
  @Override
  public Cursor query(@NonNull Uri uri, @Nullable String[] projection,
  @Nullable String selection, @Nullable String[] selectionArgs,
  @Nullable String sortOrder) {

  return null;
  }
Insert-
@Nullable
  @Override
  public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {

  return null;
  }
Update-
@Override
  public int update(@NonNull Uri uri, @Nullable ContentValues values,
  @Nullable String selection, @Nullable String[] selectionArgs) {

  return 0;
  }
Delete-
@Override
  public int delete(@NonNull Uri uri, @Nullable String selection,
  @Nullable String[] selectionArgs) {

  return 0;
  }
getType-
@Nullable
@Override
public String getType(@NonNull Uri uri) {
  return null;
}

Now we have to add two variable to chek what type of data requested. If the value is 100 then requested full table data or if value match with 101 then it's requested for a single row data.
Let's add
//use to get all data from this path
private static final int TASKS = 100;
//use to get single data from a single row
private static final int TASK_WITH_ID = 101;
Now we add a matcher to match with URI and also we add a method to match- method-
private static UriMatcher buildUriMatcher() {

  // Initialize a UriMatcher with no matches by passing in NO_MATCH to the constructor
  UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

  /*
  *All paths added to the UriMatcher have a corresponding int.
  For each kind of uri you may want to access, add the 
  corresponding match with addURI.
  The two calls below add matches for the task directory and a single item by ID.
 if you are using string then use * insted of #
  */
  matcher.addURI(DB_Contract.AUTHORITY,DB_Contract.PATH_TASKS,TASKS);
  matcher.addURI(DB_Contract.AUTHORITY,DB_Contract.PATH_TASKS + "/#",TASK_WITH_ID);

  return matcher;
  }
now add a UriMatcher variable and initialize it through calling builUriMatcher():
//match with which uri
private static final UriMatcher sUriMatcher = buildUriMatcher();
add another instance to access variables-
private DatabaseHelper mHelper;
initialize it on Oncreate methods-
@Override
  public boolean onCreate() {

  //create db instance
  mHelper = new DatabaseHelper(getContext());
  return true;
  }
Now we have a database. Time to write insert method for data-
1.First, we create an SQLiteDatabase through mHelper and database type must be written able database.Because we insert data into the database.
2.create an integer variable and initialize it by calling sUriMatcher.match(uri) and pass uri.
3.Now create a new Uri and this uri will be returned through this methods
4.now create a switch statement on the basis of match(int variable)
5.if case is 100 we insert data
6. inserted result is will be saved in a long variable
7. If the long variable is greater that zero the data inserted successfully and we also created a URI in this condition.
8.After that, we set a notification that's data is changed. Now see the code-
@Nullable
  @Override
  public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {

  SQLiteDatabase database = mHelper.getWritableDatabase();

  int match = sUriMatcher.match(uri);
  //uri
  Uri returnUri;

  switch (match){

  case TASKS:
  long inserted = database.insert(DB_Contract.Entry.TASK_TABLE_NAME,null,values);

  if (inserted > 0){
  //success
  returnUri = ContentUris.withAppendedId(DB_Contract.Entry.CONTENT_URI,inserted);
  } else {
  throw new RuntimeException("FAILED TO INSERTED DATA: "+uri);
  }
  break;

  default:
  throw new UnsupportedOperationException("Unknown Uri: " + uri);
  }

  //notify data has changed

  if (getContext() != null){
  getContext().getContentResolver().notifyChange(uri,null);
  }

  return returnUri;
  }
Ok, Now Query method- 1.First, we create an SQLiteDatabase through mHelper and database type must be the readable database.Because we do not insert any data into the database.
2.create an integer variable and initialize it by calling sUriMatcher.match(uri) and pass uri.
3.Now create a new Cursor and this cursor will be returned through this method
4.now create a switch statement on the basis of match(int variable)
5. I f case is 100, then we have to provide all data in the table. or If the case will be 101, we have to provide a single row data
6. query result is will be saved in a cursor
7. If the cursor is not null we have to set Notification uri
See the code-
@Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection,
                        @Nullable String selection, @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {

        //get db
        final SQLiteDatabase database = mHelper.getWritableDatabase();

        //type of uri match
        int match = sUriMatcher.match(uri);

        Cursor returnCursor;

        switch (match){

            //all data in a table uri
            case TASKS:
                returnCursor = database.query(
                        //table
                        DB_Contract.Entry.TASK_TABLE_NAME,
                        //selected column
                        projection,
                        //section
                        selection,
                        //selection arg
                        selectionArgs,
                        //group by
                        null,
                        //having
                        null,
                        sortOrder);
                break;

            // Add a case to query for a single row of data by ID
            // Use selections and selectionArgs to filter for that ID
            case TASK_WITH_ID:
                // Get the task name from the URI
                String taskID = uri.getPathSegments().get(1);
                // Selection is the _ID column = ?, and the Selection args = the row ID from the URI
                String mSelection = DB_Contract.Entry._ID + " = ? ";
                String[] mSelectionArg = new String[]{taskID};

                // Construct a query as you would normally, passing in the selection/args
                returnCursor = database.query(DB_Contract.Entry.TASK_TABLE_NAME,
                        projection,
                        mSelection,
                        mSelectionArg,
                        null,
                        null,
                        sortOrder);

                break;

            default:
                throw new UnsupportedOperationException("Unknown Uri: " + uri);
        }


        //set notification for data changed
        assert getContext() != null;
        returnCursor.setNotificationUri(getContext().getContentResolver(),uri);

        return returnCursor;
    }
Note: See code comment for better understanding. Update and delete methods are same as those two methods but have some difference. Let's see the code one by one. Follow code comment for better understanding- Update-
@Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values,
                      @Nullable String selection, @Nullable String[] selectionArgs) {

        final SQLiteDatabase db = mHelper.getWritableDatabase();

        //Keep track of if an update occurs
        int tasksUpdated;

        // match code
        int match = sUriMatcher.match(uri);

        switch (match) {

            case TASK_WITH_ID:

                //update a single task by getting the id
                String taskId = uri.getPathSegments().get(1);
                //using selections

                String whereClause = DB_Contract.Entry._ID + " = ? ";
                String[] whereArgs = new String[]{taskId};

                tasksUpdated = db.update(DB_Contract.Entry.TASK_TABLE_NAME, values,
                        whereClause, whereArgs);

                break;

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }

        if (tasksUpdated != 0) {
            //set notifications if a task was updated
            assert getContext() != null;
            getContext().getContentResolver().notifyChange(uri, null);
        }

        // return number of tasks updated
        return tasksUpdated;
    }
Delete-
@Override
    public int delete(@NonNull Uri uri, @Nullable String selection,
                      @Nullable String[] selectionArgs) {

        final SQLiteDatabase db = mHelper.getWritableDatabase();

        int match = sUriMatcher.match(uri);

        //uri
        int taskDelete;

        switch (match) {

            case TASK_WITH_ID:
                // Get the id from the URI
                String taskId = uri.getPathSegments().get(1);
                // Selection is the _ID column = ?, and the Selection args = the row ID from the URI
                String whereClause = DB_Contract.Entry._ID + " = ? ";
                String[] whereArgs = new String[]{taskId};

                taskDelete = db.delete(DB_Contract.Entry.TASK_TABLE_NAME,
                        whereClause,
                        whereArgs);
                break;

            default:
                throw new UnsupportedOperationException("Unknown Uri: " + uri);
        }

        if (taskDelete != 0) {
            // A task was deleted, set notification
            assert getContext() != null;
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return taskDelete;
    }
One more method left to do. But if you are not exported you database this method is not needed anymore-
@Nullable
@Override
public String getType(@NonNull Uri uri) {
        int match = sUriMatcher.match(uri);

        switch (match) {

            case TASKS:
                // directory
                return "vnd.android.cursor.dir" + "/" + DB_Contract.AUTHORITY + "/" + DB_Contract.PATH_TASKS;

            case TASK_WITH_ID:
                // single item type
                return "vnd.android.cursor.item" + "/" + DB_Contract.AUTHORITY + "/" + DB_Contract.PATH_TASKS;

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }

    }
That's it. Now we have CRUDE methods and nor we can access database and inserted data- Now time for full code-
public class DataProvider extends ContentProvider {
    

    //use to get all data from this path
    private static final int TASKS = 100;
    //use to get single data from a single row
    private static final int TASK_WITH_ID = 101;
    //match with which uri
    private static final UriMatcher sUriMatcher = buildUriMatcher();

    private DatabaseHelper mHelper;

    private static UriMatcher buildUriMatcher() {

        // Initialize a UriMatcher with no matches by passing in NO_MATCH to the constructor
        UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

        /*
          *All paths added to the UriMatcher have a corresponding int.
          For each kind of uri you may want to access, add the corresponding match with addURI.
          The two calls below add matches for the task directory and a single item by ID.
         */
        matcher.addURI(DB_Contract.AUTHORITY,DB_Contract.PATH_TASKS,TASKS);
        matcher.addURI(DB_Contract.AUTHORITY,DB_Contract.PATH_TASKS + "/#",TASK_WITH_ID);

        return matcher;
    }

    @Override
    public boolean onCreate() {

        //create db instance
        mHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Nullable
    @Override
    public Cursor query(@NonNull Uri uri, @Nullable String[] projection,
                        @Nullable String selection, @Nullable String[] selectionArgs,
                        @Nullable String sortOrder) {

        //get db
        final SQLiteDatabase database = mHelper.getWritableDatabase();

        //type of uri match
        int match = sUriMatcher.match(uri);

        Cursor returnCursor;

        switch (match){

            //all data in a table uri
            case TASKS:
                returnCursor = database.query(
                        //table
                        DB_Contract.Entry.TASK_TABLE_NAME,
                        //selected column
                        projection,
                        //section
                        selection,
                        //selection arg
                        selectionArgs,
                        //group by
                        null,
                        //having
                        null,
                        sortOrder);
                break;

            // Add a case to query for a single row of data by ID
            // Use selections and selectionArgs to filter for that ID
            case TASK_WITH_ID:
                // Get the task name from the URI
                String taskID = uri.getPathSegments().get(1);
                // Selection is the _ID column = ?, and the Selection args = the row ID from the URI
                String mSelection = DB_Contract.Entry._ID + " = ? ";
                String[] mSelectionArg = new String[]{taskID};

                // Construct a query as you would normally, passing in the selection/args
                returnCursor = database.query(DB_Contract.Entry.TASK_TABLE_NAME,
                        projection,
                        mSelection,
                        mSelectionArg,
                        null,
                        null,
                        sortOrder);

                break;

            default:
                throw new UnsupportedOperationException("Unknown Uri: " + uri);
        }


        //set notification for data changed
        assert getContext() != null;
        returnCursor.setNotificationUri(getContext().getContentResolver(),uri);

        return returnCursor;
    }


    @Nullable
    @Override
    public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {

        SQLiteDatabase database = mHelper.getWritableDatabase();

        int match = sUriMatcher.match(uri);
        //uri
        Uri returnUri;

        switch (match){

            case TASKS:
                long inserted = database.insert(DB_Contract.Entry.TASK_TABLE_NAME,null,values);

                if (inserted > 0){
                    //success
                    returnUri = ContentUris.withAppendedId(DB_Contract.Entry.CONTENT_URI,inserted);
                } else {
                    throw new RuntimeException("FAILED TO INSERTED DATA: "+uri);
                }
                break;

            default:
                throw new UnsupportedOperationException("Unknown Uri: " + uri);
        }

        //notify data has changed

        if (getContext() != null){
            getContext().getContentResolver().notifyChange(uri,null);
        }

        return returnUri;
    }

    @Override
    public int delete(@NonNull Uri uri, @Nullable String selection,
                      @Nullable String[] selectionArgs) {

        final SQLiteDatabase db = mHelper.getWritableDatabase();

        int match = sUriMatcher.match(uri);

        //uri
        int taskDelete;

        switch (match) {

            case TASK_WITH_ID:
                // Get the id from the URI
                String taskId = uri.getPathSegments().get(1);
                // Selection is the _ID column = ?, and the Selection args = the row ID from the URI
                String whereClause = DB_Contract.Entry._ID + " = ? ";
                String[] whereArgs = new String[]{taskId};

                taskDelete = db.delete(DB_Contract.Entry.TASK_TABLE_NAME,
                        whereClause,
                        whereArgs);
                break;

            default:
                throw new UnsupportedOperationException("Unknown Uri: " + uri);
        }

        if (taskDelete != 0) {
            // A task was deleted, set notification
            assert getContext() != null;
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return taskDelete;
    }

    @Override
    public int update(@NonNull Uri uri, @Nullable ContentValues values,
                      @Nullable String selection, @Nullable String[] selectionArgs) {

        final SQLiteDatabase db = mHelper.getWritableDatabase();

        //Keep track of if an update occurs
        int tasksUpdated;

        // match code
        int match = sUriMatcher.match(uri);

        switch (match) {

            case TASK_WITH_ID:

                //update a single task by getting the id
                String taskId = uri.getPathSegments().get(1);
                //using selections

                String whereClause = DB_Contract.Entry._ID + " = ? ";
                String[] whereArgs = new String[]{taskId};

                tasksUpdated = db.update(DB_Contract.Entry.TASK_TABLE_NAME, values,
                        whereClause, whereArgs);

                break;

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }

        if (tasksUpdated != 0) {
            //set notifications if a task was updated
            assert getContext() != null;
            getContext().getContentResolver().notifyChange(uri, null);
        }

        // return number of tasks updated
        return tasksUpdated;
    }


    /* getType() handles requests for the MIME type of data
    We are working with two types of data:
    1) a directory and 2) a single row of data.
    This method will not be used in our app, but gives a way to standardize the data formats
    that your provider accesses, and this can be useful for data organization.
    For now, this method will not be used but will be provided for completeness.
    */
    @Nullable
    @Override
    public String getType(@NonNull Uri uri) {
        int match = sUriMatcher.match(uri);

        switch (match) {

            case TASKS:
                // directory
                return "vnd.android.cursor.dir" + "/" + DB_Contract.AUTHORITY + "/" + DB_Contract.PATH_TASKS;

            case TASK_WITH_ID:
                // single item type
                return "vnd.android.cursor.item" + "/" + DB_Contract.AUTHORITY + "/" + DB_Contract.PATH_TASKS;

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }

    }
}
Thank's you once again. Hope you can use the content provider in your project. Happy coding

Read More

Sunday, June 11, 2017

Android Sql Database with Contract Class

June 11, 2017

Welcome to my Blog.
Today our tutorial is covered Android database.

sql



For database we use SQLite. It's a light weight. There is a lot of benefits to using SQLite database. you can find on online about why developers use SQLite. But In this post, I am not going to tell you about it, I am just showing it uses.

Let's start-
First, we create a Java Class and extend it by SQLiteOpenHelper class-
In this case, my class name is DatabaseHelper.
class DatabaseHelper extends SQLiteOpenHelper {
}
Now we have to override two methods
1.onCreate

2.onUpgrade
Let's do this
class DatabaseHelper extends SQLiteOpenHelper {

  @Override
  public void onCreate(SQLiteDatabase db) {

  }
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  
  }
}
One more thing left that we have to add- Constructor.
But In the constructor, we just take one parameter that is Context. To fill super we create two global variables of this class
1.DATABASE_NAME
2.VERSION
and CursorFactory is null in this case
Let's add this-
// The name of the database
private static final String DATABASE_NAME = "tasks.db";

// database version
private static final int VERSION = 1;

// Constructor
DatabaseHelper(Context context) {
  super(context, DATABASE_NAME, null, VERSION);
}
Before working on OnCreate methods we are going to add a new Class that name is Contract Class. what is Contract Class? Contract Class is a class that contains all the columns name variable of Database. It's really helpful. By adding this class we can reference it from any class so we don't think about correct column names. If we want to modify a column name then we easily modify this class. we don't need to search for the whole project.
Ok, Let's add a contract class.
In this case, Name is DB_Contract
public class DB_Contract {
}
Now we add an another inner class and implements Base columns-
public class DB_Contract {

  public static class Entry implements BaseColumns{
  }
}
Now time to create table name and column name-
public class DB_Contract {

  public static class Entry implements BaseColumns{

  //column name
  public static final String COLUMN_TASK_NAME= "task_name";
  public static final String COLUMN_TASK_SOLUTION= "task_solution";
  public static final String COLUMN_TASK_TYPE= "task_type";
  public static final String COLUMN_TASK_STATUS= "task_status";
  public static final String COLUMN_TASK_DUE= "task_due";
  public static final String COLUMN_TASK_DATE= "task_date";
  public static final String COLUMN_TASK_TIME= "task_time";
  
  //task type table name
  static final String TASK_TABLE_NAME = "tasks";

  }

}
Now time to write SQL Command-
final String CREATE_TABLE = "CREATE TABLE " + DB_Contract.Entry.TASK_TABLE_NAME + " (" +
  DB_Contract.Entry._ID+ " INTEGER PRIMARY KEY, " +
  DB_Contract.Entry.COLUMN_TASK_NAME + " TEXT NOT NULL, " +
  DB_Contract.Entry.COLUMN_TASK_SOLUTION + " TEXT, " +
  DB_Contract.Entry.COLUMN_TASK_TYPE + " TEXT, " +
  DB_Contract.Entry.COLUMN_TASK_STATUS + " BOOLEAN, " +
  DB_Contract.Entry.COLUMN_TASK_DUE + " BOOLEAN, " +
  DB_Contract.Entry.COLUMN_TASK_TIME + " TEXT, " +
  DB_Contract.Entry.COLUMN_TASK_DATE+ " TEXT, "+
  " UNIQUE (" + DB_Contract.Entry.COLUMN_TASK_NAME + ") ON CONFLICT REPLACE);";
Note: In the last line we add a unique keyword and make COLUMN_TASK_NAME as unique. and at last, we write ON CONFLICT REPLACE. For this line of code, If any task name is same as previous then it will be replaced.

now we add a log statement to print SQL command and also execute SQL command-
Log.e("TABLE",CREATE_TABLE);
db.execSQL(CREATE_TABLE);
oh! we finish onCreate method.
Now we are going to write onUpgrade method-
if our database update then we drop the previous table and create a new table.
For creating new table we just call again OnCreate-
db.execSQL("DROP TABLE IF EXISTS " + DB_Contract.Entry.TASK_TABLE_NAME);
onCreate(db);
That's it. we just finish our DatabaseHelper Class.
Now we have a database but we don't have any methods to access this database. To access database we are going to use Content Provider. In the next post, we will learn how to use the content provider.

Full code of DatabaseHelper-
class DatabaseHelper extends SQLiteOpenHelper {


    // The name of the database
    private static final String DATABASE_NAME = "tasks.db";

    //database version
    private static final int VERSION = 2;

    // Constructor
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }



    /**
     * Called when the tasks database is created for the first time.
     */

    @Override
    public void onCreate(SQLiteDatabase db) {

        // Create tasks table (careful to follow SQL formatting rules)
        final String CREATE_TABLE = "CREATE TABLE "  + DB_Contract.Entry.TASK_TABLE_NAME + " (" +
                DB_Contract.Entry._ID+ " INTEGER PRIMARY KEY, " +
                DB_Contract.Entry.COLUMN_TASK_NAME + " TEXT NOT NULL, " +
                DB_Contract.Entry.COLUMN_TASK_SOLUTION + " TEXT, " +
                DB_Contract.Entry.COLUMN_TASK_TYPE + " TEXT, " +
                DB_Contract.Entry.COLUMN_TASK_STATUS + " BOOLEAN, " +
                DB_Contract.Entry.COLUMN_TASK_DUE + " BOOLEAN, " +
                DB_Contract.Entry.COLUMN_TASK_TIME + " TEXT, " +
                DB_Contract.Entry.COLUMN_TASK_DATE+ " TEXT, "+
                " UNIQUE (" + DB_Contract.Entry.COLUMN_TASK_NAME + ") ON CONFLICT REPLACE);";


        //Log.e("TABLE",CREATE_TABLE);
        db.execSQL(CREATE_TABLE);
    }


    /**
     * This method discards the old table of data and calls onCreate to recreate a new one.
     * This only occurs when the version number for this database (DATABASE_VERSION) is incremented.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + DB_Contract.Entry.TASK_TABLE_NAME);
        onCreate(db);
    }
}
Thank you for reading.
Hope you will learn how to create a database in Android.
Next, we will learn how to access the database.
Happy coding.

Read More

Monday, May 29, 2017

Kotlin: working with String

May 29, 2017

Welcome to kotlin Series




In this tutorial, we are working with String of Kotlin.
In this post, we are going to learn about-
#variable type
#variable declaring
#String
#Join String
#Compare two String
#Find index from any String.

Ok Let's start by Creating the main method
fun main(arg : Array<String>){
  println("Hello world kotlin")
}

In Kotlin we have two types of variable-
1.mutable
2.immutable

1.mutable variable can change after declaring
2.immutable can not change Declare a string

the mutable variable can declare as using prefix val and
the immutable variable can declare as using prefix var

Let's add two type of variable-
val name = "shudipto"
var id = 1215

Defina a string-
val name = "Shudipto"
you can also declare a multiline string by using triple double quotation (""")
val des ="""I am shudipto trafder lives in Khulna.
  I study on the Khulna University """
Now print a string-
println("Name: "+name)
we can print a string in another way. we use dollar sign $ and directly type the variable name that's we want to print in the double quotation -
println("Name: $name")
Note: you probably confuse with semi-clone but Kotlin does not care about semi-clone.

Now join two String-
we take two string in two variable and join those variables into a new variable and print this newly created variable.
val FName = "Shudipto"
val LName = "Trafder"
    
var fullName = FName + LName
    
println("Full name: "+fullName)
we can use the alternative methods directly joint variable int the print statement-
 val FName = "Shudipto"
 val LName = "Trafder"

 println("Full name: ${FName+" "+LName}")
Compare two String- we declare two string and compare with equals function or using '=='
    //compare two string
    val string1 = "user"
    val string2 = "User"

    println("Strings are same: ${string1.equals(string2)}")
    println("Strings are same: ${string1 == string2}")
If you are working with ignore case then use-
println("Strings are same: ${string1.equals(string2,true)}")
Contains a word in particular String- we add a String like "I love you". we are checking that this String contains love word. Let jump on code-
var s = "I love you"

//check a word that exists in a string
println("Word is exist: ${s.contains("love")}")
the result will be shown in a boolean value.

Today's Last Topics. Find an Index of any String.
First, we declare a String "I love you". We are going to find what char is in the position
var s = "I love you"

//get a character with specific index
println("2nd index: ${s[2]}")
If we want to find a specific range of the index. For example, we want to find the index position 2 to 5. On code
var s = "I love you"
    

//a specific index from 2 to 5
println("2nd index to 5 Index: ${s.subSequence(2,6)}")

Read More

Sunday, May 21, 2017

Android CollapsingToolbarLayout

May 21, 2017

Android CollapsingToolbarLayout is one of the most common features on android material design. By using collapsing toolbar we can now collapse our android app toolbar and use image or others things on the toolbar and that visibility is gone with collapse.

In this post, We will learn how to use Collapsing Tollbar layout.

Let's check documentation

Now start- First, add design dependence on your build.graddle file. (But it automatically added by the android studio. But lets a check)

dependencies {
    //some code
    compile 'com.android.support:design:23.0.1'
}

Now go to your XML file. In my case activity_main.xml it looks like-

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"/>

    </android.support.design.widget.AppBarLayout>

Now we add collapsing toolbar layout in AppBarLayout. Let's add-

<android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/main_collapsing_tb"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary">

here we use scroll flag for how our layout should be scrolled. we want to scroll and exit until collapsed. now modify Toolbar. just adding a line.

app:layout_collapseMode="pin"

Now our collapsing toolbar is working. We here use only a toolbar in collapsing toolbar layout. But you can add picture and others things. If you are adding picture the modify code

app:layout_collapseMode="parallax"

Ok. That's it. If you miss some code or don't understand code where to use then see below full code.

<android.support.design.widget.AppBarLayout
        android:layout_height="@dimen/main_app_bar"
        android:layout_width="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/main_collapsing_tb"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:contentScrim="?attr/colorPrimary">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                android:layout_gravity="top"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
Thanks for reading this post.
Hope you are able to use this feature.



 Happy coding

Read More

Friday, May 19, 2017

Bookstore a java example code

May 19, 2017

Bookstore a java example code
LEVEL: BEGINNER

java


This example is good for understanding
  1. Array
  2. methods
  3. conditions(if and else)
the process of this bookstore: 1.First, we have a collection of books name:
static String[] book = { "java", "c", "c++", "php", "javascript", "html" };
2.we ask the user to which book is he want? 3. we search that book name in our list of books 4. if we find that book we ask again to our user about his occupation 5. because we want to give a discount to our user. here all source code
package com.blogspot.shudiptotrafder;

import java.util.Scanner;

public class BookStore {

    static String[] book = { "java", "c", "c++", "php", "javascript", "html" };
    static Scanner scanner = new Scanner(System.in);

    final static float studentdiscount = .3f;
    final static float teacherdiscount = .2f;
    static boolean flag = true;

    public static void main(String[] args) {
        if (flag) {
            pl("*************WELCOME TO OUR BOOK STORE**********");
        }
        pl("Which book do you want?");
        p("Answer: ");
        String bookname = scanner.nextLine();

        if (bookname.toLowerCase().equals(book[0])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[1])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[2])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[3])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[4])) {
            wantedbook(bookname);
            discount();

        } else if (bookname.toLowerCase().equals(book[5])) {
            wantedbook(bookname);
            discount();

        } else {
            pl("Sorry we don't have " + bookname + " book.");
        }

        pl("\nDo you Want more book?");
        p("Answer: ");
        String ans = scanner.nextLine();
        flag = false;

        if (ans.toLowerCase().equals("yes")) {
            pl("\n");
            String[] ret = null;
            main(ret);
        } else {
            pl("\n");
            pl("********Thank YOU FOR SHOPPING********");
        }

    }

    // methods

    public static void discount() {
        pl("\nAre you Student or Teacher or General Customar?");
        p("Answer: ");
        String userinput = scanner.nextLine();

        if (userinput.toLowerCase().equals("student")) {
            calculateprice(studentdiscount);
        } else if (userinput.toLowerCase().equals("teacher")) {
            calculateprice(teacherdiscount);
        } else {
            pl("You Can not get Discount.");
            pl("your Total Payable Price is 200 TK.");

        }

    }

    public static void calculateprice(float discount) {
        double price = 200;
        price -= price * discount;
        showprice(price);
    }

    public static void showprice(double price) {
        String prices = String.format("%.2f", price);
        pl("your Total Payable Price is : " +prices+ " TK.");

    }

    public static void wantedbook(Object object) {
        pl("You Want " + object + " book. price 200 Tk.");
    }

    public static void p(Object object) {
        System.out.print(object);
    }

    public static void pl(Object object) {
        System.out.println(object);
    }

}

Read More

Java String Example

May 19, 2017

String in Java
java string

Strings Example

Example 1:

Get first two characters of any String
public String firstTwo(String str) {
  if (str.length() >= 2) {
    return str.substring(0, 2);
  } else {
    return str;
  }
  // Solution notes: need an if/else structure to call substring if the length
  // is 2 or more, and otherwise return the string itself
} 

Alternative example of getting first two characters of any strings

public String firstTwo(String str) {

    if (str.length() >= 2) {

        char s = str.charAt(0);
        char s1 = str.charAt(1);

    String string = String.valueOf(s) + s1;
 
 return string;
  }
  return str;
}

Example 2:

get last two characters of any string
public static void main(String[] args) {

    String str = "hello";

    System.out.println(str.substring(str.length()-2));
}

Example 3:

Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
public String firstHalf(String str) {
  return str.substring(0,(str.length())/2); 
}

Example 4:

Given a string, return a new version without the first and last character
public String withoutEnd(String str) {
    return str.substring(1,str.length()-1);
  }

Example 5:

Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside
public String comboString(String a, String b) {
  
  int a1 = a.length();
  
  int b1 = b.length();
  
  if(a1 > b1){
     return b+a+b;
  }
  
  return a+b+a;
}

Example 6:

Given 2 strings, return their concatenation, except omit the first char of each.
public String nonStart(String a, String b) {
  
    String s = a.substring(1,a.length());
  
 String s1 = b.substring(1,b.length());
 
 return s+s1;
}

Example 7:

Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end
public String left2(String str) {
  
  if (str.length() >= 2) {
   String s = str.substring(0, 2);
   String s1 = str.substring(2, str.length());
   
   return s1+s;
  }
  return str;
}

Read More