This tutorial assumes you are familiar with the basic android programming. Lets move to a little higher form of android programming. In this tutorial we will cover.
We are going to build a List-managing App. You are going to build an app which will be able to show you a large and nested list.
The steps for the generation of application are :-
At the Start of the App, the very top level of the list will appear. Clicking on the particular list will take you to the immediate children. You can create a new list-Item Under the current Item by clicking the Add button on the top Action Menu and the fourth Activity with option to insert a title and content will appear.
1. Create a new Android Project.
This tutorial assumes you are familiar with the very basics. Just click on the File->New->Project->Android Project. You will also create an Activity in this phase. Name this as MainActivity. Set the package Name to com.ktm.listapp.
2. Add another activity for data insertion.
There are two activities in this Application. One is to show the List-Items and another activity is to insert a new List Item. Add another java class in the same package. Name it ListAddActivity.java and extend it from android.app.Activity class. Create a layout for this Activity. It needs a label "Title" and then a EditText item then again a TextView "Content" and then again a EditText component. Finally two buttons, one for Save and another for cancel. Add a xml file on the res->layout folder named list_add.xml and paste the following code.
Note the onClick methods. This is where we bind the click event of the button with a method in the corresponding activity. The ListAddActivity.java looks like this.
In the onCreate Method You see parent_id getting assigned by extra parameter passed to it by the Intent. Actually this Activity is called from the first Activity and One extra parameter is passed, indicating the current context and parentList_id under which the new listItem is being saved. We will see how we pass the parameter after a few mements.
3.Add Menu
In the first three activity-images, you can see a + signed image in the Action bar. First you need to add this image or similar one res->drawable-mdpi folder of the project. Name the image as ic_add.png (all-small letters). In the res->menu folder add a xml file named activity_main.xml. Paste the given code.
Up to now Your MainAcvivity.java class looks like this.
4. Capture Click event.
After step 3, You will see a button in the ActionBar of MainActivity. What we need to do is bind the click event with a method in the MainActivity.java so that the method will start ListAddActivity.java. Add this method to the MainActivity class.
This class contains all the Crud operations you need for now. We shold also add a ListItem.java as the list object. Create another package com.ktm.listapp.objects and add class ListItem.java with following code.
5. Design Database.
Now that we have the two activities ready. We see blank activity and a action-bar button. We click on it and another activity appears with an option to insert title, content and click save , cancel. We need to do some database operations on those click events. Our ListItem has the following properties.
6. Create DatabaseHelper for your particular Object.
So we create a package called com.ktm.listapp.database and create a class ListDatabaseHelper.java
7. Display Saved lists in the MainActivity.
Now that the Database handlers are ready, basic framework is ready, we need to view our list in the activity. Copy paste the code below in MainActivity.java.
- Multiple activity call and parameter passing.
- Database(SQLite) with android
- List adapter
- Menu and click handle
We are going to build a List-managing App. You are going to build an app which will be able to show you a large and nested list.
The steps for the generation of application are :-
- Create a new Android Project.
- Add another activity for data insertion.
- Add menu (to MainActivity).
- Capture click events.
- Design Database
- Create a database Helper for your particular object.(CRUD operations)
- Display Saved lists in the MainActivity.
At the Start of the App, the very top level of the list will appear. Clicking on the particular list will take you to the immediate children. You can create a new list-Item Under the current Item by clicking the Add button on the top Action Menu and the fourth Activity with option to insert a title and content will appear.
1. Create a new Android Project.
This tutorial assumes you are familiar with the very basics. Just click on the File->New->Project->Android Project. You will also create an Activity in this phase. Name this as MainActivity. Set the package Name to com.ktm.listapp.
2. Add another activity for data insertion.
There are two activities in this Application. One is to show the List-Items and another activity is to insert a new List Item. Add another java class in the same package. Name it ListAddActivity.java and extend it from android.app.Activity class. Create a layout for this Activity. It needs a label "Title" and then a EditText item then again a TextView "Content" and then again a EditText component. Finally two buttons, one for Save and another for cancel. Add a xml file on the res->layout folder named list_add.xml and paste the following code.
<?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:orientation="vertical" > <TextView android:id="@+id/titleLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Title" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/title" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" > <requestFocus /> </EditText> <TextView android:id="@+id/contentLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Content" android:layout_marginTop="5dp" android:textAppearance="?android:attr/textAppearanceMedium" /> <EditText android:id="@+id/content" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="40" android:inputType="textMultiLine" /> <Button android:id="@+id/saveButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Save" android:onClick="onSave" /> <Button android:id="@+id/cancelButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Cancel" android:onClick="onCancel" /> </LinearLayout>
Note the onClick methods. This is where we bind the click event of the button with a method in the corresponding activity. The ListAddActivity.java looks like this.
public class ListAddActivity extends Activity { Integer parent_id; private EditText title; private EditText content; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_add); parent_id = getIntent().getExtras().getInt("parent_id"); title = (EditText) findViewById(R.id.title); content = (EditText) findViewById(R.id.content); } public void onSave(View view){ String titleText = title.getText().toString(); String contentText = content.getText().toString(); ListOpenHelper loh = new ListOpenHelper(this); loh.insertItem(new ListItem(titleText, contentText, parent_id)); finish(); } public void onCancel(View view){ finish(); } }
In the onCreate Method You see parent_id getting assigned by extra parameter passed to it by the Intent. Actually this Activity is called from the first Activity and One extra parameter is passed, indicating the current context and parentList_id under which the new listItem is being saved. We will see how we pass the parameter after a few mements.
3.Add Menu
In the first three activity-images, you can see a + signed image in the Action bar. First you need to add this image or similar one res->drawable-mdpi folder of the project. Name the image as ic_add.png (all-small letters). In the res->menu folder add a xml file named activity_main.xml. Paste the given code.
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_settings" android:title="@string/menu_settings" android:orderInCategory="100" android:showAsAction="never" /> <item android:id="@+id/new_list" android:icon="@drawable/ic_add" android:title="Add" android:showAsAction="ifRoom" /> </menu>
Up to now Your MainAcvivity.java class looks like this.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; }
4. Capture Click event.
After step 3, You will see a button in the ActionBar of MainActivity. What we need to do is bind the click event with a method in the MainActivity.java so that the method will start ListAddActivity.java. Add this method to the MainActivity class.
Integer id = -1;// at the top @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case R.id.new_list: addNewList(); return true; case R.id.menu_settings : return true; default: return false; } } public void addNewList(){ Intent i = new Intent(getBaseContext(), ListAddActivity.class); i.putExtra("parent_id", this.id); startActivity(i); }
This class contains all the Crud operations you need for now. We shold also add a ListItem.java as the list object. Create another package com.ktm.listapp.objects and add class ListItem.java with following code.
package com.ktm.listapp.objects; public class ListItem { Integer id = 0; String title = "TITLE"; String content = "CONTENT"; Integer parent_id = null; public ListItem(){}; public ListItem(Integer id, String title, String content, Integer parent_id){ this.id = id; this.title = title; this.content = content; this.parent_id = parent_id; } public ListItem (String title, String content, Integer parent_id){ this.title = title; this.content = content; this.parent_id = parent_id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Integer getParent_id() { return parent_id; } public void setParent_id(Integer parent_id) { this.parent_id = parent_id; } }
5. Design Database.
Now that we have the two activities ready. We see blank activity and a action-bar button. We click on it and another activity appears with an option to insert title, content and click save , cancel. We need to do some database operations on those click events. Our ListItem has the following properties.
ListItem(id integer, title text, content text, parent_id integer)
6. Create DatabaseHelper for your particular Object.
So we create a package called com.ktm.listapp.database and create a class ListDatabaseHelper.java
package com.ktm.listapp.database; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.ktm.listapp.objects.ListItem; public class ListDatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 2; private static final String DATABASE_NAME = "LISTAPPDB"; public static final String LIST_TABLE_NAME = "LISTAPP"; // queries public static final String TABLE_CREATE_QUERY = "CREATE TABLE " + LIST_TABLE_NAME + "(" + " list_id integer primary key autoincrement default 0, " + "title text, " + "content text, " + "parent_id integer " + ")"; public ListDatabaseHelper(Context context) { super(context, DATABASE_NAME, null , DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { try { //db.execSQL("Drop table " + LIST_TABLE_NAME); db.execSQL(TABLE_CREATE_QUERY); } catch (Exception e) { Log.i(LIST_TABLE_NAME, "tables already exist"); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + LIST_TABLE_NAME); // Create tables again onCreate(db); } //CRUD operations public void deleteAll(){ SQLiteDatabase db = getWritableDatabase(); db.delete(LIST_TABLE_NAME, null, null); } //insert single item public boolean insertItem(ListItem listItem) { boolean status = true; SQLiteDatabase db = getWritableDatabase(); ContentValues values = new ContentValues(); values.put("title", listItem.getTitle()); values.put("content", listItem.getContent()); values.put("parent_id", listItem.getParent_id()); status = (db.insert(LIST_TABLE_NAME, null, values) > 0); db.close(); return status; } //Get all list items in a category public List<ListItem> getList(Integer parent_id){ List<ListItem> listItem = new ArrayList<ListItem> (); String query = "SELECT * FROM " + LIST_TABLE_NAME + " WHERE parent_id = " + parent_id; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if(cursor.moveToFirst()){ do{ listItem.add(new ListItem( Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Integer.parseInt(cursor.getString(3)) )); } while(cursor.moveToNext()); } return listItem; } //Get single list public ListItem getListItem(Integer id){ SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(LIST_TABLE_NAME, new String[] {"list_id", "title", "content", "parent_id"}, "parent_id = ?", new String[] {String.valueOf(id)}, null, null, null ); if(cursor != null){ cursor.moveToFirst(); } ListItem listItem = new ListItem( Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), Integer.parseInt(cursor.getString(3)) ); return listItem; } // Get count of lists inside a category public Integer getCount(Integer parent_id){ return 0; } //Updating single contact public int update(ListItem listItem){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("title", listItem.getTitle()); values.put("content", listItem.getContent()); values.put("parent_id", listItem.getParent_id()); // updating row return db.update(LIST_TABLE_NAME, values, "list_id = ?", new String[] { String.valueOf(listItem.getId()) }); } //delete single contact public void deleteList(ListItem listItem){ SQLiteDatabase db = this.getWritableDatabase(); db.delete(LIST_TABLE_NAME, "list_id = ?", new String[] { String.valueOf(listItem.getId()) }); db.close(); } }
7. Display Saved lists in the MainActivity.
Now that the Database handlers are ready, basic framework is ready, we need to view our list in the activity. Copy paste the code below in MainActivity.java.
package com.ktm.listapp; import java.util.ArrayList; import java.util.List; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.ktm.listapp.database.ListDatabaseHelper; import com.ktm.listapp.objects.ListItem; public class MainActivity extends ListActivity { Integer id = -1; ListDatabaseHelper loh = new ListDatabaseHelper(this); String [] list = {"DB not Working"}; Integer[] idList = {-1}; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); //loh.deleteAll(); try{ id = getIntent().getExtras().getInt("parent_id"); }catch(NullPointerException e){ Log.d("Exception", "The intent throws null"); } list = getListTitles(id); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list); setListAdapter (adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); drillListActivity(idList[position]); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()){ case R.id.new_list: addNewList(); return true; case R.id.menu_settings : return true; default: return false; } } //other than the android stuff //returns the array of titles private String[] getListTitles(Integer parent_id){ String [] titles = null; Integer[] ids = null; List<String> titleList = new ArrayList<String>(); List<Integer> idList = new ArrayList<Integer>(); for(ListItem item : loh.getList(parent_id)){ titleList.add(item.getTitle()); idList.add(item.getId()); } titles = new String[titleList.size()];//titleList.toArray(titles); ids = new Integer[idList.size()]; for(int i=0;i<titleList.size(); i++){ titles[i] = titleList.get(i); ids[i] = idList.get(i); } this.idList = ids; return titles; } public void drillListActivity(Integer parent_id){ Intent i = new Intent(getBaseContext(), MainActivity.class); i.putExtra("parent_id", parent_id); startActivity(i); } public void addNewList(){ Intent i = new Intent(getBaseContext(), ListAddActivity.class); i.putExtra("parent_id", this.id); startActivity(i); } }If anything do not work, tell me. Have fun and enjoy.