Android-Null pointer Exception in setText - android

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)

Related

Getting db string in textview

I read out data from a database into a String. Now i want to put this String into a textview to show my data in list. I execute the read method and want to show the return string mit the data. Problem is: Android studio cannot resolve the "symbol" aka dbString.
Databasetostring:
public String databaseToString(){
String dbString = "";
SQLiteDatabase db = getWritableDatabase();
//Every Column and row
String query = "SELECT * FROM " + TABLE_TODO + " WHERE 1";
//Cursor points to a location in your results
//First row point here, second row point here
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
//Extracts first name and adds to string
if(c.getString(c.getColumnIndex("firstName"))!=null){
dbString += c.getString(c.getColumnIndex("firstName"));
c.moveToNext();
/*
* Displaying all other columns
*/
}
}
db.close();
return dbString;
MainActivity:
Button refresh_list;
ToDoDB showDb;
TextView datalist;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
datalist = (TextView)findViewById(R.id.showallData);
refresh_list = (Button)findViewById(R.id. refresh_list);
refresh_list.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view) {
datalist.setText(dbString);
}
});
}

Android-value not able to set in textview

I have a SQLite database add2cart which stores details of products added to cart.I need to display the number of products each user have in their cart,in a text view. crtno is my textview.I want to display the number in textview when each user clicks add2cart button.
code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_dtls);
name = (TextView) findViewById(R.id.txtPr_name);
price = (TextView) findViewById(R.id.txtprice);
specification=(TextView)findViewById(R.id.txtPr_spec);
feature=(TextView)findViewById(R.id.txtPr_feature);
crtno=(TextView)findViewById(R.id.crtno);
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;
Boolean val=false;
int count=crsr.getCount();
Toast.makeText(getApplicationContext(),"count"+count, Toast.LENGTH_LONG).show();
crtno.setText(Integer.toString(count));
// abc=crtno.getText().toString();
if (crtno!=null) {
val=true;
crtno.setText(Integer.toString(count));
}
if (val=false) {
crtno.setText("0");
}
}
}
});
}
}
change condition.(make sure you have done above on click listner crtno = findviewbyId....)
if(count != null && count > 0){
crtno.setText(count+"");
}else{
crtno.setText("0");
}

Android SQLite Database table - Created table.But error log says no such table

I am developing a shopping cart app.But got an error in adding item details to database, on
clicking ADD TO CART button. Error log says there is no such database table.and force me to SHUTTING DOWN VM. Please help me out.
I have two database in this activity.problem is with add2cart table in addcart database
Product_Detail.java
public class Product_Details extends Activity{
TextView name,price,specification,feature
String nme;
SQLiteDatabase mydb;
String pname;
String prprice;
String pspec;
String pfeature;
Button add2cart,by_nw;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_dtls);
image=(ImageView)findViewById(R.id.pr_img);
name = (TextView) findViewById(R.id.txtPr_name);
price = (TextView) findViewById(R.id.txtprice);
specification=(TextView)findViewById(R.id.txtPr_spec);
feature=(TextView)findViewById(R.id.txtPr_feature);
add2cart=(Button)findViewById(R.id.add2cart);
by_nw=(Button)findViewById(R.id.buy_nw);
Intent in = getIntent();
Bundle bn = in.getExtras();
nme = bn.getString("key");
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS add2cart(img BLOB,pnme varchar,prate varchar,pqty varchar,ptotl vachar)");
mydb = Product_Details.this.openOrCreateDatabase("products", MODE_PRIVATE, null);
Cursor cr = mydb.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
String nm=name.getText().toString();
String rate=price.getText().toString();
mydb.execSQL("INSERT INTO add2cart VALUES('"+nm+"','"+rate+"')");
Toast.makeText(getApplicationContext(),"add to cart",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Product_Details.this,add2cart.class);
startActivity(in);
}
});
by_nw.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent(Product_Details.this,buy_nw.class);
startActivity(in);
}
});
}
}
I opened my addcart database in setOnClickListner and my code worked.
Problem was the place where i opened the addcart database.It consider only the last opened database in Main.
Corrected code
public class Product_Details extends Activity{
TextView name,price,specification,feature;
String nme;
SQLiteDatabase mydb;
String pname;
String prprice;
String pspec;
String pfeature;
Button add2cart,by_nw;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.product_dtls);
image=(ImageView)findViewById(R.id.pr_img);
name = (TextView) findViewById(R.id.txtPr_name);
price = (TextView) findViewById(R.id.txtprice);
specification=(TextView)findViewById(R.id.txtPr_spec);
feature=(TextView)findViewById(R.id.txtPr_feature);
add2cart=(Button)findViewById(R.id.add2cart);
by_nw=(Button)findViewById(R.id.buy_nw);
Intent in = getIntent();
Bundle bn = in.getExtras();
nme = bn.getString("key");
mydb = Product_Details.this.openOrCreateDatabase("products", MODE_PRIVATE, null);
Cursor cr = mydb.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
String nm=name.getText().toString();
String rate=price.getText().toString();
mydb=Product_Details.this.openOrCreateDatabase("addcart", MODE_PRIVATE, null);
mydb.execSQL("INSERT INTO add2cart (pnme,prate)VALUES('"+nm+"','"+rate+"')");
Toast.makeText(getApplicationContext(),"add to cart",Toast.LENGTH_SHORT).show();
Intent in=new Intent(Product_Details.this,add2cart.class);
startActivity(in);
}
});
You use this line mydb = Product_Details.this.openOrCreateDatabase("products", MODE_PRIVATE, null); to reset the mydb,now the mydb is the batabase products

Sqlite data don't show after close the apps

This is my MainActivity.
public class MainActivity extends Activity {
EditText etName, etEmail;
DatabaseHelper dbHelper;
Button save;
// declare view
ListView lvEmployees;
// declare adapter
CustomizedAdapter adapter;
// datasource
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
save = (Button) findViewById(R.id.btnSave);
lvEmployees = (ListView) findViewById(R.id.lvEmployees);
dbHelper = new DatabaseHelper(this);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
save(v);
}
});
}
public void save(View v) {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
Employee employee = new Employee(name, email);
Toast.makeText(getApplicationContext(), employee.toString(),
Toast.LENGTH_LONG).show();
long inserted = dbHelper.insertEmployee(employee);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "Data inserted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Data insertion failed...",
Toast.LENGTH_LONG).show();
}
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
}
}
This is my DataBaseHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "task_management";
public static final int DB_VERSION = 1;
public static final String EMPLOYEE_TABLE = "employee";
public static final String ID_FIELD = "_id";
public static final String NAME_FIELD = "name";
public static final String EMAIL_FIELD = "email";
public static final String EMPLOYEE_TABLE_SQL = "CREATE TABLE "
+ EMPLOYEE_TABLE + " (" + ID_FIELD + " INTEGER PRIMARY KEY, "
+ NAME_FIELD + " TEXT, " + EMAIL_FIELD + " DATETIME);";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create tables
db.execSQL(EMPLOYEE_TABLE_SQL);
Log.e("TABLE CREATE", EMPLOYEE_TABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// upgrade logic
}
// insert
public long insertEmployee(Employee emp) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NAME_FIELD, emp.getName());
values.put(EMAIL_FIELD, emp.getEmail());
long inserted = db.insert(EMPLOYEE_TABLE, null, values);
db.close();
return inserted;
}
// query
public ArrayList<Employee> getAllEmployees() {
ArrayList<Employee> allEmployees = new ArrayList<Employee>();
SQLiteDatabase db = this.getReadableDatabase();
// String[] columns={NAME_FIELD, EMAIL_FIELD, PHONE_FIELD};
// SELECT * FROM EMPLOYEE;
Cursor cursor = db.query(EMPLOYEE_TABLE, null, null, null, null, null,
null);
// Cursor cursor = db.rawQuery("SELECT * FROM EMPLOYEE", null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
//
int id = cursor.getInt(cursor.getColumnIndex(ID_FIELD));
String name = cursor.getString(cursor
.getColumnIndex(NAME_FIELD));
String email = cursor.getString(cursor
.getColumnIndex(EMAIL_FIELD));
Employee e = new Employee(id, name, email);
allEmployees.add(e);
cursor.moveToNext();
}
}
cursor.close();
db.close();
return allEmployees;
}
}
When i put data and pressed the save button then my data is saved and show in my ListView.
But when i close the apps and open it then i don't see any data in my ListView.
After putting data and pressed save button my new and existing data show in my ListView.
So how can i show my existing data in ListView after open my apps and without press the save button.
If you want to show data each time app starts, you would need to move your list populating code in onCreate
Move this code to onCreate instead of Save button's onClick
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
Hope it helps.
P.S: If you need to repopulate list after Save button's click, make a separate function which contains this code. And call tha function in onCreate as well as in Save button's onClick
You are setting the adapter for the list view in your save method that is called only when you actually press the save button. Here's the part where you do it.
ArrayList<Employee> employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
Thats why there is no data in the listview when you open the app.
You should do this in your onCreate method, and in your save you should do something like this:
1. declare the the arraylist of employees along with listview;
ArrayList<Employee> employees;
in your oncreate call this code that you should remove from the save method
employees = dbHelper.getAllEmployees();
if (employees != null && employees.size() > 0) {
adapter = new CustomizedAdapter(this, employees);
lvEmployees.setAdapter(adapter);
}
in save method just add one more item to the list, and notify adapter that there has been a change in the data it's displaying.
employees.add(employee);
adapter.notifyDataSetChanged();

setting view data on new activity

So I have a ListView on which I click to start new Activity called MerchantView.
Between the activities I am passing the uid which is a unique identifier of a merchant.
Im then extracting merchant data from DB and want to view this data in this view.
Everything works (while debugging i can see that data is taken from DB and passed properly to setText methods) but the data does not show, am I doing this right?
public class MerchantView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant);
String desc = "";
String name = "";
Bundle extras = getIntent().getExtras();
String uid = "0";
if(extras !=null) {
uid = extras.getString("uid");
}
// get merchant from database
if(Integer.valueOf(uid) > 0){
Cursor c = Utilities.db.query(mydb.TABLE_MERCHANT,
null,
"uid=?", new String[] {uid}, null, null, null);
if(c.moveToFirst() != false){
name = c.getString(c.getColumnIndex(MerchantsColumns.COLname));
desc = c.getString(c.getColumnIndex(MerchantsColumns.COLdesc));
}
// set values to UI
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
}
else{
}
Button buttonMerchants = (Button) findViewById(R.id.buttonMerchants);
buttonMerchants.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
}
Data was set properly. The problem was in layout. The header (LinearLayout) at the top had two buttons and it was set to android:layout_height="fill_parent" which was taking whole space. After fixing that, data is showing properly.
Try Below code hope it helps
SQLiteDatabase myDB = this.openOrCreateDatabase("databasename.db", SQLiteDatabase.OPEN_READWRITE, null);
try{
Cursor c = myDB.rawQuery("select name, desc from abctable where uid="+uid, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("desc");
// Check if our result was valid.
c.moveToFirst();
if (c != null) {
int i = 0;
// Loop through all Results
do {
i++;
String name = c.getString(Column1);
String desc = c.getString(Column2);
TextView descUI = (TextView) findViewById(R.id.merchantDescription);
descUI.setText(desc);
TextView nameUI = (TextView) findViewById(R.id.merchantName);
nameUI.setText(name);
} while (c.moveToNext());
}
} catch (SQLiteException e) {
e.printStackTrace();
} finally {
if (myDB != null)
myDB.close();
}

Categories

Resources