Translate

Saturday, February 23, 2013

Android Database Example1

Project Name : SQLiteStorageOption
 Activity Name :MainActivity
 PackageName : com.rakesh.sqlitestorageoption
 we need to create 4 java classes and 4 xml files .
  
MainActivity.java 
 package com.rakesh.sqlitestorageoption;

import java.util.ArrayList;
import java.util.HashMap;


import com.rakesh.sqlitestorageoption.DBController;
import com.rakesh.sqlitestorageoption.NewAnimal;

import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ListView;


public class MainActivity extends ListActivity {
    Intent intent;
    TextView animalId;
    DBController controller = new DBController(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayList<HashMap<String, String>> animalList =  controller.getAllAnimals();
        if(animalList.size()!=0) {
            ListView lv = getListView();
            lv.setOnItemClickListener(new OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                      animalId = (TextView) view.findViewById(R.id.animalId);
                      String valAnimalId = animalId.getText().toString();                      
                      Intent  objIndent = new Intent(getApplicationContext(),EditAnimal.class);
                      objIndent.putExtra("animalId", valAnimalId);
                      startActivity(objIndent);
                  }
            });
            ListAdapter adapter = new SimpleAdapter( MainActivity.this,animalList, R.layout.view_animal_entry, new String[] { "animalId","animalName"}, new int[] {R.id.animalId, R.id.animalName});
            setListAdapter(adapter);
        }
    }
    public void showAddForm(View view) {
        Intent objIntent = new Intent(getApplicationContext(), NewAnimal.class);
        startActivity(objIntent);
    }
}

 NewAnimal.java 
 package com.rakesh.sqlitestorageoption;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Spinner;


public class NewAnimal extends Activity{
    EditText animalName;
    DBController controller = new DBController(this);
    
     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.add_new_animal);
            animalName = (EditText) findViewById(R.id.animalName);
        }
    public void addNewAnimal(View view) {
        HashMap<String, String> queryValues =  new  HashMap<String, String>();
        queryValues.put("animalName", animalName.getText().toString());
        controller.insertAnimal(queryValues);
        this.callHomeActivity(view);
    }
    public void callHomeActivity(View view) {
        Intent objIntent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(objIntent);
    }    
}

EditAnimal.java 
 package com.rakesh.sqlitestorageoption;

import java.util.Calendar;

import java.util.HashMap;

import android.os.Bundle;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.EditText;




import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

public class EditAnimal extends Activity{
    EditText animalName;
    DBController controller = new DBController(this);
     @Override
        public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_edit_animal);
            animalName = (EditText) findViewById(R.id.animalName);
            Intent objIntent = getIntent();
            String animalId = objIntent.getStringExtra("animalId");
            Log.d("Reading: ", "Reading all contacts..");
            HashMap<String, String> animalList = controller.getAnimalInfo(animalId);
            Log.d("animalName",animalList.get("animalName"));
            if(animalList.size()!=0) {
            animalName.setText(animalList.get("animalName"));
            }
        }
    public void editAnimal(View view) {
        HashMap<String, String> queryValues =  new  HashMap<String, String>();
        animalName = (EditText) findViewById(R.id.animalName);
        Intent objIntent = getIntent();
        String animalId = objIntent.getStringExtra("animalId");
        queryValues.put("animalId", animalId);
        queryValues.put("animalName", animalName.getText().toString());
        
        controller.updateAnimal(queryValues);
        this.callHomeActivity(view);
        
    }
    public void removeAnimal(View view) {
        Intent objIntent = getIntent();
        String animalId = objIntent.getStringExtra("animalId");
        controller.deleteAnimal(animalId);
        this.callHomeActivity(view);
        
    }
    public void callHomeActivity(View view) {
        Intent objIntent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(objIntent);
    }
}

DBController.java 
 package com.rakesh.sqlitestorageoption;

import java.util.ArrayList;
import java.util.HashMap;

import android.util.Log;

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

public class DBController  extends SQLiteOpenHelper {
    private static final String LOGCAT = null;

    public DBController(Context applicationcontext) {
        super(applicationcontext, "androidsqlite.db", null, 1);
        Log.d(LOGCAT,"Created");
    }
    
    @Override
    public void onCreate(SQLiteDatabase database) {
        String query;
        query = "CREATE TABLE animals ( animalId INTEGER PRIMARY KEY, animalName TEXT)";
        database.execSQL(query);
        Log.d(LOGCAT,"animals Created");
    }
    @Override
    public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
        String query;
        query = "DROP TABLE IF EXISTS animals";
        database.execSQL(query);
        onCreate(database);
    }
    
    public void insertAnimal(HashMap<String, String> queryValues) {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("animalName", queryValues.get("animalName"));
        database.insert("animals", null, values);
        database.close();
    }
    
    public int updateAnimal(HashMap<String, String> queryValues) {
        SQLiteDatabase database = this.getWritableDatabase();    
        ContentValues values = new ContentValues();
        values.put("animalName", queryValues.get("animalName"));
        return database.update("animals", values, "animalId" + " = ?", new String[] { queryValues.get("animalId") });
        //String updateQuery = "Update  words set txtWord='"+word+"' where txtWord='"+ oldWord +"'";
        //Log.d(LOGCAT,updateQuery);
        //database.rawQuery(updateQuery, null);
        //return database.update("words", values, "txtWord  = ?", new String[] { word });
    }
    
    public void deleteAnimal(String id) {
        Log.d(LOGCAT,"delete");
        SQLiteDatabase database = this.getWritableDatabase();    
        String deleteQuery = "DELETE FROM  animals where animalId='"+ id +"'";
        Log.d("query",deleteQuery);        
        database.execSQL(deleteQuery);
    }
    
    public ArrayList<HashMap<String, String>> getAllAnimals() {
        ArrayList<HashMap<String, String>> wordList;
        wordList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM animals";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("animalId", cursor.getString(0));
                map.put("animalName", cursor.getString(1));
                wordList.add(map);
            } while (cursor.moveToNext());
        }
    
        // return contact list
        return wordList;
    }
    
    public HashMap<String, String> getAnimalInfo(String id) {
        HashMap<String, String> wordList = new HashMap<String, String>();
        SQLiteDatabase database = this.getReadableDatabase();
        String selectQuery = "SELECT * FROM animals where animalId='"+id+"'";
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                    //HashMap<String, String> map = new HashMap<String, String>();
                wordList.put("animalName", cursor.getString(1));
                   //wordList.add(map);
            } while (cursor.moveToNext());
        }                    
    return wordList;
    }    
}

XML Files

activity_main.xml

<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" >
   
    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:background="#000000"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="Animals"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#FFFFFF" />

        <Button
            android:id="@+id/button1"
            android:layout_width="41dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="#454545"
            android:onClick="showAddForm"
            android:text="+"
            android:textColor="#FFFFFF"
            android:textSize="30sp" />

    </RelativeLayout>
     <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/relativeLayout1"
        android:orientation="vertical"
        android:layout_marginTop="40dp">

    <ListView
         android:id="@android:id/list"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true">
     </ListView>
     </RelativeLayout>

</RelativeLayout>


add_new_animal.xml


<?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="match_parent"
    android:background="#CCCCCC"
    android:orientation="vertical"
    android:paddingTop="1dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:padding="5dp"
        android:text="Add Animal"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFFFFF" />

       <RelativeLayout
     android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"
        android:orientation="vertical"
        android:padding="10dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="30dp"
        android:text="Animal" />

    <EditText
        android:id="@+id/animalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" >

        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/btnadd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/animalName"
        android:layout_below="@+id/animalName"
        android:layout_marginTop="32dp"
        android:text="Save"     
        android:onClick="addNewAnimal" />

  

</RelativeLayout>
       

</LinearLayout>



activity_edit_animal


<?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="match_parent"
    android:background="#CCCCCC"
    android:orientation="vertical"
    android:paddingTop="1dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:padding="5dp"
        android:text="Edit Animal"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFFFFF" />

        <RelativeLayout
     android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"
        android:orientation="vertical"
        android:padding="10dp" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="30dp"
        android:text="Task" />

    <EditText
        android:id="@+id/animalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:ems="10" >

        <requestFocus />
    </EditText>

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/animalName"
            android:layout_below="@+id/animalName"
            android:layout_marginTop="19dp"
            android:onClick="editAnimal"
            android:text="Edit" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/button1"
            android:layout_alignBottom="@+id/button1"
            android:layout_centerHorizontal="true"
            android:onClick="removeAnimal"
            android:text="Delete" />

    </RelativeLayout>

</LinearLayout>



view_animal_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
        <TextView
        android:id="@+id/animalId"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

       <TextView
           android:id="@+id/animalName"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_marginBottom="5dp"
           android:layout_marginTop="5dp"
           android:paddingLeft="6dip"
           android:paddingTop="6dip"
           android:textColor="#A4C739"
           android:textSize="17sp"
           android:textStyle="bold" />

</LinearLayout>



And,finally AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rakesh.sqlitestorageoption"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <activity
            android:name=".NewAnimal"
            android:label="" >
        </activity>
        <activity
            android:name=".EditAnimal"
            android:label="" >
        </activity>
    </application>

</manifest>




                                                                    screen 1 :




                                                            

                                                                    screen 2:


 



screen 3:
                                                                     

                                                                      screen 4:
 

1 comment: