I have one application in which initially I am inserting parameter for font color and font size manually and by getting thoes data into adpater by reading database i was able to make change in fontsize and fontcolor of list items.
Important code:
insert method of helper:
public boolean insertData(ContactModel contactModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// contentValues.put(col_0,contactModel.getId());
contentValues.put(col_1,contactModel.getName());
contentValues.put(col_2,contactModel.getNumber());
contentValues.put(col_3,contactModel.getColor());
contentValues.put(col_4,contactModel.getFSize());
contentValues.put(col_5,contactModel.getDataIndex());
// long result =db.insert(Table_name,null,contentValues);
long result = db.insertWithOnConflict(Table_name, null, contentValues,SQLiteDatabase.CONFLICT_REPLACE);
if(result == -1){
return false;
}else{
return true;
}
}
method for insert data :
public void tempinsert(String name,String num,String color,int size,int index){
boolean inSamedata=tempSqliteDatabaseHelper.IsItemExist(name,num);
if(inSamedata==false){
boolean indata = tempSqliteDatabaseHelper.insertData(new ContactModel(name,num,color,size,index));
if (indata == true) {
Log.e("DataSave","DataSave");
}
else{
Log.e("In_Data_not_True","In Data not True");
}
}else if(inSamedata==true){
Log.e("Record_Exist","Record Exist");
}
}
Calling above method:
tempinsert(getDisplayName(),getPhNumber(),"#2d2d2d",35,1);
As you can see I am inserting font color and size statically.
Code inside onBind method adapter for make change in list item:
#Override
public void onBindViewHolder(#NonNull MyContactHolder myContactHolder, int i) {
myContactHolder.Name.setText(customDataListModels.get(i).getName());
myContactHolder.Number.setText(customDataListModels.get(i).getNumber());
Log.e("poistionAdapter:", String.valueOf(myContactHolder.getPosition()));
Cursor cursor = tempSqliteDatabaseHelper.getAllData();
if (cursor.getCount() == 0) {
Toast.makeText(mcontext.getApplicationContext(), "No Contact Selected", Toast.LENGTH_SHORT).show();
return;
}
while (cursor.moveToNext()) {
Integer SFontsize=cursor.getInt(4);
String SColor=cursor.getString(3);
myContactHolder.Name.setTextColor(Color.parseColor(cursor.getString(3)));
myContactHolder.Name.setTextSize(SFontsize);
Log.d("Font_Size", String.valueOf(SFontsize));
Log.d("Font_color", String.valueOf(SColor));
}
}
Here inside log I am getting same value as inserted, Everything is fine uptil this point, Problem occurs After i am updating fontsize and fontcolor in database.After update I am able get updated fontsize/color in log but whenever I am give thoes value to
myContactHolder.Name.setTextColor(Color.parseColor(cursor.getString(3)));
myContactHolder.Name.setTextSize(SFontsize);
Textview not updating it's font size and color according to update , Funny thing is for cursor.getString(3) and SFontsize ,, I am getting updating value.If u reqiued any other code for understand my problem post in comment.
Related
I created a database with a table named flagTable, this table only has two fields, which are id(auto increment) and an integer field. Next, in my program, I have a button that will trigger a thread to start. When the thread is starting, it constantly retrieve data from database, and check for the for the value, if the value is equal to one then it will trigger another new Thread, something like this:
private class statusOfStrummingInAnotherDevice extends Thread {
int value;
public void run() {
try{
while(true){
try{
if(flagCursor == null){
flagCursor = cdb1.getFlagAll();
}
}catch(Exception e){break;}
try{
Log.i("MAIN3ACTIVITY","getting status");
int size = cdb1.getSize(flagCursor);
Log.i("MAIN3ACTIVITY","SIZE is" + String.valueOf(xyz));
for(int i = 0 ; i < size ; i++){
flagCursor.moveToPosition(i);
Log.i("MAIN3ACTIVITY","getting status jkasdfasdf");
value = cdb1.getFlag();
if(value == 1){
Log.i("FLAGCURSOR=====>>>>","Succesful");
releasingNotes = new ReleasingNotes(IntendedChord);
releasingNotes.start();
//break;
}
cdb1.updateFlag(0);
Log.i("FLAGCURSOR=====>>>>",String.valueOf(value));
}
flagCursor = null;
}catch(Exception e){break;}
Log.i("MAIN3ACTIVITY","thread is sleeping");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}catch(Exception e){
}
}
}
In the meantime, the data that were retrieved from the database is using this function:
public Cursor getFlagAll(){
return getReadableDatabase().rawQuery(
"SELECT _ID, flag from flagTable", null);
}
And, the data that were updated to the database through this method:
public int updateFlag(int i) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("flag",i);
return db.update("flagTable" , contentValues , "_ID" + "= ?",new String[]{String.valueOf(1)});
}
Now, above codes will give no error, however, the data that were retrieved from the database is always 1, it keeps trigger a new function. In my above codes, I stated if the value is equal to 1, then the current thread will trigger a new thread to start, When its finished, the program will update the current data to 0. So that, the next round of the infinite loop can stop triggering new thread until a the conditon is met. What is problem overhere? did my codes really updated the new value? or I need to referesh the database every time I updated a new value.
Use Listeners to your database.
use SQLiteTransactionListener and do your things in onCommit()
Some guide in details here :
https://developer.android.com/reference/android/database/sqlite/SQLiteTransactionListener.html and
http://www.programcreek.com/java-api-examples/index.php?api=android.database.sqlite.SQLiteTransactionListener
I have a database with foods that are displayed in a tablelayout with up to 20 lines of foods. The foods may have different measurement units that are retrieved through a union select query among three tables, and displayed in a spinner for each food in the table. When the user selects a unit of measurement in the spinner, the cursor is moved to the appropriate position so as to get the nutrients for the food's selected unit of measurement (through spinner's onItemSelected Listener).
Well the problem is when I select a food record from a listview in order to update it in the food insertion display, when I try to recreate the food record iterating through the different foods in the record. When the food cursor is in a food row it calls the method that loads the different units of measurement for that particular food, and also selects the record's unit of measurement for that food, which I remind you, on selecting the unit the unitsCursor moves to the appropriate column to get the nutrients for that unit.
Unfortunately the unitsCursor misses to deliver the data in time and the food row is partially filled when the foodCursor moves to the next lines. I cannot figure out why this is happening. Below is the method that loads the units spinner with the units of measurement and some code from the method that recreates the food record in the food insertion screen
protected void fillUnitsSpinner(String food) {
unitsCursor = mDataBaseHelper.getFoodMatches(food, null, CURSOR_FOR_UNITS_SPINNER);
foodUnits.clear();
if(unitsCursor != null) {
unitsCursor.moveToFirst();
while(!unitsCursor.isAfterLast()) {
// Get unit string
String unit = unitsCursor.getString(unitsCursor.getColumnIndex(FoodDBHelper.UNITS));
// Get practical units' extra columns if present
String fingerTip = unitsCursor.getString(unitsCursor.getColumnIndex(
FoodDBHelper.FINGERTIP));
// If practical units are present
if(fingerTip != null) {
foodUnits.add(FINGERTIP.getpUnit());
foodUnits.add(FINGER.getpUnit());
foodUnits.add(HAND.getpUnit());
foodUnits.add(FIST.getpUnit());
foodUnits.add(CUP.getpUnit());
}
else foodUnits.add(unit);
unitsCursor.moveToNext();
}
unitsCursor.moveToFirst();
ArrayAdapter<CharSequence> unitsAdapter = new ArrayAdapter<CharSequence>(this,
R.layout.food_act_units_spinner_dropdown_item);
unitsAdapter.addAll(foodUnits); // load adapter with food units
unitsAdapter.setDropDownViewResource(R.layout.food_act_units_spinner_dropdown_item);
mUnitsSpinner.setAdapter(unitsAdapter); // set adapter
Log.i(TAG, "spinnerItem = " + unitsAdapter.getItem(foodUnits.indexOf(foodUnits.get(0))));
// Select and set unit from the main table to the spinner
if(!editRecord)
mUnitsSpinner.setSelection(unitsAdapter.getPosition(foodUnits.get(0)));
mUnitsSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "pos = " + pos);
TextView unitsText = (TextView) view.findViewById(R.id.f_a_units_item);
int pUnitsPos = -1;
String pShortcutUnit;
switch(pos) {
case MAIN_TABLE:
unitsCursor.moveToPosition(MAIN_TABLE);
break;
// other cases
String unitsChoice = unitsText.getText().toString();
assigned = getValuesFromCursor(unitsCursor, unitsChoice);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// do nothing
}
});
}
}
and...
// Fill foodTable with records
if(c != null && c.moveToFirst()) {
Log.i(TAG, "c.getCount = " + c.getCount());
while(!c.isAfterLast() && makeRow(c)) {
c.moveToNext();
}
}
setListenersToFoodRows();
foodTable.requestLayout();
In the makeRow(Cursor c) method there is a call to fillUnitsSpinner(foodName);
I finally solved it. The problem was that I used a class variable as unitsCursor, while the correct was to use an instance variable.
Here My update database table methods
public void insertionchallanval(ArrayList<String> itemcode,ArrayList<String> item,ArrayList<String> quantity,
ArrayList<String> date,ArrayList<String> status,ArrayList<String> id)
{
ContentValues insertValues = new ContentValues();
for(int i=0;i<status.size();i++)
{
if(!retriveidstatus(id.get(i)))
{
insertValues.put("id", id.get(i));
insertValues.put("itemcode", itemcode.get(i));
insertValues.put("item", item.get(i));
insertValues.put("status", status.get(i));
insertValues.put("date", date.get(i));
insertValues.put("quantity", quantity.get(i));
//insertValues.put("category", category.get(i));
myDataBase.insert("create_challan", null, insertValues);
}
else
{
insertValues.put("id", id.get(i));
insertValues.put("itemcode", itemcode.get(i));
insertValues.put("item", item.get(i));
insertValues.put("quantity", quantity.get(i));
insertValues.put("status", status.get(i));
insertValues.put("date", date.get(i));
//insertValues.put("category", category.get(i));
myDataBase.update("create_challan", insertValues, "id="+"'"+id.get(i)+"'",null );
}
}
}
Here my check Id Methods
public boolean retriveidstatus(String id)
{
Cursor curCalllog = myDataBase.rawQuery("SELECT id FROM create_challan", null);
if(curCalllog.moveToNext() && curCalllog != null) {
while(!curCalllog.isAfterLast())
{
if(id.contains(curCalllog.getString(0)))
{
return true;
}
curCalllog.moveToNext();
}
}
return false;
}
Table Structure
id String
status String
date String
challanno String
itemcode String
item String
quantity String
When i call methods for insertion new value then its working fine but when i call again with new updated value then update methods return 0 means no row effected
Please Help me how i can fix this problem
Thanks IN Advance
Instead of checking wether the _IDs exist or not you can use replace() method of the class SQLiteDatabase like this :
myDataBase.replace("create_challan", null, insertValues);
hope it helps Cheers :)
I have created a table and trying to fetch data from it using a cursor as follow:
public Cursor getcontent() {
Cursor d = database.query(DatabaseHandler.Table_Name2,allColumns,selection, null, null,null,null);
return d;
}
Cursor r = X.getcontent();
if (r.getCount() > 0) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext()==true);
r.close();
} else {
Log.i("TAG"," No value found");
}
}
I am showing the result in the TextView to see what data it is fetched. My problem is when I run this code sometimes it shows the data in the TextView, whatever it has fetched and sometimes it doesn't. Its a 50:50 ratio, according to me it should show fetched values every time as data is fetched every time I don't know what is wrong here, can someone tell me what's the issue here?
Check Whether Cursor you are getting is Null or not . and if yes then What is the Count of Cursor. you can Do it by Below Way.
Cursor r = X.getcontent();
if ((r != null) && (r.getCount() > 0)) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
r.close();
} else {
Log.i("TAG"," No value found inside Cursor");
}
try like this
Cursor r = X.getcontent();
try {
if (r.moveToFirst()) {
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
}
} finally {
if(r!=null) {
r.close();
}
}
I am working on android project and am making using of a ListView that retrieves data from the SQLite database.
I am making a dataset using an ArrayList and then adding this ArrayList into an ArrayAdapter.
When the data is being retrieved from the database, I am telling SQLite to do the sorting so everything is in alphabetical order when it is added into the ListView. At certain times, the information will be added dynamically to to the ListView without it requiring to re-fetch everythin from the database again. However, I want to keep everything in alphabetical order.
How would I do this, do I sort the DataSet and then call the notifyDataSet Changes or do I do the sort directly on the ArrayAdapter. I've looked into performing the sort on the ArrayAdapter but this wants an argument that uses a Comparator but not sure what this is and can't find any working examples that may be of any help for what I want to achieve.
Below is the code that populates the array and sets the list adapter
ArrayList<Spanned> passwords = managePasswordList.getPasswordList();
if (passwords != null && passwords.size() > 0)
{
passwordArrayAdapter = new ArrayAdapter<Spanned>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_activated_1, passwords);
setListAdapter(passwordArrayAdapter);
myListView.setTextFilterEnabled(true);
txtNoRecords.setVisibility(View.GONE);
}
else
{
txtNoRecords.setVisibility(View.VISIBLE);
}
I am then adding data to the dataset and refreshing the list view using the following
String company = Encryption.decrypt(passwords.get(i).company);
String username = Encryption.decrypt(passwords.get(i).username);
details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
passwordArrayAdapter.notifyDataSetChanged();
Thanks for any help you can provide.
UPDATE 1
I've tried doing what Nick Bradbury suggested but I am having a problem with the comparator. I have the following code but I don't know where to go from here.
SQLiteDatabase myDb = null;
Cursor cursor = null;
ArrayList<Spanned> passwords = new ArrayList<Spanned>();
try
{
myDb = context.openOrCreateDatabase("PasswordManager", Context.MODE_PRIVATE, null);
cursor = myDb.rawQuery("SELECT * FROM password ASC", null);
while (cursor.moveToNext())
{
final String company = Encryption.decrypt(cursor.getString(2));
final String username = Encryption.decrypt(cursor.getString(4));
Spanned details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
Collections.sort(passwords, new Comparator<Spanned>() {
public int compare(Spanned lhs, Spanned rhs) {
return 0;
}
});
}
}
catch (SQLiteException ex)
{
common.showBasicAlertDialog("Unfortunately something has gone wrong.\n\nWe will fix this as soon as we can", false);
Log.e("Database Error", ex.toString());
return null;
}
In the return statement I have no idea what to do, I've tried return lhs.compareTo but the lhs and rhs variables don't have the compareTo function so I have not got a clue what to do.
Here's a simple example of sorting an ArrayList using Comparator. In this example, the ArrayList is defined as:
public class StatusList extends ArrayList<Status>
A sort routine for this ArrayList could look like this:
public void sort() {
Collections.sort(this, new Comparator<Status>() {
#Override
public int compare(Status item1, Status item2) {
return item2.getDate().compareTo(item1.getDate());
}
});
}
Replace <Status> with whatever object your ArrayList contains, then change the comparison to compare the values of the object you wish to sort by.