I have a broadcastreceiver to detect incoming sms and I'm storing the sms's in sqlite database. Then I'm trying to view the database content using query. The code was working perfectly when I wasn't using "id INTEGER PRIMARY KEY AUTOINCREMENT". After adding "id", when I try to view database content, its showing "No records found". So either its not entering values properly or there is error in view query code. I searched in other posts but not able find the error. Any help in this would be really helpful.
Broadcastreceiver:
public class MyBroadcast extends BroadcastReceiver{
Context mContext;
String msg_body;
String mob_no, name;
String dttm, key;
SQLiteDatabase db;
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
db=context.openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
}
StringBuffer content = new StringBuffer();
if (messages.length > 0) {
for (int i = 0; i < messages.length; i++) {
content.append(messages[i].getMessageBody());
mob_no = messages[i].getOriginatingAddress();
Calendar calendar = Calendar.getInstance();
Date finaldate = calendar.getTime();
dttm = finaldate.toString();
}
}
msg_body = content.toString();
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(mob_no));
Cursor c = context.getContentResolver().query(lookupUri, new String[]{ContactsContract.Data.DISPLAY_NAME},null,null,null);
try {
if(c.moveToFirst()){
name = c.getString(0);
db.execSQL("INSERT INTO student (sender, timestamp, mesg) VALUES('"+name+"','"+dttm+"','"+msg_body+"');");
}else{
db.execSQL("INSERT INTO student (sender,timestamp,mesg) VALUES('"+mob_no+"','"+dttm+"','"+msg_body+"');");
}
} catch (Exception e) {
// TODO: handle exception
}finally{
c.close();
}
}
}
}
MainActivity:
public class MainActivity extends Activity {
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db=openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS student(id INTEGER PRIMARY KEY AUTOINCREMENT, sender TEXT, timestamp TEXT, mesg TEXT);");
} //oncreate
public void ViewAll(View v){
try{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Sender: "+c.getString(1)+"\n");
buffer.append("TimeStamp: "+c.getString(2)+"\n");
buffer.append("Mesg: "+c.getString(3)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void Delete(View v){
Cursor c=db.rawQuery("SELECT * FROM student WHERE id=(SELECT MIN(id) FROM student)", null);
if(c.moveToFirst())
{
db.execSQL("DELETE FROM student WHERE id=(SELECT MIN(id) FROM student)");
showMessage("Success", "Record Deleted");
}
else
{
showMessage("Error", "Invalid Entry");
}
}
private void showMessage(String title, String message) {
// TODO Auto-generated method stub
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
} //activty
Related
I am fetching some json data into an EventApp and I am trying to store in SQLite database some of the events. I am showing the events in another activity, not the main one and whenever I go back from that activity to the main one and the I go back to the activity with the listview, the data gets duplicated every time. SO if I click to go to that activity 10 time, my data gets 10 times in the listview and in the database as well. How can I fix this?
SQLiteDatabase db = getWritableDatabase();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add new row to the database
public void addEvent(Event ev){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
contentValues.put(DatabaseHelper.URL, ev.getUrl());
contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
db.insert(TABLE_NAME, null, contentValues);
//db.close();
}
//Delete event from database
public void deleteEvent(String eventTitle){
db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}
public int deleteEvents() {
return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}
//Print the database as string
public String databaseToString(){
String dbString="";
//points to a location in results
Cursor c = getEvents();
while (c.moveToNext()){
if(c.getString(c.getColumnIndex("Title")) != null){
dbString += c.getString(c.getColumnIndex("Title"));
dbString += "\n";
}
}
//db.close();
return dbString;
}
public Cursor getEvents(){
return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}
}
This is the activity where I show the data from the database
public class StoredEventsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stored_events);
ListView listView = (ListView) findViewById(R.id.lv_stored_events);
Intent intent = getIntent();
ArrayList<Event> events = new ArrayList<Event>();
events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");
EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
listView.setAdapter(adapter);
}
}
Here is the method that returns the stored events
public static ArrayList<Event> returnStoredEvents(){
long id = -1;
//getStoredEvents();
Cursor c = eventsDB.getEvents();
while (c.moveToNext()){
id = c.getInt(c.getColumnIndex(eventsDB.ID));
String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
organizeEvents.add(new Event(title, start, end, true));
}
c.close();
Log.d("DATABASE", organizeEvents.toString());
return organizeEvents;
}
Here is where I actually add some of the events:
private void readEvents(String str){
Event ev = null;
try {
JSONObject geoJSON = new JSONObject(str);
JSONArray jsonEvents = geoJSON.getJSONArray("events");
for (int i = 0; i < jsonEvents.length(); i++) {
JSONObject event = jsonEvents.getJSONObject(i);
JSONArray timeJsonEvent = event.getJSONArray("datelist");
JSONObject time = timeJsonEvent.getJSONObject(0);
title = event.getString("title_english");
Date date = new Date(time.getLong("start"));
startDate = dateFormat.format(date);
date = new Date(time.getLong("end"));
endDate = dateFormat.format(date);
imageURL = event.getString("picture_name");
url = event.getString("url");
subtitle = event.getString("subtitle_english");
description = event.getString("description_english");
if (title.charAt(0) == 'T') {
ev = new Event(title, startDate, endDate, true);
eventsDB.addEvent(ev);
}else {
ev = new Event(title, startDate, endDate, false);
}
// Process a newly found event
final Event finalEv = ev;
handler.post(new Runnable() {
public void run() {
addNewEvent(finalEv);
}
});
}
}catch (Exception e) {
Log.d(null, e.getMessage());
}
}
And here is my main:
public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventsDB = new DatabaseHelper(this);
//storedEvents.addAll(EventsListFragment.returnStoredEvents());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Sort by name")){
Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
EventsListFragment.sort(-1);
}else if (item.getTitle().equals("Sort by date")) {
EventsListFragment.sort(1);
}else if (item.getTitle().equals("Stored events")){
showSavedEvents();
Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
}
return true;
}
public void showSavedEvents(){
intent = new Intent(this, StoredEventsActivity.class);
intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
startActivity(intent);
}
}
I'm developing an app in which the app has to show the receiving messages starts with #. Now i have to show notification for them and i also want to update the notifications in a ListView inside an Activity. Currently i get the messages from inbox using ContentResolver. Because of that once processed messages still shows up in activity. I don't want to show that. I want notifications i receive for the messages starts with # listed in ListView inside an activity.
My Code is
My Activity
public class ActivationActivity extends ActionBarActivity implements OnItemClickListener {
private static ActivationActivity inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
Context context;
public static ActivationActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activation);
smsListView=(ListView)findViewById(R.id.listView);
arrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,smsMessagesList);
smsListView.setAdapter(arrayAdapter);
refreshSmsInbox();
smsListView.setOnItemClickListener(this);
}
public void refreshSmsInbox(){
ContentResolver contentResolver=getContentResolver();
final Cursor smsInboxCursor=contentResolver.query(Uri.parse("content://sms/inbox"),null,null,null,null);
int indexBody=smsInboxCursor.getColumnIndex("body");
int indexAddress=smsInboxCursor.getColumnIndex("address");
if (indexBody<0||!smsInboxCursor.moveToFirst()) return;
arrayAdapter.clear();
do {
if (smsInboxCursor.getString(smsInboxCursor.getColumnIndex("body")).startsWith("#")) {
String str = smsInboxCursor.getString(indexAddress)+ smsInboxCursor.getString(indexBody)+"\n";
arrayAdapter.add(str);
}else {
}
} while (smsInboxCursor.moveToNext());
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
String[] smsMessages=smsMessagesList.get(position).split("#");
String address=smsMessages[0];
String dCode=smsMessages[1];
String user=smsMessages[2];
String addrs1=smsMessages[3];
String pin=smsMessages[4];
String addrs=addrs1+","+pin;
String sNo=smsMessages[5];
databaseHelper=new DatabaseHelper(this);
SQLiteDatabase db=databaseHelper.getReadableDatabase();
SmsManager smsManager=SmsManager.getDefault();
Cursor cursor= db.rawQuery("select uSerialNo,dealerCode from unittable", null);
cursor.moveToFirst();
String srNo=cursor.getString(0);
String drCode=cursor.getString(1);
if (srNo.equals(sNo) || drCode.equals(dCode)){
ContentValues cv=new ContentValues();
cv.put("userName",user);
cv.put("mobileNo", address);
cv.put("address", addrs);
db.update("unittable", cv, "uSerialNo='" + srNo + "'", null);
db.update("unittable", cv, "uSerialNo='" + srNo + "'", null);
db.update("unittable", cv, "uSerialNo+'" + srNo + "'", null);
Toast.makeText(ActivationActivity.this,"Updation Success",Toast.LENGTH_LONG).show();
smsManager.sendTextMessage(address,null,"YES. ACTIVATE. Default Password is 1234",null,null);
} else {
Toast.makeText(ActivationActivity.this,"Failed",Toast.LENGTH_LONG).show();
smsManager.sendTextMessage(address,null,"NO. Details or Incorrect. Check the details or Call the Customer Care",null,null);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
My BroadcastReceiver is
public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String smsBundle="pdus";
public void onReceive(Context context, Intent intent){
Bundle intentExtras=intent.getExtras();
if (intentExtras!=null){
Object[] sms=(Object[])intentExtras.get(smsBundle);
String SmsManager="";
for (int i = 0; i < sms.length; i++) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String smsAddress = smsMessage.getOriginatingAddress();
SmsManager += "SMS From: " + smsAddress + "\n";
SmsManager += smsBody + "\n";
}
Toast.makeText(context, SmsManager, Toast.LENGTH_LONG).show();NotificationCompat.Builder(this);
ActivationActivity inst = ActivationActivity.instance();
inst.updateList(SmsManager);
}
}
}
In my Android app,i am retreiving phone contacts through cursor. Then i want to add all these contacts in database as follows:
public class SettingsActivity extends Activity {
ToggleButton tb_hide;
ToggleButton tb_unhide;
TextView tv_add_contacts;
TextView tv_restore_contacts;
DbManager manager;
Context context;
String[] privateContacts;
Uri queryUri;
String selectIds = "";
String ContactId[];
String ContactNames[];
String ContactNumbers[];
public static String[] wholContactData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
try{
context = this;
findView();
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
privateContacts=showEvents(Cursor);
wholContactData=new String[privateContacts.length];
tv_add_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addcontacts();
}
});
tv_restore_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
for(int i=0;i<privateContacts.length;i++){
selectIds = selectIds + " | " + privateContacts[i];
wholContactData[i]=privateContacts[i];
}
try{
addAllContacts(wholContactData);
}
catch(Exception ex)
{
Log.e("ERROR in adding all contacts", ex.toString());
}
Toast.makeText(getApplicationContext(),""+selectIds, 3000).show();
}});
}
catch(Exception ex){
Log.e("Add all contacts ERROR", ex.toString());
}
}
private void addAllContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
protected String[] showEvents(Cursor cursor) {
ContactId= new String[cursor.getCount()];
ContactNames = new String[cursor.getCount()];
ContactNumbers = new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
ContactId[i] = i+"";
ContactNames[i] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
ContactNumbers[i] = Util.getContactNumber(ContactNames[i], context);
i++;
}
return ContactNames;
}
private void findView() {
TextView tv_hide = (TextView)findViewById(R.id.tv_hide);
TextView tv_hide_desc = (TextView)findViewById(R.id.tv_hide_desc);
tv_add_contacts = (TextView)findViewById(R.id.tv_add_contacts);
TextView tv_add_contacts_desc = (TextView)findViewById(R.id.tv_add_contacts_desc);
tv_restore_contacts = (TextView)findViewById(R.id.Tv_restore_contacts);
TextView tv_restore_contacts_desc = (TextView)findViewById(R.id.tv_restore_contacts_desc);
tb_hide = (ToggleButton)findViewById(R.id.tb_hide);
tb_hide.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
HideUnhideIcon();
}});
}
private void HideUnhideIcon() {
if(tb_hide.isChecked()){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "Your app is hidden now, Dial provided security code to get into discrete app.", 3000).show();
}
else if(tb_hide.isChecked()==false){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
,
PackageManager.DONT_KILL_APP );
}
}
private void addcontacts() {
final ProgressDialog myPd_ring=ProgressDialog.show(this, "Phone Contacts", "Loading please wait..", true);
myPd_ring.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try
{
movetoPrivateContacts();
}catch(Exception e){}
myPd_ring.dismiss();
}
}).start();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void movetoPrivateContacts() {
Intent intent = new Intent(this,privateContacts.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
}
Database code is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
i want to add all contacts to database when i click "tv_restore_contacts" .But i am getting NullPointerException. I don't know where i am wrong?
logcat Error stack is java.lang.NullPointerException.
Use the following code to grab the contacts & return them to a list datatype to save them whole list in a db or open a DB connection inside the method and do sql insert statements on each contact object you wish to store. N/B The Contacts API is deprecated be sure to use ContactsContract Api.
Private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
i have developed an app for 'bank simulation' which uses sqlite to create databases...
when i run the app on my mobile it stops unexpectedly....do i need to install any server to run sqlite based apps on mobile?
Thanks in advance!
DbHelper.java
private static final String DATABASE_NAME = "saket.db";
private static final int DATABASE_VERSION = 1;
public static final String SUBH_TABLE_NAME = "login";
public static final String SUBH_TABLE_DATA = "TBL_Transaction";
public static final String KEY_ROWID = "_id";
private static final String SUBH_TABLE_CREATE =
"CREATE TABLE " + SUBH_TABLE_NAME + "(" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
"username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, balance INTEGER);";
private static final String SUBH_TABLE_DATA_CREATE =
"CREATE TABLE " + SUBH_TABLE_DATA + "(" +
"trans_id INTEGER PRIMARY KEY AUTOINCREMENT, "+
"user_id INTEGER, " +
"trans TEXT NOT NULL);";
private static final String SAKET_DB_ADMIN = "INSERT INTO "+ SUBH_TABLE_NAME +" values(1, admin, password, admin#gmail.com);";
//private static final String SAKET_DB_ADMIN_Trans = "INSERT INTO "+ SUBH_TABLE_DATA +" values(1, asdf);";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}
/* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
try{
//Create Database
db.execSQL(SUBH_TABLE_CREATE);
//create transaction account
db.execSQL(SUBH_TABLE_DATA_CREATE);
//create admin account
db.execSQL(SAKET_DB_ADMIN);
//db.execSQL(SAKET_DB_ADMIN_Trans);
System.out.println("In onCreate");
}catch(Exception e){
e.printStackTrace();
}
}
DatabaseActivity.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mNewUser = (Button) findViewById(R.id.buttonNewUser);
mNewUser.setOnClickListener(this);
mLogin = (Button) findViewById(R.id.buttonLogin);
mLogin.setOnClickListener(this);
mShowAll = (Button) findViewById(R.id.buttonShowAll);
mShowAll.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonLogin:
mUsername = (EditText) findViewById(R.id.editUsername);
mPassword = (EditText) findViewById(R.id.editPassword);
String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
if (uname.equals("") || uname == null) {
Toast.makeText(getApplicationContext(), "Username Empty",
Toast.LENGTH_SHORT).show();
} else if (pass.equals("") || pass == null) {
Toast.makeText(getApplicationContext(), "Password Empty",
Toast.LENGTH_SHORT).show();
} else {
boolean validLogin = false;
try {
validLogin = validateLogin(uname, pass,
DatabaseActivity.this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (validLogin) {
System.out.println("In Valid");
Intent i_login = new Intent(DatabaseActivity.this,
UserLoggedInPage.class);
try {
id = getID(uname, pass, DatabaseActivity.this);
Ubal = getBAL(uname, pass, DatabaseActivity.this);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "putting the extra " + id);
i_login.putExtra("key", id);
i_login.putExtra("bkey", Ubal);
startActivity(i_login);
finish();
}
}
break;
case R.id.buttonNewUser:
Intent i = new Intent(DatabaseActivity.this, NewUserActivity.class);
startActivity(i);
finish();
break;
case R.id.buttonShowAll:
Intent i_admin = new Intent(DatabaseActivity.this, AdminPage.class);
startActivity(i_admin);
finish();
break;
}
}
public boolean validateLogin(String uname, String pass, Context context)
throws Exception {
myDb = new DbHelper(context);
SQLiteDatabase db = myDb.getReadableDatabase();
// SELECT
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = null;
try {
// SELECT _id FROM login WHERE username = uname AND password=pass
cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns, selection,
selectionArgs, null, null, null);
startManagingCursor(cursor);
} catch (Exception e) {
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if (numberOfRows <= 0) {
Toast.makeText(getApplicationContext(),
"Login Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
// get rowid
// public int getID(String uname, String pass, Context context)
// throws Exception {
//
// myDb = new DbHelper(context);
// SQLiteDatabase db = myDb.getReadableDatabase();
// cursor = db.rawQuery("select * from " + DbHelper.SUBH_TABLE_NAME +
// " where username = " + uname + "&" + "password = " + pass + ";)", null);
// if (cursor != null) {
// if(cursor.moveToFirst()){
// int id = cursor.getInt(cursor.getColumnIndex(DbHelper.KEY_ROWID));
// }
//
// }
//
// return id;
//
// }
public String getID(String uname, String pass, Context context) {
try {
String idddd = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "_id" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
idddd = cursor.getString(0);
}
return idddd;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String getBAL(String uname, String pass,
DatabaseActivity databaseActivity) {
try {
String ballll = null;
SQLiteDatabase db = myDb.getReadableDatabase();
String[] columns = { "balance" };
// WHERE clause
String selection = "username=? AND password=?";
// WHERE clause arguments
String[] selectionArgs = { uname, pass };
Cursor cursor = db.query(DbHelper.SUBH_TABLE_NAME, columns,
selection, selectionArgs, null, null, null);
if (cursor != null) {
startManagingCursor(cursor);
while (cursor.moveToNext()) {
ballll = cursor.getString(0);
}
return ballll;
}
System.out.println("Cursor NuLL");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onDestroy() {
super.onDestroy();
if (myDb != null && cursor != null ) {
cursor.close();
myDb.close();
}
}
}
I am following a tutorial, and trying to create a database, then add put texts into the database, but the application crashes when it reaches ".open()"
public class SmsReceiver extends BroadcastReceiver
{
CommentsDataSource datasource;
#Override
public void onReceive( Context context, Intent intent )
{
Log.d("tag", "0");
datasource = new CommentsDataSource(this);
Log.d("tag", "1");
datasource.open();
Log.d("tag", "2");
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
//String str = "";
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String str = msgs[i].getOriginatingAddress();
//str += " :";
String str2 =msgs[i].getMessageBody().toString();
//str += "\n";
Log.d("tag", "3");
abortBroadcast();
Log.d("tag", "4");
String From = "Send: " + str + " Message: " + str2;
Log.d("tag", "5");
TestDatabaseActivity Test = new TestDatabaseActivity();
ArrayAdapter<Comment> adapter = (ArrayAdapter<Comment>) Test.getListAdapter();
Comment comment;
Log.d("tag", "6");
String[] comments = new String[] { From };
Log.d("tag", "7");
int nextInt = new Random().nextInt(3);
Log.d("tag", "8");
// Save the new comment to the database
comment = datasource.createComment(comments[nextInt]);
Log.d("tag", "9");
adapter.add(comment);
Log.d("tag", "10");
datasource.close();
break;
}
}
}
}
and here is the database:
public class CommentsDataSource {
// Database fields
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_COMMENT };
public CommentsDataSource(Context context) {
dbHelper = new MySQLiteHelper(context);
}
public CommentsDataSource(SmsReceiver smsReceiver) {
// TODO Auto-generated constructor stub
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Comment createComment(String comment) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
long insertId = database.insert(MySQLiteHelper.TABLE_COMMENTS, null,
values);
// To show how to query
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
return cursorToComment(cursor);
}
public void deleteComment(Comment comment) {
long id = comment.getId();
System.out.println("Comment deleted with id: " + id);
database.delete(MySQLiteHelper.TABLE_COMMENTS, MySQLiteHelper.COLUMN_ID
+ " = " + id, null);
}
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<Comment>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Comment comment = cursorToComment(cursor);
comments.add(comment);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
private Comment cursorToComment(Cursor cursor) {
Comment comment = new Comment();
comment.setId(cursor.getLong(0));
comment.setComment(cursor.getString(1));
return comment;
}
}
logcat gets to tag 0 then 1, then it says "Unable to start receiver"
What's going on, and why won't it open?
replace this with context in constructor:
datasource = new CommentsDataSource(this);
to
datasource = new CommentsDataSource(context);