How to insert integer and add value in database - android

Hi I would like to ask how can I make it an integer here is my code
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String scoreValue = String.valueOf(scoreEdit);
long val = adapter.insertDetails(scoreValue + 3);
finish();
}
what I'm tryng to make is that everytime I click the button it will get the scoreValue and add 3 in it but when I put a number in the scoreValue like "2" it have "23" not "5" as I want it to be. I know it's about the String but when I change the
String scoreValue = String.valueOf(scoreEdit);
to
IntegerscoreValue = String.valueOf(scoreEdit);
I'm having an error can someone please help me please thanks
EDITED:
new code
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int scoreValue = Integer.parseInt(scoreEdit.getText().toString());
long val = adapter.insertDetails(scoreValue + 3);
finish();
}
taken from
public long insertDetails(int score) {
ContentValues contentValues = new ContentValues();
contentValues.put(openHelper_ob.SCORE, score);
opnToWrite();
long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
contentValues);
Close();
return val;
}

Adding strings together will give you concatenation, but if you want to take the sum of two integers than convert the values to integer do the calculation AND THEN String.valueOf(x) will return the string value of the sum. Where X is the end sum of your result.

Chang to
try
{
int scoreValue = Integer.parseInt(scoreEdit);
}
catch(NumberFormatException ne)
{
ne.printStacktrace();
}
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)

use this, have to get string form EditText first
int scoreValue = Integer.parseInt(scoreEdit.getText().toString());
instead of
String scoreValue = String.valueOf(scoreEdit);

Related

Whats wrong with my query? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Can anyone see any errors in this code? I've checked to make sure the data has been written to the database. Every time I click the button it gives me the "Incorrect Password" text. It's probably something stupid that I'm overlooking. Any help is appreciated.
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
#Override
public void onClick(View v) {
if (passInputStr == rpq) {
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
EDIT:
This is not a duplicate of the referenced question because changing == to equals() did not fix my problem.
EDIT 2:
Thought maybe I should Include the cursor class for regPwdQuery
public Cursor regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor result = uDB.rawQuery(regQuery, null);
return result;
The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true.
The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values).
To compare two strings for equality, use equals( ).
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
#Override
public void onClick(View v) {
if (passInputStr.equals(rpq))
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
your comparisons checks the refferences instead the actual content of the strings. Instead use .equals() to check the value of the String.
if (passInputStr == rpq)
Should be changed to:
if(passInputStr.equals(rpq))
EDIT:
you toString the result you get from the query:
String rpq = regPwdQuery().toString();
if your result only contains the password it might work, but otherwise I don't think it will give the correct result.
Since I don't know how the table UsrPass_table looks like I can only guess but I think something like this has to be implemented:
public String regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor result = uDB.rawQuery(regQuery, null);
String password = "";
while(result.moveToNext()){
password = result.getString(0); //Parameter should match the column from where you get your data, normally 0 is an ID.
}
return password;
Hope it helps.
That essentially means passInputStr != rpq , You could try the .equalsIgnoreCase() method or the .equals() method. That is because you are comparing strings! You can read more about this here
You can not compare Strings in java with == operator. Use equals() method instead:
if (passInputStr.equals(rpq))
Try the
if (passInputStr.equals(rpq))
reference:
What is the difference between == vs equals() in Java?
Here is an example (you can run it):
public final class MyEqualityTest
{
public static void main( String args[] )
{
String s1 = new String( "Test" );
String s2 = new String( "Test" );
System.out.println( "\n1 - PRIMITIVES ");
System.out.println( s1 == s2 ); // false
System.out.println( s1.equals( s2 )); // true
A a1 = new A();
A a2 = new A();
System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
System.out.println( a1 == a2 ); // false
System.out.println( a1.s == a2.s ); // true
System.out.println( a1.s.equals( a2.s ) ); // true
B b1 = new B();
B b2 = new B();
System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
System.out.println( b1 == b2 ); // false
System.out.println( b1.getS() == b2.getS() ); // false
System.out.println( b1.getS().equals( b2.getS() ) ); // true
}
}
final class A
{
// static
public static String s;
A()
{
this.s = new String( "aTest" );
}
}
final class B
{
private String s;
B()
{
this.s = new String( "aTest" );
}
public String getS()
{
return s;
}
}
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
if (passInputStr == rpq) {
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
Try this.. Put rpq and passInputStr in onClick method. also change if condition if (passInputStr.equals(rpq))
Simply, replace:
if (passInputStr == rpq)
with
if (passInputStr.equals(rpq))
Use string.equals(anotherString) method when you want to compare between two different strings.
Edit:
public String regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor cursor = uDB.rawQuery(regQuery, null);
//Modify this
String result = cursor.getString(cursor.getColumnIndex("password"));
return result;

Android-Null pointer Exception in setText

I have a SQLite database to store items in cart. I need to get the count of products in cart corresponding to each user and set it to a textview,each time the user clicks addtocart button.But my code throws an null point exception.please help me.
I am getting nullpointer Exception in line 109: if (!crtno.getText().toString().equals(""))
code
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_dtls);
crtno=(TextView)findViewById(R.id.crtno);
imgbtn=(ImageButton)findViewById(R.id.cartimg);
add2cart=(Button)findViewById(R.id.add2cart);
DataBaseHandler dbh = new DataBaseHandler(this);
SQLiteDatabase db = dbh.getWritableDatabase();
Intent in = getIntent();
Bundle bn = in.getExtras();
Bundle bun=in.getExtras();
final String dtl=bun.getString("key");
nme = bn.getString("name");
Cursor cr = db.rawQuery("SELECT * FROM product WHERE pname = '"+nme+"'", null);
while(cr.moveToNext())
{
String name = cr.getString(cr.getColumnIndex("pname"));
String pr1price = cr.getString(cr.getColumnIndex("pprice"));
String prspc=cr.getString(cr.getColumnIndex("pspec"));
String prfeature=cr.getString(cr.getColumnIndex("pfeature"));
pname = name;
prprice = pr1price;
pspec=prspc;
pfeature=prfeature;
}
name.setText(pname);
price.setText("Rs " +prprice + "/-");
specification.setText(pspec);
feature.setText(pfeature);
add2cart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean incart=false;
String nm=name.getText().toString();
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS add2cart(usr TEXT,img BLOB,pnme TEXT,prate NUMERIC,pqty NUMERIC,ptotl NUMERIC)");
Cursor cur=mydb.rawQuery("select * from add2cart where pnme='"+nm+"' AND usr='"+dtl+"'",null);
if (cur.moveToFirst()){
String prdname=cur.getString(cur.getColumnIndex("pnme"));
if (nm.equals(prdname)){
add2cart.setText("Already in Cart");
incart=true;
}
}
if(incart==false){
mydb.execSQL("INSERT INTO add2cart (usr,pnme,prate)VALUES('"+dtl+"','"+nm+"','"+prprice+"')");
Toast.makeText(getApplicationContext(),"added to cart",Toast.LENGTH_SHORT).show(); Cursor crsr=mydb.rawQuery("select pnme from add2cart where usr='"+dtl+"'", null);
int count=0;
if (!crtno.getText().toString().equals("")) {
count=crsr.getCount();
}
crtno.setText(Integer.toString(count));
}
}
});
}
}
Try like
crtno.getText().toString().equals("")
instead of
crtno.equals("")
Because crtno.getText().toString().equals("") is the command for checking equality of the text inside the textview.
At first you should first pull string displayed in textview and it's done as by:
getText()
Return the text the TextView is displaying.
so your way should be
crtno.getText().toString().equals("")
also try this
crtno.getText().toString().equals(null)

Android check user in Database

First sorry for my poor english :)
I click button but app close automaticly
I want if user exist database , read editttext "exist"
Database activity code:
public Boolean varmi(String KULLANICI) {
// TODO Auto-generated method stub
Cursor c = DB_Database.query(DATABASE_TABLOSU, kolonlar, K_ADI + "=" + KULLANICI, null, null, null, null);
if(c.moveToFirst()){
return true;
}
else{
return null;
}
}
Main activity code:
buttonGiris.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String KULLANICI=editKullanici.getText().toString();
db.dbyiac();
if(db.varmi(KULLANICI) != null){
textBilgiler.setText("User exist");
}
else{textBilgiler.setText("User don't exist");}
db.dbyikapat();
}
String literals in SQL must be in single quotes. Better yet, use ? literal placeholder and argument binding:
Cursor c = DB_Database.query(DATABASE_TABLOSU, kolonlar, K_ADI + "=?", new String[] { KULLANICI }, null, null, null);
cursor.getColumnIndex(String columnName) returns -1 if, the column doesn't exist :) and call this method textBilgiler.setText("User don't exist"); :) kolay gele.

android get count total rows?

I will appreciate if someone help me with this code below:
i'm trying to get total rows in my table: i'm calling from the button but it always crash...
public int countjournals() {
Cursor dataCount = CountryDB.rawQuery("select count(*) from" + TABLE_NAME, null);
dataCount.moveToFirst();
int jcount = dataCount.getInt(0);
dataCount.close();
Toast.makeText(getApplicationContext(),
"Total:", Toast.LENGTH_LONG).show();
return jcount;
}
I have created it method in CountyDB like this:
public static Cursor rawQuery(String string, Object object) {
// TODO Auto-generated method stub
return null;
}
thanks in advance
First you need to either implement your rawQuery() or remove it. What you want is SQLiteDatabase's rawQuery().
Also, you need space between from and table name here:
"select count(*) from" + TABLE_NAME
change to:
"select count(*) from " + TABLE_NAME
Ideally it should work if not....
rawQuery method is returning null every time it seems once check with that
public static Cursor rawQuery(String string, Object object) {
// TODO Auto-generated method stub
return null;
}
private int getCount(){
int count = 0;
String query = "SELECT * FROM "+"Table_Name";
Cursor cursor = CountryDB.rawQuery(query, null);
while(!cursor.isAfterLast()){
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int x = cursor.getInt(0);
Log.e("", "x = "+x);
count++;
cursor.moveToNext();
}
}
cursor.close();
CountryDB.close();
return count;
}
Make sure that database object is not null and your table is created first and column data type is integer . If you are putting string data then use getString(0);
this code is working fine for me.

Android sqlite query multiply with the edit text integers?

protected void cal() {
// TODO Auto-generated method stub
Company obj1 = new Company();
String val1 = obj1.getCompanyID();
edite.getText().toString();
Cursor sumw = dbObject.rawQuery(
"SELECT sum(Volume)FROM SHARE WHERE _id2 LIKE ?",
new String[] { "%" + val1 + "%" });
sumw.moveToFirst();
editT.setText(sumw.getString(0));
}
i want to get the value of the EditText value, to multiply with the selected sum value of the query
Try this,
protected void cal() {
// TODO Auto-generated method stub
Company obj1 = new Company();
String val1 = obj1.getCompanyID();
int n = Integer.parseInt(edite.getText().toString());
Cursor sumw = dbObject.rawQuery(
"SELECT sum(Volume)FROM SHARE WHERE _id2 LIKE ?",
new String[] { "%" + val1 + "%" });
sumw.moveToFirst();
editT.setText(sumw.getString(0)*n);
}
If they're integer values, try this:
int multiplierOne = Integer.parseInt(edite.getText().toString());
....
int multiplierTwo = sumw.getInt(0);
int product = multiplierOne * multiplierTwo;
editT.setText("" + product);

Categories

Resources