Get String Array from Cursor - android

I have a SQLite Database with 45 different entries, each with:
public static final String TABLE = "Table";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_HOUR = "hour";
public static final String COLUMN_WEEK = "week";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_COLOUR = "colour";
public static final String COLUMN_ROOM = "room";
now I want to read out all. I Do this with following:
public Cursor fetchAllSubject(){
Cursor mCursor = database.query(true, TABLE, new String[] {
COLUMN_ID, COLUMN_HOUR, COLUMN_WEEK, COLUMN_DAY, COLUMN_NAME, COLUMN_DESCRIPTION, COLUMN_COLOUR, COLUMN_ROOM},null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
In a other class I have this code to read all out:
dao = new DAO(this);
Cursor subjectList = dao.fetchAllSubject();
Now I want to have for each entry an array with ID, Hour, week, ... but I have no idea how to do that.
My first try was following:
ArrayList<String> mo1h = new ArrayList<String>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_WEEK)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DAY)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_NAME)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DESCRIPTION)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_COLOUR)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ROOM)));
subjectList.moveToNext();
}
But everything is in mo1h, and I dont know how to devide it.
The best would be to have a String[] for each. Has anybody an Idea?
Thanks!

You can create on Bean class and then create one ArrayList (Collection class)
public class Bean
{
public Bean();
String id, hour, week, day, name, description, color, room;
}
now create list of Bean
ArrayList<Bean> mo1h = new ArrayList<Bean>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
Bean b = new Bean();
b.id = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID));
b.hour =subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR));
...
...
// all your column
mo1h.add(b);
}

Why not continue with your strategy, but instead use an ArrayList of String[]:
ArrayList<String[]> mo1h = new ArrayList<String[]>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
String[] toUse = new String[8];
toUse[0] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID));
toUse[1] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR));
toUse[2] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_WEEK));
toUse[3] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DAY));
toUse[4] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_NAME));
toUse[5] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DESCRIPTION));
toUse[6] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_COLOUR));
toUse[7] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ROOM));
mo1h.add(toUse);
subjectList.moveToNext();
}

Related

Java Android about Hashmap

I am trying to retrieve from UpdateProduct (Hashmap) to be able to modify my items by clicking the button. I implemented void modifyItem, but I see it is missing something.
File DataBase.java
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NOM = "Produits.db";
private static final String TABLE_PRODUCT = "Produits";
private static final String COLONNE_ID = "_id";
private static final String COLONNE_NAMEPRODUCT = "_nameProduct";
public void UpdateProduct(HashMap<String,String> object, String newValue) {
if(object == null) return;
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLONNE_NAMEPRODUCT, newValue);
int rows = db.update(TABLE_PRODUCT, values, "_id = ?", new String[]{object.get("id")});
db.close();
}
// MainActivity
Here my method to retrieve Hashmap data from UpdateProduct**
public void modifyItem(View view) {
if (objectSelected == null) return;
**????** selectedProduct = objectSelected.get("product");
if (selectedProduct != null && !selectedProduct.isEmpty()) {
DataBase.UpdateProduct(selectedProduct);
}
}`
Tryning to solve my project problems

SQLiteDatabase query method

I am using the query method of SQLiteDatabase. How do I do a query that gives me items by a particular STRING?
this query :
public ArrayList<RecipeInfo> getTypeRecipe() {
ArrayList<RecipeInfo> recipeInfo = new ArrayList();
Cursor cursor = null;
try {
cursor = db.query(TABLE_RECIPES_NAME, TABLE_RECIPE_COLUMNS,
RECIPE_COLUMN_TITLE+" =lunch", null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
RecipeInfo ri=cursorToRecipes(cursor);
recipeInfo.add(ri);
cursor.moveToNext();
}
}
catch (Throwable t){
t.printStackTrace();
}
return recipeInfo;
}
If you want the record corresponding to a particular String as its title, (say, title="lunch"), you do the query as follows:
cursor=db.query(TABLE_RECIPES_NAME, TABLE_RECIPE_COLUMNS,
"title=?", new String[]{"lunch"}, null, null, null);
OR
cursor=db.query(TABLE_RECIPES_NAME, TABLE_RECIPE_COLUMNS,
RECIPE_COLUMN_TITLE+"=?", new String[]{"lunch"}, null, null, null);
This will query the table TABLE_RECIPES_NAME and return all columns specified by TABLE_RECIPE_COLUMNS , corresponding to the record where "title" is "lunch".
//database info
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "cookpadDB";
//recipe table
private static final String TABLE_RECIPES_NAME ="recipes";
private static final String RECIPE_COLUMN_ID ="id";
private static final String RECIPE_COLUMN_TITLE ="title";
private static final String RECIPE_COLUMN_DESCRIPTION ="description";
private static final String RECIPE_COLUMN_FOOD_IMAGE = "food_image";
private static final String RECIPE_COLUMN_TYPE="type";
private static final String RECIPE_COLUMN_LIKE="like";
private static final String[] TABLE_RECIPE_COLUMNS = {RECIPE_COLUMN_ID, RECIPE_COLUMN_TITLE,
RECIPE_COLUMN_DESCRIPTION, RECIPE_COLUMN_FOOD_IMAGE,RECIPE_COLUMN_TYPE,RECIPE_COLUMN_LIKE};

How to search for a string in an SQLite database [duplicate]

This question already has answers here:
Using String[] selectionArgs in SQLiteDatabase.query()
(2 answers)
Closed 6 years ago.
I am new to SQLite in Android. I have successfully created the database with this schema:
public final class BookDbSchema {
private BookDbSchema() {
}
public static final class BookEntry implements BaseColumns{
public static final String NAME = "bookItems";
public static final String ID = "id";
public static final String URL = "url";
public static final String TITLE = "title";
}
}
The problem I am having is searching the database for a particular string.
I want to search the id column if 1993 exists. Please how do I do that?
I have read the documentation but I don’t know where to input "1993" for in the query method.
i belive you are looking for this
Context context;
BookDbSchema mDbHelper;
public BookDbSchema (Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
...
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> titles = new ArrayList<>();
ArrayList<String> ids= new ArrayList<>();
mDbHelper = new BookDbSchema(context);
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
FeedEntry.ID,
FeedEntry.URL,
FeedEntry.TITLE
};
String selection = FeedEntry.ID + " LIKE ? "; //WHERE
String[] selectionArgs = {"1993"}; //VALUE
Cursor c = db.query(
FeedEntry.NAME, // Your Table Name
projection,
selection,
selectionArgs,
null,
null,
null
);
if(c.getCount() != 0) {
c.moveToFirst();
for(int i = 0; i<c.getCount(); i++) {
urls.add(c.getString(c.getColumnIndex(FeedEntry.URL)));
titles.add(c.getString(c.getColumnIndex(FeedEntry.TITLE)));
ids.add(c.getString(c.getColumnIndex(FeedEntry.ID)));
c.moveToNext();
}
String firstUrl = urls.get(0); //Returns the first url found
String firstID = ids.get(0); //Returns the first id found
int urlSize = urls.size(); // returns the count of urls found
}else{
//Nothing found
}
c.close();
db.close();
You can use the below method :
Cursor query (String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
query(NAME, new String[]{ID, URL, TITLE}, ID + "=?", new String[]{"1993"}, null, null, null, null);

Will the address field store multiple phone numbers when I send a sms to multiple phone numbers at one time?

When I send a sms in Android mobile phone, I can select multiple contact (Please see A.png ), and the sms will be as one record.
Can the sms be query using "content://sms/" ? will the field "address" return multiple phone numbers?
Thanks!
A.png
public static List<String> ListDeleteOld(Context myContext, SMSRange mSMSRange, int beforeDays ) {
List<String> mListSmsID=new ArrayList<String>();
Uri uri=PublicParFun.GetUriBySMSRange(mSMSRange);
Date beforeDate=getCurrentBefore(beforeDays);
String[] projection = new String[] {"_id","address"};
Cursor cur = myContext.getContentResolver().query(uri, projection, "date<=" + beforeDate.getTime(), null, "date desc");
while(cur.moveToNext()){
String s=cur.getString(cur.getColumnIndex("address"));
}
cur.close();
return mListSmsID;
}
public static Uri GetUriBySMSRange(SMSRange mSMSRange){
Uri uri=null;
final String SMS_URI_ALL = "content://sms/";
final String SMS_URI_INBOX = "content://sms/inbox";
final String SMS_URI_SEND = "content://sms/sent";
final String SMS_URI_OUTBOX = "content://sms/outbox";
final String SMS_URI_DRAFT = "content://sms/draft";
switch (mSMSRange){
case All:
uri = Uri.parse(SMS_URI_ALL);
break;
case Inbox:
uri = Uri.parse(SMS_URI_INBOX);
break;
case Sentbox:
uri = Uri.parse(SMS_URI_SEND);
break;
case Outbox:
uri = Uri.parse(SMS_URI_OUTBOX);
break;
case Draft:
uri = Uri.parse(SMS_URI_DRAFT);
break;
}
return uri;
}
set variables for example:
private static final Uri SMS_SENT_URI = Uri.parse("content://sms/sent");
private static final String SMS_ORDER = "date DESC";
private static final String ADDRESS_COLUMN_NAME = "address";
private static final String DATE_COLUMN_NAME = "date";
private static final String BODY_COLUMN_NAME = "body";
private static final String TYPE_COLUMN_NAME = "type";
private static final String ID_COLUMN_NAME = "_id";
private static final String SMS_PREFERENCES = "SMS_PREFERENCES";
You have to crete SmsObject.
Then just loop trough Cursor.
The whole code: (call checkNewOutgoingSms(context))
private void checkNewOutgoingSms(Context context) {
Cursor smsCursor = getSmsCursor(context);
List<Sms> smsList = getLastSmsList(smsCursor,context);
if (smsList != null && smsList.size() > 0) {
ProtectorWSODao mwtProtectorDao = new ProtectorWSODao();
for (Sms sms : smsList) {
//
//
//read sms content
//
//
}
Manager.getInstance(context).sendDataToServer(mwtProtectorDao);
}
smsCursor.close();
}
public static Cursor getSmsCursor(Context context) {
return context.getContentResolver().query(SMS_SENT_URI, null, null, null, SMS_ORDER);
}
private List<Sms> getLastSmsList(Cursor smsCursor, Context context) {
List<Sms> smsList = new ArrayList<Sms>();
final int lastSmsIntercepted = smsStorage.getLastSmsIntercepted();
boolean update = false;
if (smsCursor != null) {
if (smsCursor.moveToFirst()) {
do {
Sms smsParsed = parseSms(smsCursor, context);
smsList.add(smsParsed);
} while (smsCursor.moveToNext());
}
}
return smsList;
}
public static Sms parseSms(Cursor cursor, Context context) {
String number = cursor.getString(cursor.getColumnIndex(ADDRESS_COLUMN_NAME));
String date = cursor.getString(cursor.getColumnIndex(DATE_COLUMN_NAME));
String content = cursor.getString(cursor.getColumnIndex(BODY_COLUMN_NAME));
int smsId = cursor.getInt(cursor.getColumnIndex(ID_COLUMN_NAME));
return new Sms(Sms.SEND, smsId, number, date, content);
}

Failing to query the max number in database

I am trying to find the max number in a column of one of the tables in my database.
I thought I had this one sorted (I posted similar question previously), however after some testing I have realised my code isn't working as I thought.
The database consists of a table with the following columns:
_id, inspection_link, area_number, area_reference
I have created the following code in my database helper class:
public static final String AREAS_TABLE = "areas";
public static final String AREA_ID = "_id";
public static final String AREA_NUMBER = "area_number";
public static final String AREA_REF = "area_reference";
public static final String AREA_LINK = "area_link";
public static final String INSPECTION_LINK = "inspection_link";
public Cursor selectMaxAreaNumber (long inspectionId) {
String inspectionIdString = String.valueOf(inspectionId);
String[] tableColumns = new String[] {
AREA_NUMBER,
"(SELECT max(" + AREA_NUMBER + ") FROM " + AREAS_TABLE + ") AS max"
};
String whereClause = INSPECTION_LINK + " = ?";
String[] whereArgs = new String[] {
inspectionIdString
};
Cursor c = rmDb.query(AREAS_TABLE, tableColumns, whereClause, whereArgs,
null, null, null);
if (c != null) {
c.moveToFirst();
}
c.close();
return c;
}
Then in the activity where I want to query the database I have written the following:
public class AreaEdit extends Activity {
private EditText AreaNumber;
private EditText AreaReference;
private Button saveButton;
private Button cancelButton;
protected boolean changesMade;
private AlertDialog unsavedChangesDialog;
private RMDbAdapter rmDbHelper;
private long inspectionId;
private long areaId;
private int nextAreaNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rmDbHelper = new RMDbAdapter(this);
rmDbHelper.open();
Intent i = getIntent();
inspectionId = i.getLongExtra("Intent_InspectionID", -1);
areaId = i.getLongExtra("Intent_AreaID", -1);
if (areaId == -1) {
Cursor c = rmDbHelper.selectMaxAreaNumber(inspectionId);
startManagingCursor(c);
c.moveToFirst();
nextAreaNumber = c.getInt(c.getColumnIndex("max")) + 1;
}
setContentView(R.layout.edit_area);
setUpViews();
populateFields();
setTextChangedListeners();
}
private void setUpViews() {
AreaNumber =(EditText)findViewById(R.id.area_number);
AreaReference =(EditText)findViewById(R.id.area_reference);
saveButton = (Button)findViewById(R.id.area_save_button);
cancelButton = (Button)findViewById(R.id.area_cancel_button);
}
private void populateFields() {
if (areaId > 0) {
Cursor c = rmDbHelper.fetchArea(areaId);
startManagingCursor(c);
c.moveToFirst();
AreaNumber.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_NUMBER)));
AreaReference.setText(c.getString(
c.getColumnIndexOrThrow(RMDbAdapter.AREA_REF)));
c.close();
}
else {
AreaNumber.setText(String.valueOf(nextAreaNumber));
}
}
However, when it returns the wrong number - it seems to pick up the maximum number from the whole table which includes data from other inspections.
I guess this may be down to the conversion between Strings and Longs etc maybe, but I have a brickwall with this?
Any help much appreciated.
You can simply try below:
String sql = "SELECT MAX(ColumnNameHere) AS MaxValue FROM myTable WHERE AnotherColumn = 'SomValue'";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
c.getInt(c.getColumnIndex("MaxValue"));
Detailed solution to this question found here:
Solution to this detailed in the following post: SELECT statement not returning MAX number
Basically, it was an issue with the query as thought and how I used the cursor.

Categories

Resources