Tuesday, 30 October 2018

Android SQLlite Database Example

1) DatabaseHelper.java

package com.example.admin.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "Student.db";
    public static final String TABLE_NAME = "student_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "SURNAME";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT)");
    }

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

    public boolean insertData(String name,String surname) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,surname);
        long result = db.insert(TABLE_NAME,null ,contentValues);
        if(result == -1)
            return false;
        else
            return true;
    }

    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
        return res;
    }

    public boolean updateData(String id,String name,String surname) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_1,id);
        contentValues.put(COL_2,name);
        contentValues.put(COL_3,surname);
        db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
        return true;
    }

    public Integer deleteData (String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
    }

}


2) MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/add_data"
            android:orientation="vertical"
            android:layout_marginTop="20dp"
            android:padding="15dp">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Name"
                android:id="@+id/et_name"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Surname"
                android:id="@+id/et_surname"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add Data"
                android:id="@+id/btn_add"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/edit_data"
            android:layout_marginTop="20dp"
            android:padding="15dp">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Id"
                android:id="@+id/et_id_edit"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Name"
                android:id="@+id/et_name_edit"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Surname"
                android:id="@+id/et_surname_edit"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Edit Data"
                android:id="@+id/btn_edit"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/delete_data"
            android:layout_marginTop="20dp"
            android:padding="15dp">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Id"
                android:id="@+id/et_id_delete"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Delete Data"
                android:id="@+id/btn_delete"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center"
            android:padding="10dp">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Get Data"
                android:id="@+id/btn_get"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>


3) MainActivity.java

package com.example.admin.myapplication;

import android.app.AlertDialog;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    Button btn_get, btn_add, btn_edit, btn_delete;
    EditText et_name, et_surname, et_id_edit, et_name_edit, et_surname_edit, et_id_delete;
    DatabaseHelper db;

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

        db = new DatabaseHelper(this);


        btn_get = (Button)findViewById(R.id.btn_get);
        btn_add = (Button)findViewById(R.id.btn_add);
        btn_edit = (Button)findViewById(R.id.btn_edit);
        btn_delete = (Button)findViewById(R.id.btn_delete);

        //Add Data
        et_name = (EditText)findViewById(R.id.et_name);
        et_surname = (EditText)findViewById(R.id.et_surname);

        // Update Data
        et_id_edit = (EditText)findViewById(R.id.et_name_edit);
        et_name_edit = (EditText)findViewById(R.id.et_name_edit);
        et_surname_edit = (EditText)findViewById(R.id.et_surname_edit);

        // Delete Data
        et_id_delete = (EditText)findViewById(R.id.et_id_delete);


        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddData();
            }
        });

        btn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateData();
            }
        });

 btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeleteData();
            }
        });

    }

 public void viewAll() {
        Cursor res = db.getAllData();
        if(res.getCount() == 0) {
            // show message
            showMessage("Error","Nothing found");
            return;
        }

        StringBuffer buffer = new StringBuffer();
        while (res.moveToNext()) {
            buffer.append("Id :"+ res.getString(0)+"\n");
            buffer.append("Name :"+ res.getString(1)+"\n");
            buffer.append("Surname :"+ res.getString(2)+"\n");
            buffer.append("Marks :"+ res.getString(3)+"\n\n");
        }

        // Show all data
        showMessage("Data",buffer.toString());

    }

    public void DeleteData() {
        Integer deletedRows = db.deleteData(et_id_delete.getText().toString());
        if(deletedRows > 0) {
            Toast.makeText(MainActivity.this,"Data Deleted",Toast.LENGTH_LONG).show();
            et_id_delete.setText("");
        } else{
            Toast.makeText(MainActivity.this,"Data not Deleted",Toast.LENGTH_LONG).show();
        }
    }
    public void UpdateData() {
        boolean isUpdate = db.updateData(et_id_edit.getText().toString(),
                et_name_edit.getText().toString(),
                et_surname_edit.getText().toString());
        if(isUpdate == true) {
            Toast.makeText(MainActivity.this,"Data Update",Toast.LENGTH_LONG).show();
            et_id_edit.setText("");
            et_name_edit.setText("");
            et_surname_edit.setText("");
        } else{
            Toast.makeText(MainActivity.this,"Data not Updated",Toast.LENGTH_LONG).show();
        }

    }
    public  void AddData() {
        boolean isInserted = db.insertData(et_name.getText().toString(),
                et_surname.getText().toString());
        if(isInserted == true)
        {
            Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
            et_name.setText("");
            et_surname.setText("");
        } else{
            Toast.makeText(MainActivity.this,"Data not Inserted", Toast.LENGTH_LONG).show();
        }
    }


    public void showMessage(String title,String Message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(Message);
        builder.show();
    }

Friday, 19 October 2018

Android Take Image From Phone And Add In Imageview

1) Manifext.xml

 Add This Permission On Your Manifest.mls File

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


2) Mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            tools:srcCompat="@tools:sample/avatars[0]"
            android:visibility="gone"/>



        <Button
            android:id="@+id/btn_take"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Get Picture"/>


        <Button
            android:id="@+id/btn_upload"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Upload Picture"
            android:layout_marginTop="10dp"/>
    </LinearLayout>

</RelativeLayout>

3) Mainactivity.java

public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private Button btn_take;
    //Request code for taking image
    private final int IMG_REQUEST = 1;
    //Bitmap for geting image and set into imageview
    private Bitmap bitmap;

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

        imageView = (ImageView) findViewById(R.id.imageView);
        btn_take = (Button) findViewById(R.id.btn_take);

        btn_take.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImg();
            }
        });

    }

    //Function for open gallry to select image
    private void selectImg(){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, IMG_REQUEST);  // add your image code here
    }

    //For adding onActivityResult type alt + insert
     //Find onActivityResult and added

     @Override
     protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
         super.onActivityResult(requestCode, resultCode, data);

         //my conditions to set a image into imageview

         if(requestCode == IMG_REQUEST && resultCode == RESULT_OK && data!=null) {
             //To add a get a image file

             Uri path = data.getData();

             try {
                 //Assign image into bitmap
                 bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
                 imageView.setImageBitmap(bitmap);
                 imageView.setVisibility(View.VISIBLE);
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }
 }

Saturday, 13 October 2018

Android RecyclerView With Animation



1) Add this line in gradle file

    implementation 'com.android.support:recyclerview-v7:28.0.0'

2) Create Animation Resource File In anim Folder

i) item_animation_fall_down.xml 

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300">

    <translate
        android:fromYDelta="-20%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"/>

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator"/>

    <scale
        android:fromXScale="105%"
        android:fromYScale="105%"
        android:toXScale="100%"
        android:toYScale="100%"
        android:pivotX="50%"
        android:pivotY="50%"
        android:interpolator="@android:anim/decelerate_interpolator"/>

</set>

ii) layout_fall_down.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/item_animation_fall_down"
    android:delay="15%"
    android:animationOrder="normal">

</layoutAnimation>

iii) item_slide_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300">

    <translate
        android:fromXDelta="100%p"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"/>

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator"/>

<!--Todo: Lets Run this App In Android Device-->
</set>

iv) layout_slide_right.xml

<?xml version="1.0" encoding="utf-8"?>
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
    android:animation="@anim/item_slide_from_right"
    android:delay="15%"
    android:animationOrder="normal">

</layoutAnimation>


3) item.xml custom list of recyclerview

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/card_rect"
        android:layout_gravity="center">
        ]
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txt_home"
            android:textAlignment="center"
            android:text="Title"
            android:textColor="#000000"
            android:textSize="18dp"
            android:textStyle="bold"
            android:layout_marginBottom="5dp"/>


    </LinearLayout>


</LinearLayout>

4) Item_Card.java

public class Item_Card {

    String name;

    public Item_Card(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}


5) ItemAdapter.java

class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{

    List<Item_Card> list;
    Context context;

    public ItemAdapter(List<Item_Card> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.items, viewGroup, false);
        return new ItemAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        Item_Card Cards = list.get(position);
        final String name = Cards.getName();

        viewHolder.home_title.setText(name);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        TextView home_title;
        public ViewHolder(View itemView) {
            super(itemView);

            home_title = (TextView) itemView.findViewById(R.id.txt_home);

        }
    }
}


6) activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_fall_down"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Fall Down" />


        <Button
            android:id="@+id/btn_slide_right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Slide Right" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_editor_absoluteY="55dp"
        tools:ignore="MissingConstraints" />


</LinearLayout> 

7) MainActivity.java

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ItemAdapter adapter;
    private List<Item_Card> Cardss;
    private RecyclerView.LayoutManager mLayoutManager;

    Button btn_fall_down, btn_slide_right;

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

        btn_fall_down = (Button) findViewById(R.id.btn_fall_down);
        btn_slide_right = (Button) findViewById(R.id.btn_slide_right);

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

        recyclerView.setHasFixedSize(true);

        mLayoutManager = new GridLayoutManager(MainActivity.this,2);
        recyclerView.setLayoutManager(mLayoutManager);
        Cardss = new ArrayList<>();

        btn_fall_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Data(recyclerView, 0);
            }
        });



        btn_slide_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Data(recyclerView, 2);
            }
        });
    }

    private void Data(RecyclerView recyclerView, int type) {


        Context context = recyclerView.getContext();
        LayoutAnimationController controller = null; // for animation

        if (type == 0){
            controller = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_fall_down);
        } if(type == 2){
            controller = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_slide_right);
        }

        for (int i = 0; i <=20; i++) {
            Cardss.add(new Item_Card(
                    String.valueOf(i)
            ));
        }
        //adapter.notifyDataSetChanged();
        adapter = new ItemAdapter(Cardss, MainActivity.this);
        recyclerView.setAdapter(adapter);

        recyclerView.setLayoutAnimation(controller);
        recyclerView.getAdapter().notifyDataSetChanged();
        recyclerView.scheduleLayoutAnimation();
    }
}


Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file     implementation 'com.google.android.gms:play-services-location:18.0.0' 2. Add this p...