I am not able to match or compare two dates one from Database and second is current date.I have five checkboxes. When 1st user checkes a checkbox and insert its value by clicking the save button. 2nd time when he check 2 or more checkboxes Now here I want to update last record by date. I set date as primary key in that table.
NamazCounterActivity
package com.example.shakeelmughal.assanislam;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class NamazCounterActivity extends AppCompatActivity {
DatabaseHelper mydb;
CheckBox cb1,cb2,cb3,cb4,cb5;
Button B1,B2,B3;
TextView tv;
int vcb1=0,vcb2=0,vcb3=0,vcb4=0,vcb5=0;
Date date = new Date();
String a="1";
public static final String SHARED_PREF = "sharedPrefs";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";
public static final String CHECK3 = "check3";
public static final String CHECK4 = "check4";
public static final String CHECK5 = "check5";
private Boolean chb1,chb2,chb3,chb4,chb5;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namaz_counter);
try {
mydb = new DatabaseHelper(this);
} catch (IOException e) {
e.printStackTrace();
}
tv = findViewById(R.id.textView24);
cb1 = findViewById(R.id.namaz1);
cb2 = findViewById(R.id.namaz2);
cb3 = findViewById(R.id.namaz3);
cb4 = findViewById(R.id.namaz4);
cb5 = findViewById(R.id.namaz5);
B1 = findViewById(R.id.result);
B2 = findViewById(R.id.dateee);
B3 = findViewById(R.id.sumr);
c_date();
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData1();
if (c.moveToFirst())
{
if(mydb.date().equals(c.getString(0)))
{
Updateingdata();
}
else
{
InsertingData();
}
}
else
{
InsertingData();
}
SaveData();
}
});
B3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = mydb.getAllData();
if(c.getCount() == 0)
{
Toast.makeText(NamazCounterActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
StringBuffer stringBuffer = new StringBuffer();
while (c.moveToNext())
{
stringBuffer.append("ID: " +c.getString(0 )+"\n");
stringBuffer.append("Fajar: " +c.getString(1)+"\n");
stringBuffer.append("Zohr: " +c.getString(2)+"\n");
stringBuffer.append("Asr: " +c.getString(3)+"\n");
stringBuffer.append("Magrib: " +c.getString(4)+"\n" );
stringBuffer.append("Isha: " +c.getString(5)+"\n");
}
showData("Data",stringBuffer.toString());
}
});
//home button
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
//functions for save old values
loadData();
updateViews();
}
//function for going back to previous activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
public void InsertingData()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean result = mydb.InsertData(date().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(result == true)
{
Toast.makeText(NamazCounterActivity.this, "Prayer Saved",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(NamazCounterActivity.this, "Some Error", Toast.LENGTH_LONG).show();
}
}
public void Updateingdata()
{
if(cb1.isChecked())
{
vcb1 = 1;
}
else
{
vcb1 = 0;
}
if(cb2.isChecked())
{
vcb2 = 1;
}
else
{
vcb2 = 0;
}
if(cb3.isChecked())
{
vcb3 = 1;
}
else
{
vcb3 = 0;
}
if(cb4.isChecked())
{
vcb4 = 1;
}
else
{
vcb4 = 0;
}
if(cb5.isChecked())
{
vcb5 = 1;
}
else
{
vcb5 = 0;
}
boolean res = mydb.UpdateData(B2.getText().toString(),Integer.toString(vcb1),Integer.toString(vcb2),Integer.toString(vcb3),Integer.toString(vcb4),Integer.toString(vcb5));
if(res == true)
{
Toast.makeText(NamazCounterActivity.this,"Data Updated",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(NamazCounterActivity.this,"Data Not Updated",Toast.LENGTH_SHORT).show();
}
}
//for date ()
public void c_date() {
date.setTime(System.currentTimeMillis()); //set to current time
B2.setText(date.toString());
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEEEEEEE, MMM dd, yyyy");
B2.setText(dateFormat.format(date));
}
public void SaveData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(CHECK1, cb1.isChecked());
editor.putBoolean(CHECK2, cb2.isChecked());
editor.putBoolean(CHECK3, cb3.isChecked());
editor.putBoolean(CHECK4, cb4.isChecked());
editor.putBoolean(CHECK5, cb5.isChecked());
editor.apply();
}
public void loadData()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF,MODE_PRIVATE);
chb1 = sharedPreferences.getBoolean(CHECK1, false);
chb2 = sharedPreferences.getBoolean(CHECK2, false);
chb3 = sharedPreferences.getBoolean(CHECK3, false);
chb4 = sharedPreferences.getBoolean(CHECK4, false);
chb5 = sharedPreferences.getBoolean(CHECK5, false);
}
public void updateViews()
{
cb1.setChecked(chb1);
cb2.setChecked(chb2);
cb3.setChecked(chb3);
cb4.setChecked(chb4);
cb5.setChecked(chb5);
}
public void showData(String title, String message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public java.sql.Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
}
DatabaseHelper.java
package com.example.shakeelmughal.assanislam;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Date;
import static android.content.ContentValues.TAG;
import static java.time.LocalTime.now;
/**
* Created by Shakeel Mughal on 5/30/2018.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public Context context;
private SQLiteDatabase db2;
public AssetManager mngr;
SQLiteDatabase db;
private Resources mResources;
private InputStream inputstream = null;
private final static String Dbname = "NamazCounter.db";
private final static String Tbname = "DailyWork";
private final static String Tbname2 = "items";
private final static String Col_1 = "ID";
private final static String Col_2 = "Fajar";
private final static String Col_3 = "Zohr";
private final static String Col_4 = "Asr";
private final static String Col_5 = "Magrib";
private final static String Col_6 = "Isha";
private final static String NCol_1 = "date_for";
private final static String NCol_2 = "fajr";
private final static String NCol_3 = "shurooq";
private final static String NCol_4 = "dhuhr";
private final static String NCol_5 = "asr";
private final static String NCol_6 = "maghrib";
private final static String NCol_7 = "isha";
public DatabaseHelper(Context context) throws IOException {
super(context, Dbname, null, 1);
this.context = context;
mResources = context.getResources();
mngr = context.getAssets();
db = this.getWritableDatabase();
db = this.getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
//namaz counter
final String Table1 = "CREATE TABLE "+Tbname+"(ID PRIMARY KEY TEXT, Fajar TEXT, Zohr TEXT, Asr TEXT, Magrib TEXT, Isha TEXT)";
//for namaz timing
final String Table2 = "CREATE TABLE "+Tbname2+"(date_for TEXT, fajr TEXT, shurooq TEXT, dhuhr TEXT, asr TEXT, maghrib TEXT,isha TEXT)";
db.execSQL(Table1);
db.execSQL(Table2);
Log.d(TAG, "DataBase Created");
try {
readDataToDb(db);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ Tbname);
db.execSQL("DROP TABLE IF EXISTS "+ Tbname2);
onCreate(db);
}
public void openDatabase() {
String dbPath = context.getDatabasePath(Dbname).getPath();
if (db != null) {
db.isOpen();
return;
}
db = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase() {
if (db != null) {
db.close();
}
}
//Json fun
private String readJsonDataFromFile() throws IOException {
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputstream = mngr.open("NamazTiming.json");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputstream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputstream != null) {
inputstream.close();
}
}
return new String(builder);
}
public void readDataToDb(SQLiteDatabase db) throws IOException, JSONException {
final String date = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
String jsonDataString = readJsonDataFromFile();
JSONArray jsonfileJSONArray = new JSONArray(jsonDataString);
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String dateid;
String nmz1;
String nmz2;
String nmz3;
String nmz4;
String nmz5;
String nmz6;
JSONObject jsonfileObject = jsonfileJSONArray.getJSONObject(i);
dateid = jsonfileObject.getString(date);
nmz1 = jsonfileObject.getString(namaz1);
nmz2 = jsonfileObject.getString(namaz2);
nmz3 = jsonfileObject.getString(namaz3);
nmz4 = jsonfileObject.getString(namaz4);
nmz5 = jsonfileObject.getString(namaz5);
nmz6 = jsonfileObject.getString(namaz6);
ContentValues jsonfilevalues = new ContentValues();
jsonfilevalues.put(NCol_1, dateid);
jsonfilevalues.put(NCol_2, nmz1);
jsonfilevalues.put(NCol_3, nmz2);
jsonfilevalues.put(NCol_4, nmz3);
jsonfilevalues.put(NCol_5, nmz4);
jsonfilevalues.put(NCol_6, nmz5);
jsonfilevalues.put(NCol_7, nmz6);
long rowID= db.insert(Tbname2, null, jsonfilevalues);
if(rowID>-1){
int catid=0;
Cursor cursor = db.rawQuery("SELECT "+ NCol_1 + " FROM "+ Tbname2+" where "+ NCol_1 + "='" + now() + "'" , null);
cursor.moveToFirst();
if (cursor.moveToNext()) {
catid = (cursor.getInt(0));
}
cursor.close();
JSONArray jsonitemsarray= (JSONArray) jsonfileObject.get("itemsList");
readitem(db,jsonitemsarray);
}
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void readitem(SQLiteDatabase db,JSONArray jsonfileJSONArray) throws IOException, JSONException {
final String date1 = "date_for";
final String namaz1 = "fajr";
final String namaz2 = "shurooq";
final String namaz3 = "dhuhr";
final String namaz4 = "asr";
final String namaz5 = "maghrib";
final String namaz6 = "isha";
try {
for (int i = 0; i < jsonfileJSONArray.length(); i++) {
String Did;
String nmzz1 ;
String nmzz2 ;
String nmzz3 ;
String nmzz4 ;
String nmzz5 ;
String nmzz6 ;
JSONObject jsonfileObject1 = jsonfileJSONArray.getJSONObject(i);
Did = jsonfileObject1.getString(date1);
nmzz1 = jsonfileObject1.getString(namaz1);
nmzz2 = jsonfileObject1.getString(namaz2);
nmzz3 = jsonfileObject1.getString(namaz3);
nmzz4 = jsonfileObject1.getString(namaz4);
nmzz5 = jsonfileObject1.getString(namaz5);
nmzz6 = jsonfileObject1.getString(namaz6);
ContentValues jsonfilevalues1 = new ContentValues();
jsonfilevalues1.put(NCol_1, Did);
jsonfilevalues1.put(NCol_2, nmzz1);
jsonfilevalues1.put(NCol_3, nmzz2);
jsonfilevalues1.put(NCol_4, nmzz3);
jsonfilevalues1.put(NCol_5, nmzz4);
jsonfilevalues1.put(NCol_6, nmzz5);
jsonfilevalues1.put(NCol_7, nmzz6);
db.insert(Tbname2, null, jsonfilevalues1);
Log.d(TAG, "Inserted sucessfully" + jsonfilevalues1);
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
//inserting for counter
public boolean InsertData(String d_date, String Fjr, String zhr, String assr, String mgrb, String isa)
{
SQLiteDatabase db = this.getReadableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,d_date);
contentValues.put(Col_2,Fjr);
contentValues.put(Col_3,zhr);
contentValues.put(Col_4,assr);
contentValues.put(Col_5,mgrb);
contentValues.put(Col_6,isa);
long success = db.insert(Tbname,null,contentValues);
if(success == -1)
{
return false;
}
else
{
return true;
}
}
public boolean UpdateData(String id,String n1, String n2, String n3,String n4,String n5)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_1,id);
contentValues.put(Col_2,n1);
contentValues.put(Col_3,n2);
contentValues.put(Col_4,n3);
contentValues.put(Col_3,n4);
contentValues.put(Col_4,n5);
db.update(Tbname,contentValues,"ID = ?", new String[]{id});
return true;
}
public Cursor getAllDataForNamaz()
{
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname2 + " WHERE date_for = "+ date(),null);
closeDatabase();
return cs;
}
public Date date()
{
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
return date;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT * FROM "+ Tbname,null);
return cs;
}
public Cursor getAllData1()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cs = db.rawQuery("SELECT ID FROM "+ Tbname,null);
return cs;
}
}
I advise you to convert all your date into timestamp and use only timestamp for comparaison (you can also save date as timestamp in your database) :
System.currentTimeMillis() // Current timestamp
date.time // timestamp of the SQL Date object
if (timestamp1 > timestamp2) {
// timestamp1 after timestamp2
} else if (timestamp1 < timestamp2) {
// timestamp1 before timestamp2
} else {
// timestamp1 == timestamp2
}
Try this code first convert data into this format..."dd/mm/yyyy"
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
// define log
}
Related
I developed an android app for auto replying to Whatsapp. My app is perfect working for replying with text. But I am unable to send images in auto reply in background.
This activity is for managing notifications.
NotificationService.java
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.ContactsContract;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.text.SpannableString;
import android.util.Log;
import android.widget.TextView;
import androidx.core.app.NotificationCompat;
import com.templatemela.whatsbot.model.Action;
import com.templatemela.whatsbot.model.AutoReply;
import com.templatemela.whatsbot.model.StatisticsReplyMsgListModel;
import com.templatemela.whatsbot.utilities.Const;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class NotificationService extends NotificationListenerService {
public static final String TAG = "Auto Reply";
private String autoReplyText;
private List<String> cntList;
private String contactType;
private long count = 0;
private List<String> getUserList;
private String headerText;
private String noMatch = "";
private SharedPreference preference;
private int replyTime;
private String sendMessage;
private TextView text;
private Uri string;
private Bitmap bitmap;
#Override
public void onListenerConnected() {
super.onListenerConnected();
Log.e(TAG, "Notification Listener Connected");
}
#Override
public void onCreate() {
super.onCreate();
preference = new SharedPreference(this);
count = preference.getFromPref_Long("Counter");
getUserList = new ArrayList();
cntList = new ArrayList();
Const.staticsReplyList = new ArrayList();
Const.contactList = new ArrayList();
}
#Override
public int onStartCommand(Intent intent, int i, int i2) {
Log.e("Service Class", "Service is started-----");
return Service.START_STICKY;
}
#Override
public void onNotificationRemoved(StatusBarNotification statusBarNotification) {
super.onNotificationRemoved(statusBarNotification);
Log.e("AUTO REPLY", "Notificationremoved");
}
#Override
public void onNotificationPosted(StatusBarNotification statusBarNotification) {
if (preference.getFromPref_Boolean("CheckedState")) {
boolean fromPref_Boolean = preference.getFromPref_Boolean("ScheduleTime");
Log.e("scheduleTime", fromPref_Boolean + ":::");
contactType = preference.getFromPref_String("ContactType");
Const.contactList = preference.getContactList("ContactList");
try {
if (Const.contactList.isEmpty()) {
Const.contactList = new ArrayList();
}
} catch (Exception unused) {
Const.contactList = new ArrayList();
}
Const.replyList = preference.getList("MessageList");
try {
if (Const.replyList.isEmpty()) {
Const.replyList = new ArrayList();
}
} catch (Exception unused2) {
Const.replyList = new ArrayList();
}
Const.staticsReplyList = preference.getReplyList("StaticsReplyList");
try {
if (Const.staticsReplyList.isEmpty()) {
Const.staticsReplyList = new ArrayList();
}
} catch (Exception e) {
Const.staticsReplyList = new ArrayList();
Log.e("StaticsList", e.getMessage());
}
String fromPref_String = preference.getFromPref_String("BoldHeaderText");
if (fromPref_String.isEmpty()) {
headerText = "*Auto Reply*\n\n";
} else if (fromPref_String.equals(" ")) {
headerText = fromPref_String;
} else {
headerText = "*" + fromPref_String + "*\n\n";
}
autoReplyText = headerText + preference.getFromPref_String("autoReplyText");
if (isScheduleTime(fromPref_Boolean)) {
Log.e("IS SCHEDULE TIME", isScheduleTime(fromPref_Boolean) + "::::");
cancelNotification(statusBarNotification.getKey());
final Action quickReplyAction = NotificationUtils.getQuickReplyAction(statusBarNotification.getNotification(), getPackageName());
Log.e("Action", quickReplyAction + "::Action:");
if (quickReplyAction == null) {
return;
}
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp")||statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp.w4b"))
{
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp")&&preference.getFromPref_Boolean("WAState") ){
final String string = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TITLE);
Log.e("USERNAME", string + ":::");
final String string2 = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TEXT);
if (EveryOne(contactType) || ContactList(contactType, string) || ExceptContactList(contactType, string) || ExceptPhoneList(contactType, string)) {
Log.e("CONTACT TYPE", contactType + "::::");
if (string2 != null && !string2.equalsIgnoreCase("📷 Photo") && isGroupMessageAndReplyAllowed(statusBarNotification) && NotificationUtils.isNewNotification(statusBarNotification) && selfName(statusBarNotification)) {
if (preference.getFromPref_Boolean("Immediately")) {
Log.e("Immediately", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
} else if (preference.getFromPref_Boolean("Time")) {
Log.e("Time", "True");
String fromPref_String2 = preference.getFromPref_String("TimeofMsg");
String fromPref_String3 = preference.getFromPref_String("SpinTime");
if (fromPref_String3.equals("Minutes")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000 * 60;
} else if (fromPref_String3.equals("Seconds")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000;
}
Log.e("REPLY TIME", replyTime + ":::::");
new Handler().postDelayed(new Runnable() {
public void run() {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}, (long) replyTime);
} else if (preference.getFromPref_Boolean("Once")) {
Log.e("Once", "True");
List<String> userList = preference.getUserList("UserList");
getUserList = userList;
try {
if (userList.isEmpty()) {
getUserList = new ArrayList();
}
} catch (Exception e2) {
Log.e("ONCE", e2.getMessage());
getUserList = new ArrayList();
}
if (getUserList.contains(string)) {
stopService(new Intent(getApplicationContext(), getClass()));
} else {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
} else {
Log.e("ELse", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}
}
}
if (statusBarNotification.getPackageName().equalsIgnoreCase("com.whatsapp.w4b")&&preference.getFromPref_Boolean("WBState")){
final String string = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TITLE);
Log.e("USERNAME", string + ":::");
final String string2 = statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_TEXT);
if (EveryOne(contactType) || ContactList(contactType, string) || ExceptContactList(contactType, string) || ExceptPhoneList(contactType, string)) {
Log.e("CONTACT TYPE", contactType + "::::");
if (string2 != null && !string2.equalsIgnoreCase("📷 Photo") && isGroupMessageAndReplyAllowed(statusBarNotification) && NotificationUtils.isNewNotification(statusBarNotification) && selfName(statusBarNotification)) {
if (preference.getFromPref_Boolean("Immediately")) {
Log.e("Immediately", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
} else if (preference.getFromPref_Boolean("Time")) {
Log.e("Time", "True");
String fromPref_String2 = preference.getFromPref_String("TimeofMsg");
String fromPref_String3 = preference.getFromPref_String("SpinTime");
if (fromPref_String3.equals("Minutes")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000 * 60;
} else if (fromPref_String3.equals("Seconds")) {
replyTime = Integer.valueOf(fromPref_String2).intValue() * 1000;
}
Log.e("REPLY TIME", replyTime + ":::::");
new Handler().postDelayed(new Runnable() {
public void run() {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}, (long) replyTime);
} else if (preference.getFromPref_Boolean("Once")) {
Log.e("Once", "True");
List<String> userList = preference.getUserList("UserList");
getUserList = userList;
try {
if (userList.isEmpty()) {
getUserList = new ArrayList();
}
} catch (Exception e2) {
Log.e("ONCE", e2.getMessage());
getUserList = new ArrayList();
}
if (getUserList.contains(string)) {
stopService(new Intent(getApplicationContext(), getClass()));
} else {
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
} else {
Log.e("ELse", "True");
sendMsg(quickReplyAction, string2, string, string, bitmap);
}
}
}
}
}
else {
Log.e(TAG, "not success");
}
}
}
}
#Override
public void onTaskRemoved(Intent intent) {
super.onTaskRemoved(intent);
Intent intent2 = new Intent(getApplicationContext(), getClass());
intent2.setPackage(getPackageName());
startService(intent2);
}
public void sendMsg(Action action, String str, String str2, String tetStr, Bitmap image4) {
String str3;
String str4;
Intent phonebookIntent = new Intent();
image4 = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
boolean z;
try {
Log.e("RECEIVE MSG", str);
Const.replyList.isEmpty();
boolean z2 = false;
boolean isContain=preference.getFromPref_Boolean("contain");
boolean isExtra=preference.getFromPref_Boolean("exact");
Log.e("rules","contain=="+String.valueOf(isContain)+" "+"exact==="+String.valueOf(isExtra));
boolean fromPref_Boolean = preference.getFromPref_Boolean("customAutoReplySwitch");
Log.e("CustomReply", fromPref_Boolean + ":::");
Iterator<AutoReply> it = Const.replyList.iterator();
while (true) {
if (!it.hasNext()) {
str3 = "autoReplyText";
str4 = "Counter";
z = true;
break;
}
AutoReply next = it.next();
if (isContain?next.getReceiveMsg().equalsIgnoreCase(str)||str.contains(next.getReceiveMsg()):next.getReceiveMsg().equalsIgnoreCase(str)) {
if (fromPref_Boolean) {
long currentTimeMillis = System.currentTimeMillis();
Context applicationContext = getApplicationContext();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
action.sendReply(applicationContext, headerText + next.getSendMsg(), "okay kar", bitmap);
stopService(new Intent(getApplicationContext(), getClass()));
long j = count + 1;
count = j;
preference .addToPref_Long("Counter", j);
sendMessage = next.getSendMsg();
List<StatisticsReplyMsgListModel> list = Const.staticsReplyList;
str3 = "autoReplyText";
str4 = "Counter";
z = true;
StatisticsReplyMsgListModel statisticsReplyMsgListModel = new StatisticsReplyMsgListModel((int) count, next.getSendMsg(), str2, currentTimeMillis);
list.add(statisticsReplyMsgListModel);
preference.setReplyList("StaticsReplyList", Const.staticsReplyList);
if (preference.getFromPref_Boolean("Once") && !Const.userList.contains(str2)) {
Const.userList.add(str2);
preference.setUserList("UserList", Const.userList);
}
} else {
str3 = "autoReplyText";
str4 = "Counter";
z = true;
stopService(new Intent(getApplicationContext(), getClass()));
}
z2 = true;
}
}
if (!z2 && preference.getFromPref_Boolean("autoReplyTextSwitch") == z) {
Log.e(TAG, "Else");
if (autoReplyText.equals(str)) {
Log.e("Equal", "Message");
stopService(new Intent(getApplicationContext(), getClass()));
}
long currentTimeMillis2 = System.currentTimeMillis();
action.sendReply(getApplicationContext(), autoReplyText, "okay kar bhai", bitmap );
stopService(new Intent(getApplicationContext(), getClass()));
String str7 = str3;
sendMessage = preference.getFromPref_String(str7);
long j2 = count + 1;
count = j2;
preference.addToPref_Long(str4, j2);
Const.staticsReplyList.add(new StatisticsReplyMsgListModel((int) count, preference.getFromPref_String(str7), str2, currentTimeMillis2));
preference.setReplyList("StaticsReplyList", Const.staticsReplyList);
if (preference.getFromPref_Boolean("Once") == z && !Const.userList.contains(str2)) {
Const.userList.add(str2);
preference.setUserList("UserList", Const.userList);
}
}
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
Log.e("Replied Message Error", e.getMessage());
}
}
private Intent getIntent() {
return null;
}
private boolean selfName(StatusBarNotification statusBarNotification) {
String title = NotificationUtils.getTitle(statusBarNotification);
return title == null || !title.equalsIgnoreCase(statusBarNotification.getNotification().extras.getString(NotificationCompat.EXTRA_SELF_DISPLAY_NAME));
}
private boolean isGroupMessageAndReplyAllowed(StatusBarNotification statusBarNotification) {
String titleRaw = NotificationUtils.getTitleRaw(statusBarNotification);
SpannableString valueOf = SpannableString.valueOf("" + statusBarNotification.getNotification().extras.get(NotificationCompat.EXTRA_TEXT));
boolean z = titleRaw != null && (": ".contains(titleRaw) || "# ".contains(titleRaw)) && valueOf != null && valueOf.toString().contains("📷");
if (!statusBarNotification.getNotification().extras.getBoolean(NotificationCompat.EXTRA_IS_GROUP_CONVERSATION)) {
return !z;
}
boolean fromPref_Boolean = preference.getFromPref_Boolean("GroupEnable");
Log.e("Group Message", "Return" + fromPref_Boolean);
return fromPref_Boolean;
}
private boolean EveryOne(String str) {
return str.equals("Everyone") || str.equals("");
}
private boolean ContactList(String str, String str2) {
return str.equals("ContactList") && Const.contactList.contains(str2);
}
private boolean ExceptContactList(String str, String str2) {
return str.equals("ExceptContList") && !Const.contactList.contains(str2);
}
#SuppressLint("Range")
private boolean ExceptPhoneList(String str, String str2) {
if (!str.equals("ExceptPhoneList")) {
return false;
}
Cursor query = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, (String[]) null, (String) null, (String[]) null, "display_name ASC");
while (query.moveToNext()) {
cntList.add(query.getString(query.getColumnIndex("display_name")));
}
query.close();
return !cntList.contains(str2);
}
private boolean isScheduleTime(boolean z) {
if (z) {
try {
Calendar instance = Calendar.getInstance();
String fromPref_String = preference.getFromPref_String("StartTime");
String fromPref_String2 = preference.getFromPref_String("EndTime");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
Date parse = simpleDateFormat.parse(simpleDateFormat.format(instance.getTime()));
Date parse2 = simpleDateFormat.parse(fromPref_String);
Date parse3 = simpleDateFormat.parse(fromPref_String2);
if (!parse.after(parse2) || !parse.before(parse3)) {
return false;
}
return true;
} catch (ParseException e) {
e.printStackTrace();
Log.e("CURRENTTIME", e.getMessage());
}
}
return true;
}
}
This is action activity that is sending reply in background.
Action.java
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;
import com.templatemela.whatsbot.NotificationService;
import com.templatemela.whatsbot.R;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Iterator;
public class Action implements Parcelable {
public static final Creator CREATOR = new Creator() {
public Action createFromParcel(Parcel parcel) {
return new Action(parcel);
}
public Action[] newArray(int i) {
return new Action[i];
}
};
private final boolean isQuickReply;
private final PendingIntent p;
private final String packageName;
private final ArrayList<RemoteInputParcel> remoteInputs;
private final String text;
private final Uri imageUri = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/AwakiFolder/" + "aifile" + ".jpeg");
public int describeContents() {
return 0;
}
public Action(Parcel parcel) {
ArrayList<RemoteInputParcel> arrayList = new ArrayList<>();
remoteInputs = arrayList;
text = parcel.readString();
packageName = parcel.readString();
p = (PendingIntent) parcel.readParcelable(PendingIntent.class.getClassLoader());
isQuickReply = parcel.readByte() != 0;
parcel.readTypedList(arrayList, RemoteInputParcel.CREATOR);
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(text);
parcel.writeString(packageName);
parcel.writeParcelable(p, i);
parcel.writeByte(isQuickReply ? (byte) 1 : 0);
parcel.writeTypedList(remoteInputs);
}
public Action(String str, String str2, PendingIntent pendingIntent, RemoteInput remoteInput, boolean z) {
ArrayList<RemoteInputParcel> arrayList = new ArrayList<>();
remoteInputs = arrayList;
text = str;
packageName = str2;
p = pendingIntent;
isQuickReply = z;
arrayList.add(new RemoteInputParcel(remoteInput));
}
public Action(NotificationCompat.Action action, String str, boolean z) {
remoteInputs = new ArrayList<>();
text = action.title.toString();
packageName = str;
p = action.actionIntent;
if (action.getRemoteInputs() != null) {
for (RemoteInput remoteInputParcel : action.getRemoteInputs()) {
remoteInputs.add(new RemoteInputParcel(remoteInputParcel));
}
}
isQuickReply = z;
}
public void sendReply(Context context, String str, String tetStr, Bitmap bitmap) throws PendingIntent.CanceledException {
Log.e("AutoReply", "inside sendReply");
Intent intent = new Intent();
Bundle bundle = new Bundle();
Bitmap image4 = BitmapFactory.decodeResource(getResources(), R.drawable.msg_vector);
bundle.putParcelable( "image/png", image4);
String both = imageUri+ str + tetStr;
ArrayList arrayList = new ArrayList();
Iterator<RemoteInputParcel> it = remoteInputs.iterator();
while (it.hasNext()) {
RemoteInputParcel next = it.next();
Log.e("", "RemoteInput: " + next.getLabel());
intent.setAction(Intent.ACTION_SEND);
intent.setPackage("com.whatsapp");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
bundle.putCharSequence(next.getResultKey(), both);
RemoteInput.Builder builder = new RemoteInput.Builder(next.getResultKey());
builder.setLabel(next.getLabel());
builder.setChoices(next.getChoices());
builder.setAllowFreeFormInput(next.isAllowFreeFormInput());
builder.addExtras(next.getExtras());
arrayList.add(builder.build());
}
RemoteInput.addResultsToIntent((RemoteInput[]) arrayList.toArray(new RemoteInput[arrayList.size()]), intent, bundle);
p.send(context, 0, intent);
context.stopService(new Intent(context, NotificationService.class));
}
private Resources getResources() {
return null;
}
public ArrayList<RemoteInputParcel> getRemoteInputs() {
return remoteInputs;
}
public boolean isQuickReply() {
return isQuickReply;
}
public String getText() {
return text;
}
public PendingIntent getQuickReplyIntent() {
if (isQuickReply) {
return p;
}
return null;
}
public String getPackageName() {
return packageName;
}
}
Much like the title says. I have followed my class tutorials but chunks seem to be missing and it gets a bit confusing flicking between video lectures and pdf's when you're not too well versed in such.
When the app is executed the user can search for a song by year, or display all records within the database. However, originally all records would display from clicking the search by year button instead of the display all button. The search function works as intended but the display all button I cannot seem to figure out, despite following my lecturer's tutorials.
The first section of code is "MainActivity.java" and the second is "OpenDatabse.java"
package com.example.dbcopyexample1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity
{
private static String DATABASE_PATH_AND_NAME;
private static String CHECK_DATABASES_FOLDER;
//private static final String DATABASE_NAME = "music.db";
private static final String LOG_TAG = "MUSIC_DB";
Context ctx;
OpenDatabase sqh;
SQLiteDatabase sqdb;
// Control Objects
EditText searchByYearEditText;
Button searchButton;
TextView numRecordTextView;
Button displayAllRecordsButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupDatabaseStrings();
setUpDatabase();
InitDataBase(); // open the music.db for reading and writing
//sqh.DisplayRecords( sqdb ); // Display the songtable records to the run window
setupControls();
numRecordTextView.setText( Integer.toString( sqh.numberOfRecordsInSongtable( sqdb ) ) );
} // protected void onCreate(Bundle savedInstanceState)
protected void setupControls()
{
searchByYearEditText = findViewById(R.id.searchByYearEditText);
searchButton = findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
resultsTextView.setText( sqh.searchByYearInSongtable( sqdb,
searchByYearEditText.getText().toString()) );
}
});
numRecordTextView = findViewById(R.id.numRecordTextView);
displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);
displayAllRecordsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
}
});
resultsTextView = findViewById(R.id.resultsTextView);
} // protected void setupControls()
protected void setupDatabaseStrings()
{
// Full path to where we will copy music.db to on the emulator!
DATABASE_PATH_AND_NAME = "/data/data/" + getApplicationContext().getPackageName() +
"/databases/" + OpenDatabase.DATABASE_NAME;
// Used to check if the "databases" folder exists
CHECK_DATABASES_FOLDER = "/data/data/" + getApplicationContext().getPackageName() +
"/databases";
// Debug information
Log.i("DATABASE_PATH_AND_NAME","DATABASE_PATH_AND_NAME = " + DATABASE_PATH_AND_NAME);
Log.i("CHECK_DATABASES_FOLDER","CHECK_DATABASES_FOLDER = " + CHECK_DATABASES_FOLDER);
} // protected void setupDatabaseStrings()
protected void setUpDatabase()
{
ctx = this.getBaseContext();
Log.w("CTX","ctx = " + ctx);
Log.w("getBaseContext()","getBaseContext = " + getBaseContext());
try
{
CopyDataBaseFromAsset();
}
catch (IOException e)
{
e.printStackTrace();
}
} // protected void setUpDatabase()
protected void CopyDataBaseFromAsset() throws IOException
{
Log.w( LOG_TAG , "Starting copying...");
String outputFileName = DATABASE_PATH_AND_NAME;
File databaseFolder = new File( CHECK_DATABASES_FOLDER );
// databases folder exists ? No - Create it and copy !!!
if ( !databaseFolder.exists() )
{
databaseFolder.mkdir();
// Open the sqlite database "music.db" found in the assets folder
InputStream in = ctx.getAssets().open(OpenDatabase.DATABASE_NAME);
OutputStream out = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ( (length = in.read(buffer)) > 0 )
{
out.write(buffer,0,length);
} // while ( (length = in.read(buffer)) > 0 )
out.flush();
out.close();
in.close();
Log.w(LOG_TAG, "Completed.");
} // if ( !databaseFolder.exists() )
} // protected void CopyDataBaseFromAsset() throws IOException
public void InitDataBase()
{
// Init the SQLite Helper Class
sqh = new OpenDatabase(this);
// RETRIEVE A READABLE AND WRITEABLE DATABASE
sqdb = sqh.getWritableDatabase();
} // public void InitDataBase()
public void DisplayRecords()
{
Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
String songtitle = c.getString(1);
String year = c.getString(2);
String artist = c.getString(3);
String album = c.getString(4);
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
} while (c.moveToNext());
}
}
c.close();
} // public void DisplayRecords()
} // public class MainActivity extends AppCompatActivity
package com.example.dbcopyexample1;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class OpenDatabase extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "music.db";
// TOGGLE THIS NUMBER FOR UPDATING TABLES AND DATABASE
private static final int DATABASE_VERSION = 1;
OpenDatabase(Context context)
{
super( context, DATABASE_NAME, null, DATABASE_VERSION );
} // OpenDatabase(Context context)
#Override
public void onCreate(SQLiteDatabase db)
{
} // public void onCreate(SQLiteDatabase db)
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
} // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
public String searchByYearInSongtable(SQLiteDatabase sqdb, String searchYear)
{
String result = "";
Cursor c = sqdb.rawQuery("SELECT * FROM songtable where year = '" + searchYear + "'",
null);
if (c != null) {
if (c.moveToFirst()) {
do {
String id = c.getString(0);
result = result + id + ",";
String songtitle = c.getString(1);
result = result + songtitle + ",";
String year = c.getString(2);
result = result + year + ",";
String artist = c.getString(3);
result = result + artist + ",";
String album = c.getString(4);
result = result + album + "\n"; // new line control character
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
} while (c.moveToNext());
} else
{
result = "No Records Found for the Search Year = " + searchYear;
}
}
c.close();
return result;
} // public String allRecordsInSongtable(SQLiteDatabase sqdb)
public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)
{
int count = 0;
Cursor c = sqdb.rawQuery("SELECT count(*) FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
count = Integer.parseInt( id );
} while (c.moveToNext());
}
}
c.close();
return count;
} // public int numberOfRecordsInSongtable(SQLiteDatabase sqdb)
} // public class OpenDatabase extends SQLiteOpenHelper
You have not called your DisplayRecords() function to display records on tap of displayAllRecordsButton.
displayAllRecordsButton = findViewById(R.id.displayAllRecordsButton);
displayAllRecordsButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
DisplayRecords();
}
});
Also, in the DisplayRecords() method, you need to set text to the text view.
Below is your code I edited to display records.
public void DisplayRecords()
{
String result = "";
Cursor c = sqdb.rawQuery("SELECT * FROM songtable", null);
if (c != null)
{
if (c.moveToFirst())
{
do
{
String id = c.getString(0);
String songtitle = c.getString(1);
String year = c.getString(2);
String artist = c.getString(3);
String album = c.getString(4);
Log.w("SONG_TABLE", "ID = " + id + " Songtitle = " + songtitle);
result = result + "ID = " + id + "Song Title = " + songtitle + "Artist = " + artist + "Album = " + album + "Year = " + year + "\n";
} while (c.moveToNext());
}
}
c.close();
resultsTextView.setText(result);
} // public void DisplayRecords()
I have code that imports data with sms! And now I need one method to export this data from the database to a variable on the IncomingSMSReceiver (I will probably make one method for each field); Can I export a single cell value to a variable?
E.g I tried to do it for the onoma column but I don't know what database method I should use and what sql, and how to export it.
DatabaseHelper.java
package toulios.ptixiakh.toulios;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Toulios.db";
public static final String TABLE_NAME="Foitites_table";
public static final String Col_AM="AM";
public static final String Col_ONOMA="ONOMA";
public static final String Col_EPITHETO="EPITHETO";
public static final String Col_EXAMINO="EXAMINO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME+"(AM INTEGER PRIMARY KEY,ONOMA TEXT,EPITHETO TEXT, EXAMINO INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}
public boolean eisagoghfititi(String am,String onoma,String epitheto,String examino)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Col_AM,am);
contentValues.put(Col_ONOMA,onoma);
contentValues.put(Col_EPITHETO,epitheto);
contentValues.put(Col_EXAMINO,examino);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result == -1)
return false;
else
return true;
}
public String exagwgh_onoma(String am){
String str="";
final String SQL_SELECT_QUERY = "SELECT "+DatabaseHelper.Col_ONOMA+" FROM "+DatabaseHelper.TABLE_NAME+" WHERE "+DatabaseHelper.Col_AM+" = "+am;
DatabaseHelper queryDbHelperObj = new DatabaseHelper(this);
SQLiteDatabase sqLiteDatabase = queryDbHelperObj.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(SQL_SELECT_QUERY,null);
if (cursor.moveToFirst()) {
str = cursor.getString(cursor.getColumnIndex("content"));
}
cursor.close();
return str;
}
}
IncomingSMSReceiver.java
public class IncomingSMSReceiver extends BroadcastReceiver{
private static final String SMS_RECEIVED ="android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context _context, Intent _intent) {
if (_intent.getAction().equals(SMS_RECEIVED)) {
Bundle bundle = _intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage
.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message : messages)
{
String strPhoneNo = message.getOriginatingAddress();
String msg = message.getMessageBody();
if (msg.startsWith("01"))
{
try {
final String[] temaxismeno_sms = msg.split(":");
DatabaseHelper dbHelper = new DatabaseHelper(_context.getApplicationContext());
dbHelper.eisagoghfititi(temaxismeno_sms[1],temaxismeno_sms[2],temaxismeno_sms[3],temaxismeno_sms[4]);
Toast.makeText(_context, "Egine eisagwgh fititi!!", Toast.LENGTH_LONG).show();
String message1 = "H Eisagwgh egine sthn vash.";// minima pou tha stalthei
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(strPhoneNo, null, message1, null, null);
Toast.makeText(_context, "O fititis idopiithike", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(_context, "SMS failed, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if (msg.startsWith("02"))
{
final String[] temaxismeno_sms = msg.split(":");
String apotelesma;
DatabaseHelper dbHelper = new DatabaseHelper(_context.getApplicationContext());
apotelesma = dbHelper.exagwgh_onoma(temaxismeno_sms[1]);
String message2 = "To onoma tou am pou epilexate einai "+apotelesma;
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(strPhoneNo, null, message2, null, null);
}
}
}
}
}
}
You can achieve that in the below way --
public static final String SQL_SELECT_QUERY = "SELECT COLUMN1 FROM "+AndroidOpenDbHelper.TEST_TABLE;
AndroidOpenDbHelper queryDbHelperObj = new AndroidOpenDbHelper(this);
SQLiteDatabase sqLiteDatabase = queryDbHelperObj.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery(SQL_SELECT_QUERY,null);
if(cursor != null)
{
if(cursor.moveToFirst())
{
do
{
String ColumnVal = cursor.getString(cursor.getColumnIndex("Column1"));
}while(cursor.moveToNext());
}
}
EDITED:
"SELECT "+AndroidOpenDbHelper.ONOMA+" FROM "+AndroidOpenDbHelper.TEST_TABLE+" WHERE "+AndroidOpenDbHelper._ID+" = "+am;
Hope this helps!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to get all database value into my arraylist and show in logcat. but i am facing some problem during getting value from arraylist. i put my hole code, i am able to get value but getting last value from model.
my MainActivity
package com.example.databasework;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button btnInsertCW, btnInsertCD, btnGetAllVAlue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInsertCW = (Button) findViewById(R.id.btnInsertCW);
btnInsertCD = (Button) findViewById(R.id.btnInsertCD);
btnGetAllVAlue = (Button) findViewById(R.id.btnGetAllVAlue);
btnInsertCW.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1) {
// TODO Auto-generated method stub
Database transactionDb = new Database(getApplicationContext());
TransactionModel transactionModel = new TransactionModel();
transactionDb.open();
transactionModel.setDate("14/2/2015");
transactionModel.setTime("11:12:15");
transactionModel.setEnrollment("CW");
transactionDb.insert(transactionModel);
transactionDb.close();
}
});
btnInsertCD.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
Database transactionDb = new Database(getApplicationContext());
TransactionModel transactionModel = new TransactionModel();
transactionDb.open();
transactionModel.setDate("28/3/2014");
transactionModel.setTime("09:08:06");
transactionModel.setEnrollment("CD");
transactionDb.insert(transactionModel);
transactionDb.close();
}
});
btnGetAllVAlue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v3) {
// TODO Auto-generated method stub
ArrayList<TransactionModel> arrayList = new ArrayList<TransactionModel>();
Database transactionDb = new Database(getApplicationContext());
transactionDb.open();
arrayList = transactionDb.getReportPrintTrns();
transactionDb.close();
System.err.println(arrayList);
for (int i = 0; i < arrayList.size(); i++)
{
TransactionModel transactionModel = arrayList.get(i);
System.err.println(transactionModel.getEnrollment());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(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;
}
}
in arrayList = transactionDb.getReportPrintTrns(); want all database value.
My Database
package com.example.databasework;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class Database {
private static final String DATABASE_NAME = "KisanMitra.db";
public static final String DATABASE_TABLE = "TransactionDb";
private static final int DATABASE_VERSION = 1;
public static final String TrnsNo = "TrnsNo";
public static final String Enrollment = "Enrollment";
public static final String CardNumber = "CardNumber";
public static final String EnrollmentAmount = "EnrollmentAmount";
public static final String Date = "Date";
public static final String Time = "Time";
public static final String ReturnStatus = "ReturnStatus";
public static final String TotalCashWithdrawalAmount = "TotalCashWithdrawalAmount";
public static final String TotalCashDepositAmount = "TotalCashDepositAmount";
public static final String TallyCash = "TallyCash";
public static final String KindPurchase = "KindPurchase";
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table " +DATABASE_TABLE + "("
+ TrnsNo + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ Enrollment + " text,"
+ Date + " text,"
+ CardNumber + " text,"
+ Time + " text,"
+ ReturnStatus + " text,"
+ EnrollmentAmount + " text,"
+ TotalCashDepositAmount + " text,"
+ TotalCashWithdrawalAmount + " text,"
+ KindPurchase + " text,"
+ TallyCash + " text);");
Log.e("TransationDb", "Create Succssfully");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;
String sql = null;
if (oldVersion == 1)
sql = "alter table " + DATABASE_TABLE + " add note text;";
if (oldVersion == 2)
sql = "";
Log.d("EventsData", "onUpgrade : " + sql);
if (sql != null)
db.execSQL(sql);
}
}
public Database open() throws SQLException {
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public Database(Context c) {
ourContext = c;
}
public void close() {
ourHelper.close();
}
public void insert(TransactionModel TransactionSetter)
{
String iEnrollment = TransactionSetter.getEnrollment();
String iEnrollmentAmount = TransactionSetter.getEnrollmentAmount();
String iDate = TransactionSetter.getDate();
String iTime = TransactionSetter.getTime();
String iReturnStatus = TransactionSetter.getReturnStatus();
String iCardNumber = TransactionSetter.getCardNumber();
String iTotalCashWithdrawalAmount = TransactionSetter.getTotalCashWithdrawalAmount();
String iTotalCashDepositAmount = TransactionSetter.getTotalCashDepositAmount();
String iTallyCash = TransactionSetter.getTallyCash();
String iKindPurchase = TransactionSetter.getKindPurchase();
ContentValues contentValues = new ContentValues();
contentValues.put(Enrollment, iEnrollment);
contentValues.put(EnrollmentAmount, iEnrollmentAmount);
contentValues.put(Date, iDate);
contentValues.put(Time, iTime);
contentValues.put(ReturnStatus, iReturnStatus);
contentValues.put(CardNumber, iCardNumber);
contentValues.put(TotalCashWithdrawalAmount,iTotalCashWithdrawalAmount);
contentValues.put(TotalCashDepositAmount, iTotalCashDepositAmount);
contentValues.put(TallyCash, iTallyCash);
contentValues.put(KindPurchase, iKindPurchase);
ourDatabase.insert(DATABASE_TABLE, null, contentValues);
}
public ArrayList<TransactionModel> getReportPrintTrns() {
ArrayList<TransactionModel> list = new ArrayList<TransactionModel>();
TransactionModel model = new TransactionModel();
String whereClause = Enrollment + " in ('CW', 'CD')";
String[] columns = new String[] { TrnsNo, Enrollment, EnrollmentAmount,
Date, Time, ReturnStatus, CardNumber,
TotalCashWithdrawalAmount, TotalCashDepositAmount, TallyCash, KindPurchase };
Cursor c=ourDatabase.query(DATABASE_TABLE, columns, whereClause,null,null,null,null);
int itransno = c.getColumnIndex(TrnsNo);
int iEnrollment = c.getColumnIndex(Enrollment);
int iEnrollmentAmount = c.getColumnIndex(EnrollmentAmount);
int iDate = c.getColumnIndex(Date);
int iTime = c.getColumnIndex(Time);
int iReturnStatus = c.getColumnIndex(ReturnStatus);
int iCardNumber = c.getColumnIndex(CardNumber);
int iTotalCashWithdrawalAmount = c.getColumnIndex(TotalCashWithdrawalAmount);
int iTotalCashDepositAmount = c.getColumnIndex(TotalCashDepositAmount);
int iTallyCash = c.getColumnIndex(TallyCash);
int iKindPurchase = c.getColumnIndex(KindPurchase);
if (c.moveToFirst()) {
do {
model.setTrnsNo(c.getString(itransno));
model.setEnrollment(c.getString(iEnrollment));
System.err.println("iEnrollmentType :- "+c.getString(iEnrollment));
model.setEnrollmentAmount(c.getString(iEnrollmentAmount));
model.setDate(c.getString(iDate));
model.setTime(c.getString(iTime));
model.setReturnStatus(c.getString(iReturnStatus));
model.setCardNumber(c.getString(iCardNumber));
model.setTotalCashWithdrawalAmount(c.getString(iTotalCashWithdrawalAmount));
model.setTotalCashDepositAmount(c.getString(iTotalCashDepositAmount));
model.setTallyCash(c.getString(iTallyCash));
model.setKindPurchase(c.getString(iKindPurchase));
list.add(model);
} while (c.moveToNext());
}
c.close();
c.deactivate();
return list;
}
}
My SetGet Model
package com.example.databasework;
public class TransactionModel {
String TrnsNo, Enrollment, EnrollmentAmount, Date, Time, ReturnStatus,
CardNumber, TotalCashWithdrawalAmount,
TotalCashDepositAmount, TallyCash, KindPurchase;
public TransactionModel() {
// TODO Auto-generated constructor stub
TrnsNo = "";
Enrollment = "";
EnrollmentAmount = "";
Date = "";
ReturnStatus = "";
Time = "";
CardNumber = "";
TotalCashWithdrawalAmount = "";
TotalCashDepositAmount = "";
TallyCash = "";
KindPurchase = "";
}
public String getTrnsNo() {
return TrnsNo;
}
public void setTrnsNo(String trnsNo) {
TrnsNo = trnsNo;
}
public String getEnrollment() {
return Enrollment;
}
public void setEnrollment(String enrollment) {
Enrollment = enrollment;
}
public String getEnrollmentAmount() {
return EnrollmentAmount;
}
public void setEnrollmentAmount(String enrollmentAmount) {
EnrollmentAmount = enrollmentAmount;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getReturnStatus() {
return ReturnStatus;
}
public void setReturnStatus(String returnStatus) {
ReturnStatus = returnStatus;
}
public String getCardNumber() {
return CardNumber;
}
public void setCardNumber(String cardNumber) {
CardNumber = cardNumber;
}
public String getTotalCashWithdrawalAmount() {
return TotalCashWithdrawalAmount;
}
public void setTotalCashWithdrawalAmount(String totalCashWithdrawalAmount) {
TotalCashWithdrawalAmount = totalCashWithdrawalAmount;
}
public String getTotalCashDepositAmount() {
return TotalCashDepositAmount;
}
public void setTotalCashDepositAmount(String totalCashDepositAmount) {
TotalCashDepositAmount = totalCashDepositAmount;
}
public String getTallyCash() {
return TallyCash;
}
public void setTallyCash(String tallyCash) {
TallyCash = tallyCash;
}
public String getKindPurchase() {
return KindPurchase;
}
public void setKindPurchase(String kindPurchase) {
KindPurchase = kindPurchase;
}
}
Getting Value
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CW
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CD
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CW
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CW
02-14 10:31:23.620: W/System.err(10564): iEnrollmentType :- CD
02-14 10:31:23.631: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
02-14 10:31:23.640: W/System.err(10564): CD
in Last Fine line i Am getting same value, but database has value like
CW
CD
CW
CW
CD
Create each time new object for TransactionModel in dowhile as follows
public ArrayList<TransactionModel> getReportPrintTrns() {
ArrayList<TransactionModel> list = new ArrayList<TransactionModel>();
TransactionModel model;
String whereClause = Enrollment + " in ('CW', 'CD')";
String[] columns = new String[] { TrnsNo, Enrollment, EnrollmentAmount,
Date, Time, ReturnStatus, CardNumber,
TotalCashWithdrawalAmount, TotalCashDepositAmount, TallyCash, KindPurchase };
Cursor c=ourDatabase.query(DATABASE_TABLE, columns, whereClause,null,null,null,null);
int itransno = c.getColumnIndex(TrnsNo);
int iEnrollment = c.getColumnIndex(Enrollment);
int iEnrollmentAmount = c.getColumnIndex(EnrollmentAmount);
int iDate = c.getColumnIndex(Date);
int iTime = c.getColumnIndex(Time);
int iReturnStatus = c.getColumnIndex(ReturnStatus);
int iCardNumber = c.getColumnIndex(CardNumber);
int iTotalCashWithdrawalAmount = c.getColumnIndex(TotalCashWithdrawalAmount);
int iTotalCashDepositAmount = c.getColumnIndex(TotalCashDepositAmount);
int iTallyCash = c.getColumnIndex(TallyCash);
int iKindPurchase = c.getColumnIndex(KindPurchase);
if (c.moveToFirst()) {
do {
model=new TransactionModel();
model.setTrnsNo(c.getString(itransno));
model.setEnrollment(c.getString(iEnrollment));
System.err.println("iEnrollmentType :- "+c.getString(iEnrollment));
model.setEnrollmentAmount(c.getString(iEnrollmentAmount));
model.setDate(c.getString(iDate));
model.setTime(c.getString(iTime));
model.setReturnStatus(c.getString(iReturnStatus));
model.setCardNumber(c.getString(iCardNumber));
model.setTotalCashWithdrawalAmount(c.getString(iTotalCashWithdrawalAmount));
model.setTotalCashDepositAmount(c.getString(iTotalCashDepositAmount));
model.setTallyCash(c.getString(iTallyCash));
model.setKindPurchase(c.getString(iKindPurchase));
list.add(model);
} while (c.moveToNext());
}
c.close();
c.deactivate();
return list;
}
hope it helps you.
Only one Problem In getReportPrintTrns() method. you have to initialize your Transaction Model. Like TransactionModel model=new TransactionModel();
I have here my code. Data on the database are filtered by the title, how can i filter data by title or author? I think it is on these lines of codes on Catalogue.java:
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
Here are my codes:
Catalogue.java
package com.cvsu.catalogue.db;
import com.cvsu.catalogue.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
#SuppressLint("NewApi")
public class Catalogue extends Activity {
private CollectionsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
public final static String TITLE_EXTRA = "com.cvsu.catalogue.db._TITLE";
public final static String AUTHOR_EXTRA = "com.cvsu.catalogue.db._AUTHOR";
public final static String LOCATION_EXTRA = "com.cvsu.catalogue.db._LOCATION";
public final static String CALLNUMBER_EXTRA = "com.cvsu.catalogue.db._CALLNUMBER";
public final static String PUBLISHER_EXTRA = "com.cvsu.catalogue.db._PUBLISHER";
public final static String DATEPUBLISHED_EXTRA = "com.cvsu.catalogue.db._DATEPUBLISHED";
public final static String DESCRIPTION_EXTRA = "com.cvsu.catalogue.db._DESCRIPTION";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalogue_title);
dbHelper = new CollectionsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCollections();
// The desired columns to be bound
String[] columns = new String[] {
CollectionsDbAdapter.KEY_TITLE,
CollectionsDbAdapter.KEY_AUTHOR,
CollectionsDbAdapter.KEY_LOCATION,
CollectionsDbAdapter.KEY_CALLNUMBER,
CollectionsDbAdapter.KEY_PUBLISHER,
CollectionsDbAdapter.KEY_DATEPUBLISHED,
CollectionsDbAdapter.KEY_DESCRIPTION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.txtTitle,
R.id.txtAuthor,
//R.id.location,
//R.id.callnumber,
//R.id.publisher,
//R.id.datepublished,
//R.id.description,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.book_info_title,
cursor,
columns,
to,
0);
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view,
int position, long id ) {
// Get the cursor, positioned to the corresponding row in the result set
/*Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String bookTitle =
cursor.getString(cursor.getColumnIndexOrThrow("title"));
Toast.makeText(getApplicationContext(),
bookTitle, Toast.LENGTH_SHORT).show();*/
Intent i = new Intent (CatalogueTitle.this, BookInfoPage.class);
i.putExtra(TITLE_EXTRA, String.valueOf(id));
i.putExtra(AUTHOR_EXTRA, String.valueOf(id));
i.putExtra(LOCATION_EXTRA, String.valueOf(id));
i.putExtra(CALLNUMBER_EXTRA, String.valueOf(id));
i.putExtra(PUBLISHER_EXTRA, String.valueOf(id));
i.putExtra(DATEPUBLISHED_EXTRA, String.valueOf(id));
i.putExtra(DESCRIPTION_EXTRA, String.valueOf(id));
startActivity(i);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
}
});
}
public static void main(String[] args) {
}
}
Collections.Java
package com.cvsu.catalogue.db;
public class Collections {
String title = null;
String author = null;
String location = null;
String callnumber = null;
String publisher = null;
String datepublished = null;
String description = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCallNumber() {
return callnumber;
}
public void setCallNumber(String callnumber) {
this.callnumber = callnumber;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDatePublished() {
return datepublished;
}
public void setDatePublished(String datepublished) {
this.datepublished = datepublished;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CollectionsDbAdapter.java
package com.cvsu.catalogue.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class CollectionsDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_LOCATION = "location";
public static final String KEY_CALLNUMBER = "callnumber";
public static final String KEY_PUBLISHER = "publisher";
public static final String KEY_DATEPUBLISHED = "datepublished";
public static final String KEY_DESCRIPTION = "description";
private static final String TAG = "CollectionsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryCollections";
private static final String SQLITE_TABLE = "Collections";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_TITLE + "," +
KEY_AUTHOR + "," +
KEY_LOCATION + "," +
KEY_CALLNUMBER + "," +
KEY_PUBLISHER + "," +
KEY_DATEPUBLISHED + "," +
KEY_DESCRIPTION + "," +
" UNIQUE (" + KEY_CALLNUMBER +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
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 " + SQLITE_TABLE);
onCreate(db);
}
}
public CollectionsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CollectionsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCollections(String title, String author,
String location, String callnumber, String publisher, String datepublished, String description) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_CALLNUMBER, callnumber);
initialValues.put(KEY_PUBLISHER, publisher);
initialValues.put(KEY_DATEPUBLISHED, datepublished);
initialValues.put(KEY_DESCRIPTION, description);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public Cursor fetchCollectionsByTitle(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_TITLE + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchCollectionsByAuthor(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_AUTHOR + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCollections() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = null;
database.openDataBase();
if(constraint!=null){
cur = database.selectDataWithConstrain(constraint.toString());
}
return cur;
}
using this constarint write a query in your Database Class and get the data required either title or author
public Cursor selectDataWithConstrain(String c) {
// TODO Auto-generated method stub
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tbl_xxx WHERE title LIKE '%"+c+"%'", null);
return cursor;
}
public Cursor fetchdatabyfilter(String inputText, String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM " + dbTable;
if (inputText == null || inputText.length() == 0 ) {
row = sqlDb.rawQuery(query, null);
} else {
query = "SELECT * FROM " + dbTable + " WHERE " + filtercolumn + " like '%" + inputText + "%' ";
row = sqlDb.rawQuery(query, null);
}
if (row != null)
{
row.moveToFirst();
}
return row;
}
mainactivity:
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchdatabyfilter(constraint.toString(),"title" );
}
});