Failed to retrieve data in Search View in android - 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);
}
});
}
}
}

Related

Fetching values from Cursor but Application Crashes

I am trying to fetch values from the database when I click on the view button which is another activity for navigation when I click on the view all button the CustodianViewActivity is triggered to display all the values from the database on a list view but in my case the application crashes every time I try to view the data from the database. Am not sure where I am going wrong.
Database Class
import android.content.ContentValues;
import android.content.Context;import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHandler extends SQLiteOpenHelper {
private static DBHandler instance;
// Database Name
public static final String DATABASE_NAME ="AssetDB.db";
//Database version
public static final int Databasevr = 1;
//Custodian Table Name
public static final String TABLE_CUSTODIAN = " Custodian";
// Columbs in the Custodian Table
public static final String CUSTODIAN_ID = "_CustID";
public static final String CUSTODIAN_NAME = "CustName";
public static final String CUSTODIAN_DESIGNATION = "CustDesign";
public static final String CUSTODIAN_DEPARTMENT = "CustDepart";private static final String CREATE_TABLE_CUSTODIAN = "CREATE TABLE" + TABLE_CUSTODIAN + "("
+ CUSTODIAN_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"
+ CUSTODIAN_NAME + " TEXT NOT NULL,"
+ CUSTODIAN_DESIGNATION + " TEXT NOT NULL,"
+ CUSTODIAN_DEPARTMENT + " TEXT NOT NULL" + ");";
// constructor passing parameter passing Database name and Database version
public DBHandler(Context ct)
{
super(ct, DATABASE_NAME, null, Databasevr);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// Creating the tables
db.execSQL(CREATE_TABLE_CUSTODIAN);
db.execSQL(CREATE_TABLE_ASSET);
Log.d("Tables","Tables have been created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// dropping the tables
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CUSTODIAN );
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_ASSET);
// recreate the tables
onCreate(db);
}
public Cursor getAllCustodians(){
try {
SQLiteDatabase db_database = getWritableDatabase();
Cursor cursor = db_database.rawQuery("SELECT * FROM" + TABLE_CUSTODIAN, null);
if (cursor != null) {
return cursor;
} else {
return null;
}
}
catch(Exception e)
{
return null;
}
}}
CustodianViewActivity
package com.example.nfcams;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class CustodianViewActivity extends Activity {
ListView CustodianListview;
DBHandler db_database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custodian_view);
db_database = new DBHandler(getApplicationContext());
CustodianListview = (ListView) findViewById(R.id.custodianlistView);
new Handler().post(new Runnable() {
#Override
public void run() {
populateCustoListView();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_custodian_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void populateCustoListView()
{
Cursor c = db_database.getAllCustodians();
CustodianListview.setAdapter(new CustodiansListAdapter(this,c));
}
private class CustodiansListAdapter extends CursorAdapter
{
private Cursor cursor;
public CustodiansListAdapter(Context context, Cursor cur) {
super(context, cur);
cursor = cur;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView custID = (TextView) view.findViewById(R.id.Custodianid_view);
int CustodID = cursor.getInt(cursor.getColumnIndex("_CustID"));
custID.setText(String.valueOf(CustodID));
TextView name = (TextView) view.findViewById(R.id.Custodianname_view);
String Custname = cursor.getString(cursor.getColumnIndex("CustName"));
name.setText(Custname);
TextView Designation = (TextView) view.findViewById(R.id.CustodianDesignation_view);
String CustDesignation = cursor.getString(cursor.getColumnIndex("CustDesign"));
Designation.setText(CustDesignation);
TextView Department = (TextView) view.findViewById(R.id.CustodianDepartment_view);
String CustDepartment = cursor.getString(cursor.getColumnIndex("CustDepart"));
Department.setText(CustDepartment);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View retView = inflater.inflate(R.layout.custodianrow_views, parent, false);
bindView(retView,context,cursor);
return retView;
}
}
}
Custodianview Activity layout
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.nfcams.CustodianViewActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/custodianlistView"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
List view layout
<?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="wrap_content"
android:background="#color/list_item_bg"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="#+id/layout_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/Custodianname_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="6dp" />
<TextView
android:id="#+id/Custodianid_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/Custodianname_view"
android:padding="6dp" />
<TextView
android:id="#+id/CustodianDesignation_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Custodianid_view"
android:padding="6dp" />
<TextView
android:id="#+id/CustodianDepartment_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/CustodianDesignation_view"
android:padding="6dp" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/layout_item"
android:background="#color/view_divider_color" />
</RelativeLayout>
Error Log
05-30 09:42:16.471 1334-1334/com.example.nfcams E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.nfcams, PID: 1334
java.lang.IllegalArgumentException: column '_id' does not exist
at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
at android.widget.CursorAdapter.init(CursorAdapter.java:172)
at android.widget.CursorAdapter.<init>(CursorAdapter.java:120)
at com.example.nfcams.CustodianViewActivity$CustodiansListAdapter.<init>(CustodianViewActivity.java:95)
at com.example.nfcams.CustodianViewActivity.populateCustoListView(CustodianViewActivity.java:84)
at com.example.nfcams.CustodianViewActivity.access$000(CustodianViewActivity.java:17)
at com.example.nfcams.CustodianViewActivity$1.run(CustodianViewActivity.java:42)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)

Can't populate textview from database

I can't understand why I doesen't get any data out of the database. I have to admit that I am confues about listviews, textviews and adapters.
The database contains a person and a gift. That should be poured into a textview. Somehow it seems that I have to make a listview, but.... I am confused.
I have read a lot, and worked hard, but I have no idea. I would appreciate it if anyone could help me :-)
The only thing that happens is that na empty list is appearing.
Here is the code:
Main Activity.java:
package com.example.julegaveliste2;
import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends ListActivity {
DatabaseHelper db;
Button knapp1;
Button knapp2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper db = new DatabaseHelper(MainActivity.this);
knapp1 = (Button) findViewById(R.id.Legg_Til);
knapp2 = (Button) findViewById(R.id.Les_database);
knapp2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
visliste(db.getWritableDatabase());
}
});
knapp1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
LagTabell(db.getWritableDatabase());
}
});
}
public static void LagTabell(SQLiteDatabase db)
{
ContentValues jul = new ContentValues();
jul.put("person", "Ida");
jul.put("gave", "blomst");
db.insert("julegaveliste2", "person", jul);
}
public void visliste(SQLiteDatabase db)
{
Cursor cursor=db.rawQuery("SELECT _id, person, gave FROM julegaveliste2", null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.activity_list_item, cursor, new String[]{"person","gave"}, new int[]{R.id.person,R.id.gave},0);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
}
}
DatabaseHelper.java:
package com.example.julegaveliste2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String DATABASE_NAME="julegaveliste2.db";
private static final int SCHEMA=1;
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, SCHEMA);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE julegaveliste2 (_id INTEGER PRIMARY KEY AUTOINCREMENT, person TEXT NOT NULL, gave TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
throw new RuntimeException("How did we get here?");
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<TextView
android:id="#+id/gave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
<Button
android:id="#+id/Legg_Til"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="15dp"
android:layout_marginRight="17dp"
android:text="#string/opprett_database" />
<Button
android:id="#+id/Les_database"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Legg_Til"
android:layout_alignBottom="#+id/Legg_Til"
android:layout_toRightOf="#+id/person"
android:text="#string/les_database" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_above="#+id/Legg_Til"
android:layout_alignParentLeft="true"
android:layout_marginBottom="42dp" >
</ListView>
<ListView
android1:id="#+id/listView1"
android1:layout_width="match_parent"
android1:layout_height="100dp" >
</ListView>
</RelativeLayout>
You should try to replace your SimpleCursorAdapter with an ArrayAdapter. To do this we would need a few modifications to your code. We need a new class in your application, which I will call PresentItem, an ArrayAdapter for your list, an XML layout for each row in the list, and a method for converting SQLite rows to PresentItems. First out is the new model, PresentItem:
public class PresentItem {
private String name, present;
private int id;
public PresentItem(int id, String name, String present) {
// Init
}
// Getters, setters, etc.
}
So, when we now read from your database, we can convert each rows we get from our query to new PresentItems:
public List<PresentItem> getPresentItems(SQLiteDatabase db) {
Cursor cursor = db.query("julegaveliste2",
new String[] {"_id", "person", "gave"}, null, null, null, null, null);
List<PresentItem> result = new ArrayList<PresentItem>();
PresentItem item;
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndex("_id");
int id = cursor.getInt(index));
index = cursor.getColumnIndex("name");
String name = cursor.getString(index));
index = cursor.getColumnIndex("present");
String present = cursor.getString(index);
item = new PresentItem(id, name, present);
result.add(item);
}
return result;
}
Once we have the PresentItems parsed from the database, we need a way to display them. To display the PresentItems in your app, we need our own ArrayAdapter, which would look something like this:
public class PresentListAdapter extends ArrayAdapter<PresentItem> {
private Context ctx;
private List<PresentItem> presentItems;
public PresentListAdapter(Context ctx, int layoutResourceId, List<PresentItem> presentItems) {
super(context, layoutResourceId, presentItems);
this.ctx = ctx;
this.presentItems = presentItems;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
convertView = inflater.inflate(mLayoutResourceId, parent, false);
}
PresentItem item = presentItems.get(position);
((TextView) convertView.findViewById(R.id.row_id)).setText("" + item.getId());
((TextView) convertView.findViewById(R.id.name)).setText(item.getName());
((TextView) convertView.findViewById(R.id.present)).setText(item.getPresent());
return convertView;
}
To use the adapter in your app, do something like this:
public void visListe(SQLiteDatabase db){
List<PresentItem> items = getPresentItems(db);
PresentItemAdapter adapter = new PresentItemAdapter(this, R.layout.presentListItem, items);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
And, as you might notice, our adapter uses presentListItem as its layout, which we define in res/layout/presentListItem.xml as:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/row_id"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/name"
/>
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/present"
/>
</LinearLayout>
I hope I made it clear and beware bugs in the code - I wrote most of it from memory with a few quick Google searches to help me :) Ask if you need anymore help ^^

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

ListFragment and Custom Adapter Issue

Two issue with List Fragment: 1. I have a class that extends ListFragments.In the onCreated, I am setting my custom Adapter. The issue is that when the user logs in, the adadpter is null and would not have a value until the user searches for an owner. As a result, it throws an exception when it tries to set up the listadapter and it finds the ArrayAdapter object to be null. I have a custome layout that has a listview and a textview, but I still gets the error. See sample code below. I bold the line of code where the issue happens. Also, I bold few other section where I think it may be important to notice.
I implemented Parcelable in the class "Owner" so that I can pass the object as a ParcelableArray. Even though the object is not null, retrieving it in the OwnerDetail class shows null as if I did not pass it it. I've seen several example, but I am not able to get it right. What am I doing wrong here?
Note: If I were to call the AsyncTask in the OwnerDetail class and set the ListAdapter, it will work fine. The issue with that is that it will display a list of owners as soon as the user is logged in which is not the expected behavior. The behavior that I want is to login first, search for an owner, display the owner, double click on an owner, and finally display a list of cars that the owner owns. I am doing this project, so I can learn how to use ListFraments.
// Here is the entire code
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Car implements Parcelable {
private String _make;
private String _model;
private String _year;
public Car()
{
this._make = "";
this._model = "";
this._year = "";
}
public Car(String make)
{
this._make = make;
}
public Car(String make, String year)
{
this._make = make;
this._year = year;
}
public Car(String make, String model, String year)
{
this._make = make;
this._model = model;
this._year = year;
}
//Getters
public String getMake()
{
return _make;
}
public String getModel()
{
return _model;
}
public String getYear()
{
return _year;
}
//Setters
public void setMake(String make)
{
_make = make;
}
public void setModel(String model)
{
_model = model;
}
public void setYear(String year)
{
_year = year;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CarDetail extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String[] myCars = {};
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> carAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, myCars);
setListAdapter(carAdapter);
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Login extends Activity implements OnClickListener{
private Button btnLogin;
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initializeVariables();
}
public void initializeVariables()
{
btnLogin = (Button) this.findViewById(R.id.bLogin);
etUsername = (EditText)this.findViewById(R.id.etUserName);
etPassword = (EditText)this.findViewById(R.id.etPassword);
btnLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
Log.i("Tag", "In Onclick Litener");
String uName = etUsername.getText().toString();
String pWord = etPassword.getText().toString();
if(uName.equals("owner") && pWord.equals("1234"))
{
Log.i("Tag", "username =" + uName + "Password =" + pWord);
Intent intent = new Intent(this, People.class);
startActivity(intent);
}
}
}
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Owner implements Parcelable {
private String _firstName;
private String _lastName;
private String _carId;
private Car _car;
public Owner()
{
this._firstName = "";
this._lastName = "";
this._carId = "";
}
public Owner(String lName)
{
this._lastName = lName;
}
public Owner(String lName, String cId)
{
this._lastName = lName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId, Car car)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
this._car = car;
}
//Getters
public String getFirstName()
{
return _firstName;
}
public String getLastName()
{
return _lastName;
}
public String getCarId()
{
return _carId;
}
public Car getCar()
{
return _car;
}
//Setters
public void setFirstName(String fName)
{
_firstName = fName;
}
public void setLastName(String lName)
{
_lastName = lName;
}
public void setCarId(String cId)
{
_carId = cId;
}
public void setCar(Car car)
{
_car = car;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_firstName);
dest.writeString(_lastName);
dest.writeString(_carId);
dest.writeParcelable(_car, flags);
}
public Owner(Parcel source){
_firstName = source.readString();
_lastName = source.readString();
_carId = source.readString();
_car = source.readParcelable(Car.class.getClassLoader());
}
public class MyCreator implements Parcelable.Creator<Owner> {
public Owner createFromParcel(Parcel source) {
return new Owner(source);
}
public Owner[] newArray(int size) {
return new Owner[size];
}
}
}
package com.mb.carlovers;
import com.mb.carlovers.adapter.OwnerAdapter;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container, false);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Owner[] myOwners = null;
super.onCreate(savedInstanceState);
Bundle values = getActivity().getIntent().getExtras();
if(values != null)
{
myOwners = (Owner[]) values.getParcelableArray("test");
}
super.onActivityCreated(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail , myOwners);
ownerAdapter.notifyDataSetChanged();
}
package com.mb.carlovers;
import java.util.List;
import com.mb.carlovers.asynctask.OnwerAsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class People extends FragmentActivity implements OnClickListener, OnItemSelectedListener {
private Button search;
private EditText etSearchBy, etSearchByID;
private Spinner spOption;
private String selectedOption = null;
private TextView tvErrorMessage;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.people);
InitializeVariables();
}
private void InitializeVariables()
{
etSearchBy = (EditText) this.findViewById(R.id.etByLastName);
etSearchByID = (EditText) this.findViewById(R.id.etCarID);
spOption = (Spinner) this.findViewById(R.id.spOption);
search = (Button) this.findViewById(R.id.bSearch);
search.setOnClickListener(this);
tvErrorMessage = (TextView) this.findViewById(R.id.tvErrorMessage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.spOptions, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOption.setAdapter(adapter);
spOption.setOnItemSelectedListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
String searchByName = etSearchBy.getText().toString();
String searchById = etSearchByID.getText().toString();
if(selectedOption == null || selectedOption == "All")
{
if(searchByName.matches("") || searchById.matches(""))
{
tvErrorMessage.setText("You must select a last name and car id");
} else
{
}
} else if(selectedOption == "Name")
{
if(!searchByName.matches(""))
{
OnwerAsyncTask asynTask = new OnwerAsyncTask();
List<Owner> lt = null;
try {
lt = asynTask.execute("").get();
} catch (Exception e) {
e.printStackTrace();
}
Owner myOwners[] = lt.toArray(new Owner[lt.size()]);
Bundle data = new Bundle();
data.putParcelableArray("test", myOwners);
} else
{
tvErrorMessage.setText("You must enter the last name of the owner.");
}
} else if (selectedOption == "ID")
{
if(!searchById.matches(""))
{
String st = null;
String d = st;
} else
{
tvErrorMessage.setText("You must enter the car id that you'd like to search.");
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
switch(pos)
{
case 0:
selectedOption = "All";
break;
case 1:
selectedOption ="Name";
break;
case 2:
selectedOption ="ID";
break;
default:
selectedOption = null;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedOption ="ALL";
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Car;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CarAdapter extends ArrayAdapter<Car> {
private Context context;
private int layoutResourceId;
private Car data[] = null;
public CarAdapter(Context context, int resource, Car[] data) {
super(context, resource, data);
this.context = context;
this.layoutResourceId = resource;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CarHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CarHolder();
holder.tvMake = (TextView) row.findViewById(R.id.tvMake);
holder.tvModel = (TextView) row.findViewById(R.id.tvModel);
holder.tvYear = (TextView) row.findViewById(R.id.tvYear);
row.setTag(holder);
} else
{
holder = (CarHolder) row.getTag();
}
Car item = data[position];
holder.tvMake.setText(item.getMake().toString());
holder.tvModel.setText(item.getModel().toString());
holder.tvYear.setText(item.getYear().toString());
return row;
}
public static class CarHolder
{
TextView tvMake;
TextView tvModel;
TextView tvYear;
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Owner;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText("Example");
holder.tvCId.setText("1");
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Car;
import android.os.AsyncTask;
public class CarAsyncTask extends AsyncTask<String, Void, List<Car>> {
private List<Car> item = null;
#Override
protected List<Car> doInBackground(String... params) {
item = new ArrayList<Car>();
item.add(new Car("Chevy","Caprice","2002"));
item.add(new Car("Chevy","Malibu","2014"));
item.add(new Car("Dodge","Stratus","2002"));
item.add(new Car("Saturn","L300","2004"));
return item;
}
#Override
protected void onPostExecute(List<Car> result) {
super.onPostExecute(result);
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Owner;
import android.os.AsyncTask;
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
#Override
protected List<Owner> doInBackground(String... params) {
try
{
items = new ArrayList<Owner>();
Owner own = new Owner();
own.setFirstName("John");
own.setLastName("Smith");
own.setCarId("1");
items.add(own);
Owner own1 = new Owner();
own1.setFirstName("Samantha");
own1.setLastName("Right");
own1.setCarId("2");
items.add(own1);
Owner own2 = new Owner();
own2.setFirstName("Regie");
own2.setLastName("Miller");
own2.setCarId("3");
items.add(own2);
Owner own3 = new Owner();
own3.setFirstName("Mark");
own3.setLastName("Adam");
own3.setCarId("4");
items.add(own3);
} catch(Exception ex)
{
ex.toString();
}
return items;
}
#Override
protected void onPostExecute(List<Owner> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
// car_detail.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Detail Page" />
</LinearLayout>
// car_row.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="horizontal" >
<TextView
android:id="#+id/tvMake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvModel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
//customize_layout.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" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No record to be displayed."
/>
</LinearLayout>
//Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".Login" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etUserName"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
>
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etPassword"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:text="Login" />
</LinearLayout>
//owner_detail.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="horizontal" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// People.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="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by last name"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
/>
<EditText
android:id="#+id/etByLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by car id"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<EditText
android:id="#+id/etCarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<Spinner
android:id="#+id/spOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spOptions"
/>
<TextView
android:id="#+id/tvErrorMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:layout_marginTop="10dp"
android:text="" />
<Button
android:id="#+id/bSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2"
>
<fragment
android:id="#+id/fOwnerDetail"
android:name="com.mb.carlovers.OwnerDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<fragment
android:id="#+id/fragment1"
android:name="com.mb.carlovers.CarDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
/>
</LinearLayout>
</LinearLayout>
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(ownerAdapter);
}
}
Your code has a lot of problems:
1 Never call lifecycle methods on your own like you do in the OwnerDetail class with super.onActivityCreated(savedInstanceState);
2 Bundle values = getActivity().getIntent().getExtras(); ... values.getParcelableArray("test"); will normally fail because this piece of code will get the activity reference, get the Intent that started the activity and then try to find data passed in under the test key in that Intent. You don't pass such data to the People activity so there will be nothing to be found. You'd normally want to pass a Bundle containing the data at the moment of the creation of the fragment.
3 If you use the fragment in the xml layout you'll not be able to use a Bundle to pass data, instead you either add the fragment manually with transactions and then use a Bundle or you create a setter method in the fragment class and use that. So instead of Bundle data = new Bundle(); data.putParcelableArray("test", myOwners);, which does nothing, get a reference to your fragment and pass the myOwners array through a method.
4 Your AsyncTask will be pretty useless if you use them with .get() because the get() method will wait the AsyncTask to finish, blocking the UI tread as well. Instead you should just start the AsyncTask and then in the onPostExecute() pass the data around.
Here is an example with a simple method which will not change most of your code(which will happen if you manually add the fragments):
// where you start the owner asynctask
if(!searchByName.matches("")) {
OnwerAsyncTask asynTask = new OnwerAsyncTask(People.this);
asynTask.execute("");
}
//...
Then change the OnwerAsyncTask like this:
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
private FragmentActivity mActivity;
public OnwerAsyncTask(FragmentActivity activity) {
mActivity = activity;
}
// doInBackground()...
#Override
protected void onPostExecute(List<Owner> result) {
//I'm assuming that items is the data you want to return, so
// find the OwnerDetail fragment and directly assign the data
OwnerDetail fragment = (OwnerDetail)mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.setData(); // to setData you'll pass the data you have in the AsyncTask
// the items list? or you transform that into an array?
}
and in the OwnerDetail fragment:
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
public void setData() {
// update the adapter, create a new one etc.
}

insert code causing app to stop

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);
}

Categories

Resources