insert code causing app to stop - android

i have this set of codes used for inserting data into my sqlite database. but why does my app stop when i try to insert?
package edu.nyp.project;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
public class AddData extends Activity {
Button insertButton = null;
EditText shopText= null;
EditText dealText= null;
EditText locationText= null;
EditText websiteText= null;
EditText categoryText= null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adddata);
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdapter = new
DBAdapter(getApplicationContext());
try{
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
}
catch(Exception e){
Log.d("Add Data ", e.getMessage());
}
finally{
if (dbAdapter != null)
dbAdapter.close();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.adddata, menu);
return true;
}
}
here is the code for the DBAdapter file for reference.
package edu.nyp.project;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_SHOP = "shop";
public static final String KEY_DEAL = "deal";
public static final String KEY_LOCATION = "location";
public static final String KEY_WEBSITE = "website";
public static final String KEY_CATEGORY = "category";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "Project";
private static final String DATABASE_TABLE = "Deals";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table Deals (_id integer primary key autoincrement, " +
"shop varchar not null, deal varchar not null, " +
"location varchar not null, website varchar not null, category text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter (Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate (SQLiteDatabase db)
{
try{
db.execSQL(DATABASE_CREATE);
}
catch(SQLException e){
e.printStackTrace();
}
}
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion+ "to "+ newVersion
+ "which will destroy all data");
db.execSQL("DROP TABLE IF EXISTS Deals");
onCreate(db);
}
}
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
public void close()
{
DBHelper.close();
}
public long insertDeal(String shop, String deal, String location, String website, String category)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_SHOP, shop);
initialValues.put(KEY_DEAL, deal);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_WEBSITE, website);
initialValues.put(KEY_CATEGORY, category);
return db.insert(DATABASE_TABLE, null, initialValues);
}
}
and xml file is below, also for reference as well.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/shopText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Shop name" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/dealText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Deal" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/locationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Location" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/websiteText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Website" >
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/categoryText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Category" >
</EditText>
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/LinearLayout1"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="60px"
android:text="Insert" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="60px"
android:text="Delete" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="60px"
android:text="Search" />
</LinearLayout>
</LinearLayout>

becouse I think you dont bind that components with findViewById:
shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
result should be a NullPointerException.
Show us youre LogCat...
Otherwise add this to youre on create and try it again:
shopText= (EditText)findViewById(R.id.THE_ID);
dealText= (EditText)findViewById(R.id.THE_ID);;
locationText= (EditText)findViewById(R.id.THE_ID);;
websiteText= (EditText)findViewById(R.id.THE_ID);;
categoryText= (EditText)findViewById(R.id.THE_ID);;

First of all get all EditText By id.
try{
shopText=(EditText)findViewById(R.id.shopText)
//get All EditText by id like above
dbAdapter.open();
String shop = shopText.getText().toString();
String deal = dealText.getText().toString();
String location = locationText.getText().toString();
String website = websiteText.getText().toString();
String category = categoryText.getText().toString();
//secondly
dbAdapter.insertDeal(shop,deal,location,website,category);
}

Related

Android SQLite cursor/adapter cannot get data from database

I have a gridview class here:
<?xml version="1.0" encoding="utf-8"?>
<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:background="#color/colorPrimaryDark"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/topContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="7">
<TextView
android:id="#+id/textView0"
android:background="#color/white"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID: "
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView1"
android:background="#color/purple"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridCode"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView2"
android:background="#color/green"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDay"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView3"
android:background="#color/orange"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridStart"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView4"
android:background="#color/blue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridDuration"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView5"
android:background="#color/yellow"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridType"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
<TextView
android:id="#+id/textView6"
android:background="#color/red"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/gridRoom"
android:textSize="18sp"
android:textColor="#color/black"
android:gravity="center"
/>
</LinearLayout>
<GridView
android:id="#+id/gridTable"
android:layout_below="#+id/topContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="10dip"
android:verticalSpacing="15dip"
android:stretchMode="columnWidth"
android:gravity="center"
android:numColumns="7"
android:background="#color/colorPrimary"
android:textSize="14sp"
>
</GridView>
</RelativeLayout>
and a database helper:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
//database information
public static final String DATABASE_NAME = "timetable.db";
public static final String TABLE_NAME = "timetable_data";
//the data each column will store
public static final String COL_1 = "ID";
public static final String COL_2 = "CODE";
public static final String COL_3 = "DAY";
public static final String COL_4 = "START";
public static final String COL_5 = "DURATION";
public static final String COL_6 = "TYPE";
public static final String COL_7 = "ROOM";
//construct the database
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,CODE TEXT,DAY TEXT,START TEXT,DURATION TEXT,TYPE TEXT,ROOM TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
public boolean insertData(String code, String day, String start, String duration, String type, String room)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,code);
contentValues.put(COL_3,day);
contentValues.put(COL_4,start);
contentValues.put(COL_5,duration);
contentValues.put(COL_6,type);
contentValues.put(COL_7, room);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("select * from "+TABLE_NAME,null);
return data;
}
public Integer deleteEntry(String id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME,"ID = ?", new String [] {id});
}
}
I'm trying to populate this gridview with data stored in the database, everything compiles fine, but in the app i get an error saying that data from Col-1 (the id column) cannot be retrieved.
this is the gridviewactivity.java class mentioned in the above code:
public class GridViewActivity extends MainActivity
{
private GridView gridTable;
private ArrayList<String> moduleList;
private ArrayAdapter<String> adapter;
private Cursor data;
DatabaseHelper timetableDB;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState); setContentView(R.layout.gridview);
//GridView
gridTable=(GridView) findViewById(R.id.gridTable);
String id, code, day, time, duration, type, room;
id = ""; code = ""; day = ""; time = "";
duration = ""; type = ""; room = "";
timetableDB = new DatabaseHelper(getBaseContext());//getting the context object
timetableDB.getAllData();
try
{
//for holding retrieve data from query and store in the form of rows
Cursor data=timetableDB.getAllData();
moduleList = new ArrayList<>();
//Move the cursor to the first row.
if(data.moveToFirst())
{
do
{
id = data.getString(data.getColumnIndex ("id"));
code = data.getString(data.getColumnIndex ("code"));
day = data.getString(data.getColumnIndex ("day"));
time = data.getString(data.getColumnIndex ("time"));
duration = data.getString(data.getColumnIndex ("duration"));
type = data.getString(data.getColumnIndex ("type"));
room = data.getString(data.getColumnIndex ("room"));
//add in to array list
moduleList . add(id);
moduleList . add(code);
moduleList . add(day);
moduleList . add(time);
moduleList . add(duration);
moduleList . add(type);
moduleList . add(room);
}
while(data.moveToNext());//Move the cursor to the next row.
adapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_spinner_item,moduleList);
gridTable.setAdapter(adapter);
}
else
{
Toast.makeText(getApplicationContext(),
"No data found", Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Toast.makeText(getApplicationContext(),
"No data found "+e.getMessage(), Toast.LENGTH_LONG).show();
}
timetableDB.close();
}
}
am i using the cursor correctly in this class?
thanks!
am i using the cursor correctly in this class?
Yes, but problem is creating ArrayAdapter in wrong place.
Create object of ArrayAdapter after adding all items in moduleList ArrayList from Cursor.like:
do{
// add items in moduleList
}
while(data.moveToNext());//Move the cursor to the next row.
// create ArrayAdapter object here:
adapter = new ArrayAdapter<>(getApplicationContext(),
android.R.layout.simple_spinner_item,moduleList);
// call setAdapter
gridTable.setAdapter(adapter);
The "id" column doesn't exist.
When you're creating the database you're using "ID" as the column name and not "id" so when you're calling data.getString(data.getColumnIndex("id")); it won't be able to find the column.

Failed to retrieve data in Search View in android

I'm trying to do a simple retrieval of data from SQLite Database to the SearchView.
My problem is the SearchView is not populated with respect to the data stored in the database, although it always shows the green signal of
successfully created the database
Below is the code.
fragment_search.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#E6E6E6"
android:orientation="vertical" >
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:background="#FFFFFF" />
<SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp" >
</SearchView>
<ListView
android:id="#+id/listview_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchView"
android:layout_centerHorizontal="true"
android:divider="#E6E6E6"
android:dividerHeight="5dp" />
<LinearLayout
android:id="#+id/rightLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/view1"
android:layout_alignTop="#+id/view1"
android:orientation="vertical"
android:paddingTop="25dp" >
</LinearLayout>
</RelativeLayout>
Search_list.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" >
<LinearLayout
android:id="#+id/hotelLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/section_search"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnCount="2" >
<ImageView
android:id="#+id/hotel_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="left"
android:src="#drawable/aaa" />
<EditText
android:id="#+id/hotel_name"
android:layout_width="209dp"
android:layout_height="56dp"
android:layout_gravity="fill_horizontal" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/hotel_city"
android:layout_width="96dp"
android:layout_column="1"
android:layout_gravity="left|bottom"
android:layout_row="0"
android:ems="10" />
<EditText
android:id="#+id/hotel_country"
android:layout_width="106dp"
android:layout_column="1"
android:layout_gravity="right|bottom"
android:layout_row="0"
android:ems="10" />
</GridLayout>
</TableRow>
</LinearLayout>
</RelativeLayout>
TableData.java
package com.mytry.test;
import android.provider.BaseColumns;
public class TableData
{
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String DATABASE_NAME = "tourDguide";
public static final String TABLE_NAME = "Hotels";
public static final String HOTEL_ID = "id";
public static final String HOTEL_NAME = "hotel_name";
public static final String HOTEL_ADDRESS = "hotel_address";
public static final String HOTEL_CITY = "hotel_city";
public static final String HOTEL_COUNTRY = "hotel_country";
public static final String HOTEL_POSTAL = "postal_code";
}
}
DataBaseHandler.java
package com.mytry.test;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mytry.test.TableData.TableInfo;
public class DataHandler
{
public static final int DATABASE_VERSION = 1;
SQLiteDatabase db;
DataBaseHelper dbhelper;
Context ctx;
private static class DataBaseHelper extends SQLiteOpenHelper
{
public String CREATE_QUERY = "CREATE TABLE "+TableInfo.TABLE_NAME+"("+TableInfo.HOTEL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+TableInfo.HOTEL_NAME+" VARCHAR,"+TableInfo.HOTEL_ADDRESS+" VARCHAR,"+TableInfo.HOTEL_CITY+" VARCHAR,"+TableInfo.HOTEL_COUNTRY+" VARCHAR,"+TableInfo.HOTEL_POSTAL+" INT );";
public DataBaseHelper(Context ctx) {
super(ctx,TableInfo.DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Database Operations", "Successfully Created Database");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try{
db.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Successfully Created Table");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop table if exists "+TableInfo.TABLE_NAME);
onCreate(db);
}
}
public DataHandler(Context ctx) {
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
// TODO Auto-generated constructor stub
}
public DataHandler open()
{
dbhelper = new DataBaseHelper(ctx);
db = dbhelper.getReadableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public Cursor searchHotels(String inputText) throws SQLException
{
String query = "Select "+TableInfo.HOTEL_ID+" as _id,"+TableInfo.HOTEL_NAME+","+TableInfo.HOTEL_ADDRESS+","+TableInfo.HOTEL_CITY+","+TableInfo.HOTEL_COUNTRY+","+TableInfo.HOTEL_POSTAL+" from "+TableInfo.TABLE_NAME+" where "+TableInfo.HOTEL_NAME+" LIKE '" + inputText + "';";
Log.d("table operations","Successfully transferred query");
Cursor cr = db.rawQuery(query, null);
if(cr!=null)
{
cr.moveToFirst();
}
return cr;
}
}
SeachViewActivity.java
package com.mytry.test;
import com.mytry.test.TableData.TableInfo;
import android.R.anim;
import android.app.Activity;
import android.app.DownloadManager.Query;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SearchViewActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener
{
private ListView list;
private SearchView search;
private DataHandler dbHandler;
private TextView name,city,country;
private EditText edit;
Context ctx=this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_search);
search = (SearchView) this.findViewById(R.id.searchView);
list = (ListView) this.findViewById(R.id.listview_search);
name = (TextView)this.findViewById(R.id.hotel_name);
city = (TextView)this.findViewById(R.id.hotel_city);
country = (TextView)this.findViewById(R.id.hotel_country);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
dbHandler = new DataHandler(getBaseContext());
dbHandler.open();
}
public boolean onQueryTextSubmit(String query)
{
showResults(query + "*");
return false;
}
public boolean onQueryTextChange(String newText)
{
showResults(newText + "*");
return false;
}
public boolean onClose()
{
showResults("");
return false;
}
private void showResults(String query)
{
Cursor cr = dbHandler.searchHotels((query!=null?query.toString(): "####"));
if(cr==null)
{
}
else
{
String[] from = new String[]
{TableInfo.HOTEL_NAME,TableInfo.HOTEL_ADDRESS,TableInfo.HOTEL_CITY,TableInfo.HOTEL_COUNTRY,TableInfo.HOTEL_POSTAL};
int[] to = new int[]{R.id.hotel_name,R.id.hotel_city,R.id.hotel_country};
SimpleCursorAdapter hotels = new SimpleCursorAdapter(this,R.layout.search_list, cr, from, to);
list.setAdapter(hotels);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Cursor cr = (Cursor)list.getItemAtPosition(position);
String hotel_name = cr.getString(cr.getColumnIndexOrThrow("hotel_name"));
String hotel_city = cr.getString(cr.getColumnIndexOrThrow("hotel_city"));
String hotel_country = cr.getString(cr.getColumnIndexOrThrow("hotel_country"));
LinearLayout hotelLayout = (LinearLayout)findViewById(R.id.hotelLayout);
if(hotelLayout == null){
//Inflate the Customer Information View
LinearLayout leftLayout = (LinearLayout)findViewById(R.id.rightLayout);
View hotelInfo = getLayoutInflater().inflate(R.layout.search_list, leftLayout, false);
leftLayout.addView(hotelInfo);
}
name.setText(hotel_name);
city.setText(hotel_city);
country.setText(hotel_country);
search.setQuery("", true);
}
});
}
}
}

how to display one row from SQLite database to textview/edittext

I'm very new to android and about to create an app which holds customers and then related to it some actions.
My current unsolvable problem: After inserting customer data into database I want to switch the view and display the last entry with all fields. The inserted values like title, name but also automatically created fields like id and date. I can see that the data are in the database when I pull the database file from the DDMS but I don't know how to retrieve and display them in the desired view.
I saw dozens of examples for passing it to a listview but I couldn't find any example which would suit my needs. Maybe it's because I don't know how to ask correctly for it. If so, please point me in the right direction.
My DatabaseHelper:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
public class DbHelper {
public static final String TABLE_CUSTOMERS = "customers";
public static final String COLUMN_CUSTOMER_ID = "_id";
public static final String COLUMN_CUSTOMER_TITLE = "title";
public static final String COLUMN_CUSTOMER_FIRST_NAME = "first_name";
public static final String COLUMN_CUSTOMER_LAST_NAME = "last_name";
public static final String COLUMN_CUSTOMER_DATE = "date";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "myround.db";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE = "CREATE TABLE if not exists "
+ TABLE_CUSTOMERS + " (" + COLUMN_CUSTOMER_ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_CUSTOMER_TITLE + " VARCHAR, "
+ COLUMN_CUSTOMER_FIRST_NAME + " VARCHAR, " + COLUMN_CUSTOMER_LAST_NAME + " VARCHAR, " + COLUMN_CUSTOMER_DATE + " VARCHAR);";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CUSTOMERS);
onCreate(db);
}
}
public DbHelper(Context ctx) {
this.mCtx = ctx;
}
public DbHelper open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCustomer(String Title, String FirstName, String LastName,
String Date) {
ContentValues initialValues = new ContentValues();
initialValues.put(COLUMN_CUSTOMER_TITLE, Title);
initialValues.put(COLUMN_CUSTOMER_FIRST_NAME, FirstName);
initialValues.put(COLUMN_CUSTOMER_LAST_NAME, LastName);
initialValues.put(COLUMN_CUSTOMER_DATE, Date);
long id = mDb.insert(TABLE_CUSTOMERS, null, initialValues);
return id;
}
public Cursor displayLastCustomer() {
Cursor mCursor = mDb.query(TABLE_CUSTOMERS, new String[] {COLUMN_CUSTOMER_ID,
COLUMN_CUSTOMER_TITLE, COLUMN_CUSTOMER_FIRST_NAME, COLUMN_CUSTOMER_LAST_NAME, COLUMN_CUSTOMER_DATE},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToLast();
}
return mCursor;
}
}
And my CustomerHelper:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
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 CustomerHelper extends Activity implements OnClickListener {
public static final String TAG = "CustomerHelper";
EditText txtTtitle, txtFirstName, txtLastName,
editID, editTitle, editFirstName, editLastName, editDate;
Button btn_add_customer_to_db;
DbHelper dbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_customer);
txtTtitle = (EditText) findViewById(R.id.txt_title);
txtFirstName = (EditText) findViewById(R.id.txt_first_name);
txtLastName = (EditText) findViewById(R.id.txt_last_name);
editID = (EditText) findViewById(R.id.ntxt_customer_id);
btn_add_customer_to_db = (Button) findViewById(R.id.add_customer_to_db);
btn_add_customer_to_db.setOnClickListener(this);
dbHelper = new DbHelper(this);
dbHelper.open();
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
public void onClick(View view) {
if (view == btn_add_customer_to_db) {
String Title = txtTtitle.getText().toString();
String FirstName = txtFirstName.getText().toString();
String LastName = txtLastName.getText().toString();
String Date = getDateTime();
long id = dbHelper.createCustomer(Title, FirstName, LastName, Date);
if (id < 0) {
Toast.makeText(this, "Error - Unsuccessful", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(this, "Success - Record added",
Toast.LENGTH_LONG).show();
}
}
}
}
I'm looking for a solution to implement this view with the last entry into my CustomerHelperClass so that I can also modify or delete this entry.
For Inserting new customer I have add_new_customer.xml and I want to switch view to update_customer.xml with the last entry displayed. Both of them have the text fields for title, name etc
update_customer.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="#string/update_customer_xml_title"
android:textSize="14sp" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" >
<Button
android:id="#+id/add_activity_to_customer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:text="#string/add_activity_to_customer_sm_btn"
android:textSize="10sp" />
<Button
android:id="#+id/go_to_view_customer_management"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:text="#string/go_to_customer_mgmt"
android:textSize="10sp" />
<Button
android:id="#+id/go_to_main_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.3"
android:text="#string/go_to_main_menu"
android:textSize="10sp" />
</LinearLayout>
<Button
android:id="#+id/delete_customer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_marginBottom="5dp"
android:text="#string/delete_customer" />
<Button
android:id="#+id/save_customer_changes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/delete_customer"
android:layout_alignBottom="#+id/delete_customer"
android:layout_alignRight="#+id/linearLayout1"
android:text="#string/save_customer_changes" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/save_customer_changes"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginTop="5sp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/ntxt_customer_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView" />
<EditText
android:id="#+id/ntxt_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ntxt_customer_id"
android:hint="#string/title"
android:inputType="text"
android:textAppearance="?android:attr/textAppearance"
android:textColor="#android:color/black" />
<EditText
android:id="#+id/ntxt_first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ntxt_title"
android:layout_marginTop="8dp"
android:hint="#string/first_name"
android:inputType="text"
android:textAppearance="?android:attr/textAppearance"
android:textColor="#android:color/black" />
<EditText
android:id="#+id/ntxt_last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ntxt_first_name"
android:layout_marginTop="8dp"
android:hint="#string/last_name"
android:inputType="text"
android:textAppearance="?android:attr/textAppearance"
android:textColor="#android:color/black" />
<EditText
android:id="#+id/ntxt_customer_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ntxt_last_name"
android:layout_marginTop="8dp"
android:hint="date"
android:inputType="text"
android:textAppearance="?android:attr/textAppearance"
android:textColor="#android:color/black" />
</RelativeLayout>
</ScrollView>
edit:
} else {
Toast.makeText(this, "Success - Record added",
Toast.LENGTH_LONG).show();
setContentView(R.layout.update_customer);
}
}
DbHelper dbHelperInstance = new DbHelper(this); // Assuming it's running
// in an Activity
Cursor cursor = dbHelperInstance.displayLastCustomer();
if (cursor != null) {
EditText editTextFirstName = (EditText) findViewById(R.id.ntxt_first_name);
editTextFirstName.setText(cursor.getString(cursor
.getColumnIndex(DbHelper.COLUMN_CUSTOMER_FIRST_NAME)));
}
}
}
Hopefully you can build upon this answer, if you need further guidance, feel free to comment.
Let's assume you want the EditText with id ntxt_first_name to be populated with customer name. You'd write this code after you call displayLastCustomer()
DatabaseHelper dbHelperInstance = new DbHelper(this); //Assuming it's running in an Activity
Cursor cursor = dbHelperInstance.displayLastCustomer();
if(cursor != null) {
EditText editTextFirstName = (EditText) findViewById(R.id.ntxt_first_name);
editTextFirstName.setText(cursor.getString(cursor.getColumnIndex(DbHelper.COLUMN_CUSTOMER_FIRST_NAME)));
}
The above snippet tries to find the View (EditText) with id ntxt_frist_name within the inflated View hierarchy that was supplied using the setContentView(int resourceId) method (hopefully you have supplied R.layout.update_customer as its parameter. Then it simply sets its mText field to the value it obtains from the entry cursor is currently pointing at (set to last entry in the query by your displayLastCustomer() method) for the column DbHelper.COLUMN_CUSTOMER_FIRST_NAME.
Like I already wrote, I hope you can get from this snippet how to populate other Views obtaining data from other columns in your Cursor object.
Cheers and good luck!
EDIT: In case you are not running this code inside an Activity object (or object of a class derived from it) , you need to obtain the Context of the Activity which has the update_customer.xml file inflated.

java.lang.ClassCastException error when trying to save data in the sqlite on button click

I have tab in the activity when i click on the button to open tab view it works fine. Now after entering the data in the fields then when i click on the button to save it it gives me error.May be i have error in sqlite database constructor but not sure.Some one please help:
this is my code for a tab:
package com.example.doctormanager;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
public class General extends Activity {
Context context;
private Button proceed;
private EditText patient_name,mobile,address,email,dob,age;
ListView template_list;
Intent data_intent;
String name="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_general);
data_intent=getIntent();
name=data_intent.getStringExtra("name");
patient_name=(EditText)findViewById(R.id.txt17);
patient_name.setText(""+name);
mobile=(EditText)findViewById(R.id.txt23);
address=(EditText)findViewById(R.id.txt21);
email=(EditText)findViewById(R.id.txt19);
dob=(EditText)findViewById(R.id.txt25);
age=(EditText)findViewById(R.id.txt27);
ImageButton save= (ImageButton)findViewById(R.id.ib13);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SqlHandler db = new SqlHandler(this);
String p_name = patient_name.getText().toString();
String p_mobile = mobile.getText().toString();
String p_addr = address.getText().toString();
String p_email = email.getText().toString();
String p_dob = dob.getText().toString();
String p_age = age.getText().toString();
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Patient_entery(0, p_name, p_mobile, p_addr, p_email, p_dob, p_age, null));
}
});
}
}
and this is for the database:
package com.example.doctormanager;
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.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View.OnClickListener;
public class SqlHandler extends SQLiteOpenHelper {
public SqlHandler(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "doctormanager";
// Contacts table name
private static final String TABLE_PATIENT_GENERAL= "general";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_PATIENT_NAME = "patient_name";
private static final String KEY_EMAIL = "patient_email";
private static final String KEY_PATIENT_ADDR = "patient_addr";
private static final String KEY_PATIENT_CONTACT_NUMBER = "patient_contact_number";
private static final String KEY_PATIENT_DOB = "patient_dob";
private static final String KEY_PATIENT_AGE = "patient_age";
private static final String KEY_PATIENT_SEX = "patient_sex";
public SqlHandler (OnClickListener onClickListener) {
super((Context) onClickListener, DATABASE_NAME, null, DATABASE_VERSION);
}
// public SqlHandler(OnClickListener onClickListener) {
// // TODO Auto-generated constructor stub
// }
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PATIENT_TABLE = "CREATE TABLE " + TABLE_PATIENT_GENERAL + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_PATIENT_NAME + " TEXT,"
+ KEY_PATIENT_CONTACT_NUMBER + " TEXT," + KEY_EMAIL +"TEXT," + KEY_PATIENT_ADDR + "TEXT,"
+ KEY_PATIENT_DOB + "TEXT," + KEY_PATIENT_AGE + "TEXT," + KEY_PATIENT_SEX + "TEXT " + ")";
db.execSQL(CREATE_PATIENT_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PATIENT_GENERAL);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Patient_entery patient) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PATIENT_NAME, patient.getName()); // Contact Name
values.put(KEY_PATIENT_CONTACT_NUMBER, patient.getPhoneNumber()); // Contact Phone
values.put(KEY_EMAIL, patient.getPatientEmail()); // Contact Name
values.put(KEY_PATIENT_ADDR, patient.getAddress()); // Contact Phone
values.put(KEY_PATIENT_DOB, patient.getDob()); // Contact Name
values.put(KEY_PATIENT_AGE, patient.getAge()); // Contact Phone
values.put(KEY_PATIENT_SEX, patient.getSex()); // Contact Name
// Inserting Row
db.insert(TABLE_PATIENT_GENERAL, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Patient_entery getPatient(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PATIENT_GENERAL, new String[] { KEY_ID,
KEY_PATIENT_NAME, KEY_PATIENT_CONTACT_NUMBER, KEY_EMAIL, KEY_PATIENT_ADDR, KEY_PATIENT_DOB, KEY_PATIENT_AGE, KEY_PATIENT_SEX }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Patient_entery patient = new Patient_entery(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7));
// return contact
return patient;
}
public String getAllStringValues() {
ArrayList<String> yourStringValues = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(true, TABLE_PATIENT_GENERAL,
new String[] { KEY_PATIENT_NAME }, null, null, null, null,
null, null);
if (result.moveToFirst()) {
do {
yourStringValues.add(result.getString(result
.getColumnIndex(KEY_PATIENT_NAME)));
} while (result.moveToNext());
} else {
return null;
}
return KEY_PATIENT_NAME;
}
}
and this is the XML file:
<?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"
android:background="#drawable/login_back">
<LinearLayout
android:layout_height="30dip"
android:layout_width="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txt16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<EditText
android:id="#+id/txt17"
android:layout_width="200dp"
android:layout_height="20dp"
android:background="#drawable/edit_text_lines"
android:ems="10"
android:textSize="10dip" />
</LinearLayout>
<LinearLayout
android:layout_height="40dip"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txt18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<EditText
android:id="#+id/txt19"
android:layout_width="200dp"
android:layout_height="20dp"
android:text=""
android:textSize="10dip"
android:background="#drawable/edit_text_lines"
/>
</LinearLayout>
<LinearLayout
android:layout_height="40dip"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txt20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<EditText
android:id="#+id/txt21"
android:layout_width="200dp"
android:layout_height="20dp"
android:text=""
android:textSize="10dip"
android:background="#drawable/edit_text_lines" />
</LinearLayout>
<LinearLayout
android:layout_height="40dip"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txt22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone No.: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<EditText
android:id="#+id/txt23"
android:layout_width="200dp"
android:layout_height="20dp"
android:text=""
android:textSize="10dip"
android:background="#drawable/edit_text_lines"/>
</LinearLayout>
<LinearLayout
android:layout_height="40dip"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txt24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DOB: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<EditText
android:id="#+id/txt25"
android:layout_width="200dp"
android:layout_height="20dp"
android:text=""
android:textSize="10dip"
android:background="#drawable/edit_text_lines"/>
</LinearLayout>
<LinearLayout
android:layout_height="40dip"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/txt26"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<EditText
android:id="#+id/txt27"
android:layout_width="200dp"
android:layout_height="20dp"
android:text=""
android:textSize="10dip"
android:background="#drawable/edit_text_lines"/>
</LinearLayout>
<LinearLayout
android:layout_height="40dip"
android:layout_width="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/stxt27"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sex: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:textColor="#FFFFFF" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:textColor="#FFFFFF"/>
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#FFFFFF" />
</RadioGroup>
</LinearLayout>
<TextView
android:id="#+id/txt28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Patient/Family History: "
android:textSize="20dip"
android:textColor="#FFFFFF"/>
<EditText
android:id="#+id/edttxt27"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#FFFFFF" />
<ImageButton
android:id="#+id/ib14"
android:src="#drawable/template"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="1dip"
/>
<ImageButton
android:id="#+id/ib13"
android:src="#drawable/next_visit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
THANKS IN ADVANCE.
You need to pass Activity context on SqlHandler like:
SqlHandler db = new SqlHandler(youractivity.this);
in Button onclick()
And also Remove OnClickListener onClickListener() from SqlHanlder Constructer like:
public SqlHandler (Context con) {
super(con, DATABASE_NAME, null, DATABASE_VERSION);
}

how to take picture and save to DataBase and add to ListView?

i am new in android. i created a database and a listview. i want to add picture to listview by take picture by camera.
this is my input class:
package com.kalagar.warehouse;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class AddNew extends Activity implements View.OnClickListener {
ImageButton ib;
Button b;
ImageView iv;
EditText etName,etKharid,etForoush;
Intent i;
final static int CameraData = 0;
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addnew);
startAddNew();
}
private void startAddNew() {
ib = (ImageButton) findViewById(R.id.ibTakePic);
b = (Button) findViewById(R.id.bSave);
iv = (ImageView) findViewById(R.id.ivPic);
etName = (EditText) findViewById(R.id.etName);
etKharid = (EditText) findViewById(R.id.etKharid);
etForoush = (EditText) findViewById(R.id.etForoush);
b.setOnClickListener(this);
ib.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraData);
break;
case R.id.bSave:
boolean didItWork = true;
try {
String name = etName.getText().toString();
String kharid = etKharid.getText().toString();
String foroush = etForoush.getText().toString();
DataBase entry = new DataBase(AddNew.this);
entry.open();
entry.createEntry(name, kharid, foroush);
entry.close();
} catch (Exception e) {
// TODO Auto-generated catch block
didItWork = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("oooh ! Nooo !!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
e.printStackTrace();
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heck Yea!");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}
this is my input 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" >
<EditText
android:id="#+id/etName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="نام محصول"
>
<requestFocus />
</EditText>
<EditText
android:id="#+id/etKharid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="قیمت خرید"
android:inputType="number"
/>
<EditText
android:id="#+id/etForoush"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="قیمت فروش"
android:inputType="number"
/>
<ImageButton
android:id="#+id/ibTakePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_gravity="center"/>
<ImageView
android:id="#+id/ivPic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_gravity="center"/>
<Button
android:id="#+id/bSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ذخیره"
android:layout_gravity="center" />
</LinearLayout>
this is my DataBase :
package com.kalagar.warehouse;
import java.util.ArrayList;
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.util.Log;
public class DataBase {
private static final String LOGTAG = "WAREHOUSE";
private static final String DATABASE_TABLE = "WareHouse";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "SellList";
public static final String ROW_ID = "_id";
public static final String ROW_NAME = "nameOfObject";
public static final String ROW_KHARID = "ghBuy";
public static final String ROW_FOROUSH = "ghSell";
public static final String ROW_PICTURE = "picture";
private static final String TABLE_CREATE = "CREATE TABLE " + DATABASE_TABLE
+ " (" + ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ROW_NAME
+ " TEXT, " + ROW_KHARID + " NUMERIC, " + ROW_FOROUSH
+ " NUMERIC, " + ROW_PICTURE + " TEXT " + ")";
private WareHouseDdbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class WareHouseDdbHelper extends SQLiteOpenHelper {
public WareHouseDdbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
Log.i(LOGTAG, "Table has been create");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
onCreate(db);
}
}
public DataBase(Context c) {
ourContext = c;
}
public DataBase open() throws SQLException {
ourHelper = new WareHouseDdbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String name, String kharid, String foroush) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(ROW_NAME, name);
cv.put(ROW_KHARID, kharid);
cv.put(ROW_FOROUSH, foroush);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public ArrayList<String> getDataName() {
// TODO Auto-generated method stub
String[] columns = new String[] { ROW_ID, ROW_NAME, ROW_KHARID,
ROW_FOROUSH };
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null,
null, null);
ArrayList<String> result = new ArrayList<String>();
int iRow = c.getColumnIndex(ROW_ID);
int iName = c.getColumnIndex(ROW_NAME);
int iKharid = c.getColumnIndex(ROW_KHARID);
int iForoush = c.getColumnIndex(ROW_FOROUSH);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result.add(c.getString(iRow) + " " + c.getString(iName)
+ " " + c.getString(iKharid) + " " + c.getString(iForoush));
}
return result;
}
}
this is my class for show data in listView:
package com.kalagar.warehouse;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Show extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
Name();
}
private void Name() {
ListView tvName = (ListView) findViewById(R.id.lvListOfObject);
DataBase infoName = new DataBase(this);
infoName.open();
ArrayList<String> dataName = infoName.getDataName();
infoName.close();
tvName.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, dataName));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.show, menu);
return true;
}
}
and this is my ListView XML that i want add picture to each row:
<?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/tvListHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textSize="30dp"
android:text="لیست محصولات" />
<ListView
android:id="#+id/lvListOfObject"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView1"
android:layout_centerHorizontal="true" >
</ListView>
<SearchView
android:id="#+id/searchView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/tvListHeader" >
</SearchView>
</RelativeLayout>
how can i show ListView With this Template:
<?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" >
<ImageView
android:id="#+id/ivPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:maxHeight="80dp"
android:maxWidth="80dp"
android:src="#drawable/download" />
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/name_shown_here"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvKharid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tvForoush"
android:layout_centerHorizontal="true"
android:text="Kharid" />
<TextView
android:id="#+id/tvForoush"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ivPicture"
android:layout_alignLeft="#+id/tvKharid"
android:text="Foroush" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tvKharid"
android:layout_alignParentRight="true"
android:text="قیمت خرید" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvForoush"
android:layout_alignBottom="#+id/tvForoush"
android:layout_alignParentRight="true"
android:text="قیمت فروش" />
</RelativeLayout>
what code i need to add and where i need to add?
Sorry for my english !
why you don't save picture in Sdcard instead of databse.
This link help you to do so

Categories

Resources