Tuesday, January 27, 2015

Android :Working with DB

Android :Working with DB


You will be needing 3 user defined class files.
  1. File A which extends sqlitehelper (compulsory)
  2. File B which contains all methods like - create table,Insert data,Select etc.,
  3. File C , for Getter and Setter Class which is more for making your code more classy.

Let File A =sqllitehelperclass
Let File B = DBOperations
Let File C= Persons


sqllitehelperclass.java

public class sqllitehelperclass extends SQLiteOpenHelper
 {

    public sqllitehelperclass(Context context)
    {
        super(context, "test_db", null, 1);
    }
   
    @Override 
// onCreate() is only run when the database file did not exist and was just created    
 public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("CREATE TABLE Persons( PersonID INTEGER PRIMARY KEY AUTOINCREMENT,FirstName TEXT, Age INT)");
    }

    @Override 
//    onUpgrade() is only called when the database file exists but the stored version number is lower than requested in //constructor.    
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}


DBOperations.java

public class DBOperations {
  
    SQLiteOpenHelper sql_helper;
  
    DBOperations(Context context){  
        sql_helper=new sqllitehelperclass(context);
        //Downcasting SQLiteOpenHelper instance with the user defined class "SQLiteOpenHelperclass"
    }
  
    void create_table(){
        sql_helper.getWritableDatabase().execSQL("CREATE TABLE Persons( PersonID INTEGER PRIMARY KEY AUTOINCREMENT,FirstName TEXT, Age INT)");      
        Log.d("db","New db created");
        sql_helper.getWritableDatabase().close();
    }
  
    void delete_table(){
        sql_helper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS Persons");  
        Log.i("db", "database deleted");
        sql_helper.getWritableDatabase().close();
    }

    void insert(){
   //     sql_helper.getWritableDatabase().rawQuery("INSERT INTO Persons (FirstName,Age) VALUES ('Deepak','100');", null);


sql_helper.getWritableDatabase().execSQL("INSERT INTO Persons (FirstName,Age) VALUES ('Deepak','100');");
        sql_helper.getWritableDatabase().close();
    }
  
    List<persons> db_getall_data()
    {  
        int record_count;
        List<persons> query_res=new ArrayList<persons>();

        String[] args={"5P"};
        Cursor resultSet=sql_helper.getReadableDatabase().rawQuery("SELECT * FROM Persons", args);
        Log.d("db", "No of Records present="+String.valueOf(resultSet.getCount()));
        record_count=resultSet.getCount();
        resultSet.moveToFirst();
       
        if(record_count>0){
            while (record_count!=0)
            {
                persons Persons=new persons();
                Persons.put_age(resultSet.getInt(resultSet.getColumnIndex("Age")));
                Persons.put_name(resultSet.getString(resultSet.getColumnIndex("FirstName")));
                query_res.add(Persons);  
                resultSet.moveToNext();
                record_count=record_count-1;
            }
        }      
        sql_helper.getReadableDatabase().close();
        return query_res;
    }
  
  
    public boolean isTableExists()
    {
        try{
            Cursor cursor = sql_helper.getReadableDatabase().rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+"Persons"+"'", null);
            Log.d("DB","rows="+cursor.getCount());
            cursor.close();
        }catch(Exception e){
            sql_helper.getReadableDatabase().close();
            Log.d("Db","Table does not exist ");
            return false;
        }
       
        sql_helper.getReadableDatabase().close();
       return true;
    }
  
  }


person.java

public class persons {
   
    int age;
    String name;
   
    int get_age(){
        return age;
    }
   
    String get_name(){
        return this.name;
       
    }
   
    void put_name(String name){
        this.name=name;
       
    }
   
    void put_age(int age){
        this.age=age;
    }
}
 


Tuesday, January 6, 2015

Android : To Animate a picture file

To Animate a picture file


1.Create a new folder "anim" inside res folder
2.Goto folder res\anim and rt ck , select "Android XML File"
3.Give a resource ="Tween Animation" and File name="rotator" , root element ="rotate"
4.Open rotator.xml , delete all its contents and copy paste the below code inside :
************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:interpolator="@android:anim/linear_interpolator" >

    <!-- Use startOffset to give delay between animations -->


    <!-- Move -->
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromXDelta="0%p"
        android:startOffset="300"
        android:toXDelta="75%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromYDelta="0%p"
        android:startOffset="1100"
        android:toYDelta="70%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromXDelta="0%p"
        android:startOffset="1900"
        android:toXDelta="-75%p" />
    <translate
        android:duration="800"
        android:fillAfter="true"
        android:fromYDelta="0%p"
        android:startOffset="2700"
        android:toYDelta="-70%p" />

    <!-- Rotate 360 degrees -->
    <rotate
        android:duration="1000"
        android:fromDegrees="0"
        android:interpolator="@android:anim/cycle_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:startOffset="3000"
        android:repeatCount="infinite"
        android:repeatMode="restart"
        android:toDegrees="360" />

</set>

***************************************************************************

5.Click next ...next and Finish
6.Copy paste method in your MainActivity

        public void rotateit(View v){
        final ImageView myImage = (ImageView)findViewById(R.id.imageView2);
                final Animation myRotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotator);
                myImage.startAnimation(myRotation);
    }

7.Copy Paste any image inside your res/drawable-hdpi
8.Goto layout xml (ex: layout/activity_main.xml)
9.Select tab - Graphical Layout
10.Drag and Drop Image View  , Select the the image you pasted in "res/drawable-hdpi"
11. Select the image ,goto properties
12.Make On Click ="rotateit"
13.Save and Run



more animations in http://www.androidhive.info/2013/06/android-working-with-xml-animations/

Monday, January 5, 2015

Android: Gif animations part 2

Gif animations part 2

1.Addthis in your Manifest file inside activity "android:hardwareAccelerated="false"
Example :
        <activity
                    android:hardwareAccelerated="false"
                    android:name="foo.GifActivity"
                    android:label="The state of computer animation 2014">
        </activity>

2.Code for Main_Activity

        public class GifActivity extends Activity {
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(new GifView(this));
            }
       
            static class GifView extends View {
                Movie movie;
       
                GifView(Context context)
                {
                    super(context);
                    movie = Movie.decodeStream(context.getResources().openRawResource(R.drawable.some_gif));
                }
                              
                // inHeriting onDraw of View Class
                @Override
                protected void onDraw(Canvas canvas) {  
                    if (movie != null) {
                        movie.setTime((int) SystemClock.uptimeMillis() % movie.duration());
                        canvas.scale((this.getWidth()/movie.width()), (this.getHeight()/movie.height()));// Size
                        movie.draw(canvas, 0, 0);//Location
                        invalidate();
                    }
                }
            }
        }

       
3.Paste the gif file in "res/hdpi or res/xhdpi"
4.Run the Code

Android:Creating Gif Animation in Android

Creating Gif Animation in Android


1. Create a new Android Project.
2. Add the below code in your Main_activity

//******************Main_activity*************************
public class Your_Class extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Gif_loading_View view = new Gif_loading_View(this);
        setContentView(view);
    }

}

//Adding the webView
public class Gif_loading_View extends WebView{

    public Gif_loading_View(Context context) {

        super(context);    
        loadUrl("file:///android_asset/loading_position.html");

        }
}
//**************************************************************


3.Create a file "loading_position.html" and add the below code inside and svae it.

<html>
<body bgcolor="white">
    <table width="100%" height="100%">
        <tr>
            <td align="center" valign="center">               
                <br/>
                <br/>
                <br/>
                <font size="6">Please wait...</font>
                <br/>
                <br/>
                <img src="your_gif_filename.gif" />

            </td>
        </tr>
    </table>
</body>

4. Copy paste the html file inside "assets" folder in your project.
5. Copy paste any gif file from the internet and rename it as "your_gif_filename"
6. Paste it inside the same assets folder
7.Run the project