I am saving the patient details in the sqlite database. Patient details includes BP,sugar, creatinin, date, time of admission. Regarding BP I am storing Systolic and Diastolic values in the database. I want to show the values and date entered by the user in the graph. I am trying to show the date in x axis which is stored in the database. But I am not getting the date on x-axis.
ViewBloodPressureActivity.java
public class ViewBloodPressureActivity extends Activity {
SQLiteDatabase db;
String pName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_blood_pressure);
Intent intent = getIntent();
final String action = intent.getAction();
String gName = intent.getExtras().getString("GroupName");
pName = intent.getExtras().getString("PatientName");
Cursor cursor = null;
TextView tvPatientName = (TextView) this.findViewById(R.id.textViewPatientNameViewBP);
TextView tvDate = (TextView) this.findViewById(R.id.textViewPatientBPDate);
TextView tvTime = (TextView) this.findViewById(R.id.textViewPatientBPTime);
TextView tvSystolic = (TextView) this.findViewById(R.id.textViewPatientBPSystolic);
TextView tvDiastolic = (TextView) this.findViewById(R.id.textViewPatientBPDiastolic);
TextView tvNumOfRecords = (TextView) this.findViewById(R.id.textViewPatientBPNumOfRecords);
Button back = (Button) this.findViewById(R.id.buttonPatientBPBack);
Button trend = (Button) this.findViewById(R.id.buttonPatientBPTrend);
tvPatientName.setText(pName);
openPatientBPDatabase();
cursor = db.rawQuery("SELECT * FROM PatntBP WHERE PatientName = '"+pName+"';", null);
int rows = cursor.getCount();
tvNumOfRecords.setText(" "+rows+" for this patient");
switch (rows) {
case 0:Toast.makeText(getApplicationContext(), "No records in Database", Toast.LENGTH_LONG).show();break;
case 1: { cursor.moveToFirst();
tvDate.setText(cursor.getString(cursor.getColumnIndex("date")));
tvTime.setText(cursor.getString(cursor.getColumnIndex("time")));
tvSystolic.setText(cursor.getString(cursor.getColumnIndex("systolic")));
tvDiastolic.setText(cursor.getString(cursor.getColumnIndex("diastolic")));
break;
}
default : {
Log.v("BPDB", "There are :"+cursor.getCount()+" records.");
cursor.moveToLast();
tvDate.setText(cursor.getString(cursor.getColumnIndex("date")));
tvTime.setText(cursor.getString(cursor.getColumnIndex("time")));
tvSystolic.setText(cursor.getString(cursor.getColumnIndex("systolic")));
tvDiastolic.setText(cursor.getString(cursor.getColumnIndex("diastolic")));
Toast.makeText(getApplicationContext(), "Use Charts to view the Data", Toast.LENGTH_LONG).show();
}
}
closePatientBPDatabase();
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(ViewBloodPressureActivity.this, ListPatientForViewHDActivity.class);
intent.setAction(action);
startActivity(intent);
}
});
trend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(ViewBloodPressureActivity.this, TrendAnalysisForBPActivity.class);
intent.setAction(action);
intent.putExtra("PatientName", pName);
startActivity(intent);
}
});
}
private void closePatientBPDatabase() {
// TODO Auto-generated method stub
db.close();
}
private void openPatientBPDatabase() {
// TODO Auto-generated method stub
db = openOrCreateDatabase("HCDatabase", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS PatntBP (GroupName VARCHAR, PatientName VARCHAR, systolic VARCHAR, diastolic VARCHAR, date VARCHAR, time VARCHAR);");
}
public void lineGraphHandler(View view) {
LineGraph lineGraph = new LineGraph();
Intent lineIntent = lineGraph.getIntent(this);
startActivity(lineIntent);
}
private class LineGraph {
public Intent getIntent(Context context) {
//SQLiteDatabase db = context.openOrCreateDatabase("HCDatabase", 0, null);
// Cursor cursor = db.rawQuery("SELECT * FROM PatntBP", new String[] { pName });
SQLiteDatabase db1 = openOrCreateDatabase("HCDatabase", MODE_PRIVATE, null);
String sqlQuery = "SELECT * FROM PatntBP where PatientName = '"+pName+"';";
Log.v("BP Query", sqlQuery);
Cursor cursor = db1.rawQuery(sqlQuery, null);
int rows = cursor.getCount();
int y[] = new int[rows];
int y1[] = new int[rows];
if (cursor.getCount() > 0) {
cursor.moveToFirst();
int i = 0;
do {
String name = cursor.getString(cursor.getColumnIndex("PatientName"));
String systolic = cursor.getString(cursor.getColumnIndex("systolic"));
String diastolic = cursor.getString(cursor.getColumnIndex("diastolic"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String[] ss = date.split("/");
Log.v("BP Query", "Row : "+name+" "+systolic+" "+diastolic+" "+ss[1]);
y[i] = Integer.parseInt(systolic);
y1[i] = Integer.parseInt(diastolic);
i++;
} while (cursor.moveToNext());
}
db1.close();
int x[] = {1,2,3,4,5,6,7,8,9,10};
int x1[] = {1,2,3,4,5,6,7,8,9,10};
TimeSeries series = new TimeSeries("Systolic");
for (int i = 0; i < y.length; i++) {
series.add(x[i], y[i]);
}
TimeSeries series1 = new TimeSeries("Diastolic");
for (int i = 0; i < y1.length; i++) {
series1.add(x1[i], y1[i]);
}
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
dataset.addSeries(series);
dataset.addSeries(series1);
XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();
XYSeriesRenderer renderer = new XYSeriesRenderer();
renderer.setPointStyle(PointStyle.CIRCLE);
renderer.setColor(Color.RED);
XYSeriesRenderer renderer1 = new XYSeriesRenderer();
renderer1.setPointStyle(PointStyle.DIAMOND);
renderer1.setColor(Color.BLUE);
mRenderer.setChartTitle("Blood Pressure Variation");
mRenderer.addSeriesRenderer(renderer);
mRenderer.addSeriesRenderer(renderer1);
mRenderer.setYAxisMax(200);
mRenderer.setYAxisMin(40);
Intent intent = ChartFactory.getTimeChartIntent(context, dataset, mRenderer, "Blood Pressure Graph");
return intent;
}
}
}
EnterBloodPressureActivity.java
public class EnterBloodPressureActivity extends Activity {
SQLiteDatabase db;
Date date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_blood_pressure);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Date date = new Date();
String dateStringAndTime = sdf.format(date);
String dateAndTime[] = dateStringAndTime.split(" ");
String dateString = dateAndTime[0];
String timeString = dateAndTime[1];
final EditText etSystolic = (EditText) this.findViewById(R.id.editTextSystolic);
final EditText etDiastolic = (EditText) this.findViewById(R.id.editTextDiastolic);
final EditText etDate = (EditText) this.findViewById(R.id.editTextBPDate);
etDate.setText(dateString);
final EditText etTime = (EditText) this.findViewById(R.id.editTextBPTime);
etTime.setText(timeString);
TextView patientName = (TextView) this.findViewById(R.id.textViewEnterBPDataPatientName);
Intent intent = getIntent();
final String action = intent.getAction();
patientName.setText(intent.getExtras().getString("PatientName"));
Button save = (Button) this.findViewById(R.id.buttonBPDataSave);
Button reset = (Button) this.findViewById(R.id.buttonBPDataReset);
Button back = (Button) this.findViewById(R.id.buttonBPDataBack);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openPatientBPDatabase();
//get GroupName and PatientName
Intent intent = getIntent();
String gName = intent.getExtras().getString("GroupName");
String pName = intent.getExtras().getString("PatientName");
// ensure input data is not null
String systolic = etSystolic.getText().toString();
String diastolic = etDiastolic.getText().toString();
String date = etDate.getText().toString();
String time = etTime.getText().toString();
if (!systolic.equals("") && !diastolic.equals("") && !date.equals("") && !time.equals("")) {
String sqlStmt = "INSERT INTO PatntBP VALUES('"+gName+"', '"+pName+"', '"+systolic+"', '"+diastolic+"', '"+date+"', '"+time+"');";
Log.v("BP DEBUG", sqlStmt);
db.execSQL(sqlStmt);
closePatientBPDatabase();
Intent intent1 = new Intent(EnterBloodPressureActivity.this, ListPatientForEnterHDActivity.class);
intent1.setAction(action);
Toast.makeText(getApplicationContext(), "Data successfully entered", Toast.LENGTH_LONG).show();
startActivity(intent1);
} else {
Toast.makeText(getApplicationContext(), "No blank values allowed", Toast.LENGTH_LONG).show();
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
etSystolic.setText("");
etDiastolic.setText("");
etDate.setText("");
etTime.setText("");
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(EnterBloodPressureActivity.this, ListPatientForEnterHDActivity.class);
intent.setAction(action);
startActivity(intent);
}
});
}
protected void closePatientBPDatabase() {
// TODO Auto-generated method stub
db.close();
}
protected void openPatientBPDatabase() {
// TODO Auto-generated method stub
db = openOrCreateDatabase("HCDatabase", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS PatntBP (GroupName VARCHAR, PatientName VARCHAR, systolic VARCHAR, diastolic VARCHAR, date VARCHAR, time VARCHAR);");
}
}
Related
I am using sqlitedatabase,and i am able to insert data properly,but issue is when i am trying to display inserted data,my app got crash and giving nullpointer exception,can any one tell the what is the issue with my code,following is my snippet code,
Error in this line
if (c1 != null & c1.getCount() != 0) {
MAinActivity.java
public class MainActivity extends Activity {
private ListView upcominglist;
private ListView todays;
private ListView eventhistory;
private ImageView addnewevent;
public ArrayList<ContactListItems> contactList;
public ContactListItems contactListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
upcominglist=(ListView)findViewById(R.id.listview_upcoming);
todays=(ListView)findViewById(R.id.listview_todays);
eventhistory=(ListView)findViewById(R.id.listview_eventhistory);
addnewevent=(ImageView)findViewById(R.id.addneweventbutton);
addnewevent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddNewEvent.class);
startActivity(intent);
}
});
contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
else
{
c1.close();
}
c1.close();
String first=contactListItems.getSlno();
System.out.println("First" + first);
String second=contactListItems.getNameofevent();
System.out.println("SEcond"+second);
String third=contactListItems.getDtofevent();
System.out.println("Third"+third);
String fourth=contactListItems.getTimeofevent();
System.out.println("Fourth"+fourth);
String fifth=contactListItems.getDuration();
System.out.println("Fifth"+fifth);
}
Addnewevent.java
public class AddNewEvent extends Activity {
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
static final int TIME_PICKER_ID = 11111;
int flag = 0;
private ImageView addnewdata;
private LinearLayout lnr;
private Button submit;
private EditText edtnmofevent;
private EditText edtdtofevent;
private EditText edttmofevent;
private EditText edtdurationofevent;
SqlHandler sqlHandler;
private ImageView datepicks;
private ImageView timepicks;
private Calendar cal;
private int hour;
private int min;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_new_event);
sqlHandler = new SqlHandler(getApplicationContext());
addnewdata = (ImageView) findViewById(R.id.addnewdata);
submit = (Button) findViewById(R.id.btnsubmit);
edtnmofevent = (EditText) findViewById(R.id.edtnameofevent);
edtdtofevent = (EditText) findViewById(R.id.edtdateofevent);
edttmofevent = (EditText) findViewById(R.id.edttimeofevent);
edtdurationofevent = (EditText) findViewById(R.id.edtdurationofevent);
datepicks = (ImageView) findViewById(R.id.calndrdat);
timepicks = (ImageView) findViewById(R.id.timepickrs);
cal = Calendar.getInstance();
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
timepicks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(TIME_PICKER_ID);
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
StringBuilder dateValue1 = new StringBuilder().append(day).append("-").append(month + 1).append("-")
.append(year).append(" ");
// for Converting Correct Date format Save into Database
SimpleDateFormat sdf123 = new SimpleDateFormat("dd-MM-yyyy");
String abs1 = dateValue1.toString();
Date testDate1 = null;
try {
try {
testDate1 = sdf123.parse(abs1);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MM-yyyy");
String DateFormat = formatter1.format(testDate1);
edtdtofevent.setText(DateFormat);
edtdtofevent.setFocusable(false);
edtdtofevent.setInputType(InputType.TYPE_NULL);
datepicks.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_PICKER_ID);
}
});
addnewdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater li = LayoutInflater.from(AddNewEvent.this);
View promptsView = li.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
AddNewEvent.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
lnr = (LinearLayout) findViewById(R.id.addnewlinear);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(25, 0, 0, 0);
TextView valueTV = new TextView(AddNewEvent.this);
// valueTV.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
valueTV.setText(userInput.getText());
valueTV.setLayoutParams(lp);
valueTV.setTextSize(18);
valueTV.setTextColor(Color.parseColor("#2d6cae"));
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp1.setMargins(25, 0, 25, 0);
lp1.height = 50;
EditText edtvalues = new EditText(AddNewEvent.this);
edtvalues.setBackgroundResource(R.drawable.rect_edt);
edtvalues.setLayoutParams(lp1);
lnr.addView(valueTV);
lnr.addView(edtvalues);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AddNewEvent.this, EventDetails.class);
startActivity(intent);
String nameofevent = edtnmofevent.getText().toString();
String dtofevent = edtdtofevent.getText().toString();
String timeofevent = edttmofevent.getText().toString();
String duration = edtdurationofevent.getText().toString();
String query = "INSERT INTO PHONE_CONTACTS(nameofevent,dtofevent,timeofevent,duration) values ('"
+ nameofevent + "','" + dtofevent + "','" + timeofevent + "','" + duration + "')";
sqlHandler.executeQuery(query);
System.out.println("Querys" + query);
}
});
}
SQL
public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "PHONE_CONTACTS";
public static final String COLUMN1 = "slno";
public static final String COLUMN2 = "nameofevent";
public static final String COLUMN3 = "dtofevent";
public static final String COLUMN4 = "timeofevent";
public static final String COLUMN5 = "duration";
/* public static final String COLUMN6 = "dlabl";
public static final String COLUMN7 = "dedt";*/
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ DATABASE_TABLE + " (" + COLUMN1
+ " integer primary key autoincrement, " + COLUMN2
+ " text not null, " + COLUMN3 + " text not null, " + COLUMN4 + " text not null, " + COLUMN5 + " text not null);";
public SqlDbHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
The problem is in your SqlHandler.selectQuery() that returns a null, and another problem here checking the result:
if (c1 != null & c1.getCount() != 0)
You're using bitwise and & and not the short-circuiting logical and &&. Without short circuiting the complete expression including c1.getCount() on a null reference is evaluated.
There is too much here to explain it all, so I will give you the flaws causing a null pointer exception.
I can see your method of programming is coming from worrying too much about closing things and clearing up
resources to a point, it's causing problems.
contactList = new ArrayList<ContactListItems>();
// You are clearing your list, it should be empty, you have just created it.
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
// As mentioned by the other answer. You need && not &
// if (c1 != null & c1.getCount() != 0) {
if (c1 != null && c1.getCount() != 0) {
// Move to the first entry.
c1.moveToFirst();
//if (c1.moveToNext()) {
// do {
// Continue while it has not passed the last entry.
while (!cursor.isAfterLast())
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1.getColumnIndex("slno")));
contactListItems.setNameofevent(c1.getString(c1.getColumnIndex("nameofevent")));
contactListItems.setDtofevent(c1.getString(c1.getColumnIndex("dtofevent")));
contactListItems.setTimeofevent(c1.getString(c1.getColumnIndex("timeofevent")));
contactListItems.setDuration(c1.getString(c1.getColumnIndex("duration")));
contactList.add(contactListItems);
// Move the cursor along to the next entry.
cursor.moveToNext();
}
}
// Close cursor after while and within if (so you know it is not null).
c1.close();
}
else
{
// You can't close c1 if it is Null. This will throw and error. Lose the else.
c1.close();
}
// Move this to within your if statment.
c1.close();
From your code you provided in the chat.
Don't open and close your database continuously, just close each cursor you use when you're done. Just open it at the beginning and end of your program run.
public static Cursor selectQuery(String query) {
Cursor c1 = null;
try {
if (sqlDatabase.isOpen()) {
// You are closing the database.
sqlDatabase.close();
}
sqlDatabase = dbHelper.getWritableDatabase();
c1 = sqlDatabase.rawQuery(query, null);
} catch (Exception e) {
System.out.println("DATABASE ERROR " + e);
}
return c1;
}
There are many other flaws in your project. Like the structure and how and when you are calling things. You need to modularise it out, create methods for particular tasks and call those methods, rather than have a great lump of code in oncreate.
I am sure you will have many questions about this. But currently this question is addressing your null pointer exception and that is all I will discuss here. For questions about this not relating to this exception, please ask a new question. Hope this helps.
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");
}
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
My listView works well when only 1 item added to the listview at one time. But when multiple item is added, listener in listview is not wokring. Can anyone guide me what i am doing wrong here? Thanks.
Here is my listView code:
public class Participant extends ListFragment implements OnClickListener{
Intent intent;
TextView friendId;
Button addparticipant;
String eventId;
ListView lv;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> friendList = controller
.getAllFriends(queryValues);
if (friendList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
friendId = (TextView) view.findViewById(R.id.friendId);
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EventPage.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
friendId = (TextView) arg1.findViewById(R.id.friendId);
registerForContextMenu(getListView());
return false;
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
friendList, R.layout.view_friend_entry, new String[] {
"friendId", "friendName", "friendSpending" },
new int[] { R.id.friendId, R.id.friendName,
R.id.friendSpending });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.participant, container, false);
addparticipant = (Button) rootView.findViewById(R.id.addpart);
addparticipant.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(),
AddParticipant.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
EventController controller = new EventController(getActivity());
switch (menuItemIndex) {
case 0:
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditParticipant.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
break;
case 1:
String valFriendId2 = friendId.getText().toString();
controller.deleteFriend(valFriendId2);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(UpdateReceiver.NEW_UPDATE_BROADCAST);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
getActivity().sendBroadcast(broadcastIntent);
onResume();
}
return true;
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllFriends(queryValues),
R.layout.view_friend_entry, new String[] { "friendId",
"friendName", "friendSpending" }, new int[] {
R.id.friendId, R.id.friendName, R.id.friendSpending });
setListAdapter(adapter);
}
Here i add item to listView:
public class AddParticipant extends Activity implements OnClickListener {
private static final int REQUEST_CODE_PICK_CONTACTS = 1;
private static final String TAG = AddParticipant.class.getSimpleName();
private Uri uriContact;
private String contactID;
EditText friendName;
EditText friendNumber;
EditText friendEmail;
EventController controller = new EventController(this);
Button btnadd;
Button addcontact;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addparticipant);
friendName = (EditText) findViewById(R.id.friendName);
friendNumber = (EditText) findViewById(R.id.friendNumber);
friendEmail = (EditText) findViewById(R.id.friendEmail);
btnadd = (Button) findViewById(R.id.saveButton);
btnadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getIntent();
String eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
queryValues.put("friendName", friendName.getText().toString());
queryValues.put("friendNumber", friendNumber.getText()
.toString());
queryValues
.put("friendEmail", friendEmail.getText().toString());
controller.insertFriend(queryValues);
callHomeActivity(v);
finish();
}
});
addcontact = (Button) findViewById(R.id.fromcontact);
addcontact.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI),
REQUEST_CODE_PICK_CONTACTS);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_PICK_CONTACTS
&& resultCode == RESULT_OK) {
Log.d(TAG, "Response: " + data.toString());
uriContact = data.getData();
retrieveContactName();
retrieveContactNumber();
retrieveContactEmail();
}
}
private void retrieveContactNumber() {
String contactNumber = null;
// getting contacts ID
Cursor cursorID = getContentResolver().query(uriContact,
new String[] { ContactsContract.Contacts._ID }, null, null,
null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID
.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.d(TAG, "Contact ID: " + contactID);
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND "
+ ContactsContract.CommonDataKinds.Phone.TYPE + " = "
+ ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[] { contactID }, null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone
.getString(cursorPhone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
cursorPhone.close();
Log.d(TAG, "Contact Phone Number: " + contactNumber);
friendNumber.setText(contactNumber);
}
private void retrieveContactName() {
String contactName = null;
// querying contact data store
Cursor cursor = getContentResolver().query(uriContact, null, null,
null, null);
if (cursor.moveToFirst()) {
// DISPLAY_NAME = The display name for the contact.
// HAS_PHONE_NUMBER = An indicator of whether this contact has at
// least one phone number.
contactName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
cursor.close();
Log.d(TAG, "Contact Name: " + contactName);
friendName.setText(contactName);
}
private void retrieveContactEmail() {
ContentResolver contactResolver = this.getContentResolver();
Cursor emailCursor = contactResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[] { contactID }, null);
while (emailCursor.moveToNext()) {
String phone = emailCursor
.getString(emailCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int type = emailCursor
.getInt(emailCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
String s = (String) ContactsContract.CommonDataKinds.Email
.getTypeLabel(this.getResources(), type, "");
Log.d("TAG", s + " email: " + phone);
friendEmail.setText(phone);
}
emailCursor.close();
}
public void callHomeActivity(View view) {
super.onResume();
}
You have write custom adapter for multiple items
http://www.javacodegeeks.com/2013/09/android-listview-with-adapter-example.html
In my application I use SimpleCursorAdapter. If CheckBox.isChecked() then text should be strikethrough. But why then the first line is always crossed out, even if the CheckBox is not checked
public class MainActivity extends Activity {
// Button btnCalendar;
//*******************************************8
String[] names = {"Иван", "Марья", "Петр", "Антон", "Даша", "Борис",
"Костя", "Игорь", "Анна", "Денис", "Андрей"};
//Button buttonAddTask;
final String Tag="States";
final String Ten = "Ten";
TextView txtDataTaskToday;
String id_for_listtsk_today;
ListView lvMain_today;
String[] arr_date;
SharedPreferences sPref;
static Cursor c;
private ListView listView = null;
SQLiteDatabase db;
//public static String id_for_listtsk_today;
// static SQLiteDatabase db;
MySqlCursorAdapter adapter = null;
//***********************************************8
#Override
protected void onCreate(Bundle savedInstanceState) {
if (getIntent().getBooleanExtra("finish", false)) finish();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// btnCalendar = (Button) findViewById(R.id.btnActTwo);
// btnCalendar.setOnClickListener(this);
//*********************************************
// переменные для query
String[] columns = null;
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
//*********работа с БД****************
// создаем объект для данных
txtDataTaskToday = (TextView) findViewById(R.id.txtDataTaskToday);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String id_for_listtsk_today = sdf.format(new Date());
//final String b = id_for_listtsk_today;
txtDataTaskToday.setText("Today: "+id_for_listtsk_today.toString());
// txtDataTaskToday.setPaintFlags(txtDataTaskToday.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Log.d(Tag, "id_for_listtsk_today ="+id_for_listtsk_today );
ContentValues cv = new ContentValues();
DBHelper dbHelper = new DBHelper(this);
final SQLiteDatabase db = dbHelper.getWritableDatabase();
columns = new String[] {"name"};
selection = "data_id = ?";
selectionArgs = new String[] {id_for_listtsk_today};
//c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
try {
c=dbHelper.getCursor(id_for_listtsk_today);
} catch (SQLException sqle) {
Log.d(Tag, "неудача");
throw sqle;
}
String[] arr_date = logCursor(c);
//*********работа с БД****************
lvMain_today = (ListView) findViewById(R.id.list);
// lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//this.listView=getl
//listView = MainActivity.this.getlgetListView();
lvMain_today.setItemsCanFocus(false);
lvMain_today.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//ArrayAdapter<String> adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_multiple_choice, arr_date);// R.layout.item, my_list_item
startManagingCursor(c);
int[] listFields = new int[] { R.id.txtTitle, R.id.txtDataTaskToday };
String[] dbColumns = new String[] { DBHelper.COLUMN_NAME, DBHelper.COLUMN_TASK };
Log.d(Tag, "трассировка" );
MainActivity.this.adapter = new MySqlCursorAdapter(
this, R.layout.my_list_item,
c, dbColumns, listFields,
dbHelper);
//
lvMain_today.setAdapter(MainActivity.this.adapter);
// setListAdapter(MainActivity.this.adapter);
names = arr_date;
//c.close();
//db.close();
//dbHelper.close();
lvMain_today.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView txtView = (TextView) findViewById(R.id.txtTitle);
txtView.setText("blah blah blah");
Log.d(Tag, "position="+position);
// ((TextView) txtDataTaskToday).setTextColor(android.R.color.white);
SparseBooleanArray chosen = ((ListView) parent).getCheckedItemPositions();
for (int i = 0; i < chosen.size(); i++) {
int key = chosen.keyAt(i);
if (chosen.get(key))
Log.d(Tag, "выделены ====="+names[key]);
Log.d(Tag, "itemClick: position = " + position + ", id = "
+ id);}
//****************nen пробная фигня**************
// String[] columns = null;
// String selection = null;
// String[] selectionArgs = null;
// String groupBy = null;
// String having = null;
// String orderBy = null;
// columns = new String[] {"name"};
// selection = "data_id = ?";
// selectionArgs = new String[] {id_for_listtsk_today};//id_for_listtsk_today
// Cursor c = db.query("mytable", columns, selection, selectionArgs, null, null, null);
// String[] arr = logCursor(c);
//**************************************************
// String s=test();
}
});
// lvMain_today.setOnItemSelectedListener(new OnItemSelectedListener() {
// public void onItemSelected(AdapterView<?> parent, View view,
// int position, long id) {
// Log.d(Tag, "Было выделение позиции меню!!!!position = " + position + ", id = "
// + id);
// }
//
// public void onNothingSelected(AdapterView<?> parent) {
// Log.d(Tag, "itemSelect: nothing");
// }
// });
}
private String[] logCursor(Cursor c) {
// TODO Auto-generated method stub
final String Tag="States";
String[] arr_date = new String[c.getCount()];//String[] arr_date = new String[] {};
Log.d(Tag,"мы в курсоре");
if (c!=null) {
if (c.moveToFirst()) {
// Log.d(Tag,"мы в курсоре1");
String str;
int i=-1;
do {
// Log.d(Tag,"мы в курсоре2");
str="";
i=i+1;
for (String cn: c.getColumnNames()) {
str = str.concat(c.getString(c.getColumnIndex(cn)));
}
Log.d(Tag, "++++"+str);
arr_date[i]=String.valueOf(str);
} while (c.moveToNext());
}
}
return arr_date;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add(0, 1, 0, "календарь");
menu.add(0, 2, 0, "Убрать выполненные");
menu.add(0, 3, 3, "Уйти");
// menu.add(1, 4, 1, "copy");
// menu.add(1, 5, 2, "paste");
// menu.add(1, 6, 4, "exit");
return super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.main, menu);
//return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
// Выведем в TextView информацию о нажатом пункте меню
// txtDataTaskToday.setText("Item Menu");
// txtDataTaskToday.setText(item.getGroupId());
txtDataTaskToday.setText("\r\n itemId: " + String.valueOf(item.getItemId()));
// txtDataTaskToday.setText("\r\n order: " + String.valueOf(item.getOrder()));
// txtDataTaskToday.setText("\r\n title: " + item.getTitle());
switch (item.getItemId()) {
case 1:
Intent intent = new Intent(this, ToDoCalendarActivity.class);
startActivity(intent);
onDestroy();
break;
case 2:
SparseBooleanArray sbArray = lvMain_today.getCheckedItemPositions();
for (int i = 0; i < sbArray.size(); i++) {
int key = sbArray.keyAt(i);
if (sbArray.get(key))
Log.d(Tag, "выделены "+names[key]);
sPref = getPreferences(MODE_PRIVATE);
Editor ed = sPref.edit();
ed.putString(Ten, "1");
ed.commit();
Log.d(Tag, "ставим константу для скрытия");
}
break;
case 3:
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(Ten, "");
Log.d(Tag, "ten= "+ savedText);
onDestroy();
//finish();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
try {
MainActivity.this.onRestart();
} catch (Exception e) {
Log.d(Tag, "не получилось рестартануть");
}
Log.d(Tag, "MainActivity: onStart()");
}
#Override
protected void onResume() {
super.onResume();
Log.d(Tag, "MainActivity: onResume()");
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
// ToDoCalendarActivity.this.finish();
Log.d(Tag, "MainActivity: onDestroy()");
finish();
// db.close();
}
#Override
protected void onPause() {
super.onPause();
//this.dbHelper.close();
Log.d(Tag, "MainActivity: onPause()");
}
#Override
protected void onStop() {
super.onStop();
Log.d(Tag, "MainActivity: onStop()");
}
#Override
protected void onRestart() {
super.onRestart();
// new SelectDataTask().execute();
Log.d(Tag, "MainActivity: onRestart()");
}
// #Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// switch (v.getId()) {
// case R.id.btnActTwo:
//
// Intent intent = new Intent(this, ToDoCalendarActivity.class);
// startActivity(intent);
// break;
// }
// }
}
MySqlCursorAdapter
public class MySqlCursorAdapter extends SimpleCursorAdapter implements OnClickListener {
final String Tag="States";
private Context context;
private DBHelper dbHelper;
private Cursor currentCursor;
TextView txtTitle;
TextView txtTitle1;
public MySqlCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, DBHelper dbHelper) {
super(context, layout, c, from, to);
Log.d(Tag, "трассировка1" );
this.currentCursor = c;
this.context = context;
this.dbHelper = dbHelper;
Log.d(Tag, "MySqlCursorAdapter()");
Integer b = c.getCount();
Log.d(Tag, "b="+b);
}
public View getView(int pos, View inView, ViewGroup parent) {
Log.d(Tag, "getView() + posss=" + pos);
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.my_list_item, null);
}
this.currentCursor.moveToPosition(pos);
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(Integer.parseInt(this.currentCursor.getString(this.currentCursor.getColumnIndex(DBHelper.COLUMN_ID))));
Log.d(Tag, "tag="+cBox.getTag().toString());
if (this.currentCursor.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS)) != null
&& Integer.parseInt(this.currentCursor
.getString(this.currentCursor
.getColumnIndex(DBHelper.COLUMN_STATUS))) != 0) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
cBox.setOnClickListener(this);
txtTitle = (TextView) v.findViewById(R.id.txtTitle);
txtTitle1 = (TextView) v.findViewById(R.id.txtDataTaskToday);
txtTitle.setText(this.currentCursor.getString(this.currentCursor.getColumnIndex(DBHelper.COLUMN_NAME)));
txtTitle1.setText(this.currentCursor.getString(this.currentCursor.getColumnIndex(DBHelper.COLUMN_TASK)));
if (cBox.isChecked()) {
Log.d(Tag, " pos=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
return (v);
}
public void ClearSelections() {
Log.d(Tag, "ClearSelections()");
this.dbHelper.clearSelections();
this.currentCursor.requery();
}
#Override
public void onClick(View v) {
if(dbHelper.dbSqlite==null) {
//Log.d(Tag, "00000000000");
SQLiteDatabase db = dbHelper.getWritableDatabase();
//Log.d(Tag, "onClick");
CheckBox cBox = (CheckBox) v;
Integer _id = (Integer) cBox.getTag();
//Integer _id = 4;
//Log.d(Tag, "Integer _id="+_id.toString());
ContentValues values = new ContentValues();
values.put(" status", cBox.isChecked() ? 1 : 0);
try {
db.update("mytable", values, "_id = ?", new String[] { Integer.toString(_id) });
} catch (SQLException sqle) {
// Log.d(Tag, "неудача");
throw sqle;
}
}
txtTitle.setTextColor(Color.BLUE);
}
}
}
I put a flag in textView in functoin getView()
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Why is the first line is always crossed out?
setPaintFlags changes are persistent, so I suspect that your function gets called twice, the first time cBox.setChecked(true) is executed, but the second time cBox.setChecked(false) is executed, so the flags are not reset. Thus:
if (cBox.isChecked())
{
Log.d(Tag, " pos=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else
{
Log.d(Tag, "!pos=" + pos);
txtTitle.setPaintFlags(txtTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
txtTitle1.setPaintFlags(txtTitle.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
}