How to check if id is exists in Android? - java

I want to check if id is exists in SQLIte DB then update that id , if id is not present in SQLite then insert that id. How can i do this. Can someone help how to work with.Thanks to Appreciate.
Here is my Activity code
public void saveResult()
{
AnswerOptions = (RadioButton) findViewById(Options_RadioGroup.getCheckedRadioButtonId());
String str_AnswerOptions = AnswerOptions.getText().toString().trim();
System.out.println("rbVal = " + str_AnswerOptions);
if (str_AnswerOptions.equals(((Datastructure) Vectore_mquestionDatabaseStructure .get(StaticClass.QuestionNumber)).Answer))
{
if (!StaticClass.isTest)
{
try
{
DatabaseHelper databaseHelper = new DatabaseHelper(this.getApplicationContext());
sqdb = databaseHelper.getWritableDatabase();
String strCountQuery = "SELECT question_id, question_type , question_no FROM question_answers where question_id = " + convertVector ;
Cursor cur = sqdb.rawQuery(strCountQuery , null);
if (cur.moveToFirst())
{
int iCount = cur.getCount();
System.out.println("iCount = " + iCount);
if(cur.getCount() <= 0 )
{
String strstrqueType = txtViewQuestiontype.getText().toString().trim();
String str_que = txtViewQuestion.getText().toString().trim();
String str_marks = "1";
databaseHelper.insertQueDetails(strQueLimit, strstrqueType, str_que, str_AnswerOptions, str_marks , strOption_Id);
System.out.println("strQueLimit = " + strQueLimit + ", strstrqueType = " + strstrqueType +" , str_que = " + str_que + " , str_AnswerOptions = " + str_AnswerOptions + ", str_marks = " + str_marks + ", strOption_Id = " + strOption_Id);
Toast.makeText(this, " Right Answer ", Toast.LENGTH_LONG).show();
}
else
{
cur.moveToFirst();
qid = cur.getInt(cur.getColumnIndex("question_id"));
String strQue_Type = cur.getString(cur.getColumnIndex("question_type"));
String strQue_Nomber = cur.getString(cur.getColumnIndex("question_no"));
System.out.println("qid in checkUpdateTable() = " + qid);
System.out.println("strQue_Type in checkUpdateTable() = " + strQue_Type);
System.out.println("strQue_Nomber in checkUpdateTable()= " + strQue_Nomber);
QueId = qid;
databaseHelper.updateAnswerRow(qid, str_AnswerOptions);
}
}
}
catch (SQLiteException se )
{
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally
{ if (sqdb != null) { sqdb.close();} }
}
}
}

You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:
CREATE TABLE data (id INTEGER PRIMARY KEY, question_id INTEGER, question_type TEXT, question_no TEXT);
CREATE UNIQUE INDEX data_idx ON data(question_id);
Then you can issue:
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);

Related

error insert data in java netbeans and mysql

I am a beginner in learning programming and I am trying to apply what I learned with an application example in java , and I encountered a problem. I hope you will find a solution, please.
When I insert data the combobox (combo_produits) it doesn't give me the specified value,
The code has no errors, but the combobox does not give us the desired value despite using the function getSelectedIndex() .
/*method of combobox combo_produits */
private void combo_PRODUIT() {
try {
String qyP = "SELECT CONCAT(NOM_COM,' ',lib_court,' ',DOSAGE ,' ',UNITE , ' ', CONDIT)AS DESIGNATION "
+ "FROM produit JOIN forme USING(cd_forme) ";
prs_sort = connectio.prepareStatement(qyP);
rs_sort = prs_sort.executeQuery();
while (rs_sort.next()) {
combo_produits.addItem(rs_sort.getString("DESIGNATION"));
}
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
}
/* button of insert */
private void valider_bpActionPerformed(java.awt.event.ActionEvent evt) {
int pharID = 0;
int donid = 0;
int lotID = 0;
int prodid= 0 ;
try {
String qr1 = "insert into tbl_pharmacien (NOM_PHARM) values ('" + combo_pharm.getSelectedItem() + "')";
prs_sort = connectio.prepareStatement(qr1, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
pharID = rs_sort.getInt(1);
}
String qr2 = "insert into donner_medic (PHARM_ID , DATE_ECHANDONN) values "
+ "('" + pharID + "', '" + new SimpleDateFormat("yyyy-MM-dd").format(date_prod_sort.getDate()) + "' )";
prs_sort = connectio.prepareStatement(qr2, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
donid = rs_sort.getInt(1);
}
int index =combo_produits.getSelectedIndex();
String qr3 = " insert into tbl_lot (NUM_ENR,PPA, QNT) values "
+ "('" +index + "', '" + txtf_ppa.getText() + "', '" + txt_Qnt.getText() + "' )";
prs_sort = connectio.prepareStatement(qr3, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
lotID = rs_sort.getInt(1);
}
String qr4 = "insert into tbl_donnelot (LOT_ID,DONN_ID) values ('" + lotID + "', '" + donid + "')";
prs_sort = connectio.prepareStatement(qr4);
prs_sort.executeUpdate();
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
Table_prod_sort();
}
For example let's create a compobox with the student's name:
First, we work a class with the student's name and id for him, and we do the Setter, getter and Constructor functions.
Second, we create a function to link the database with the students' class, thus:
public class class_array {
private Connection co=get_connection.ConnDb() ;
private PreparedStatement prst ;
private ResultSet res ;
public HashMap<String, Integer> fillCombobox(){
String sqls = "SELECT `ID_student`, `Name_student` FROM `student`";
HashMap<String, Integer> hmp = new HashMap<String, Integer>();
try {
prst = co.prepareStatement(sqls);
res = prst.executeQuery();
student st ;
while(res.next()){
st = new student(res.getInt(1), res.getString(2));
hmp.put(st.getName_stud(), st.getId_stu());
}
} catch (SQLException ex) {
Logger.getLogger(student_f.class.getName()).log(Level.SEVERE, null, ex);
}
return hmp ;
}}
Third, in the form we write the compobox content display function like this :
private void combo(){
class_array std = new class_array();
HashMap<String, Integer> hmp = std.fillCombobox();
for (String cb :hmp.keySet()) {
combo_st.addItem(cb);
}
}
And finally, like in the previous example, we want to use the last Selection of combobox , so we write the following:
private void bp_valid_indexActionPerformed(java.awt.event.ActionEvent evt) {
class_array stb = new class_array();
HashMap<String,Integer> has = stb.fillCombobox();
int index = has.get(combo_st.getSelectedItem().toString()).toString();
}
I found the solution, and it lies in displaying the content of the combobox with linking it to the number of his id, so that when we work getSelectedItem the value of the combobox is selected with his id

How to get data from an ArrayList <List> in another class?

I'm using RecyclerView I have an Activity that queries my database and I insert this data into that ArrayList , and I want to list that data in another Activity.
This is where I query and add the data to the ArrayList
String queryProduto = "SELECT" +
" Produto_Servico.ID, Produto_Servico.Descricao," +
" Produto_Estoque.EstoqueAtual, ValorVenda" +
" FROM" +
" Produto_Valor" +
" INNER JOIN" +
" Produto_Servico" +
" ON" +
" Produto_Servico.ID = Produto_Valor.ID_Produto" +
" INNER JOIN" +
" Produto_Estoque" +
" ON" +
" Produto_Estoque.ID_Produto = Produto_Servico.ID" +
" WHERE" +
" Produto_Estoque.EstoqueAtual > 0" +
" ORDER BY" +
" Produto_Servico.Descricao";
Statement stmtP = connect.createStatement();
ResultSet rsP = stmtP.executeQuery(queryProduto);
String queryPessoa = "SELECT ID_Pessoa FROM Novo_Pedido";
Statement stmtPS = connect.createStatement();
ResultSet rsPS = stmtPS.executeQuery(queryPessoa);
while (rsPS.next()){
cod = rsPS.getString("ID_Pessoa");
}
if (rsP != null) {
while (rsP.next()) {
id = String.valueOf(rsP.getString("ID"));
desc = rsP.getString("Descricao");
estoque = String.valueOf(rsP.getString("EstoqueAtual"));
valorDec = rsP.getBigDecimal(4);
qtdStr = String.valueOf(qtd);
valorStr = decimalFormat.format(valorDec);
String descFinal = desc;
String qtdFinal = qtdStr;
final BigDecimal[] valorFinal = {valorDec};
try {
listProdutosPedidosFinalizar.add(new ListProdutosPedidosFinalizar(descFinal, qtdFinal, valorFinal[0], BigDecimal.ZERO));
classeLists.setListProdutosPedidosFinalizar(listProdutosPedidosFinalizar);
produtosPedidosAdapter = new ProdutosPedidosAdapter(listProdutosPedidos, this, new ProdutosPedidosAdapter.OnClickListener() {
/*METHODS*/
produtosPedidosAdapter.notifyDataSetChanged();
listProdutosPedidos.add(new ListProdutosPedidos(id, desc, estoque, valorStr, qtdStr));
} catch (Exception ex) {
ex.printStackTrace();
}
rvProdutosPedidos.setAdapter(produtosPedidosAdapter);
produtosPedidosAdapter.notifyDataSetChanged();
isSuccess = true;
}
And now I want to list the listProdutosPedidos data in another Activity.
Define listProdutosPedidos list as static member of your class and then use className.listProdutosPedidos code to access records in it.

Specific query error - SQLite Android

my problem is with very specific query. My SQLite datbase is only 1 table with 11 entries. It creates just fine, but upon execution of this piece of code it crashes. When I change the query to simply:
SELECT * FROM Items
Then it works fine, but I need more narrow results, therefore I modify with the "WHERE" clause. But then it crashes and the application stops. If I comment out the Cursor... it runs fine.
public int findPictureNumber(String itemtitle) {
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = \"" + itemtitle + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
...
}
Where is the error? I can't seem to find it even after narrowing it down to those lines of code.
EDIT:
This is a method for adding an item to a database.
public void newItemFuro () {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
String title = "Furo";
String author = "Fernando Brizio";//í
String category = "Decoracao";//çã
int date = 2012;
String type = "Taca";//ç
String country = "Portugal";
String colour = "Castanho/Cortica";//ç
String material = "Castanho/Cortica";//ç
boolean isFavourite = false;
String imgres = "furoo";
int nr_of_pics = 3;
Item item = new Item(title, author, category, date, type, country, colour, material, isFavourite, imgres, nr_of_pics);
dbHandler.addItem(item);
}
//helper for types
public static final String VARCHAR_TYPE = " VARCHAR(50)";
public static final String BOOL_TYPE = " BOOLEAN";
public static final String INT_TYPE = " INTEGER";
Here it creates the table:
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS +
"("
+ COLUMN_ENTRY_ID + INT_TYPE +" PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_TITLE + VARCHAR_TYPE + ","
+ COLUMN_AUTHOR + VARCHAR_TYPE + ","
+ COLUMN_CATEGORY + VARCHAR_TYPE + ","
+ COLUMN_DATE + INT_TYPE + ","
+ COLUMN_TYPE + VARCHAR_TYPE + ","
+ COLUMN_COUNTRY + VARCHAR_TYPE + ","
+ COLUMN_COLOUR + VARCHAR_TYPE + ","
+ COLUMN_MATERIAL + VARCHAR_TYPE + ","
+ COLUMN_FAVOURITE + BOOL_TYPE + ","
+ COLUMN_IMGRES + VARCHAR_TYPE + ","
+ COLUMN_NUMBER_OF_PICS + INT_TYPE +
")";
db.execSQL(CREATE_ITEMS_TABLE);
}
Adding item:
public void addItem(Item item) {
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, item.getItemTitle());
values.put(COLUMN_AUTHOR, item.getAuthor());
values.put(COLUMN_CATEGORY, item.getCategory());
values.put(COLUMN_DATE, item.getDate());
values.put(COLUMN_TYPE, item.getType());
values.put(COLUMN_COUNTRY, item.getCountry());
values.put(COLUMN_COLOUR, item.getColour());
values.put(COLUMN_MATERIAL, item.getMaterial());
values.put(COLUMN_FAVOURITE, item.getFavourite());
values.put(COLUMN_IMGRES, item.getImgres());
values.put(COLUMN_NUMBER_OF_PICS, item.getNumberOfPics());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_ITEMS, null, values);
db.close();
}
Here full function for searching nr_of_pics:
public int findPictureNumber(String itemtitle) {
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = '" + itemtitle + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
int PicsNumber=0;
if (cursor.moveToFirst()) {
cursor.moveToFirst();
PicsNumber=Integer.parseInt(cursor.getString(0));
cursor.close();
return PicsNumber;
} else {
//wtf?
}
db.close();
return 0;
}
And the errors say as follows:
(1) table Items has no column named imgres
Error inserting colour=Castanho/Cortiça author=Fernando Brízio
imgres=furo category=Decoração title=Furo type=Taça date=2012
nr_of_pics=3 material=Castanho/Cortiça is_favourite=false
country=Portugal
android.database.sqlite.SQLiteException: table Items has no column named imgres (code 1): , while
compiling: INSERT INTO
Items(colour,author,imgres,category,title,type,date,nr_of_pics,material,is_favourite,country)
VALUES (?,?,?,?,?,?,?,?,?,?,?)
You do not give any exception but I think you have error in your SQL. You need to use ' instead of ".
Change your query as below.
String query = "SELECT nr_of_pics FROM Items WHERE ItemTitle = '" + itemtitle + "'";
It is clear that you don't have any column that named "imgres"!
You should modify your query
"INSERT INTO Items(colour,author,imgres,category,title,type,date,nr_of_pics,material,is_favourite,country)
VALUES (?,?,?,?,?,?,?,?,?,?,?)"

If + try - catch in method not working properly

I'm working on an SQLite based app. Everything is working fine, except my if-else statements in my method. The saving and stuff works, just the checking is giving me a pretty high blood pressure. I'm hoping one of you is much smarter than i am and finds the probably obvious mistake i made:
public void save() {
// get length of EditText
int dateLength, mileageLength, amountLength, lpriceLength, tpriceLength;
dateLength = date_widget.getText().length();
mileageLength = mileage_widget.getText().length();
amountLength = amount_widget.getText().length();
lpriceLength = price_widget.getText().length();
tpriceLength = totalPrice_widget.getText().length();
// Start save method if EditTexts are not empty.
if (dateLength > 0 || mileageLength > 0 || amountLength > 0
|| lpriceLength > 0 || tpriceLength > 0) {
// Get the value of each EditText and write it into the
// String/doubles
String date = date_widget.getText().toString();
double mileage = Double
.valueOf(mileage_widget.getText().toString());
double amount = Double.valueOf(amount_widget.getText().toString());
double lprice = Double.valueOf(price_widget.getText().toString());
double tprice = Double.valueOf(totalPrice_widget.getText()
.toString());
// Check if mileage is increasing, else cancel and show toast
int checkMileage = Integer.parseInt(db
.getSearchResult("mileage", 0));
if (checkMileage < mileage) {
try {
// if (id == null) {
db.insert(date, mileage, amount, lprice, tprice);
Toast.makeText(this, R.string.action_input_saved,
Toast.LENGTH_SHORT).show();
finish();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "ERROR " + e, Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(
this,
"Your current mileage must be more than the last saved mileage",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "finish your input", Toast.LENGTH_LONG).show();
}
}
My Method in the DbAdapter class:
public String getSearchResult(String sql, int cmd) {
if (cmd == 0) {
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
cursor.moveToFirst();
String tmp = cursor.getString(0);
cursor.close();
// return count
return tmp;
} else if (cmd == 1) {
int sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
for (int i = 0; i < maxId; i++) {
int tmp = Integer.parseInt(cursor.getString(0));
sum = sum + tmp;
cursor.moveToNext();
}
cursor.close();
id.close();
return String.valueOf(sum);
} else if (cmd == 2 && sql == "mileage") {
int sum = 0;
String countQuery = "SELECT " + sql + " FROM " + TABLE_NAME;
String idQuery = "SELECT _id FROM " + TABLE_NAME
+ " WHERE _id = (SELECT max(_id) FROM " + TABLE_NAME + ")";
Cursor cursor = db.rawQuery(countQuery, null);
Cursor id = db.rawQuery(idQuery, null);
// berechnung
cursor.moveToFirst();
id.moveToFirst();
int maxId = Integer.parseInt(id.getString(0));
if (maxId > 1) {
int array[] = new int[maxId];
// Array füllen
for (int i = 0; i < maxId; i++) {
array[i] = Integer.parseInt(cursor.getString(0));
// sum = sum + tmp;
cursor.moveToNext();
}
for (int k = 1; k < maxId; k++) {
int tmp;
tmp = array[k] - array[k - 1];
sum = sum + tmp;
}
cursor.close();
id.close();
return String.valueOf(sum);
} else {
return "--";
}
}
return "Wrong CMD";
}
I is pretty messy, i know
Turning comment into an answer:
Switch all || to && in your first if. Otherwise you will try to process everything even if only one field is filled in.

Contacts photo is not displayed in Android?

Hi
I have a problem in displaying the contacts image in android.
Following is the code snippet I have used,
public String getCallersInfo(ContentResolver cnt,String phoneNumber)
{
mContentResolver = cnt;
lNumber = phoneNumber;
System.out.println("Start test");
Cursor l_Cur = mContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.NUMBER +" = ?",
new String[]{lNumber }, null);
while (l_Cur.moveToNext())
{
cid = l_Cur.getString(l_Cur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
}
System.out.println("The contact ID for person with phone number "+ lNumber + " is " + cid);
if(!(cid.equals("Unknown")))
{
Cursor cursor_contacts = mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
null,
ContactsContract.Contacts._ID + " = ?",
new String[]{cid },
null);
while(cursor_contacts.moveToNext())
{
displayname = cursor_contacts.getString(cursor_contacts.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
photoid = cursor_contacts.getString(cursor_contacts.getColumnIndex(
ContactsContract.Contacts.PHOTO_ID));
}
System.out.println("The display name & photo id for person with phone number "
+ lNumber + " is " + displayname + " & " + photoid);
Uri contactPhotoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Integer.parseInt(cid));
// Uri photoUri = Uri.withAppendedPath(contactPhotoUri, Contacts.Photo.CONTENT_DIRECTORY);
// contactPhotoUri --> content://com.android.contacts/contacts/1557
InputStream photoDataStream = Contacts.openContactPhotoInputStream(mContentResolver,contactPhotoUri); // <-- always null
if(photoDataStream == null)
{
System.out.println("No photo available ");
}
Bitmap bt = BitmapFactory.decodeStream(photoDataStream);
setmPhoto(bt);
}
return displayname;
}
Thanks in advance.
for the display image contact according to me u just do that i saw..
copy ur .png images res/drawable/a_1;
and write this where u want to see this image..
View v1=findViewById(R.drawable.a_1);

Categories

Resources