2分ごとにsqliteデータベースで一致レコードを継続的にチェックするサービスを開発しようとしています。次の 2 つのエラーが見つかりました。
ログのエラー:
カーソルウィンドウから行 0 列 -1 を読み取ることができませんでした
私のJavaファイルは以下に記載されています
**myseervice.java**
package com.blundell.tut.ui.phone;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.blundell.tut.R;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
/*---String result;
String oid1,operatorid1;*/
DatabaseHandler db = new DatabaseHandler(this);
public String tableName = db.TABLE_CONTACTS;
public String task_name = db.KEY_TASK;
public String dt = db.KEY_DATETIME;
String tname, dt1;
NotificationManager nm;
static final int uniqueID = 1394885;
ResponseHandler<String> responseHandler;
SQLiteDatabase dbobject;
Cursor c;
Context context, ctx1;
// flag for Internet connection status
// -- Boolean isInternetPresent = false;
// Connection detector class
// ---- ConnectionDetector cd;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
final Calendar c1 = Calendar.getInstance();
int hour = c1.get(Calendar.HOUR_OF_DAY);
int minutes = c1.get(Calendar.MINUTE);
int day = c1.get(Calendar.DAY_OF_MONTH);
int month = c1.get(Calendar.MONTH);
int year1 = c1.get(Calendar.YEAR);
String combine = String.valueOf(day).trim() + ":"
+ String.valueOf(month + 1).trim() + ":"
+ String.valueOf(year1).trim() + String.valueOf(hour) + ":"
+ String.valueOf(minutes);
String combine2 = String.valueOf(day).trim() + ":"
+ String.valueOf(month + 1).trim() + ":"
+ String.valueOf(year1).trim() + String.valueOf(hour) + ":"
+ String.valueOf(minutes - 1);
Log.w("trace", "date " + combine);
Log.w("trace", "date " + combine2);
// dbobject=this.openOrCreateDatabase("engdb.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
MainActivity act = new MainActivity();
dbobject = act.getInstance().openOrCreateDatabase("contactsManager",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
// setDatabase(dbobject);
// String create_table
// ="create table if not exists contact(_id integer primary key autoincrement,"
// +
// " Day text null, Month text null,Year text null, Hour text null, Minutes text )";
// dbobject.execSQL(create_table);
String q = "SELECT task_name FROM contacts WHERE date_time='" + combine
+ "'";
c = dbobject.rawQuery(q, null);
System.out.print("totle record" + c.getCount());
if (c.moveToFirst()) {
for (int i = 0; i <= c.getCount(); i++) {
tname = c.getString(c.getColumnIndex("task_name"));
dt1 = c.getString(c.getColumnIndex("date_time"));
c.moveToNext();
}
c.close();
}
// if (c!=null) {
// do {
// // Contact contact = new Contact();
// /*
// * int id1=Integer.parseInt(c.getString(0)); String tname =
// * c.getString(1); String dt1 = c.getString(2);
// */// Adding contact to list
// // contactList.add(contact);
// tname = c.getString(c.getColumnIndex("task_name"));
// dt1 = c.getString(c.getColumnIndex("date_time"));
//
// } while (c.moveToNext());
// }
/*
* c.moveToNext();
*
* String tname =c.getString(c.getColumnIndex("task_name")); String dt1
* = c.getString(c.getColumnIndex("date_time"));
*/
// Toast.makeText(getApplicationContext(), "Service method is called",
// 1000).show();
Log.w("trace", "alarm has been fired " + c.getCount() + " " + tname
+ " " + dt1);
// c.close();
// ---- creating connection detector class instance
// cd = new ConnectionDetector(getApplicationContext());
// get Internet status
// ---- isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
/*
* if (isInternetPresent) {
*/nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(uniqueID);
/*
* //open sqlite database here... localdatabase =
* context.openOrCreateDatabase("engdb.db",
* SQLiteDatabase.CREATE_IF_NECESSARY, null);
* setDatabase(localdatabase); String create_table =
* "create table if not exists contact((_id integer primary key autoincrement,"
* + " Day text not null, Month text not null,Year text)";
* localdatabase.execSQL(create_table);
*/
/*
* FileInputStream fin1; try { fin1 =openFileInput("op_id.txt");
* InputStreamReader isr1 = new InputStreamReader(fin1); char[]
* inputBuffer1 = new char[100]; String s1=""; int charRead1;
* while((charRead1 = isr1.read(inputBuffer1))>0) { String readString1
* =String.copyValueOf(inputBuffer1,0,charRead1); s1 += readString1;
* inputBuffer1=new char[100]; oid1=(s1); operatorid1=oid1;
* //Toast.makeText(getApplicationContext(), "in service."+operatorid1,
* 1000).show(); } }
*/
/*
* catch (FileNotFoundException e) { e.printStackTrace(); } catch
* (IOException e) { e.printStackTrace(); }
*/
/*
* try { ArrayList<NameValuePair> myForm=new
* ArrayList<NameValuePair>(1); myForm.add(new
* BasicNameValuePair("oid",operatorid1)); MyConnection mycon = new
* MyConnection(); String url= mycon.myurl(); HttpClient client = new
* DefaultHttpClient(); //ticket_check_service.php HttpPost postdata =
* new HttpPost(url+"op_ticket_check_service.php"); responseHandler =
* new BasicResponseHandler(); postdata.setEntity(new
* UrlEncodedFormEntity(myForm)); result = client.execute(postdata,
* responseHandler); } catch (ClientProtocolException e) {
* e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
*/
/*
* if(result.equals("0")==true) {
* //Toast.makeText(getApplicationContext(), "Sorry try again"+result,
* 1500).show(); } else { // Toast.makeText(getApplicationContext(),
* " Welcome Client "+result, 1500).show(); String str1 =
* result.substring(result.indexOf("T"),result.indexOf("T")+7); Intent
* myintent= new Intent(this,Ticket_List.class);
* myintent.putExtra("notift", "ticketnotif");
* myintent.putExtra("ticketid", str1); PendingIntent
* pi=PendingIntent.getActivity(getApplicationContext( ),0, myintent,
* 0); String body="Client Response for above Ticket id."; String title
* =result; Notification n= new
* Notification(R.drawable.notif_logo,body,System.currentTimeMillis());
* n.setLatestEventInfo(this,title, body,pi); n.defaults =
* Notification.DEFAULT_ALL; nm.notify(uniqueID,n);
*
* }
*/
/*
*
* Intent myintent= new Intent(this,SecondActivity.class); PendingIntent
* pi=PendingIntent.getActivity(getApplicationContext( ),0, myintent,
* 0); String body="Client Response for above Ticket id."; String title
* ="result"; Notification n= new
* Notification(R.drawable.nfm,body,System.currentTimeMillis());
* n.setLatestEventInfo(this,title, body,pi); n.defaults =
* Notification.DEFAULT_ALL; nm.notify(uniqueID,n);
*
* super.onStart(intent, startId);
*/
}
public void setDatabase(SQLiteDatabase db) {
this.dbobject = db;
}
}// end of IF condition
// end of start method
****database handler.java****
package com.blundell.tut.ui.phone;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "contactsManager";
// Contacts table name
public static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_TASK = "task_name";
public static final String KEY_DATETIME = "date_time";
Context ctx;
public List<Contact> contactList = new ArrayList<Contact>();
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx = context;
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TASK + " TEXT,"
+ KEY_DATETIME + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_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_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, contact.getName()); // Contact Name
values.put(KEY_DATETIME, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_TASK, KEY_DATETIME }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
try {
List<Contact> contactList = new ArrayList<Contact>();
contactList.clear();
System.out.print("clear array list :");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
// return contact list
return contactList;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
List<Contact> contactList = new ArrayList<Contact>();
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, contact.getName());
values.put(KEY_DATETIME, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting numbers of contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}