I have a java.lang.NullPointer error on the LogCat but I can't figure out why. It seems that the error lay on the second OnClick procedure. Anyone can help me??
package com.example.cinemaodeon;
import com.example.cinemaodeon.Main;
public class Main extends Activity {
private DatabaseHelper DatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
final Toast toast = Toast.makeText(this,
"Il nome utente non è presente!!! registra un nuovo nome utente!",
Toast.LENGTH_LONG);
final Toast toast2 = Toast.makeText(this,
"Il nome utente è già presente!!!Puoi accedere con questo nome utente!",
Toast.LENGTH_LONG);
Button btnGO = (Button) findViewById(R.id.main_btnentra);
btnGO.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
SQLiteDatabase db = DatabaseHelper.getReadableDatabase();
String[] columns = { "_id_user" };
Cursor cursor = db.query("users", columns, null, null, null, null, null);
String[] result = new String[]{};
int count = cursor.getCount();
while (cursor.moveToNext()) {
result[count]=cursor.getString(0);
count=count+1;
}
EditText editusername =(EditText) findViewById(R.id.main_editusername);
final String username = editusername.getText().toString();
for (int i = 0; i < count; i++) {
if (username==result[count]){
Intent openProgrammazione = new Intent(Main.this,Programmazione.class);
startActivity(openProgrammazione);
}
}
toast.show();
}
});
Button btnReg = (Button) findViewById(R.id.main_btnregistra);
btnReg.setOnClickListener(new OnClickListener(){
It seems the error lay over below on tho OnClick procedure,maybe there is some problem with the definition of the databaseHelper
#Override
public void onClick(View arg0) {
SQLiteDatabase db = DatabaseHelper.getReadableDatabase();
String[] columns = { "_id_user" };
Cursor cursor = db.query("users", columns, null, null, null, null, null);
String[] result = new String[]{};
int count = cursor.getCount();
while (cursor.moveToNext()) {
result[count]=cursor.getString(0);
count=count+1;
}
EditText editusername =(EditText) findViewById(R.id.main_editusername_registra);
final String username = editusername.getText().toString();
for (int i = 0; i < count; i++) {
if (username==result[count]){
toast2.show();
}
}
SQLiteDatabase dbW = DatabaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("_id_user", username);
#SuppressWarnings("unused")
long id = dbW.insert("users", null, values);
Intent openProgrammazione = new Intent(Main.this,Programmazione.class);
startActivity(openProgrammazione);
}
});
}
You havn't initialized DatabaseHelper DatabaseHelper.
Try initialising it
eg:DatabaseHelper DatabaseHelper=new DatabaseHelper();
Related
can any one help me to send a code for add update delete in android studio
i have done update but not working properly
public boolean updateInfor(String username, String dob, String password, String gender){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues con = new ContentValues();
con.put(UserProfile.Users.DOB, dob);
con.put(UserProfile.Users.PASSWORD, password);
con.put(UserProfile.Users.GENDER, gender);
String where = UserProfile.Users.USERNAME + " = ?";
String[] wheree = {username};
long r = db.update(UserProfile.Users.TABLE_NAME, con, where, wheree);
if(r == 1)
return false;
else
return true;
}
public void editButton(View view){
DBHelper db = new DBHelper(this);
un = (EditText) findViewById(R.id.editText9);
dob = (EditText) findViewById(R.id.editText10);
pw = (EditText) findViewById(R.id.editText11);
int res = gender.getCheckedRadioButtonId();
String ress = String.valueOf(res);
boolean x = db.updateInfor(un.getText().toString(), dob.getText().toString(), pw.getText().toString(), ress);
if(x == false)
Toast.makeText(this, "Unsuccessfull", Toast.LENGTH_SHORT);
else
Toast.makeText(this, "Successfull", Toast.LENGTH_SHORT);
}
public void delete(View view){
DBHelper db = new DBHelper(this);
un = (EditText) findViewById(R.id.editText9);
db.deleteInfo(un.getText().toString());
}
public void ReadAll(View view){
DBHelper db = new DBHelper(this);
Cursor cursor = db.readAllInfor();
List <String> l1 = new ArrayList<>() ;
while(cursor.moveToNext()){
l1.add(cursor.getString(0));
l1.add(cursor.getString(1));
l1.add(cursor.getString(2));
l1.add(cursor.getString(3));
}
AlertDialog.Builder alert = new AlertDialog.Builder(this);
CharSequence[] ch = l1.toArray(new CharSequence[l1.size()]);
alert.setItems(ch, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alert.show();
}
public void ReadOne(View view){
DBHelper db = new DBHelper(this);
un = (EditText) findViewById(R.id.editText9);
dob = (EditText) findViewById(R.id.editText10);
pw = (EditText) findViewById(R.id.editText11);
Cursor cursor = db.readAllInfor(un.getText().toString());
while(cursor.moveToNext()){
dob.setText(cursor.getString(1));
pw.setText(cursor.getString(2));
}
}
public void deleteInfo(String Username){
SQLiteDatabase db = this.getWritableDatabase();
String where = UserProfile.Users.USERNAME + "=?";
String[] whereeee = {Username};
db.delete(UserProfile.Users.TABLE_NAME,where,whereeee);
}
public Cursor readAllInfor(String username){
SQLiteDatabase db = this.getWritableDatabase();
String[] col = {UserProfile.Users.USERNAME, UserProfile.Users.DOB, UserProfile.Users.PASSWORD, UserProfile.Users.GENDER};
String where = UserProfile.Users.USERNAME + " = ?";
String[] wheree = {username};
Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,
col,
where,
wheree,
null,
null,
null);
return cursor;
}
public boolean updateInfor(String username, String dob, String password, String gender){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues con = new ContentValues();
con.put(UserProfile.Users.DOB, dob);
con.put(UserProfile.Users.PASSWORD, password);
con.put(UserProfile.Users.GENDER, gender);
String where = UserProfile.Users.USERNAME + " = ?";
String[] wheree = {username};
long r = db.update(UserProfile.Users.TABLE_NAME, con, where, wheree);
if(r == 1)
return false;
else
return true;
}
public Cursor readAllInfor(){
SQLiteDatabase db = this.getReadableDatabase();
String[] col = {UserProfile.Users.USERNAME, UserProfile.Users.DOB, UserProfile.Users.PASSWORD, UserProfile.Users.GENDER};
Cursor cursor = db.query(UserProfile.Users.TABLE_NAME,col,null,null, null, null, null);
return cursor;
}
public boolean addInfo(String username, String dob, String password, String gender){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues con = new ContentValues();
con.put(UserProfile.Users.USERNAME, username);
con.put(UserProfile.Users.DOB, dob);
con.put(UserProfile.Users.PASSWORD, password);
con.put(UserProfile.Users.GENDER, gender);
long r = db.insert(UserProfile.Users.TABLE_NAME, null, con);
if(r == 1)
return false;
else
return true;
}
I am trying to use SQLite database to store user Credential data for my Application
Whenever I try to debug my Application I always get these warnings in Debug LOGCAT due to which my app stops running and shuts down
Here are the warnings that I get
10-30 10:59:49.421 5435-5444/? W/SQLiteConnectionPool: A SQLiteConnection
object fordatabase'/data/user/0/com.google.android.gms/databases/metrics.db'
was leaked!
10-30 10:59:49.474 5435-5444/? W/SQLiteConnectionPool: A SQLiteConnection
object for database
'/data/user/0/com.google.android.gms/databases/help_responses.db.18'
Here is my DBHelper class
public class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, "UserCredentials.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table UserInfo (User_Name text,Email text,Password text,Mobile text);");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("drop table if exists UserInfo");
onCreate(sqLiteDatabase);
}
}
Here is my loginform class ( this class is used to sing up with the app)
public class LogInForm extends AppCompatActivity {
private String UserName,EmailID,Password,PhoneNum;
private Date Birth;
private EditText userName,emailID,password,phoneNum,birth;
private Date date;
int Flag ;
DbHelper Db = new DbHelper(getApplicationContext());
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration_form);
Toolbar t2 = (Toolbar) findViewById(R.id.toolbarR) ;
setSupportActionBar(t2);
getSupportActionBar().setDisplayShowTitleEnabled(false);
userName = (EditText) findViewById(R.id.editTextUE);
emailID = (EditText) findViewById(R.id.editTextEE);
password = (EditText) findViewById(R.id.editTextPE);
phoneNum = (EditText) findViewById(R.id.editTextPHE);
birth = (EditText) findViewById(R.id.editTextDE);
Button Register = (Button) findViewById(R.id.Register);
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
initialize();
SQLiteDatabase db = Db.getWritableDatabase();
ContentValues values = new ContentValues();
try{
if(validate())
{
values.put("User_Name", UserName);
values.put("Email", EmailID);
values.put("Password",Password);
values.put("Mobile",PhoneNum);
long row = db.insert("UserInfo", null, values);
Intent next = new Intent(getApplicationContext(),Success.class);
startActivity(next);
}
}
finally {
values.clear();
db.close();
}
}
});
}
public void initialize()
{
Flag=1;
UserName = userName.getText().toString().trim();
EmailID = emailID.getText().toString().trim();
PhoneNum = phoneNum.getText().toString().trim();
Birth = convertToDate(birth.getText().toString().trim());
Password = password.getText().toString().trim();
}
public boolean validate()
{
if(UserName.isEmpty())
{
Flag=0;
userName.setError(" Username cannot be blank");
}
SQLiteDatabase rdb = Db.getReadableDatabase();
Cursor c = rdb.query("UserInfo", null, null, null, null, null, null);
while(c.moveToNext()) {
String value = c.getString(c.getColumnIndex("User_Name"));
if ((value).equals(UserName))
{
Flag=0;
userName.setError(" Username Exists");
}
}
rdb.close();
c.close();
if(EmailID.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(EmailID).matches())
{
emailID.setError("Invalid EmailID");
Flag=0;
}
if(Password.length() < 9 )
{
password.setError("Password must be more than 9 characters");
Flag=0;
}
if(PhoneNum.isEmpty() || phoneNum.length()!=10)
{
phoneNum.setError("please enter valid phone Number");
Flag=0;
}
if(Flag==0)
{
return false;
}
else
{
return true;
}
}
Here is my Main java class (if user has account he logs in through this class)
public class First extends AppCompatActivity {
DbHelper Db = new DbHelper(this);
EditText UserName = (EditText) findViewById(R.id.editText4);
EditText Password = (EditText) findViewById(R.id.editText5);
int Flag = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Toolbar t = (Toolbar) findViewById(R.id.toolbarL) ;
setSupportActionBar(t);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Button RegButton = (Button) findViewById(R.id.RegisterButton);
Button logButton = (Button) findViewById(R.id.LogButton);
RegButton.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
Intent i2 = new Intent(getApplicationContext(), LogInForm.class);
startActivity(i2);
}
});
logButton.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
SQLiteDatabase sq = Db.getReadableDatabase();
Cursor c = sq.query("UserInfo", null, null, null, null, null, null);
while(c.moveToNext())
{
if(c.getString(0).equals(UserName.getText().toString())&& c.getString(2).equals(Password.getText().toString()))
{
Flag = 1;
sq.close();
c.close();
Intent i3 = new Intent(getApplicationContext(), HomeScreen.class);
startActivity(i3);
}
}
if(Flag==0)
{
Toast toast = Toast.makeText(getApplicationContext(),"INVALID UserName/Password",Toast.LENGTH_SHORT);
toast.show();
sq.close();
c.close();
}
}
});
}
}
How do i solve this issue?
In my Android app,i am retreiving phone contacts through cursor. Then i want to add all these contacts in database as follows:
public class SettingsActivity extends Activity {
ToggleButton tb_hide;
ToggleButton tb_unhide;
TextView tv_add_contacts;
TextView tv_restore_contacts;
DbManager manager;
Context context;
String[] privateContacts;
Uri queryUri;
String selectIds = "";
String ContactId[];
String ContactNames[];
String ContactNumbers[];
public static String[] wholContactData;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
try{
context = this;
findView();
queryUri = ContactsContract.Contacts.CONTENT_URI;
//String selected_data = ContactsContract.Contacts.DISPLAY_NAME + " IS NOT NULL";
Cursor Cursor = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
privateContacts=showEvents(Cursor);
wholContactData=new String[privateContacts.length];
tv_add_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addcontacts();
}
});
tv_restore_contacts.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
for(int i=0;i<privateContacts.length;i++){
selectIds = selectIds + " | " + privateContacts[i];
wholContactData[i]=privateContacts[i];
}
try{
addAllContacts(wholContactData);
}
catch(Exception ex)
{
Log.e("ERROR in adding all contacts", ex.toString());
}
Toast.makeText(getApplicationContext(),""+selectIds, 3000).show();
}});
}
catch(Exception ex){
Log.e("Add all contacts ERROR", ex.toString());
}
}
private void addAllContacts(final String[] selectedItems) {
try{
manager.open();
manager.Insert_phone_contact(selectedItems);
manager.close();
}
catch(Exception ex)
{
Log.e("ERROR", ex.toString());
}
}
protected String[] showEvents(Cursor cursor) {
ContactId= new String[cursor.getCount()];
ContactNames = new String[cursor.getCount()];
ContactNumbers = new String[cursor.getCount()];
int i=0;
while (cursor.moveToNext()) {
ContactId[i] = i+"";
ContactNames[i] = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
ContactNumbers[i] = Util.getContactNumber(ContactNames[i], context);
i++;
}
return ContactNames;
}
private void findView() {
TextView tv_hide = (TextView)findViewById(R.id.tv_hide);
TextView tv_hide_desc = (TextView)findViewById(R.id.tv_hide_desc);
tv_add_contacts = (TextView)findViewById(R.id.tv_add_contacts);
TextView tv_add_contacts_desc = (TextView)findViewById(R.id.tv_add_contacts_desc);
tv_restore_contacts = (TextView)findViewById(R.id.Tv_restore_contacts);
TextView tv_restore_contacts_desc = (TextView)findViewById(R.id.tv_restore_contacts_desc);
tb_hide = (ToggleButton)findViewById(R.id.tb_hide);
tb_hide.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
HideUnhideIcon();
}});
}
private void HideUnhideIcon() {
if(tb_hide.isChecked()){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "Your app is hidden now, Dial provided security code to get into discrete app.", 3000).show();
}
else if(tb_hide.isChecked()==false){
PackageManager pm = getPackageManager();
ComponentName com_name = new ComponentName("com.android.discrete.main",
"com.android.discrete.main.SplashScreen");
pm.setComponentEnabledSetting(com_name,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
,
PackageManager.DONT_KILL_APP );
}
}
private void addcontacts() {
final ProgressDialog myPd_ring=ProgressDialog.show(this, "Phone Contacts", "Loading please wait..", true);
myPd_ring.setCancelable(true);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try
{
movetoPrivateContacts();
}catch(Exception e){}
myPd_ring.dismiss();
}
}).start();
}
private void moveToLogActivity() {
Intent i = new Intent(this, LogActivity.class);
startActivity(i);
finish();
}
private void movetoPrivateContacts() {
Intent intent = new Intent(this,privateContacts.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
}
Database code is as follows:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
if (contact[i] !=null){
cv.put(CONTACT_NAME, ""+contact[i]);
DB.insert(TABLE_CONTACTS, null, cv);
}// insert in db
}
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
i want to add all contacts to database when i click "tv_restore_contacts" .But i am getting NullPointerException. I don't know where i am wrong?
logcat Error stack is java.lang.NullPointerException.
Use the following code to grab the contacts & return them to a list datatype to save them whole list in a db or open a DB connection inside the method and do sql insert statements on each contact object you wish to store. N/B The Contacts API is deprecated be sure to use ContactsContract Api.
Private void getDetails(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor names = getContentResolver().query(uri, projection, null, null, null);
int indexName = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = names.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
names.moveToFirst();
do {
String name = names.getString(indexName);
Log.e("Name new:", name);
String number = names.getString(indexNumber);
Log.e("Number new:","::"+number);
} while (names.moveToNext());
}
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);");
}
}
Brief of app: Add contacts / Edit Contacts
-Contato.java //Show a ListView of the contacts, when itemClicked shows a dialog of info(name/telephone) and 3Buttons (Ok/Alter/Delete) the Alter button sends the user to:
-Adicionarcontato.java with the info's to edit, but when I edit and hit the button "Salvar" (save) the error: The application Mensagem(process com.example.mensagem) has stopped unexpectedly. Please try again.
Here is the code of Contato.java of the ListView.
private void ListaContatos(){
ListView user = (ListView) findViewById(R.id.lvShowContatos);
//String = simple value ||| String[] = multiple values/columns
String[] campos = new String[] {"nome", "telefone"};
list = new ArrayList<String>();
c = db.query( "contatos", campos, null, null, null, null, null);
c.moveToFirst();
if(c.getCount() > 0) {
while(true) {
list.add(c.getString(c.getColumnIndex("nome")).toString());
if(!c.moveToNext()) break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
user.setAdapter(adapter);
user.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
reg = position;
c.moveToPosition(reg);
String nome = c.getString(c.getColumnIndex("nome"));
String telefone = c.getString(c.getColumnIndex("telefone"));
ShowMessage(nome, telefone);
}
});
}
And here is the code in the Adicionarcontato.java:
public SQLiteDatabase db;
private String mIndex = "";
private String nomeant,foneant;
static final String userTable = "contatos";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adicionarcontato);
if(getIntent().getExtras() != null) {
if(getIntent().getExtras().containsKey("reg")) mIndex = getIntent().getExtras().getString("reg");
}
db = openOrCreateDatabase("banco.db", Context.MODE_WORLD_WRITEABLE, null);
if(!mIndex.equals("")) {
Cursor c = db.query(false, "contatos", (new String[] {"nome", "telefone"}), null, null, null, null, null, null);
c.moveToPosition(Integer.parseInt(mIndex));
nomeant = c.getString(0);
foneant = c.getString(1);
EditText nome1 = (EditText) findViewById(R.id.etNome);
EditText telefone1 = (EditText) findViewById(R.id.etTelefone);
nome1.setText(nomeant);
telefone1.setText(foneant);
}
AdicionarContato();
ResetarInfo();
}
And the code of the button "Salvar" when clicked:
public void AdicionarContato() {
// TODO Auto-generated method stub
final EditText nm = (EditText) findViewById(R.id.etNome);
final EditText tlf = (EditText) findViewById(R.id.etTelefone);
Button add = (Button) findViewById(R.id.bSalvarContato);
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final String nome = nm.getText().toString();
final String telefone = tlf.getText().toString();
if(nome.length() != 0 && telefone.length() != 0){
if(mIndex.equals("")) {
ContentValues valor = new ContentValues();
valor.put("nome", nome);
valor.put("telefone", telefone);
db.insert("contatos", null, valor);
ShowMessage("Sucesso","O Contato " + nome + " foi salvo com sucesso");
}
else {
String[] whereArgs = {"nome", "telefone"};
ContentValues dataToInsert = new ContentValues();
dataToInsert.put("nome", nome);
dataToInsert.put("telefone", telefone);
db.update("contatos", dataToInsert, "nome='"+nomeant+" and telefone='"+foneant+"'", whereArgs);
ShowMessage("Sucesso","O Contato " + nome + " foi salvo com sucesso");
}
}
}
});
}
The LogCat error it shows that:
Failure 1 (table contatos already exists) on 0x2205b0 when preparing 'create table contatos(nome varchar(50),telefone varchar(20))'.
My POV: the result in the LogCat says that the table already exists but, in the code i cant see where i shows that im trying to create it, wrong, i try to connect to it and not create it.
You don't need the whereArgs here since you are attaching the arguments in the where clause itself. Just supply null to in place of whereArgs -
db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"'", null);
But it is always better to use the arguments. It prevents sql injection and also takes care of escaping special characters. In your case -
db.update("contatos", dataToInsert, "nome=? and telefone=?", whereArgs);
Also, your whereArgs is wrong. It should be -
String[] whereArgs = new String[] {nomeant, foneant};
FONT from the user Mukesh Soni.
Also using the whereArgs allows for some SQLite optimizations,
another issue in your code is that you dont check for the return values of update and insert operations
db.update("contatos", dataToInsert, "nome='"+nomeant+"' and telefone='"+foneant+"'", null);
db.insert("contatos", null, valor);
ocurrs you have a success in your operation you should check for the returned values of update
and insert to check if the operations actually have had success.
You should also check this good tutorial on SQLite on Android as a good starting point.