I have made an application simple in android for database practice,as i have no idea about Sqlite database I've gone through so many links for it,But most of them are complex,I have created 4 activities 1st (mainActivity) contains 3 Buttons "add","Edit", and "View" in 2nd activity (AddActivity) I have made 3 EditTexts its entered values should be stored in database.So can you please tell me easy steps for doing same?
MainActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button add=(Button)findViewById(R.id.button1);
Button edit=(Button)findViewById(R.id.button2);
Button view=(Button)findViewById(R.id.button3);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub]
Intent i=new Intent(MainActivity.this,AddActivity.class);
startActivity(i);
}
});
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,EditActivity.class);
startActivity(i);
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ViewActivity.class);
startActivity(i);
}
});
}
}
AddActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddActivity extends Activity {
EditText name,addres,phon;
Button ad,cn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name = (EditText)findViewById(R.id.name);
addres=(EditText)findViewById(R.id.address);
phon = (EditText)findViewById(R.id.phone);
ad =(Button)findViewById(R.id.add);
cn=(Button)findViewById(R.id.cancel);
final SQLiteDatabase db = openOrCreateDatabase("Mydb",MODE_PRIVATE, null);
db.execSQL("create table if not exists simple(name varchar,address varchar,phone varchar");
ad.setOnClickListener(new OnClickListener() {
String n=name.getText().toString();
String a=addres.getText().toString();
String p= phon.getText().toString();
#Override
public void onClick(View v) {
db.execSQL("insert into simple values('n','a','p')");
Cursor c =db.rawQuery("select * from simple",null);
c.moveToFirst();
}
});
cn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent(AddActivity.this,MainActivity.class);
startActivity(i);
}
});
}
}
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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="92dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="28dp"
android:text="Edit" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:layout_marginTop="37dp"
android:text="View" />
</RelativeLayout>
Add.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=".AddActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="60dp"
android:text="phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="14dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:layout_toLeftOf="#+id/editText2"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<EditText
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/phone"
android:layout_marginTop="62dp"
android:layout_toRightOf="#+id/textView1"
android:text="Add" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/add"
android:layout_marginLeft="36dp"
android:layout_toRightOf="#+id/add"
android:text="Cancel" />
</RelativeLayout>
ok I think you want to add the value of edit text into your db
package com.example.databasesample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
static EditText edtAdd;
Button btnAdd, btnShow;
ListView listName;
static DataBaseSqlLiteHelper mBaseSqlLiteHelper;
DBModel mDbModel;
ArrayList<DBModel> mArrayList;
ListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
mArrayList = new ArrayList<DBModel>();
mBaseSqlLiteHelper = new DataBaseSqlLiteHelper(MainActivity.this);
mBaseSqlLiteHelper.getReadableDatabase();
mBaseSqlLiteHelper.getWritableDatabase();
}
public void initialize() {
edtAdd = (EditText) findViewById(R.id.edtEnterName);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
listName = (ListView) findViewById(R.id.listName);
listName.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
deleteItem(mArrayList.get(arg2).getId());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAdd:
addName(edtAdd.getText().toString());
break;
case R.id.btnShow:
showNames();
break;
default:
break;
}
}
// for adding values
public void addName(String name) {
SQLiteDatabase mOpenHelper = mBaseSqlLiteHelper.getWritableDatabase();
ContentValues mContentValues = new ContentValues();
mContentValues.put("name", name);
mOpenHelper.insert("NAMES", null, mContentValues);
mOpenHelper.close();
}
//showing values in list
public void showNames() {
String selectQuery = "SELECT * FROM NAMES";
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
Cursor mCursor = mDatabase.rawQuery(selectQuery, null);
if (mCursor.moveToFirst()) {
do {
mDbModel = new DBModel();
mDbModel.setId(mCursor.getString(0));
mDbModel.setName(mCursor.getString(1));
mArrayList.add(mDbModel);
} while (mCursor.moveToNext());
}
mAdapter = new ListAdapter(MainActivity.this, mArrayList);
listName.setAdapter(mAdapter);
}
deleteing values
public void deleteItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String delete = "Delete from NAMES Where _id =" + id;
mDatabase.execSQL(delete);
mDatabase.close();
mAdapter.notifyDataSetChanged();
mArrayList.remove(id);
}
//updating item
public static void updateItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String update = "Update NAMES set name=\""
+ edtAdd.getText().toString() + "\" where _id=" + id;
mDatabase.execSQL(update);
mDatabase.close();
}
}
package com.example.databasesample;
public class DatabaseConstants {
public static final String CREATE_TABLE_PROFILE_QUERY = "CREATE TABLE NAMES("
+ " _id integer primary key autoincrement," + " name VARCHAR"
+ ")";
}
package com.example.databasesample;
import android.content.Context;
android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseSqlLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "My Sample DataBase";
private static final int DATABASE_VERSION = 1;
public DataBaseSqlLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DatabaseConstants.CREATE_TABLE_PROFILE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
package com.example.databasesample;
public class DBModel {
String id;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.databasesample;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
Context mContext;
ArrayList<DBModel> mArrayList;
public ListAdapter(Context mContext, ArrayList<DBModel> models) {
// TODO Auto-generated constructor stub
this.mArrayList = models;
this.mContext = mContext;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mArrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mLayoutInflater.inflate(R.layout.list_layout, parent,
false);
TextView txtId = (TextView) convertView.findViewById(R.id.txtId);
txtId.setText(mArrayList.get(position).getId());
TextView txtName = (TextView) convertView
.findViewById(R.id.txtName);
txtName.setText(mArrayList.get(position).getName());
Button btnUpdate=(Button)convertView.findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.updateItem(mArrayList.get(position).getId());
}
});
}
return convertView;
}
}
//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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edtEnterName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edtEnterName"
android:text="Add to Database" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnAdd"
android:text="Show" />
<ListView
android:id="#+id/listName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnShow" >
</ListView>
//listlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/txtId" />
<Button
android:id="#+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:text="Update" />
Here I make an app in which you can add ,edit and update your database.i use Two main classes First DataBaseSqlLiteHelper.java to create databse and DatabaseConstants.java to create table. To delete item from db click on list and for update first enter value in edit text.comment on this if you need further help.
Ok if you want only a single value to show on database then you can do like this
take a textView
TextView txtName;
initialize it in my above method of initialize();
then make a method to get single value
// Getting single Name to textView
public void getContact(String id) {
SQLiteDatabase db = mBaseSqlLiteHelper.getReadableDatabase();
String select="Select name from NAMES Where _id ="+id;
Cursor mCursor=db.rawQuery(select,null);
if (mCursor!=null) {
mCursor.moveToFirst();
String name=mCursor.getString(0);
txtName.setText(name);
}
db.close();
}
then call this method on the click of some button and pass the id of the row you want to select.
Related
I am not good at Android, learning things. I'm trying to fetch record from SQLite in Android. Here is my code. Please help where is my fault. Thanks.
//DatabaseAdapter.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
dbHelper = new DatabaseOpenHelper(context);
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public long insertTest(String no, String name) {
ContentValues values = new ContentValues();
values.put("no", no);
values.put("name", name);
return database.insert("test", null, values);
}
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT name FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
do {
result.add(mcursor.getString(mcursor.getColumnIndex("name")));
} while (mcursor.moveToNext());
return result;
}
}
//MainActivity2.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity2 extends Activity implements OnClickListener {
EditText etno, etname;
Button btnSave;
DatabaseAdapter dbAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
dbAdapter = new DatabaseAdapter(getApplicationContext());
etno = (EditText) findViewById(R.id.txtNo);
etname = (EditText) findViewById(R.id.txtName);
btnSave = (Button) findViewById(R.id.Save);
btnSave.setOnClickListener(this);
Button back = (Button) findViewById(R.id.buttonBackPg);
back.setOnClickListener(this);
Button view_list = (Button) findViewById(R.id.view_list);
view_list.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.buttonBackPg) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (v.getId() == R.id.view_list) {
ListView listview = (ListView) findViewById(R.id.list_all);
ArrayList<String> data = dbAdapter.getAllLabels();
dbAdapter.close();
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data));
}
if (v.getId() == R.id.Save) {
String no = etno.getText().toString();
String name = etname.getText().toString();
dbAdapter.open();
long inserted = dbAdapter.insertTest(no, name);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "data saved",
Toast.LENGTH_LONG).show();
etno.setText("");
etname.setText("");
} else {
Toast.makeText(getApplicationContext(), "data not saved",
Toast.LENGTH_LONG).show();
}
dbAdapter.close();
}
}
}
//activity_main2.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity2" >
<EditText
android:id="#+id/txtNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:ems="10"
android:hint="No"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/buttonBackPg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Save"
android:layout_alignParentBottom="true"
android:layout_marginBottom="77dp"
android:text="Back" />
<Button
android:id="#+id/Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonBackPg"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:onClick="onClick"
android:text="Save" />
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/txtNo"
android:layout_marginTop="36dp"
android:ems="10"
android:hint="Name"
android:inputType="text">
</EditText>
<Button
android:id="#+id/view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtName"
android:layout_below="#+id/Save"
android:text="View List" />
<ListView
android:id="#+id/list_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/msg"
android:layout_alignLeft="#+id/msg" >
</ListView>
</RelativeLayout>
Try this edit
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT name FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
if(mcursor!=null)
{
//move cursor to first result record
mcursor.moveToFirst();
do {
result.add(mcursor.getString(mcursor.getColumnIndex("name")));
} while (mcursor.moveToNext());
}
return result;
}
for fetch data use like that
public Cursor getdata()
{
Log.v(TAG + ".getdata", "getdatamethod called");
Cursor mCursor = null;
openAsWrite();
mCursor=db.query(tablenam,
new String[] {"column name"},null, null, null, null, null);
return mCursor;
}
Final Working Code is here --
//DatabaseAdapter.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
dbHelper = new DatabaseOpenHelper(context);
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public long insertTest(String no, String name) {
ContentValues values = new ContentValues();
values.put("no", no);
values.put("name", name);
return database.insert("test", null, values);
}
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT * FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
if(mcursor!=null)
{
//move cursor to first result record
mcursor.moveToFirst();
do {
String display = mcursor.getString(mcursor.getColumnIndex("name")) + " - " + mcursor.getString(mcursor.getColumnIndex("no"));
result.add(display);
} while (mcursor.moveToNext());
}
return result;
}
}
//MainActivity2.java //
package com.example.wg_an;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity2 extends Activity implements OnClickListener {
EditText etno, etname;
Button btnSave;
DatabaseAdapter dbAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
dbAdapter = new DatabaseAdapter(getApplicationContext());
etno = (EditText) findViewById(R.id.txtNo);
etname = (EditText) findViewById(R.id.txtName);
btnSave = (Button) findViewById(R.id.Save);
btnSave.setOnClickListener(this);
Button back = (Button) findViewById(R.id.buttonBackPg);
back.setOnClickListener(this);
Button view_list = (Button) findViewById(R.id.view_list);
view_list.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.buttonBackPg) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (v.getId() == R.id.view_list) {
startActivity(new Intent(getApplicationContext(),
MainActivity3.class));
}
if (v.getId() == R.id.Save) {
String no = etno.getText().toString();
String name = etname.getText().toString();
dbAdapter.open();
long inserted = dbAdapter.insertTest(no, name);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "data saved",
Toast.LENGTH_LONG).show();
etno.setText("");
etname.setText("");
} else {
Toast.makeText(getApplicationContext(), "data not saved",
Toast.LENGTH_LONG).show();
}
dbAdapter.close();
}
}
}
//MainActivity3.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity3 extends Activity implements OnClickListener {
/** Called when the activity is first created. */
DatabaseAdapter dbAdapter;
ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
dbAdapter = new DatabaseAdapter(this);
dbAdapter.open();
try {
Button back = (Button) findViewById(R.id.back_2);
back.setOnClickListener(this);
listview = (ListView) findViewById(R.id.list_all);
Log.d("Reading: ", "Reading MA3..");
ArrayList<String> data = dbAdapter.getAllLabels();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
listview.setAdapter(adapter);
dbAdapter.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG)
.show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.back_2) {
startActivity(new Intent(getApplicationContext(),
MainActivity2.class));
}
}
}
//DatabaseOpenHelper.java//
package com.example.wg_an;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public static final String DBName = "test_database.db";
public static final String TABLE_NAME = "test";
public static final String TABLE_SQL = "Create Table "+ TABLE_NAME
+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"no TEXT, "
+"name TEXT);";
public DatabaseOpenHelper(Context context) {
super(context, DBName, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(TABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
//activity_main2.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity2" >
<Button
android:id="#+id/buttonBackPg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Save"
android:layout_alignParentBottom="true"
android:layout_marginBottom="77dp"
android:text="Back Screen-1" />
<Button
android:id="#+id/Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonBackPg"
android:layout_alignLeft="#+id/txtName"
android:onClick="onClick"
android:text="Save" />
<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="16dp"
android:layout_marginTop="21dp"
android:text="Add Records - Screen-2" />
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Save"
android:layout_alignLeft="#+id/txtNo"
android:layout_marginBottom="58dp"
android:ems="10"
android:hint="Name"
android:inputType="text" />
<EditText
android:id="#+id/txtNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:hint="No"
android:inputType="text" />
<Button
android:id="#+id/view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/txtName"
android:layout_below="#+id/txtName"
android:text="View List" />
</RelativeLayout>
//activity_main3.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity3" >
<Button
android:id="#+id/back_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Back Screen-2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="List of Records - Screen-3" />
<ListView
android:id="#+id/list_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="58dp"
android:layout_marginTop="58dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
I created a custom ListView with Custom list view adapter. I want to set current time in every list item in the list. Items in the list box must update the current time every second.
MainActivity.java
package com.example.examapp;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.example.exambp.*;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView lv;
Activity act=this;
List<ListViewItem> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<ListViewItem>();
lv=(ListView)findViewById(R.id.listView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void showData(View v)
{
IntentIntegrator i=new IntentIntegrator(this);
i.initiateScan();
}
String[] onedata;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String x=scanResult.getContents();
EditText et=(EditText)findViewById(R.id.editText1);
et.setText(x);
addToList(x);
}
}
ListViewItem li;
CustomListViewAdapter adapter;
public void addToList(String str)
{
onedata=str.split("/");
li=new ListViewItem();
li.enrollId="EnrollmentID: "+onedata[0].toString();
li.ExamId="ExamID: "+onedata[1].toString();
li.UserId="UserId: "+onedata[2].toString();
li.StartedTime=onedata[3].toString();
li.Duration=onedata[4].toString();
li.AvailableTime="jiukjh";
items.add(li);
adapter=new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
}
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" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="60dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="showData"
android:text="#string/btn_val" />
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
</LinearLayout>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView9"
android:layout_toRightOf="#+id/linearLayout2" >
</ListView>
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
android:text="Started Exams"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtAvailability"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/txtEnrollmentId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtUserId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtEnrollmentId"
android:layout_alignBottom="#+id/txtEnrollmentId"
android:layout_marginLeft="78dp"
android:layout_toRightOf="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtExamId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtEnrollmentId"
android:text="TextView" />
<TextView
android:id="#+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtExamId"
android:layout_alignBottom="#+id/txtExamId"
android:layout_alignLeft="#+id/txtUserId"
android:text="TextView" />
</RelativeLayout>
CustomListViewAdapter.java
package com.example.examapp;
import java.util.Date;
import java.util.List;
import com.example.exambp.*;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomListViewAdapter extends BaseAdapter
{
LayoutInflater inflater;
List<ListViewItem> items;
Activity act;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.act=context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
View vi;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item=items.get(position);
vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
//ImageView imgThumbnail=(ImageView)vi.findViewById(R.id.imgThumbnail);
TextView txtAvailableTime1=(TextView)vi.findViewById(R.id.txtAvailability);
TextView txtEnrollmentId1=(TextView)vi.findViewById(R.id.txtEnrollmentId);
TextView txtUserId1=(TextView)vi.findViewById(R.id.txtUserId);
TextView txtExamId1=(TextView)vi.findViewById(R.id.txtExamId);
TextView txtStartedTime1=(TextView)vi.findViewById(R.id.txtStartTime);
//imgThumbnail.setImageResource(item.ThumbnailResource);
txtAvailableTime1.setText(item.AvailableTime.toString());
txtEnrollmentId1.setText(item.enrollId.toString());
txtUserId1.setText(item.UserId.toString());
txtExamId1.setText(item.ExamId.toString());
txtStartedTime1.setText(item.StartedTime.toString());
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
return vi;
}
public void doWork() {
act.runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {
//TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
//txtCurrentTime.setText(e.getMessage());
}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(true){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
}
This is only run in one time. I want to change current time in List Items continuously.
Every second you will have to loop through each item in your List<ListViewItem> items and then update each item's time. After that call listView.notifyDataSetChanged().
I have two tabs and each tab is a Fragment. In one of the fragments (Afragment.claas) I have a dialog box to insert some data, and I want to save them in a database. When I fill the text fields and press OK, the application stops.
I think when I initialize the edittext there is something wrong.
name = (EditText) activity.findViewById(R.id.etProviderName);
The above statement is returning null
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Afragment extends ListFragment {
DBAdapter db;
Activity activity;
private static final String fields[] = { "provider._providerName", "_providerMobile" };
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initAdapter();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
add();
return (true);
case R.id.menu_reset:
initAdapter();
return (true);
case R.id.menu_info:
Toast.makeText(activity, "Developed By Omar Al-Shammary", Toast.LENGTH_LONG)
.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
private void add() {
// TODO Auto-generated method stub
System.out.println("insider Add Method");
final View addView = activity.getLayoutInflater().inflate(R.layout.add_provider, null);
new AlertDialog.Builder(activity).setTitle("Add a Provider").setView(addView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
System.out.println("Befor calling insert in providers");
insertInProviders();
System.out.println("after calling insert in providers");
}
}).setNegativeButton("Cancel", null).show();
initAdapter();
}
private void initAdapter() {
activity = getActivity();
db = new DBAdapter(activity);
fillTheList();
}
public void fillTheList()
{
db.open();
Cursor data = db.getAllProviders();
CursorAdapter dataSource = new SimpleCursorAdapter(activity,
R.layout.row, data, fields,
new int[] { R.id.first, R.id.last });
setListAdapter(dataSource);
db.close();
setListAdapter(dataSource);
}
public void insertInProviders()
{
EditText name,location,number;
name = (EditText) activity.findViewById(R.id.etProviderName);
location = (EditText) activity.findViewById(R.id.etProviderName);
number = (EditText) activity.findViewById(R.id.etProviderName);
if(name == null)
System.out.println("EditeText name is null");
String provName = name.getText().toString();
if(location == null)
System.out.println("location is null");
String provLocation = location.getText().toString();
String provNumber = number.getText().toString();
System.out.println("Before Open");
db.open();
System.out.println("Before DB.Insert");
db.insertProvider(provName, provLocation, provNumber);
System.out.println("Before Close");
db.close();
}
}
add_provider.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:orientation="vertical" >
<TextView
android:id="#+id/tvProviderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="#+id/etProviderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvProvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location" />
<EditText
android:id="#+id/etProvLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvProvNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number" />
<EditText
android:id="#+id/etProvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</LinearLayout>
This is the code I use for declaring buttons in Fragments - maybe it can help you.
What I would do is access the inflated layout and then you should be able to access items underneath it. Let me know if that makes sense.
LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button)theLayout.findViewById(R.id.frag1_button);
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
}
});
return theLayout;
So maybe you should try this since you inflate your View as "addView"
name = (EditText) addView.findViewById(R.id.etProviderName);
The findViewById should not be called by the activity but by the enclosing view. You should have something like:
In the class
View aView;
In the method:
LayoutInflater inflater = getActivity().getLayoutInflater();
aView = inflater.inflate(R.layout.add_provider, null);
...
EditText name = (EditText) aView.findViewById(R.id.etProviderName);
I hope it helps.
Ok so heres the skinny i am new to the whole android platform and am trying to basically put all the info i need into a database table and then pull info into my activities basically like....
each row represents a item (lets say there are 100 of them) then there is a column for description, food, location, name, and if possible image. currently i have been just manually adding all the info into separate xml layouts which seems far more time consuming and difficult than if i could just pull the info off of a database right?
what i am currently doing:
<?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="fill_parent"
android:background="#color/white"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="center"
android:text="#string/bluefish"
android:textColor="#color/black"
android:textSize="30dp"
android:textStyle="bold" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:contentDescription="#string/bluefish"
android:src="#drawable/bluefish" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="left"
android:text="#string/desc"
android:textColor="#color/black"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="left"
android:text="text here"
android:textColor="#color/black"
android:textSize="12dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="left"
android:text="#string/food"
android:textColor="#color/black"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="left"
android:text="text here"
android:textColor="#color/black"
android:textSize="12dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="left"
android:text="#string/loc"
android:textColor="#color/black"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="left"
android:text="text here"
android:textColor="#color/black"
android:textSize="12dp" />
Create Db using following code
This will create new DB SaveImage
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
public class DbHelper extends SQLiteOpenHelper {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "SaveImage";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String tblSaveImage = "CREATE TABLE tblSaveImage (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , Image BLOB);";
db.execSQL(tblSaveImage);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Save Image into DB:
If you dont wants to play with SQL Query you can also use content values to insert the data into DB.
import java.io.ByteArrayOutputStream;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class SaveImage extends Activity {
SQLiteDatabase Db;
TextView txt;
Button btnImage,btnSaveimage;
ImageView imageView;
byte[] byteArray;
private static final int PICK_FROM_FILE = 2;
private Uri mImageCaptureUri;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Initialize();
//btnSaveImage Handler Save Byte Array to DB and Navigate to ShowImage Activity
btnSaveimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
ContentValues cv = new ContentValues();
cv.put("Image", byteArray);
Db.insert("tblSaveImage", null, cv);
startActivity(new Intent(getApplicationContext(),ShowImage.class));
} catch (Exception e) {
// TODO: handle exception
txt.setText(e.toString());
}
}
});
//btnImage Handler Access to Gallery of Device and Display all Images save in Device.
btnImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
}
});
}
// To Initialize all the Components.
private void Initialize() {
// TODO Auto-generated method stub
txt = (TextView)findViewById(R.id.txt);
btnImage = (Button)findViewById(R.id.btnImage);
imageView = (ImageView)findViewById(R.id.imageView);
btnSaveimage = (Button)findViewById(R.id.btnSaveImage);
DbHelper h = new DbHelper(this);
try {
Db = h.getWritableDatabase();
} catch (SQLException e) {
// TODO: handle exception
Db = h.getReadableDatabase();
}
}
// OnActivityResult PICK_IMAGE_FROM_FILE
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
mImageCaptureUri = data.getData();
imageView.setImageURI(mImageCaptureUri);
imageView.buildDrawingCache();
Bitmap bmp = imageView.getDrawingCache();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
super.onActivityResult(requestCode, resultCode, data);
}
}
Show image saved in DB:
import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class ShowImage extends Activity {
ImageView showImage;
SQLiteDatabase Db;
Cursor result;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
showImage = (ImageView)findViewById(R.id.showImage);
DbHelper h = new DbHelper(this);
try {
Db = h.getWritableDatabase();
} catch (SQLException e) {
// TODO: handle exception
Db = h.getReadableDatabase();
}
result = Db.rawQuery("Select Image from tblSaveImage", null);
if (result.moveToLast()) {
byte[] byteArray = result.getBlob(0);
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
showImage.setImageBitmap(bmp);
}
}
}
As with several other posts here, I am trying to create a ListView that includes a CheckBox for each row, and use a SQLite database to store the current state of the selection.
Starting with the example at http://appfulcrum.com/?p=351, which did not quite work as is, I created a simple app that creates the database, populates it with 20 items, and displays the list.
It successfully retrieves the state and stores the state of the selection.
BUT, it does not correctly show the CheckBox state if I change it, scroll to the other end of the list, and scroll back. e.g. if I select the first CheckBox, scroll to the bottom, and come back to the top, the CheckBox is no longer set. This is being run on an Android 2.1 Samsung handset.
If I return to the main screen, come back into the list, the CheckBox is correctly set, so the database has indeed been updated.
The example extends SimpleCursorAdapter, and the getView() invokes setChecked() with true or false as appropriate based on the value of the selection column in the table.
Below are all the sources.
I'd certainly appreciate being told, "Duh, here's your problem..."
CustomListViewDB.java
// src/CustomListViewDB.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class CustomListViewDB extends ListActivity {
private ListView mainListView = null;
CustomSqlCursorAdapter adapter = null;
private SqlHelper dbHelper = null;
private Cursor currentCursor = null;
private ListView listView = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple);
if (this.dbHelper == null) {
this.dbHelper = new SqlHelper(this);
}
listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//listView.setClickable(true);
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearDBSelections();
}
});
new SelectDataTask().execute();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
}
#Override
protected void onRestart() {
super.onRestart();
new SelectDataTask().execute();
}
#Override
protected void onPause() {
super.onPause();
this.dbHelper.close();
}
protected void ClearDBSelections() {
this.adapter.ClearSelections();
}
private class SelectDataTask extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
try {
CustomListViewDB.this.dbHelper.createDatabase(dbHelper.dbSqlite);
CustomListViewDB.this.dbHelper.openDataBase();
CustomListViewDB.this.currentCursor = CustomListViewDB.this.dbHelper
.getCursor();
} catch (SQLException sqle) {
throw sqle;
}
return null;
}
// can use UI thread here
protected void onPostExecute(final String result) {
startManagingCursor(CustomListViewDB.this.currentCursor);
int[] listFields = new int[] { R.id.txtTitle };
String[] dbColumns = new String[] { SqlHelper.COLUMN_TITLE };
CustomListViewDB.this.adapter = new CustomSqlCursorAdapter(
CustomListViewDB.this, R.layout.single_item,
CustomListViewDB.this.currentCursor, dbColumns, listFields,
CustomListViewDB.this.dbHelper);
setListAdapter(CustomListViewDB.this.adapter);
}
}
}
CustomSqlCursorAdapter.java
// src/CustomSqlCursorAdapter.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class CustomSqlCursorAdapter extends SimpleCursorAdapter {
private Context mContext;
private SqlHelper mDbHelper;
private Cursor mCurrentCursor;
public CustomSqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, SqlHelper dbHelper) {
super(context, layout, c, from, to);
this.mCurrentCursor = c;
this.mContext = context;
this.mDbHelper = dbHelper;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.single_item, null);
}
if (!this.mCurrentCursor.moveToPosition(pos)) {
throw new SQLException("CustomSqlCursorAdapter.getView: Unable to move to position: "+pos);
}
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
// save the row's _id value in the checkbox's tag for retrieval later
cBox.setTag(Integer.valueOf(this.mCurrentCursor.getInt(0)));
if (this.mCurrentCursor.getInt(SqlHelper.COLUMN_SELECTED_idx) != 0) {
cBox.setChecked(true);
Log.w("SqlHelper", "CheckBox true for pos "+pos+", id="+this.mCurrentCursor.getInt(0));
} else {
cBox.setChecked(false);
Log.w("SqlHelper", "CheckBox false for pos "+pos+", id="+this.mCurrentCursor.getInt(0));
}
//cBox.setOnClickListener(this);
cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.w("SqlHelper", "Selected a CheckBox and in onCheckedChanged: "+isChecked);
Integer _id = (Integer) buttonView.getTag();
ContentValues values = new ContentValues();
values.put(SqlHelper.COLUMN_SELECTED,
isChecked ? Integer.valueOf(1) : Integer.valueOf(0));
mDbHelper.dbSqlite.beginTransaction();
try {
if (mDbHelper.dbSqlite.update(SqlHelper.TABLE_NAME, values, "_id=?",
new String[] { Integer.toString(_id) }) != 1) {
throw new SQLException("onCheckedChanged failed to update _id="+_id);
}
mDbHelper.dbSqlite.setTransactionSuccessful();
} finally {
mDbHelper.dbSqlite.endTransaction();
}
Log.w("SqlHelper", "-- _id="+_id+", isChecked="+isChecked);
}
});
TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle.setText(this.mCurrentCursor.getString(this.mCurrentCursor
.getColumnIndex(SqlHelper.COLUMN_TITLE)));
return (v);
}
public void ClearSelections() {
this.mDbHelper.clearSelections();
this.mCurrentCursor.requery();
}
}
ListViewWithDBActivity.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.Activity;
import android.os.Bundle;
public class ListViewWithDBActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
SqlHelper
// SqlHelper.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class SqlHelper extends SQLiteOpenHelper {
private static final String DATABASE_PATH = "/data/data/com.appfulcrum.blog.examples.listviewcustomdb/databases/";
public static final String DATABASE_NAME = "TODOList";
public static final String TABLE_NAME = "ToDoItems";
public static final int ToDoItems_VERSION = 1;
public static final String COLUMN_ID = "_id"; // 0
public static final String COLUMN_TITLE = "title"; // 1
public static final String COLUMN_NAME_DESC = "description";// 2
public static final String COLUMN_SELECTED = "selected"; // 3
public static final int COLUMN_SELECTED_idx = 3;
public SQLiteDatabase dbSqlite;
private Context mContext;
public SqlHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
mContext = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
createDB(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("SqlHelper", "Upgrading database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS ToDoItems;");
createDB(db);
}
public void createDatabase(SQLiteDatabase db) {
createDB(db);
}
private void createDB(SQLiteDatabase db) {
if (db == null) {
db = mContext.openOrCreateDatabase(DATABASE_NAME, 0, null);
}
db.execSQL("CREATE TABLE IF NOT EXISTS ToDoItems (_id INTEGER PRIMARY KEY, title TEXT, "
+" description TEXT, selected INTEGER);");
db.setVersion(ToDoItems_VERSION);
//
// Generate a few rows for an example
//
// find out how many rows already exist, and make sure there's some minimum
SQLiteStatement s = db.compileStatement("select count(*) from ToDoItems;");
long count = s.simpleQueryForLong();
for (int i = 0; i < 20-count; i++) {
db.execSQL("INSERT INTO ToDoItems VALUES(NULL,'Task #"+i+"','Description #"+i+"',0);");
}
}
public void openDataBase() throws SQLException {
String myPath = DATABASE_PATH + DATABASE_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
#Override
public synchronized void close() {
if (dbSqlite != null)
dbSqlite.close();
super.close();
}
public Cursor getCursor() {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_TITLE,
COLUMN_NAME_DESC, COLUMN_SELECTED };
Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
null, null, null, COLUMN_ID+" ASC");
return mCursor;
}
public void clearSelections() {
ContentValues values = new ContentValues();
values.put(COLUMN_SELECTED, 0);
this.dbSqlite.update(SqlHelper.TABLE_NAME, values, null, null);
}
}
Start.java
//src/Start.java
package com.appfulcrum.blog.examples.listviewcustomdb;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Start extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnSimple = (Button) findViewById(R.id.btnSimple);
btnSimple.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked ListView From DB button", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), CustomListViewDB.class);
startActivityForResult(intent, 0);
}
});
}
}
layout/main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/buttonlayout" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="left|top" android:paddingTop="2dp"
android:paddingBottom="2dp">
<TextView android:id="#+id/txtTest" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textStyle="bold"
android:text="#string/app_name" android:textSize="15sp"
android:textColor="#FF0000" android:gravity="center_vertical"
android:paddingLeft="5dp">
</TextView>
<Button android:id="#+id/btnSimple"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="Listview from DB"
android:textColor="#000000"
>
</Button>
</LinearLayout>
layout/simple.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:id="#+id/buttonlayout"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:height="32dp"
android:gravity="left|top" android:paddingTop="2dp"
android:paddingBottom="2dp">
<LinearLayout android:id="#+id/buttonlayout2"
android:orientation="horizontal" android:layout_height="wrap_content"
android:gravity="left|center_vertical" android:layout_width="wrap_content"
android:layout_gravity="left|center_vertical">
<TextView android:id="#+id/txtTest"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textStyle="bold"
android:text="#string/list_header" android:textSize="15sp"
android:gravity="center_vertical" android:paddingLeft="5dp">
</TextView>
<Button android:id="#+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Clear"
android:textSize="15sp" android:layout_marginLeft="10px"
android:layout_marginRight="10px"
android:layout_marginBottom="2px"
android:layout_marginTop="2px" android:height="15dp"
android:width="70dp"></Button>
</LinearLayout>
</LinearLayout>
<TableLayout android:id="#+id/TableLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:stretchColumns="*">
<TableRow>
<ListView android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</TableRow>
</TableLayout>
</LinearLayout>
layout/single_item.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="horizontal" android:gravity="center_vertical">
<CheckBox android:id="#+id/bcheck"
android:layout_width="wrap_content"
android:layout_height="fill_parent" />
<TextView android:id="#+id/txtTitle"
android:layout_width="wrap_content" android:gravity="left|center_vertical"
android:layout_height="?android:attr/listPreferredItemHeight"
android:layout_alignParentLeft="true"
android:textSize="20sp" android:text="Test"
android:textStyle="bold" android:paddingLeft="5dp"
android:paddingRight="2dp" android:focusable="false"
android:focusableInTouchMode="false"></TextView>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal"
android:gravity="right|center_vertical">
</LinearLayout>
</LinearLayout>
values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ListViewWithDBActivity!</string>
<string name="app_name">ListViewWithDB</string>
<string name="list_header">List Headers</string>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1" android:versionName="1.0"
package="com.appfulcrum.blog.examples.listviewcustomdb">
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar">
>
<activity android:name=".Start" 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=".CustomListViewDB"></activity>
</application>
<uses-sdk android:minSdkVersion="7" /> <!-- android 1.6 -->
</manifest>
If you want to build, throw some arbitrary icon.png into drawable.
Thanks in advance.
I found the most complete solution to the problem off-site.
At Android ListView with CheckBox : Retain State
Appreciate the help folks.
The Views in a ListView are recycled, and this sounds like an issue with that. You probably need to invalidate your onCheckedChangedListener so that when you do setChecked() it isn't calling the previous listener inadvertently. There could be other ramifications of the recycling as well, so keep that in mind.
So try:
cBox.setOnCheckedChangeListener(null);
...
cBox.setChecked();
...
cBox.setOnCheckedChangeListner(<real listener);