So what I am trying to do is display some information from my sqlite database into a listview. I got the basics down for that but how I display the information needs to be conditional from what the cursor gets back. Currently my cursor comes back liek this.
{
id_number=1234
text=testing
type=1
datetime=null
}
What I need to do is get the type and display according. Example:
if (type == 1){ do code } else if (type == 2) { do a different code }
How exactly would I parse it to do this?
Use this code to go through each of the cursor's rows:
Cursor c = dataBase.rawQuery("SELECT id_number, text, type, datetime FROM [data base name]", null);
if(c.moveToFirst()) {
do {
int type = c.getInt(2);
if(type == 1) {
//do something
} else if (type == 2) {
//do something else
}
} while (c.moveToNext());
}
c.close();
Related
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.
I have 5 empty TextViews where I add the names. After adding a name, it is stored in a database. The database consist on 2 columns, the item ID and the item NAME. This is an example of what I'm doing:
- Mark1 //ID=1, NAME= Mark1
- Mark2 //ID=2, NAME= Mark2
- Mark3 //ID=3, NAME= Mark3
- Empty
- Empty
I add and edit perfectly the textViews, but I'm facing a problem when deleting. This has something to do with the way I'm getting the values from the database, I'll explain:
Every time the app starts, or I edit, add or delete one element, what I do is get the items from the database, get them into a Map, and copy them into the textviews (whose at a first time are invisible) making visible just the ones that have a name setted.
This is the code I use to do that:
public void getTravelers() {
/*Create map where store items*/
Map<Integer, String> nameList = new HashMap<Integer, String>();
/*Lon in providers query() method to get database's items and save them into the map*/
Cursor c = getContentResolver().query(TravelersProvider.CONTENT_URI, PROJECTION, null, null, null);
if (c.moveToFirst()) {
do {
nameList.put(Integer.parseInt(c.getString(c.getColumnIndex(Travelers._ID))), c.getString(c.getColumnIndex(Travelers.NAME)));
}while(c.moveToNext());
}
if (c != null && !c.isClosed()) {
c.close();
}
/*Check size*/
int size = nameList.size();
if (size >= 1) {
/*Save items in TextViews*/
//TODO: This is the code I should fix
for (int i = 0; i <= size; i++) {
if (i==1) {
traveler1.setText(nameList.get(i).toString());
traveler1.setVisibility(View.VISIBLE);
}
if (i==2) {
traveler2.setText(nameList.get(i).toString());
traveler2.setVisibility(View.VISIBLE);
}
if (i==3) {
traveler3.setText(nameList.get(i).toString());
traveler3.setVisibility(View.VISIBLE);
}
if (i==4) {
traveler4.setText(nameList.get(i).toString());
traveler4.setVisibility(View.VISIBLE);
}
if (i==5) {
traveler5.setText(nameList.get(i).toString());
traveler5.setVisibility(View.VISIBLE);
}
}
}
}
The problem comes in the for loop. Let's supposse that from the items named above, I want to delete Mark2 with ID=2, so then the size of the new Map would be 2, and it would enter to (i == 1) and (i == 2). But when entering to this last one, it would do traveler2.setText(nameList.get(2).toString()); and as seen, there is no element existing with the ID=2 because that is the one that I've deleted and it throws a NPE.
So my question is, what would be the right way to do this without facing this problem?
You should go for switch case other than for loop. Than code will not be in loop.
Finally I get what I need just changing the Key value of the Map that was the same as the ID of the database:
if (c.moveToFirst()) {
int key = 0;
do {
key++;
nameList.put(key, c.getString(c.getColumnIndex(Travelers.NAME)));
}while(c.moveToNext());
}
if (c != null && !c.isClosed()) {
c.close();
}
Basically this way I don't need to change nothing more as now the key value of the Map will match with the Textview position
I was able to be extracted the data that interest me in this way:
Cursor stipcursor = dataBase.rawQuery("SELECT (riepilogo) AS stip FROM "+DbHelper.RIEPILOGO+" WHERE MESI = 'Gennaio' and ANNI = "+anno+"", null);
int colIndexstip = stipcursor.getColumnIndex("stip");
if (colIndexstip == -1)
return;
else
stipcursor.moveToFirst();
double stip = stipcursor.getDouble(colIndexstip);
System.out.println("Riepilogo"+stip);
the problem is that if the database has data, everything works, but if the database is empty, the application crashes.
As given in this post, try this
if ( cursor.moveToFirst() ) {
// start activity a
} else {
// start activity b
}
cursor.moveToFirst() will return false if the cursor is empty. It works for me always.
You can try the first method given on that post also.
I'm trying to save user information in my application. I have Employee number editText and Company EditText. My employee number is not a required field so that means my table can have null values. My problem is when I am comparing if the employee number entered by the user already exist in my database, it also reads the null values when the user do not enter anything on the employee number editText. Can anyone help me do this please?
This is my code where I save all the employee number in an arraylist and remove all the null values
ArrayList<String> employeenumber = databaseAdapter.getEmployeeNumber();
employeenumber.removeAll(Collections.singleton(null));
employeenumber.removeAll(Collections.singleton(""));
What I wanna do is, if the user enter employee number, it will check if the arraylist contains it and if yes, it will all check the company corresponds to it. I need to trap duplicate entry. For example the employee number is 1234 and the company is ABCD, the program must not accept it. Thanks for anyone who could help me.
First check whether the user enter something on employee number editText. Then use int flag to compare it. Try the code below in your main activity:
int flag1 = 0;
if (!Emp.equals(""))
{
ArrayList<String> CompanyandEmp = new ArrayList<String>();
CompanyandEmp = databaseAdapter.getCompanyEmp(Emp);
CompanyandEmp.removeAll(Collections.singleton(""));
for(int i=0;i< CompanyandEmp.size();i++)
{
String cmpemp = CompanyandEmp.get(i).toString();
if(cmpemp.equalsIgnoreCase(companyName))
{
flag1 = 1;
}
}
}
if (flag1 == 0)
{
//as per your requirement
}else{
Toast.makeText(RegistrationActivity.this, "Account info already exist.", Toast.LENGTH_LONG).show();
}
Then in your databaseAdapter:
public ArrayList<String> getCompanyEmp(String emp) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> companyemp = new ArrayList<String>();
try {
Cursor c = db.query("select CompName FROM projsitemast where Emp='"+emp+"'", null);
if (c != null) {
c.moveToFirst();
for (int j = 0; j < c.getCount(); j++) {
companyemp.add(c.getString(0));
c.moveToNext();
}
c.close();
}
return companyemp;
} catch (Exception e) {
e.printStackTrace();
}
return companyemp;
}
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();
}
}