Convert String to Array (android) - android

I get a String data from Cursor, but I don't know how to convert it to Array. How can I do that?
String[] mString;
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
mTitleRaw = cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE_RAW));
}
mString = mTitleRaw ????

You could just wrap mTitleRaw into a single element array like so:
mString = new String[] { mTitleRaw };
Update:
What you probably want is to add all the rows to a single array, which you can do with an ArrayList, and mutate back to a String[] array like so:
ArrayList strings = new ArrayList();
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String mTitleRaw = cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE_RAW));
strings.add(mTitleRaw);
}
Sting[] mString = (String[]) strings.toArray(new String[strings.size()]);

As Pentium10 pointed out marshall_law's code has a bug in it. It skips the first element in the cursor. Here is a better solution:
ArrayList al = new ArrayList();
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Log.d("", "" + cursor.getString(cursor.getColumnIndex(ProfileDbAdapter.KEY_PROFILE_NAME)));
String mTitleRaw = cursor.getString(cursor.getColumnIndex(ProfileDbAdapter.KEY_ID));
al.add(mTitleRaw);
cursor.moveToNext();
}
As I said, this code will include the first element in the cursor.

Related

Sqlite : ArrayIndexOutOfBoundsException when try to fetch array from database

i have create a table in sqlite that giving me java.lang.ArrayIndexOutOfBoundsException here is code while returning the array value.
Cursor res = database.rawQuery("select "+QsDatabaseHelper.getItemName()+" from " + QsDatabaseHelper.getItemTableName(), null);
String[] array = new String[res.getCount()];
int i = 0;
while(res.moveToNext()){
String itemName = res.getString(res.getColumnIndex( QsDatabaseHelper.getItemName()));
array[i] = itemName;
Log.d("VALUE ",itemName+"name"); //There i geting all values
i++;
}
return array[i]; //error showing this line
In my fragment i am calling this function to fetching itemname in string []
String[] ItemNameArray = new String[list_counts];
for (int i = 0; i < list_counts; i++) {
ItemNameArray[i] = listcatDb.itemname();
}
you just return array. Because i value is increased inside the while loop. so just return array then use array values in the main thread or if you want to return string use i-1;
return array;
The exception ArrayIndexOutOfBounds is thrown when the index is either negative or greater than or equal to the size of the array.
In while loop the value of 'i' exceeds size of array..
so it should be like
return array[i-1];
instead of,
return array[i];

show only one of similar items in List

I have list of numbers like this:
-153
-542
-153
-153
-783
-785
-975
-153
-478
as you see "153" is showen 4 times but i want to show this number one time only like this:
-153
-542
-783
-785
-975
-478
EDIT:
i need to get all messages numbers but show only one if similar numbers here is my method:
public static List<SMSData> getAllNumbers(Context context){
List<SMSData> smsList = new ArrayList<SMSData>();
Uri uri = Uri.parse("content://sms/inbox");
Cursor c= context.getContentResolver().query(uri, null,null,null,null);
// Read the sms data and store it in the list
if(c.moveToFirst()) {
for(int i=0; i < c.getCount(); i++) {
SMSData sms = new SMSData();
sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString());
sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString());
sms.setDate(c.getString(c.getColumnIndexOrThrow("date")).toString());
smsList.add(sms);
c.moveToNext();
}
}
return smsList;
}
i fond the solution:
https://stackoverflow.com/a/19305534/3522182
tnx all.
ArrayList yourList = new ArrayList();
/*
add your values to the list
*/
ArrayList simpleList = new ArrayList();
HashSet hashset = new HashSet();
hashset.addAll(yourList);
simpleList.addAll(hashset);// your list now has the unique numbers
NOTE: the order here is unexpected. if you want it orderd, use linkedHashSet for keeping the same order.

Receive an ArrayIndexOutOfBoundsException when trying to access String array

I have a model, lineModel that I am using to populate an array items for my gridAdapter. My model works fine when I populate the entries manually. For example:
lineModel[] items = {
new lineModel(2, "B", "", "#52D017", 5, 10, 30),
new lineModel(3, "C", "", "#000000", 4, 8, 30),
};
However, when populating items with SQLite I receive the ArrayIndexOutOfBoundsException
Specifically:
04-15 15:50:21.322: E/AndroidRuntime(26804): java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
04-15 15:50:21.322: E/AndroidRuntime(26804): at com.idealiner.metrosleepuniversal.model.GridModel.getLines(GridModel.java:68)
Line 68 is when I call lineModel and populate it with the values from cursor.
items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0);
The method getLines() is supposed to return the object array, but somewhere in the while() loop I believe there is a problem, most likely when populating the array.
Any help/advice/guidance would be appreciated.
The entire method, getLines, is below:
public lineModel[] getLines() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"*"};
String sqlTables = "lines";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
lineModel[] items = {};
int i=0;
int c_line = c.getColumnIndex("line_id");
int c_name = c.getColumnIndex("line_name");
int c_ccolor = c.getColumnIndex("line_color");
int c_tcolor = c.getColumnIndex("text_color");
c.moveToFirst();
if (c != null) {
while(c.moveToNext()) {
items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0);
i++;
}
c.close();
}
return items;
}
Well, you're creating a zero-length array:
lineModel[] items = {};
so there's no items[i] when you try assigning to it.
If you can use c.getCount(), as Flavio Faria suggests, set the initial length to that. Otherwise, I suggest you use an ArrayList, and .add() items to it as you go along. You can obtain the resulting array with .toArray()
In fact, you might consider using an ArrayList anyway and passing it up as the return value, ,that's very often a good idea.
Another alternative - which depends on how you use those line model items - is to pass an Iterator instead of an array (as what you're doing is essentially iterating into an array.
You can't use "*" together with column names. You must either use only "*" or you must declare each column in the array. So, don't do it like this:
String[] sqlSelect = {"0 _id", "*"};
Add each one of them instead:
String[] sqlSelect = { "line_id", "line_name", "line_color", "text_color"};
Or:
String[] sqlSelect = { "*" };
You must also remove c.moveToFirst() call in order to avoid skipping the first row of the cursor, since c.moveToNext() already does this job for you.
Your array must also be large enough to hold all your items:
lineModel[] items = new lineModel[c.getCount()];
Besides that, keep in mind that class names in Java start with a capital letter.

Cursror into string error cursor.getcolumnIndex Key_titles and therefore cant fill my arraylist

Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
ArrayList<String> mArrayList = new ArrayList<String>();
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
for(curz.moveToFirst(); curz.moveToNext(); curz.isAfterLast())
{ mArrayList.add(name); }
name_Val = (String[]) mArrayList.toArray(new String[mArrayList.size()]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,name_Val);
txtPhoneName.setAdapter(adapter);
I am filling a autocompletetextview and i get an error at String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
it just can't get the correct column index it forcecloses ive tried to wirte mdbHelper.KEY_TITLE or just KEY_TITLE but it was the same error
curz.moveToFirst()
String name =curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
do {
mArrayList.add(name);
}while(curz.moveToNext());
First you need to move to first row, then you can get something from it. Because when cursor is created, the pointer points to the -1 index or you can say it points to beforeFirst.
Cursor curz=mDbHelper.fetchAllRemindersG();
startManagingCursor(curz);
// setTheme(android.R.style.Theme_Light);
curz.moveToFirst();
ArrayList<String> mArrayList = new ArrayList<String>();
if (curz.getCount() > 0)
{
do
{
String name = curz.getString(curz.getColumnIndex(DatabaseIN.KEY_TITLE));
if(name!=null)
{
mArrayList.add(name);
}
}while (curz.moveToNext());
}

Convert Android Cursor to ArrayList of arrays

I try to convert my Cursor data to a arraylist. But at the end all the data in the arraylist is overwrited with the last row. What do i do wrong?
Cursor c = myDbHelper.getLvl1Cata();
String[] data = new String[3];
c.moveToFirst();
while(!c.isAfterLast()) {
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
c.moveToNext();
}
Try this
Cursor c = myDbHelper.getLvl1Cata();
String[] data;
if (c != null) {
while(c.moveToNext()) {
data = new String[3]; // Note this addition
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
}
c.close();
}
data is an array of strings. In the original code, you added the same array to your catalogueData structure several times. You changed the value of the array's contents each time, but it was still the same array object. So you ended up with catalogueData holding several references to a single array, and that array can only have one value for data[0]: the last thing you set it to.
This answer fixes that by using a new and different array for each row in the cursor.
Try this:
if(mycursor!=null){
do{
TextView name = (TextView)view.findViewById(R.id.contact_name);
name.setText(cursor.getString(cursor.getColumnIndex
(Displayname)));
mycursor.moveToNext();
}while (mycursor.isLast());
}
Put String[] data = new String[3]; into the while loop. You're overwriting the array object with each iteration.

Categories

Resources