I want to retrieve all the data whose status is open in my database so that I have use LIKE command in my android application with SQLite Database.
But when I run the app I'm getting NullPointerException at the line of searchList . setAdapter (new_Lead_List_Adapter).
Here is my Database Adapter Class
public class DataBase_Adapter
{
//Database NAme
static final String DATABASE_NAME = "lead_management.db";
//Database Version
static final int DATABASE_VERSION = 4;
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public DataBase_Adapter(Context _context)
{
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DataBase_Adapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
//Table name
public static String TABLE_NEW_LEAD="new_lead";
//Creating New Lead Table Columns
public static final String KEY_NEW_LEAD_ID ="id";
public static final String KEY_NEW_LEAD_NAME ="name";
public static final String KEY_NEW_LEAD_EMAIL ="email";
public static final String KEY_NEW_LEAD_MOBILE="mobile";
public static final String KEY_NEW_LEAD_Product="define_products";
public static final String KEY_NEW_LEAD_BUDGET="budget";
public static final String KEY_NEW_LEAD_PRIORITY="priority";
public static final String KEY_NEW_LEAD_STATUS="status";
public static final String KEY_NEW_LEAD_NOTES="notes";
public static final String KEY_NEW_LEAD_REMINDER_DATE="reminder_date";
public static final String KEY_NEW_LEAD_REMINDER_TIME="reminder_time";
public static final String KEY_NEW_LEAD_ADDtoCONTACTS="add_to_contacts";
//// SQL Statement to create a New Lead Database.
static final String CREATE_NEW_LEAD_TABLE = "CREATE TABLE "+ TABLE_NEW_LEAD + "("
+ KEY_NEW_LEAD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_NEW_LEAD_NAME + " TEXT,"
+ KEY_NEW_LEAD_EMAIL + " TEXT,"
+ KEY_NEW_LEAD_MOBILE+ " TEXT,"
+ KEY_NEW_LEAD_Product + " TEXT,"
+ KEY_NEW_LEAD_BUDGET + " TEXT,"
+ KEY_NEW_LEAD_PRIORITY +" TEXT,"
+ KEY_NEW_LEAD_STATUS + " TEXT,"
+ KEY_NEW_LEAD_NOTES + " TEXT,"
+ KEY_NEW_LEAD_REMINDER_DATE + " TEXT,"
+ KEY_NEW_LEAD_REMINDER_TIME + " TEXT,"
+ KEY_NEW_LEAD_ADDtoCONTACTS + " TEXT"+");";
//");";
//Insert New Record In New Lead Table
public void insert_NewLead_Entry(New_Lead_BeanClass newLead_BeanClass)
{
SQLiteDatabase sdb = dbHelper.getWritableDatabase();
ContentValues contentNewLead_Val=new ContentValues();
contentNewLead_Val.put(KEY_NEW_LEAD_NAME, newLead_BeanClass.get_Name());
contentNewLead_Val.put(KEY_NEW_LEAD_EMAIL, newLead_BeanClass.get_Email());
contentNewLead_Val.put(KEY_NEW_LEAD_MOBILE, newLead_BeanClass.get_MobileNo());
contentNewLead_Val.put(KEY_NEW_LEAD_Product, newLead_BeanClass.get_Product());
contentNewLead_Val.put(KEY_NEW_LEAD_BUDGET, newLead_BeanClass.get_Budget());
contentNewLead_Val.put(KEY_NEW_LEAD_PRIORITY, newLead_BeanClass.get_Priority());
contentNewLead_Val.put(KEY_NEW_LEAD_STATUS, newLead_BeanClass.get_Status());
contentNewLead_Val.put(KEY_NEW_LEAD_NOTES, newLead_BeanClass.get_Notes());
contentNewLead_Val.put(KEY_NEW_LEAD_REMINDER_DATE, newLead_BeanClass.get_Reminder_Date());
contentNewLead_Val.put(KEY_NEW_LEAD_REMINDER_TIME, newLead_BeanClass.get_Reminder_Time());
contentNewLead_Val.put(KEY_NEW_LEAD_ADDtoCONTACTS, newLead_BeanClass.get_AddtoContact());
sdb.insert(TABLE_NEW_LEAD , null , contentNewLead_Val );
//Close The Database Connection
sdb.close();
}
public ArrayList<HashMap<String,String>> getAllUserData()
{
ArrayList<HashMap<String,String>> newLeadDat_Listl;
newLeadDat_Listl = new ArrayList<HashMap<String,String>>();
SQLiteDatabase sdatabase = dbHelper.getWritableDatabase();
String selectQuery= "SELECT * FROM" + TABLE_NEW_LEAD ;
Cursor cursor = sdatabase.rawQuery(selectQuery, null);
if (cursor.moveToFirst())
{
do
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_NEW_LEAD_ID, cursor.getString(0));
map.put(KEY_NEW_LEAD_NAME, cursor.getString(1));
map.put(KEY_NEW_LEAD_EMAIL, cursor.getString(2));
map.put(KEY_NEW_LEAD_MOBILE, cursor.getString(3));
map.put(KEY_NEW_LEAD_Product, cursor.getString(4));
map.put(KEY_NEW_LEAD_BUDGET, cursor.getString(5));
map.put(KEY_NEW_LEAD_PRIORITY, cursor.getString(6));
map.put(KEY_NEW_LEAD_STATUS, cursor.getString(7));
map.put(KEY_NEW_LEAD_NOTES, cursor.getString(8));
map.put(KEY_NEW_LEAD_REMINDER_DATE, cursor.getString(9));
map.put(KEY_NEW_LEAD_REMINDER_TIME, cursor.getString(10));
map.put(KEY_NEW_LEAD_ADDtoCONTACTS, cursor.getString(11));
newLeadDat_Listl.add(map);
}
while (cursor.moveToNext());
}
return newLeadDat_Listl;
}
}
Here is my Activity code
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.search_data);
searchSpinner=(Spinner)findViewById(R.id.searchSpinner);
searchBtn=(ImageButton)findViewById(R.id.searchButton);
searchSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
selectedSearchItem=parent.getItemAtPosition(position).toString().trim();
System.out.println("selectedProductItem =" + selectedSearchItem);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
searchBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
displayNewLeadData();
}
});
}
public void displayNewLeadData()
{
dbAdapter=new DataBase_Adapter(Serach_Data.this).open();
dataBase = dbAdapter.getDatabaseInstance();
//Cursor mCursor = dataBase.rawQuery("SELECT name FROM " + DataBase_Adapter.TABLE_NEW_LEAD, null);
cursor = dataBase.rawQuery("SELECT id, name, priority, status FROM new_lead WHERE status LIKE ?",
new String[]{ selectedSearchItem + "%"});
cursor.moveToFirst();
arrayList_newLead_Id.clear();
arrayList_newLead_Name.clear();
arrayList_newLead_Priority.clear();
arrayList_newLead_Status.clear();
{
do
{
arrayList_newLead_Id.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_ID)));
arrayList_newLead_Name.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_NAME)));
arrayList_newLead_Priority.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_PRIORITY)));
arrayList_newLead_Status.add(cursor.getString(cursor.getColumnIndex(DataBase_Adapter.KEY_NEW_LEAD_STATUS)));
} while (cursor.moveToNext());
}
new_Lead_List_Adapter = new New_Lead_List_Adapter(Serach_Data.this ,
arrayList_newLead_Id,
arrayList_newLead_Name ,
arrayList_newLead_Priority,
arrayList_newLead_Status);
searchList.setAdapter(new_Lead_List_Adapter);
new_Lead_List_Adapter.notifyDataSetChanged();
cursor.close();
System.out.printf("Data will Be Display." , new_Lead_List_Adapter);
}
}
Here is my Adapter Class
public class New_Lead_List_Adapter extends BaseAdapter
{
Context mContext;
protected New_Lead_List_Adapter(Context mContext,
ArrayList<String> newLead_ArrayList_ID,
ArrayList<String> newLead_ArrayList_Name,
ArrayList<String> newLead_ArrayList_Pririty,
ArrayList<String> newLead_ArrayList_Status)
{
this.mContext = mContext;
this.newLead_ArrayList_ID = newLead_ArrayList_ID;
this.newLead_ArrayList_Name = newLead_ArrayList_Name;
this.newLead_ArrayList_Pririty = newLead_ArrayList_Pririty;
this.newLead_ArrayList_Status = newLead_ArrayList_Status;
}
ArrayList<String> newLead_ArrayList_ID;
ArrayList<String> newLead_ArrayList_Name;
ArrayList<String> newLead_ArrayList_Pririty;
ArrayList<String> newLead_ArrayList_Status;
protected New_Lead_List_Adapter() {
super();
// TODO Auto-generated constructor stub
}
//#Override
public int getCount() {
// TODO Auto-generated method stub
return newLead_ArrayList_Name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
// TODO Auto-generated method stub
Holder mHolder;
LayoutInflater layoutInflater;
if(child == null)
{
layoutInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater .inflate(R.layout.search_data_item_listview, null);
mHolder = new Holder();
mHolder.txt_newLead_ID=(TextView)child.findViewById(R.id.txtId);
mHolder.txt_newLead_Name=(TextView)child.findViewById(R.id.textView2_Name);
mHolder.txt_newLead_Priority=(TextView)child.findViewById(R.id.textView7Priority);
mHolder.txt_newLead_Status=(TextView)child.findViewById(R.id.textView8_Status);
child.setTag(mHolder);
}
else
{
mHolder = (Holder) child.getTag();
}
mHolder.txt_newLead_ID.setText(newLead_ArrayList_ID.get(position));
mHolder.txt_newLead_Name.setText(newLead_ArrayList_Name.get(position));
mHolder.txt_newLead_Priority.setText(newLead_ArrayList_Pririty.get(position));
mHolder.txt_newLead_Status.setText(newLead_ArrayList_Status.get(position));
return child;
}
public class Holder
{
TextView txt_newLead_ID;
TextView txt_newLead_Name;
TextView txt_newLead_Priority;
TextView txt_newLead_Status;
}
}
And the Log Cat Stack Trace info.
12-14 11:22:30.184: E/AndroidRuntime(7872): FATAL EXCEPTION: main
12-14 11:22:30.184: E/AndroidRuntime(7872): java.lang.NullPointerException
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.lead_management_project.Serach_Data.displayNewLeadData(Serach_Data.java:142)
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.lead_management_project.Serach_Data$2.onClick(Serach_Data.java:84)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.view.View.performClick(View.java:2485)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.view.View$PerformClick.run(View.java:9080)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.os.Handler.handleCallback(Handler.java:587)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.os.Looper.loop(Looper.java:123)
12-14 11:22:30.184: E/AndroidRuntime(7872): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-14 11:22:30.184: E/AndroidRuntime(7872): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 11:22:30.184: E/AndroidRuntime(7872): at java.lang.reflect.Method.invoke(Method.java:507)
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-14 11:22:30.184: E/AndroidRuntime(7872): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-14 11:22:30.184: E/AndroidRuntime(7872): at dalvik.system.NativeStart.main(Native Method)
Related
This question already has an answer here:
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 4 years ago.
I am trying to retrieve data from database and populate a custom listview. However, I am getting error
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
and the app crashes and stops. Can you tell me how can i resolve this?
I want the listview to be like this.
Logcat:
FATAL EXCEPTION: main
Process: com.example.dell.remindme, PID: 28020
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at
com.example.dell.remindme.CustomAdapter.getView(CustomAdapter.java:68)
at android.widget.AbsListView.obtainView(AbsListView.java:3170)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1389)
at android.widget.ListView.onMeasure(ListView.java:1296)
at android.view.View.measure(View.java:21126)
at
android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at
android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at
android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:400)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at
android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
at android.view.View.measure(View.java:21126)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6461)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:899)
at android.view.View.measure(View.java:21126)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2612)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1664)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1915)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1537)
at
android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:959)
at android.view.Choreographer.doCallbacks(Choreographer.java:734)
at android.view.Choreographer.doFrame(Choreographer.java:670)
at
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:945)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
Dbhelper.java
public class DbHelper extends SQLiteOpenHelper {
public static final String TAG = DbHelper.class.getSimpleName();
// Database Version
private static final int DATABASE_VERSION = 5;
// Database Name
private static final String DATABASE_NAME = "RemindMe";
// Table Names
private static final String TABLE_TODO = "Todo";
private static final String TABLE_LOGIN = "Login";
// TODO Table - column names
private static final String TASK_ID = "task_id";
private static final String TASK_TITLE = "task_title";
private static final String TASK_DESCRIP = "task_descrip";
private static final String TASK_DATE = "task_date";
private static final String TASK_TIME = "task_time";
// LOGIN Table - column names
private static final String LOGIN_ID = "login_id";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
// Table Create Statements
// Todo table create statement
private static final String CREATE_TABLE_TODO = "CREATE TABLE " + TABLE_TODO + "(" + TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TASK_TITLE + " TEXT," + TASK_DESCRIP + " TEXT," + TASK_DATE + " TEXT," + TASK_TIME + " TEXT" + ")";
// Login table create statement
private static final String CREATE_TABLE_LOGIN = "CREATE TABLE " + TABLE_LOGIN + "(" + LOGIN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + EMAIL + " EMAIL," + PASSWORD + " TEXT" + ")";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_TODO);
db.execSQL(CREATE_TABLE_LOGIN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// create new tables
onCreate(db);
}
//Todo table
//add new task
public void Add_New_Task(String task_title, String task_descrip, String task_date, String task_time){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TASK_TITLE, task_title);
values.put(TASK_DESCRIP, task_descrip);
values.put(TASK_DATE, task_date);
values.put(TASK_TIME, task_time);
// insert row
long id = db.insert(TABLE_TODO, null, values);
db.close();
Log.d(TAG, "New task added" + id);
}
//delete task
public void Delete_Task(String title){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TODO,TASK_TITLE + " = ? ",new String[] {title});
db.close();
}
}
CustomAdapter
public class CustomAdapter extends BaseAdapter {
private Context mContext;
DbHelper dbHelper;
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> date = new ArrayList<String>();
private ArrayList<String> time = new ArrayList<String>();
public CustomAdapter(Context context,ArrayList<String> title,ArrayList<String> date, ArrayList<String> time)
{
this.mContext = context;
this.title = title;
this.date = date;
this.title = time;
}
#Override
public int getCount() {
return title.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class viewHolder {
TextView Title;
TextView Date;
TextView Time;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final viewHolder holder;
dbHelper = new DbHelper(mContext);
LayoutInflater layoutInflater;
if (convertView == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.activity_list, null);
holder = new viewHolder();
holder.Title = (TextView) convertView.findViewById(R.id.task_title);
holder.Date = (TextView) convertView.findViewById(R.id.task_date);
holder.Time = (TextView) convertView.findViewById(R.id.task_time);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.Title.setText(title.get(position));
holder.Date.setText(date.get(position));
holder.Time.setText(time.get(position));
return convertView;
}
}
Todolist.java
public class To_Do_List extends AppCompatActivity{
private DbHelper dbHelper;
private SQLiteDatabase db;
private ListView lstTask;
//ArrayAdapter<String> myAdapter;
private ArrayList<String> Title = new ArrayList<String>();
private ArrayList<String> Date = new ArrayList<String>();
private ArrayList<String> Time = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to__do__list);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
lstTask = (ListView)findViewById(R.id.List);
dbHelper = new DbHelper(this);
Load_List();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
//back button on actionbar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent main_activity = new Intent(To_Do_List.this, MainActivity.class);
startActivity(main_activity);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//load activity_list of tasks
private void Load_List() {
/*ArrayList<String> taskList = dbHelper.getTaskList();
if (myAdapter == null) {
myAdapter = new ArrayAdapter<String>(this, R.layout.activity_list, R.id.task_title, taskList);
lstTask.setAdapter(myAdapter);
} else {
myAdapter.clear();
myAdapter.addAll(taskList);
myAdapter.notifyDataSetChanged();
}*/
db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT task_title, task_date, task_time FROM todo",null);
Title.clear();
Date.clear();
Time.clear();
if (cursor.moveToFirst()) {
do {
Title.add(cursor.getString(cursor.getColumnIndex("task_title")));
Date.add(cursor.getString(cursor.getColumnIndex("task_date")));
Time.add(cursor.getString(cursor.getColumnIndex("task_time")));
} while (cursor.moveToNext());
}
CustomAdapter myadapter = new CustomAdapter(To_Do_List.this,Title,Date,Time);
lstTask.setAdapter(myadapter);
//code to set adapter to populate list
cursor.close();
}
//add new task
public void Add_New_Task(View view) {
Intent intent = new Intent(To_Do_List.this, Reminder.class);
startActivity(intent);
finish();
}
//delete existing task
public void Delete_Task(View view){
View parent = (View)view.getParent();
TextView taskTextView = (TextView)parent.findViewById(R.id.task_title);
Log.e("String", (String) taskTextView.getText());
String task = String.valueOf(taskTextView.getText());
dbHelper.Delete_Task(task);
Load_List();
}
}
Your problem is explained in this line:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java:411)
You are trying to read the first element of an empty List.
Check whether there are elements before trying to read them.
You are getting
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at
that means trying to access empty list or size that not in your arraylist.
validate first list in not empty and size is greater than 0 before access.
if(list!=null && list.size()>0){
//access list
}else {
}
Hope it will help you!!
The variable "time" was queried but not updated. My bad! I fixed it and now it works. Thank you for your help guys!
You just check the length of list before getting the value from list.
if(list.size()>0){
}else {
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I can open my Datenbase but if I try to insert an item my application crashes.
Insert the item only to my ListView works.
I create a new Object in another Activity and take the Values in an Intent.
But when I start the intent and go back to the Main/List_page Activity my App crashes. Without the Database, the application runs.
Heres my codes: ReceptListAdapter.java:
public class ReceptListDatabase {
private static final String DATABASE_NAME = "receptlist.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_TABLE = "receptlistitems";
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_KATEGORY = "kategory";
public static final String KEY_INGREDIENTS = "ingredients";
public static final String KEY_DIRECTIONS = "ingredients";
public static final int COLUMN_NAME_INDEX = 1;
public static final int COLUMN_KATEGORY_INDEX = 2;
public static final int COLUMN_INGREDIENTS_INDEX = 3;
public static final int COLUMN_DIRECTIONS_INDEX = 4;
private ReceptDBOpenHelper dbHelper;
private SQLiteDatabase DB;
public ReceptListDatabase(Context context) {
dbHelper = new ReceptDBOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION);
}
public void open() throws SQLException {
try {
db = dbHelper.getWritableDatabase();
} catch (SQLException e) {
db = dbHelper.getReadableDatabase();
}
}
public void close() {
db.close();
}
public long insertReceptItem(ListItem item) {
ContentValues itemValues = new ContentValues();
itemValues.put(KEY_NAME, item.getName());
itemValues.put(KEY_KATEGORY,item.getKategory());
itemValues.put(KEY_INGREDIENTS, item.getIngredients());
itemValues.put(KEY_DIRECTIONS, item.getDirection());
return db.insert(DATABASE_TABLE, null, itemValues);
}
public void removeReceptItem(ListItem item) {
String toDelete = KEY_NAME + "=?";
String[] deleteArguments = new String[]{item.getName()};
db.delete(DATABASE_TABLE, toDelete, deleteArguments);
}
public ArrayList<ListItem> getAllReceptItems() {
ArrayList<ListItem> items = new ArrayList<ListItem>();
Cursor cursor = db.query(DATABASE_TABLE, new String[] { KEY_ID,
KEY_NAME, KEY_KATEGORY, KEY_INGREDIENTS, KEY_DIRECTIONS, null}, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(COLUMN_NAME_INDEX);
String kategory = cursor.getString(COLUMN_KATEGORY_INDEX);
String ingredients = cursor.getString(COLUMN_INGREDIENTS_INDEX);
String directions = cursor.getString(COLUMN_DIRECTIONS_INDEX);
items.add(new ListItem(name, kategory, ingredients, directions, null));
} while (cursor.moveToNext());
}
return items;
}
private class ReceptDBOpenHelper extends SQLiteOpenHelper {
private static final String DATABASE_CREATE = "create table "
+ DATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_NAME
+ " text not null, " + KEY_KATEGORY
+ " text, " + KEY_INGREDIENTS
+ " text not null, " + KEY_DIRECTIONS
+ " text not null);";
public ReceptDBOpenHelper(Context c, String dbname,
SQLiteDatabase.CursorFactory factory, int version) {
super(c, dbname, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
And my Main Activity:
public class List_Page extends Activity {
private ListViewAdapter adapter;
private ArrayList<ListItem> itemList;
private ListView list;
private DatabaseAdapter receptDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
setupButton();
setupListView();
addObject();
setupDatabase();
}
private void setupDatabase() {
receptDB = new DatabaseAdapter(this);
receptDB.open();
}
private void setupButton() {
Button addItemButton = (Button) findViewById(R.id.addItemButton);
addItemButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonClicked();
}
});
}
private void buttonClicked() {
//get EditText
Intent newItemIntent = new Intent(List_Page.this, Add_Object.class);
startActivity(newItemIntent);
finish();
}
private void setupListView() {
itemList = new ArrayList<ListItem>();
adapter = new ListViewAdapter(List_Page.this, itemList);
list = (ListView) findViewById(R.id.listItem);
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
//fehler bei removeTaskAtPosition(position);
return true;
}
});
View header = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.activity_list_item, null);
list.addHeaderView(header);
list.setAdapter(adapter);
}
private void addObject(){
Intent intent = getIntent();
if (intent.hasExtra(Constants.KEY_RECEPT_NAME)) {
String name = intent.getExtras().getString(Constants.KEY_RECEPT_NAME);
String kategory = intent.getExtras().getString(Constants.KEY_KATEGORY);
String ingredients = intent.getExtras().getString(Constants.KEY_INGREDIENTS);
String directions = intent.getExtras().getString(Constants.KEY_DIRECTIONS);
Bitmap image = (Bitmap) intent.getParcelableExtra(Constants.KEY_IMAGE);
ListItem newObject = new ListItem(name,kategory,ingredients,directions, image);
itemList.add(newObject);
receptDB.insertReceptItem(newObject);
//refreshArrayList();
}
}
private void refreshArrayList() {
ArrayList tempList = receptDB.getAllReceptItems();
itemList.clear();
itemList.addAll(tempList);
adapter.notifyDataSetChanged();
}
private void removeTaskAtPosition(int position) {
if (itemList.get(position) != null) {
receptDB.removeReceptItem(itemList.get(position));
refreshArrayList();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onDestroy() {
super.onDestroy();
receptDB.close();
}
}
Logcat:
08-12 15:37:00.743 22879-22879/de.ur.mi.android.excercises.starter E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.ur.mi.android.excercises.starter, PID: 22879
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.ur.mi.android.excercises.starter/de.ur.mi.android.excercises.starter.List_Page}: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2720)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'long de.ur.mi.android.excercises.starter.DatabaseAdapter.insertReceptItem(de.ur.mi.android.excercises.starter.domain.ListItem)' on a null object reference
at de.ur.mi.android.excercises.starter.List_Page.addObject(List_Page.java:99)
at de.ur.mi.android.excercises.starter.List_Page.onCreate(List_Page.java:40)
at android.app.Activity.performCreate(Activity.java:6720)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2673)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2781)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1508)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:241)
at android.app.ActivityThread.main(ActivityThread.java:6274)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
In your Activity's onCreate you are calling addObject() before calling setupDatabase(). Only inside setupDatabase() you are initialising receptDB instance.
But you are accessing that receptDb inside addObject() method.
receptDB.insertReceptItem(newObject);
So during that time, your receptDB has null reference and so you are getting NullPointerException.
So swap the below two lines from,
addObject();
setupDatabase();
to this:
setupDatabase();
addObject();
I am creating a landscape layout using fragment class. But now my code is showing error in my listMovieActivity file. I tried following some answers from stackoverflow but that didnt help me on it.
This is my listMovieActivity code:
package com.example.moviemanager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
public class listMovieActivity extends FragmentActivity {
private MovieDetailFragment detailFragment = null;
private MovieListFragment listFragment = null;
private FragmentManager manager;
private int selectedItemIndex = -1;
private String title=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listmovie);
manager = getSupportFragmentManager();
detailFragment = (MovieDetailFragment) manager.findFragmentById(R.id.detailmovie_fragment);
listFragment = (MovieListFragment) manager.findFragmentById(R.id.listmovie_fragment);
}
public boolean onCreateOptionsMenu(android.view.Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
protected void onResume() {
super.onResume();
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE)
showDetails(selectedItemIndex,title);
}
public void showDetails(int selectedItem, String ttl) {
//Log.d("FRAGMENT", "Selected item " + selectedItem);
selectedItemIndex = selectedItem;
title = ttl;
int orientation = getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (detailFragment != null) {
// update entry
detailFragment.updateDetails(selectedItem,ttl);
}
} else {
// show DetailsActivity
Intent intent = new Intent(this, DetailMovie.class);
intent.putExtra("POSITION", selectedItem);
intent.putExtra("TITLE", ttl);
startActivity(intent);
}
}
}
This is my DatabaseHandler code:
public class DatabaseHandler {
String cmd;
private static final String DBTAG = "DatabaseHandler";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_KEY = "key";
public static final String KEY_TITLE = "title";
public static final String KEY_TYPE = "type";
public static final String KEY_STORY = "story";
public static final String KEY_RATING = "rating";
public static final String KEY_LANGUAGE = "language";
public static final String KEY_RUNTIME = "runtime";
public static final int COL_KEY = 1;
public static final int COL_TITLE = 2;
public static final int COL_TYPE = 3;
public static final int COL_STORY = 4;
public static final int COL_RATING = 5;
public static final int COL_LANGUAGE = 6;
public static final int COL_RUNTIME = 7;
public static final String[] ALL_KEYS = new String[] {
KEY_ROWID, KEY_KEY, KEY_TITLE, KEY_TYPE, KEY_STORY,
KEY_RATING, KEY_LANGUAGE, KEY_RUNTIME};
public static final String DATABASE_NAME = "movieDb";
public static final String DATABASE_TABLE = "movieTable";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement,"
+ KEY_KEY + " text not null,"
+ KEY_TITLE + " text not null,"
+ KEY_TYPE + " text not null,"
+ KEY_STORY + " text not null,"
+ KEY_RATING + " text not null,"
+ KEY_LANGUAGE + " text not null,"
+ KEY_RUNTIME + " integer not null"
+ ");";
private final Context context;
private DatabaseHelper dbHelper;
private SQLiteDatabase db;
public DatabaseHandler(Context ctx){
this.context = ctx;
dbHelper = new DatabaseHelper(context);
}
public DatabaseHandler open(){
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
dbHelper.close();
}
public void insertRow(String mvkey, String mvtitle, String mvtype,
String mvstory, String mvrating, String mvlanguage, int mvruntime){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_KEY, mvkey);
initialValues.put(KEY_TITLE, mvtitle);
initialValues.put(KEY_TYPE, mvtype);
initialValues.put(KEY_STORY, mvstory);
initialValues.put(KEY_RATING, mvrating);
initialValues.put(KEY_LANGUAGE, mvlanguage);
initialValues.put(KEY_RUNTIME, mvruntime);
open();
db.insert(DATABASE_TABLE, null, initialValues);
close();
}
public void deleteRow(long rowId){
open();
cmd = new String ("DELETE FROM " + DATABASE_TABLE + " WHERE ( "+KEY_ROWID+" =" + rowId + " );");
db.execSQL(cmd);
close();
// String where = KEY_ROWID + "=" + rowId;
// return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll(){
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if(c.moveToFirst()){
do{
deleteRow(c.getLong((int)rowId));
}while(c.moveToNext());
}
c.close();
}
public Cursor getAllRows(){
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if(c!= null){
c.moveToFirst();
}
return c;
}
public Cursor getRow(long rowId){
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if(c!= null){
c.moveToFirst();
}
return c;
}
public boolean updateRow(long rowId, String mvkey, String mvtitle,
String mvtype, String mvstory, String mvrating,
String mvlanguage, int mvruntime){
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_KEY, mvkey);
newValues.put(KEY_TITLE, mvtitle);
newValues.put(KEY_TYPE, mvtype);
newValues.put(KEY_STORY, mvstory);
newValues.put(KEY_RATING, mvrating);
newValues.put(KEY_LANGUAGE, mvlanguage);
newValues.put(KEY_RUNTIME, mvruntime);
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
public Cursor listMovieTitle(){
return db.rawQuery("SELECT "+ KEY_TITLE + " FROM " + DATABASE_TABLE,null);
}
public Cursor get_id(String ttl){
return db.rawQuery("SELECT "+ KEY_ROWID + " FROM " + DATABASE_TABLE + " WHERE (" + KEY_TITLE + " = " + ttl + " );",null);
}
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_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(DBTAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
This is the error stack trace i am receiving each time i click on my display button:
04-04 01:00:15.314 811-811/com.example.moviemanager E/Trace﹕ error opening trace file: No such file or directory (2)
04-04 01:01:15.098 859-859/com.example.moviemanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.moviemanager/com.example.moviemanager.listMovieActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
at android.app.Activity.setContentView(Activity.java:1881)
at com.example.moviemanager.listMovieActivity.onCreate(listMovieActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
at com.example.moviemanager.DatabaseHandler.open(DatabaseHandler.java:65)
at com.example.moviemanager.MovieListFragment.onCreateView(MovieListFragment.java:29)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:900)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1082)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1184)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:270)
at android.app.Activity.setContentView(Activity.java:1881)
at com.example.moviemanager.listMovieActivity.onCreate(listMovieActivity.java:20)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
04-04 01:01:19.447 879-879/com.example.moviemanager E/Trace﹕ error opening trace file: No such file or directory (2)
Previously, I had the same problem error inflating class fragment, but then I solved it by changing my android listview id to android custome list id. But now the problem is appearing again but this time its worst my databasehandler also is showing error it seems. Can any help me on this.
In DatabaseHandler:
private final Context context;
This makes no sense, the final field cannot be assigned.And how can you make it pass the check?
Put up MovieListFragment code, please.
I am developing a Notepad app. NotesDbAdapter is the ContentProvider. NoteEdit ( edit the note) and NoteList ( display the notes already created from database). When I make an intent from NoteList to NoteEdit class,the app crash and appear this fatal error.
My LogCat
04-17 17:49:41.981: E/Trace(26753): error opening trace file: No such file or directory (2)
04-17 17:49:45.071: E/AndroidRuntime(26753): FATAL EXCEPTION: main
04-17 17:49:45.071: E/AndroidRuntime(26753): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.note/com.example.note.contentprovider.NoteEdit}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2099)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.ActivityThread.access$600(ActivityThread.java:138)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.os.Handler.dispatchMessage(Handler.java:99)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.os.Looper.loop(Looper.java:137)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.ActivityThread.main(ActivityThread.java:4929)
04-17 17:49:45.071: E/AndroidRuntime(26753): at java.lang.reflect.Method.invokeNative(Native Method)
04-17 17:49:45.071: E/AndroidRuntime(26753): at java.lang.reflect.Method.invoke(Method.java:511)
04-17 17:49:45.071: E/AndroidRuntime(26753): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
04-17 17:49:45.071: E/AndroidRuntime(26753): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
04-17 17:49:45.071: E/AndroidRuntime(26753): at dalvik.system.NativeStart.main(Native Method)
04-17 17:49:45.071: E/AndroidRuntime(26753): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:418)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.database.CursorWrapper.getString(CursorWrapper.java:114)
04-17 17:49:45.071: E/AndroidRuntime(26753): at com.example.note.contentprovider.NoteEdit.populateFields(NoteEdit.java:265)
04-17 17:49:45.071: E/AndroidRuntime(26753): at com.example.note.contentprovider.NoteEdit.onCreate(NoteEdit.java:71)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.Activity.performCreate(Activity.java:5254)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
04-17 17:49:45.071: E/AndroidRuntime(26753): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2038)
04-17 17:49:45.071: E/AndroidRuntime(26753): ... 11 more
NotesDbAdapter.java
public class NotesDbAdapter extends ContentProvider{
private Context mCtx;
static final String PROVIDER_NAME = "com.example.note.contentprovider.notesdbadapter";
static final String URL = "content://" + PROVIDER_NAME + "/notes";
static final Uri CONTENT_URI = Uri.parse(URL);
public static final String KEY_TITLE = "title";
public static final String KEY_DATE = "date";
public static final String KEY_BODY = "body";
public static final String KEY_ROWID = "_id";
public static final int NOTES = 1;
public static final int NOTES_ID = 2;
private static HashMap<String,String> Notes;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "notes", NOTES);
uriMatcher.addURI(PROVIDER_NAME, "notes/#", NOTES_ID);
}
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mhelper;
private SQLiteDatabase database;
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null, date text not null);";
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) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public boolean onCreate() {
// TODO Auto-generated method stub
Context context = getContext();
mhelper = new DatabaseHelper(context);
// permissions to be writabl
database =mhelper.getWritableDatabase();
if(database == null)
return false;
else
return true;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// the TABLE_NAME to query on
queryBuilder.setTables(DATABASE_TABLE);
switch (uriMatcher.match(uri)) {
// maps all database column names
case NOTES:
queryBuilder.setProjectionMap(Notes);
break;
case NOTES_ID:
queryBuilder.appendWhere( KEY_ROWID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
Cursor cursor = queryBuilder.query(database, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
long row = database.insert(DATABASE_TABLE, "", values);
// If record is added successfully
if(row > 0) {
Uri newUri = ContentUris.withAppendedId(CONTENT_URI, row);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
throw new SQLException("Fail to add a new record into " + uri);
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
int count = 0;
switch (uriMatcher.match(uri)){
case NOTES:
count = database.update(DATABASE_TABLE, values, selection, selectionArgs);
break;
case NOTES_ID:
count = database.update(DATABASE_TABLE, values, KEY_ROWID +
" = " + uri.getLastPathSegment() +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri );
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
int count = 0;
switch (uriMatcher.match(uri)){
case NOTES:
// delete all the records of the table
count = database.delete(DATABASE_TABLE, selection, selectionArgs);
break;
case NOTES_ID:
String id = uri.getLastPathSegment(); //gets the id
count = database.delete( DATABASE_TABLE, KEY_ROWID + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
#Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
switch (uriMatcher.match(uri)){
// Get all friend-birthday record
case NOTES:
return "vnd.android.cursor.dir/vnd.com.example.note.contentprovider.notesdbadapter/notes";
// Get a particular friend
case NOTES_ID:
return "vnd.android.cursor.item/vnd.com.example.note.contentprovider.notesdbadapter/notes";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
public NotesDbAdapter(){
}
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public NotesDbAdapter open() throws SQLException {
mhelper = new DatabaseHelper(mCtx);
database = mhelper.getWritableDatabase();
return this;
}
public void close() {
mhelper.close();
}
NoteEdit.java
public class NoteEdit extends Activity{
public static int numTitle = 1;
public static String curDate = "";
public static String curText = "";
private EditText mTitleText;
private EditText mBodyText;
private TextView mDateText;
private Long mRowId;
private String mode;
private Cursor note;
private NotesDbAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// mDbHelper = new NotesDbAdapter(this);
// mDbHelper.open();
setContentView(R.layout.note_edit);
setTitle(R.string.app_name);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateText = (TextView) findViewById(R.id.notelist_date);
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("d'/'M'/'y");
curDate = formatter.format(curDateTime);
mDateText.setText(""+curDate);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mode = extras.getString("mode");
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
}
public static class LineEditText extends EditText{
// we need this constructor for LayoutInflater
public LineEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE);
}
private Rect mRect;
private Paint mPaint;
#Override
protected void onDraw(Canvas canvas) {
int height = getHeight();
int line_height = getLineHeight();
int count = height / line_height;
if (getLineCount() > count)
count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
int baseline = getLineBounds(0, r);
for (int i = 0; i < count; i++) {
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
baseline += getLineHeight();
super.onDraw(canvas);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.noteedit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
if(note != null){
note.close();
note = null;
}
if(mRowId != null){
//mDbHelper.deleteNote(mRowId);
Uri uri = Uri.parse(NotesDbAdapter.CONTENT_URI+"/"+mRowId);
//getContentResolver().delete(uri, null, null);
mDbHelper.delete(uri,null,null);
}
finish();
return true;
case R.id.menu_save:
saveState();
finish();
default:
return super.onOptionsItemSelected(item);
}
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
String date = mDateText.getText().toString();
ContentValues values = new ContentValues();
values.put(NotesDbAdapter.KEY_TITLE, title);
values.put(NotesDbAdapter.KEY_BODY, body);
values.put(NotesDbAdapter.KEY_DATE,date);
if(mode.trim().equalsIgnoreCase("add")){
getContentResolver().insert(NotesDbAdapter.CONTENT_URI,values);
}
else {
Uri uri = Uri.parse(NotesDbAdapter.CONTENT_URI + "/" + mRowId);
getContentResolver().update(uri, values, null, null);
}
}
private void populateFields() {
if (mRowId != null) {
String[] projection = {
NotesDbAdapter.KEY_ROWID,
NotesDbAdapter.KEY_TITLE,
NotesDbAdapter.KEY_BODY,
NotesDbAdapter.KEY_DATE};
Uri uri = Uri.parse(NotesDbAdapter.CONTENT_URI + "/" + mRowId);
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
cursor.moveToFirst();
String title = cursor.getString(cursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE));
String body = cursor.getString(cursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
String date = cursor.getString(cursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATE));
mTitleText.setText(title);
mBodyText.setText(body);
mDateText.setText(date);
}
}
}
}
NoteList.java
public class NoteList extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor>{
private SimpleCursorAdapter dataAdapter;
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int DELETE_ID = Menu.FIRST;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notelist);
// mDbHelper = new NotesDbAdapter(this);
// mDbHelper.open();
fillData();
registerForContextMenu(getListView());
Button addnote = (Button)findViewById(R.id.addnotebutton);
addnote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createNote();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.notelist_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
private void createNote() {
Intent i = new Intent(this, NoteEdit.class);
Bundle bundle = new Bundle();
bundle.putString("mode", "add");
i.putExtras(bundle);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, NoteEdit.class);
Bundle bundle = new Bundle();
bundle.putString("mode", "update");
bundle.putLong(NotesDbAdapter.KEY_ROWID, id);
i.putExtras(bundle);
// i.putExtra(NotesDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}
private void fillData() {
// The desired columns to be bound
String[] columns = new String[] {
NotesDbAdapter.KEY_TITLE,
NotesDbAdapter.KEY_DATE
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.text1,
R.id.date_row
};
// create an adapter from the SimpleCursorAdapter
dataAdapter = new SimpleCursorAdapter(
this,
R.layout.notes_row,
null,
columns,
to,
0);
setListAdapter(dataAdapter);
//Ensures a loader is initialized and active.
getLoaderManager().initLoader(0, null, this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
// mDbHelper.deleteNote(info.id);
Uri uri = Uri.parse(NotesDbAdapter.CONTENT_URI + "/" + info.id);
getContentResolver().delete(uri, null, null);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
protected void onResume() {
super.onResume();
//Starts a new or restarts an existing Loader in this manager
getLoaderManager().restartLoader(0, null, this);
}
// This is called when a new Loader needs to be created.
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
NotesDbAdapter.KEY_ROWID,
NotesDbAdapter.KEY_TITLE,
NotesDbAdapter.KEY_BODY,
NotesDbAdapter.KEY_DATE};
CursorLoader cursorLoader = new CursorLoader(this,
NotesDbAdapter.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
dataAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
dataAdapter.swapCursor(null);
}
}
this section here
if (cursor != null) {
cursor.moveToFirst();
String title = cursor.getString(cursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE));
String body = cursor.getString(cursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
String date = cursor.getString(cursor.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATE));
mTitleText.setText(title);
mBodyText.setText(body);
mDateText.setText(date);
}
you need to check if the cursor has anything in it so move cursor.moveToFirst() into the if statement
I get a error,when i try to catch latitude and longitude from the array list and pass it to function called displaymarkers() in Viewmap.java file.
i have added my code and the error . can any one help me to fix this error please.
database handler (Dbhandler.java) class
package lk.adspace.jaffnatemples;
import java.util.ArrayList;
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 final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "jaffnatempletest";
// Temple table name
private static final String TABLE_TEMPLE = "templ";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TMPNAME = "temple_name";
private static final String KEY_TMPTYPE = "temple_type";
private static final String KEY_LATITUDE = "latitude";
private static final String KEY_LONGITUDE = "longitude";
private static final String KEY_IMGNAME = "image_name";
private static final String KEY_YEARBUILD = "year_build";
private static final String KEY_ADDRESS = "address";
private static final String KEY_CITY = "city";
private static final String KEY_EMAIL = "email";
private static final String KEY_WEB = "website";
private static final String KEY_TEL1 = "telephone1";
private static final String KEY_TEL2 = "telephone2";
private static final String KEY_DESCRI = "Description";
private final ArrayList<kovil> temple_list = new ArrayList<kovil>();
public Dbhandler (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TEMPLE_TABLE = "CREATE TABLE " + TABLE_TEMPLE + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + KEY_TMPNAME + " TEXT," + KEY_TMPTYPE + " TEXT," + KEY_LATITUDE + " TEXT," + KEY_LONGITUDE + " TEXT," + KEY_IMGNAME + " TEXT,"
+ KEY_YEARBUILD + " TEXT," + KEY_ADDRESS + " TEXT," + KEY_CITY + " TEXT," + KEY_EMAIL + " TEXT," + KEY_WEB + " TEXT," + KEY_TEL1 + " TEXT," + KEY_TEL2 + " TEXT,"
+ KEY_DESCRI + " TEXT" + ")";
db.execSQL(CREATE_TEMPLE_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_TEMPLE);
// Create tables again
onCreate(db);
}
// Adding new temple
public void Add_Temple(kovil Kovil) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TMPNAME, Kovil.gettemplename());
values.put(KEY_TMPTYPE, Kovil.gettempletype());
values.put(KEY_LATITUDE, Kovil.getlatitude());
values.put(KEY_LONGITUDE, Kovil.getlongitude());
values.put(KEY_IMGNAME, Kovil.getimage_name());
values.put(KEY_YEARBUILD, Kovil.getyear_build());
values.put(KEY_ADDRESS, Kovil.getaddress());
values.put(KEY_CITY, Kovil.getcity());
values.put(KEY_EMAIL, Kovil.getemail());
values.put(KEY_WEB, Kovil.getwebsite());
values.put(KEY_TEL1, Kovil.gettelephone1());
values.put(KEY_TEL2, Kovil.gettelephone2());
values.put(KEY_DESCRI, Kovil.getDescription());
// Inserting Row
db.insert(TABLE_TEMPLE, null, values);
db.close(); // Closing database connection
}
// Getting single contact
kovil Get_Temple(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_TEMPLE, new String[] { KEY_ID,
KEY_TMPNAME, KEY_TMPTYPE, KEY_LATITUDE, KEY_LONGITUDE, KEY_IMGNAME, KEY_YEARBUILD, KEY_ADDRESS, KEY_CITY, KEY_EMAIL, KEY_EMAIL, KEY_WEB, KEY_TEL1, KEY_TEL2, KEY_DESCRI }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
kovil Kovil = new kovil(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), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), cursor.getString(12), cursor.getString(13));
// return contact
cursor.close();
db.close();
return Kovil;
}
// Getting All Contacts
public ArrayList<kovil> Get_Temple(String temple_type, int Limit) {
try {
temple_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TEMPLE +" WHERE temple_type= " + temple_type +" LIMIT " + Limit;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.print("CALLED");
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
kovil Kovil = new kovil();
Kovil.setID(Integer.parseInt(cursor.getString(0)));
Kovil.settemplename(cursor.getString(1));
Kovil.settempletype(cursor.getString(2));
Kovil.setlatitude(cursor.getString(3));
Kovil.setlongitude(cursor.getString(4));
Kovil.setimage_name(cursor.getString(5));
Kovil.setyear_build(cursor.getString(6));
Kovil.setaddress(cursor.getString(7));
Kovil.setcity(cursor.getString(8));
Kovil.setemail(cursor.getString(9));
Kovil.setwebsite(cursor.getString(10));
Kovil.settelephone1(cursor.getString(11));
Kovil.settelephone2(cursor.getString(12));
Kovil.setDescription(cursor.getString(13));
// Adding contact to list
temple_list.add(Kovil);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return temple_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_temples", "" + e);
}
return temple_list;
}
public String collect(String temptype, String limit){
SQLiteDatabase ourDatabase = this.getWritableDatabase();
String result="";
String []column =new String[]{KEY_ID,KEY_TMPNAME,KEY_TMPTYPE,KEY_LATITUDE,KEY_LONGITUDE,KEY_IMGNAME,KEY_YEARBUILD,KEY_ADDRESS,KEY_CITY,KEY_EMAIL,KEY_WEB,KEY_TEL1,KEY_TEL2,KEY_DESCRI};
Cursor c=ourDatabase.query("templ", column, null, null, null, null,null, limit);
c.moveToFirst();
int iKEY_ID = c.getColumnIndex(KEY_ID);
int iKEY_TMPNAME= c.getColumnIndex(KEY_TMPNAME);
int iKEY_TMPTYPE= c.getColumnIndex(KEY_TMPTYPE);
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
if (c.getString(iKEY_TMPTYPE).equals(temptype)){
result = result+c.getString(iKEY_ID)+"\t\t"+c.getString(iKEY_TMPNAME)+"\t\t"+c.getString(iKEY_TMPTYPE)+"\n";
}
}
return result;
}
// Getting contacts Count
public int Get_Total_Temple() {
String countQuery = "SELECT * FROM " + TABLE_TEMPLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
}
My Kovil. Java class
package lk.adspace.jaffnatemples;
public class kovil {
//public variables
public int _id;
public String _temple_name;
public String _temple_type;
public String _latitude;
public String _longitude;
public String _image_name;
public String _year_build;
public String _address;
public String _city;
public String _email;
public String _website;
public String _telephone1;
public String _telephone2;
public String _Description;
public Object temple_name;
//empty constructor
public kovil (){
}
// int id, String temple_name, String temple_type, String latitude, String longitude, String image_name, String year_build, String address, String city, String email, String website, String telephone1, String telephone2, String Description
public kovil(int id, String temple_name, String temple_type, String latitude, String longitude, String image_name, String year_build, String address,
String city, String email, String website, String telephone1, String telephone2, String Description) {
// TODO Auto-generated constructor stub
this._id= id;
this._temple_name=temple_name;
this._temple_type=temple_type;
this._latitude=latitude;
this._longitude=longitude;
this._image_name=image_name;
this._year_build=year_build;
this._address=address;
this._city=city;
this._email=email;
this._website=website;
this._telephone1=telephone1;
this._telephone2=telephone2;
this._Description=Description;
}
public kovil(String temple_name, String temple_type, String latitude, String longitude, String image_name, String year_build, String address,
String city, String email, String website, String telephone1, String telephone2, String Description) {
// TODO Auto-generated constructor stub
this._temple_name=temple_name;
this._temple_type=temple_type;
this._latitude=latitude;
this._longitude=longitude;
this._image_name=image_name;
this._year_build=year_build;
this._address=address;
this._city=city;
this._email=email;
this._website=website;
this._telephone1=telephone1;
this._telephone2=telephone2;
this._Description=Description;
}
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String gettemplename() {
return this._temple_name;
}
public void settemplename(String temple_name) {
this._temple_name=temple_name;
}
public String gettempletype() {
return this._temple_type;
}
public void settempletype(String temple_type) {
this._temple_type=temple_type;
}
public String getlatitude() {
return this._latitude;
}
public void setlatitude(String latitude) {
this._latitude=latitude;
}
public String getlongitude() {
return this._longitude;
}
public void setlongitude(String longitude) {
this._longitude=longitude;
}
public String getimage_name() {
return this._image_name;
}
public void setimage_name(String image_name) {
this._image_name=image_name;
}
public String getyear_build() {
return this._year_build;
}
public void setyear_build(String year_build) {
this._year_build=year_build;
}
public String getaddress() {
return this._address;
}
public void setaddress(String address) {
this._address=address;
}
public String getcity() {
return this._city;
}
public void setcity(String city) {
this._city=city;
}
public String getemail() {
return this._email;
}
public void setemail(String email) {
this._email=email;
}
public String getwebsite() {
return this._website;
}
public void setwebsite(String website) {
this._website=website;
}
public String gettelephone1() {
return this._telephone1;
}
public void settelephone1(String telephone1) {
this._telephone1=telephone1;
}
public String gettelephone2() {
return this._telephone2;
}
public void settelephone2(String telephone2) {
this._telephone2=telephone2;
}
public String getDescription() {
return this._Description;
}
public void setDescription(String Description) {
this._Description=Description;
}
}
View map.java file
package lk.adspace.jaffnatemples;
import java.util.ArrayList;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
public class Viewmap extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;
private static final double SEATTLE_LAT = 9.663216, SEATTLE_LNG =80.01333;
private static final float DEFAULTZOOM = 15;
LocationClient mLocationClient;
ArrayList<Marker> markers = new ArrayList<Marker>();
static final int POLYGON_POINTS = 4;
Polygon shape;
Dbhandler dbhand = new Dbhandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.view_map);
if (initMap()) {
Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
gotoLocation(SEATTLE_LAT, SEATTLE_LNG, DEFAULTZOOM);
MarkerOptions marker = new MarkerOptions().position(new LatLng(SEATTLE_LAT, SEATTLE_LNG)).title("Jaffna Clock Tower");
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
mMap.addMarker(marker);
ArrayList<kovil> object = dbhand.Get_Temple((getIntent().getExtras().getString("temple_type")), Integer.parseInt(getIntent().getExtras().getString("notemples")));
for (int i=0; i< Integer.parseInt(getIntent().getExtras().getString("notemples"));i++) {
kovil object2 = dbhand.Get_Temple(i);
String tempname = object2.gettemplename();
double latitude = Double.parseDouble(object2.getlatitude());
double longitude = Double.parseDouble(object2.getlongitude());
displaymarkers(latitude,longitude, tempname);
}
//
// displaymarkers(9.662502, 80.010239, "mugan kovil");
// displaymarkers(9.662502, 80.010239, "mugan kovil");
// displaymarkers(9.670931, 80.013201, "mugan kovil");
mMap.addPolygon(new PolygonOptions()
.add(new LatLng(9.662502, 80.010239), new LatLng(9.662502, 80.010239), new LatLng(9.670931, 80.013201), new LatLng(9.663216, 80.01333))
//.addHole(new LatLng(1, 1), new LatLng(1, 2), new LatLng(2, 2), new LatLng(2, 1), new LatLng(1, 1))
.fillColor(Color.GRAY));
int radius = Integer.parseInt(getIntent().getExtras().getString("distance"));
drawcircle(radius);
}
else {
Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show();
}
}
else {
setContentView(R.layout.main);
}
}
public void drawcircle(int rad){
int value = rad*1000;
Circle circle = mMap.addCircle(new CircleOptions()
.center(new LatLng(9.663216, 80.01333))
.radius(value)
.strokeColor(Color.RED)
.fillColor(Color.WHITE));
}
public boolean displaymarkers(double lati, double longi, String templename){
MarkerOptions marker = new MarkerOptions().position(new LatLng(lati, longi)).title(templename);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon));
//marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(marker);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Can't connect to Google Play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
private void gotoLocation(double lat, double lng,
float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
}
Error stack
02-12 14:53:34.554: E/AndroidRuntime(979): FATAL EXCEPTION: main
02-12 14:53:34.554: E/AndroidRuntime(979): java.lang.RuntimeException: Unable to start activity ComponentInfo{lk.adspace.jaffnatemples/lk.adspace.jaffnatemples.Viewmap}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.ActivityThread.access$600(ActivityThread.java:162)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.os.Handler.dispatchMessage(Handler.java:107)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.os.Looper.loop(Looper.java:194)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-12 14:53:34.554: E/AndroidRuntime(979): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 14:53:34.554: E/AndroidRuntime(979): at java.lang.reflect.Method.invoke(Method.java:525)
02-12 14:53:34.554: E/AndroidRuntime(979): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-12 14:53:34.554: E/AndroidRuntime(979): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-12 14:53:34.554: E/AndroidRuntime(979): at dalvik.system.NativeStart.main(Native Method)
02-12 14:53:34.554: E/AndroidRuntime(979): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
02-12 14:53:34.554: E/AndroidRuntime(979): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
02-12 14:53:34.554: E/AndroidRuntime(979): at lk.adspace.jaffnatemples.Dbhandler.Get_Temple(Dbhandler.java:114)
02-12 14:53:34.554: E/AndroidRuntime(979): at lk.adspace.jaffnatemples.Viewmap.onCreate(Viewmap.java:71)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.Activity.performCreate(Activity.java:5122)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-12 14:53:34.554: E/AndroidRuntime(979): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-12 14:53:34.554: E/AndroidRuntime(979): ... 11 more
By looking at the log, your problem seems that you try to get the first element in a list(index 0) and your list is empty(the size is 0)
cursor.getString(0) that seems to be the problem. your cursor has no records
Dbhandler dbhand = new Dbhandler(this);
..in ViewMap.java should be inside onCreate()
In DbHandler, Check if your cursor is getting populated at:
kovil Kovil = new kovil(Integer.parseInt(cursor.getString(0)),...
Also, instead of kovil, i think you should be adding/populating the templelist variable