W/SQLiteConnectionPool: A SQLiteConnection object for database ERROR - android

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?

Related

Update textview data sqlite Android

I have a textview that gets data from sqlite database but when I delete a row,or change it ,I also want to change what the textview has,the data the textview contains is basically the sum of all rows specific column,so how can I update the textview when updating sqlite data?
here is my main code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tinyDB = new TinyDB(getApplicationContext());
listView = findViewById(R.id.listt);
pharmacynme = findViewById(R.id.pharmacynme);
constraintLayout = findViewById(R.id.thelayout);
mBottomSheetDialog2 = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
inflater2 = (LayoutInflater) LoggedIn.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mBottomSheetDialog = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
content = inflater2.inflate(R.layout.activity_main2, null);
content2 = inflater2.inflate(R.layout.smalldialog, null);
total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
pharmacydescrr = findViewById(R.id.pharmacydiscribtion);
String nme = getIntent().getStringExtra("pharmacy_name");
String diskr = getIntent().getStringExtra("pharmacy_disk");
pharmacydescrr.setText(diskr);
pharmacynme.setText(nme);
//Listview Declaration
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListItems>();// Connection Class Initialization
etSearch = findViewById(R.id.etsearch);
etSearch.setSingleLine(true);
chat = findViewById(R.id.chat);
mDatabaseHelper = new DatabaseHelper(this);
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
System.out.println("IDKSDKASDJKAS"+mDatabaseHelper.ifExists());
if (mDatabaseHelper.ifExists()){
mBottomSheetDialog2.show();
total.setText(mDatabaseHelper.getPriceSum());
}else {
}
chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameid = getIntent().getStringExtra("nameid");
Intent intent = new Intent(LoggedIn.this,ChatActivity.class);
intent.putExtra("nameid",nameid);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
// myAppAdapter.filter(text);
}
});
SyncData orderData = new SyncData();
orderData.execute("");
}
public void AddData(String newEntry,String price,String amount){
boolean insertData = mDatabaseHelper.addData(newEntry,price,amount);
if (insertData){
toastMessage("Data Successfully inserted!");
}else {
toastMessage("Al anta 4abebto da ya youssef >:(");
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(LoggedIn.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String nme = getIntent().getStringExtra("pharmacy_name");
System.out.println(nme);
String query = "Select StoreArabicName,StoreEnglishName,StoreSpecialty,StoreCountry,StoreLatitude,StoreLongitude,Store_description,ProductData.ProductArabicName,ProductData.ProductImage,ProductData.ProductEnglishName,ProductData.ProductDescription,ProductData.ProductPrice FROM StoresData INNER JOIN ProductData ON StoresData.StoreID = ProductData.StoreID WHERE StoreEnglishName = '"+nme+"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("ProductEnglishName"), rs.getString("ProductDescription"), rs.getString("ProductPrice"),rs.getString("ProductImage")));
System.out.println(rs.getString("ProductImage"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg!=null){
Toast.makeText(LoggedIn.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, LoggedIn.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter//has a class viewholder which holds
{
private ArrayList<ClassListItems> mOriginalValues; // Original Values
private ArrayList<ClassListItems> mDisplayedValues;
public class ViewHolder {
TextView textName;
TextView textData;
TextView textImage;
ImageView producticon;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.sdadprice);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.setContentView(content);
total.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoggedIn.this,Listitemsbought.class);
startActivity(intent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
final Float allitemscount = Float.parseFloat(parkingList.get(position).getImage());
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
AddData(parkingList.get(position).getProname(),String.valueOf(last),String.valueOf(counter));
total.setText(mDatabaseHelper.getPriceSum());
mBottomSheetDialog2.show();
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
// if (tinyDB.getString("selecteditem").equals("English")){
// Toast.makeText(LoggedIn.this,"Sorry this ability isn't here yet",Toast.LENGTH_LONG).show();
// }else {
// Toast.makeText(LoggedIn.this,"عفوا هذه الخاصية ليست متوفرة حاليا",Toast.LENGTH_LONG).show();
// }
}
});
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
itemArrayList.clear();
if (charText.length() == 0) {
itemArrayList.addAll(arraylist);
} else {
for (ClassListItems st : arraylist) {
if (st.getProname().toLowerCase(Locale.getDefault()).contains(charText)) {
itemArrayList.add(st);
}
}
}
notifyDataSetChanged();
}
}
private Float parseFloat(String s){
if(s == null || s.isEmpty())
return 0.0f;
else
return Float.parseFloat(s);
}
And here is my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "DatabaseHelper";
private static final String NAME = "Name";
private static final String PRICE = "Price";
private static final String AMOUNT = "Amount";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null , 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ("+PRICE+" TEXT, "+ NAME + " TEXT,"+ AMOUNT +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String Price,String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PRICE,Price);
contentValues.put(NAME, item);
contentValues.put(AMOUNT, amount);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long insert = db.insert(TABLE_NAME,null,contentValues);
if (insert == -1){
return false;
}else {
return true;
}
}
public Cursor getDataOfTable(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT Name,Amount FROM " + TABLE_NAME ;
Cursor data = db.rawQuery(query, null);
return data;
}
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor price = db.rawQuery(query, null);
String result = "" + price.getString(0);
price.close();
db.close();
return result;
}
public boolean ifExists()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String checkQuery = "SELECT * FROM " + TABLE_NAME + " LIMIT 1";
cursor= db.rawQuery(checkQuery,null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public void delete(String nameofrow) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+TABLE_NAME+" where "+NAME+"='"+nameofrow+"'");
}
}
Any help?!
The method getPriceSum() should return the sum and not a Cursor:
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(query, null);
String result = "";
if (c.moveToFirst()) result = "" + c.getString(0);
c.close();
db.close();
return result;
}
I don't think that you need the if block:
if (mDatabaseHelper.ifExists()) {
.......................
}
All you need to do is:
total.setText(mDatabaseHelper.getPriceSum());

SQLiteDatabase.query() method not returning any data in the cursor

I tried using query method in my login system.My logic is simple.Once a user has registered using Email and Password,then he can login if the email and password matches in the Database.For the starter code, i wanted to read the row from the database that matches the email ad password.And if the query method only returns 1 row,then the user is taken to the next page.
But the problem is that query method does not return any row.I have provided the code below.Thanks
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_signup);
demoText = (TextView) findViewById(R.id.demoText);
input_email = (EditText) findViewById(R.id.login_email);
input_password = (EditText) findViewById(R.id.login_password);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.register);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login_email = input_email.getText().toString();
login_password = input_password.getText().toString();
Log.v("login_signup","Email= "+login_email+" Password"+login_password);
if(checkEntry(login_email,login_password)){
Intent i = new Intent(login_signup.this,anotherscreen.class);
startActivity(i);
Toast.makeText(login_signup.this,"Login Successful",Toast.LENGTH_SHORT).show();
}
else Toast.makeText(login_signup.this,"Login Failed",Toast.LENGTH_SHORT).show();
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(login_signup.this,Register.class);
startActivity(i);
}
});
toolbar= (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setIcon(R.drawable.text_icon);
dbHelper = new scannerDbHelper(this);
}
public boolean checkEntry(String email,String password){
db = dbHelper.getReadableDatabase();
String projection[] = {loginEntry.COLUMN_EMAIL_ID,loginEntry.COLUMN_PASSWORD};
String selection = loginEntry.COLUMN_EMAIL_ID + "= ?"+" AND "+loginEntry.COLUMN_PASSWORD + "= ?";
String selectionArgs[] = {email,password};
Cursor cursor = db.query(loginEntry.TABLE_NAME,projection,selection,selectionArgs,null,null,null);
demoText.setText("Rows returned "+ cursor.getCount());
if(cursor.getCount()== 1)
return true;
else
return false;
}

Listview gets popuplated from the database everytime I start the activity

I am fetching some json data into an EventApp and I am trying to store in SQLite database some of the events. I am showing the events in another activity, not the main one and whenever I go back from that activity to the main one and the I go back to the activity with the listview, the data gets duplicated every time. SO if I click to go to that activity 10 time, my data gets 10 times in the listview and in the database as well. How can I fix this?
SQLiteDatabase db = getWritableDatabase();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add new row to the database
public void addEvent(Event ev){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
contentValues.put(DatabaseHelper.URL, ev.getUrl());
contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
db.insert(TABLE_NAME, null, contentValues);
//db.close();
}
//Delete event from database
public void deleteEvent(String eventTitle){
db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}
public int deleteEvents() {
return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}
//Print the database as string
public String databaseToString(){
String dbString="";
//points to a location in results
Cursor c = getEvents();
while (c.moveToNext()){
if(c.getString(c.getColumnIndex("Title")) != null){
dbString += c.getString(c.getColumnIndex("Title"));
dbString += "\n";
}
}
//db.close();
return dbString;
}
public Cursor getEvents(){
return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}
}
This is the activity where I show the data from the database
public class StoredEventsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stored_events);
ListView listView = (ListView) findViewById(R.id.lv_stored_events);
Intent intent = getIntent();
ArrayList<Event> events = new ArrayList<Event>();
events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");
EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
listView.setAdapter(adapter);
}
}
Here is the method that returns the stored events
public static ArrayList<Event> returnStoredEvents(){
long id = -1;
//getStoredEvents();
Cursor c = eventsDB.getEvents();
while (c.moveToNext()){
id = c.getInt(c.getColumnIndex(eventsDB.ID));
String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
organizeEvents.add(new Event(title, start, end, true));
}
c.close();
Log.d("DATABASE", organizeEvents.toString());
return organizeEvents;
}
Here is where I actually add some of the events:
private void readEvents(String str){
Event ev = null;
try {
JSONObject geoJSON = new JSONObject(str);
JSONArray jsonEvents = geoJSON.getJSONArray("events");
for (int i = 0; i < jsonEvents.length(); i++) {
JSONObject event = jsonEvents.getJSONObject(i);
JSONArray timeJsonEvent = event.getJSONArray("datelist");
JSONObject time = timeJsonEvent.getJSONObject(0);
title = event.getString("title_english");
Date date = new Date(time.getLong("start"));
startDate = dateFormat.format(date);
date = new Date(time.getLong("end"));
endDate = dateFormat.format(date);
imageURL = event.getString("picture_name");
url = event.getString("url");
subtitle = event.getString("subtitle_english");
description = event.getString("description_english");
if (title.charAt(0) == 'T') {
ev = new Event(title, startDate, endDate, true);
eventsDB.addEvent(ev);
}else {
ev = new Event(title, startDate, endDate, false);
}
// Process a newly found event
final Event finalEv = ev;
handler.post(new Runnable() {
public void run() {
addNewEvent(finalEv);
}
});
}
}catch (Exception e) {
Log.d(null, e.getMessage());
}
}
And here is my main:
public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventsDB = new DatabaseHelper(this);
//storedEvents.addAll(EventsListFragment.returnStoredEvents());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Sort by name")){
Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
EventsListFragment.sort(-1);
}else if (item.getTitle().equals("Sort by date")) {
EventsListFragment.sort(1);
}else if (item.getTitle().equals("Stored events")){
showSavedEvents();
Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
}
return true;
}
public void showSavedEvents(){
intent = new Intent(this, StoredEventsActivity.class);
intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
startActivity(intent);
}
}

how to get previous and next data on button click from SQlite database

I am working on QuizActivity and unable to get the Previous question from database when reach on last question then on clicking previous button then first question appears in activity. Need help stuck from last 2 days.Thanks
DATABASE
public List<NotificationListItem> getNQuestions() {
List<NotificationListItem> quest = new ArrayList<NotificationListItem>();
String selectQuery = "SELECT * FROM " + TABLE_NAME2;
openToRead();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
NotificationListItem item = new NotificationListItem();
item.setqID(cursor.getInt(1));
item.setAnswer(cursor.getString(2));
item.setTestID(cursor.getString(3));
item.setquestions(cursor.getString(4));
item.setOption1(cursor.getString(5));
item.setOption2(cursor.getString(6));
item.setOption3(cursor.getString(7));
item.setOption4(cursor.getString(8));
item.setOption5(cursor.getString(9));
item.setAnscount(cursor.getString(10));
item.setTc(cursor.getString(11));
quest.add(item);
} while (cursor.moveToNext());
}
return quest;
}
public List<NotificationListItem> getPQuestions() {
List<NotificationListItem> quest = new ArrayList<NotificationListItem>();
String selectQuery = "SELECT * FROM " + TABLE_NAME2;
openToRead();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
NotificationListItem pitem = new NotificationListItem();
pitem.setqID(cursor.getInt(1));
pitem.setAnswer(cursor.getString(2));
pitem.setTestID(cursor.getString(3));
pitem.setquestions(cursor.getString(4));
pitem.setOption1(cursor.getString(5));
pitem.setOption2(cursor.getString(6));
pitem.setOption3(cursor.getString(7));
pitem.setOption4(cursor.getString(8));
pitem.setOption5(cursor.getString(9));
pitem.setAnscount(cursor.getString(10));
pitem.setTc(cursor.getString(11));
quest.add(pitem);
} while (cursor.moveToNext());
}
return quest;
}
public int getpreviousid() {
int previd=0;
openToRead();
String selectQuery = "SELECT * FROM " + TABLE_NAME2;
Cursor cursor=null;
cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.moveToPrevious()) {
previd=cursor.getInt(cursor.getColumnIndex(KEY_QID));
}
cursor.close();
return previd;
}
QUIZACTIVITY
NotificationListItem Nitem,Pitem;
List<NotificationListItem> Nquest,Pquest;
int score=0;
int qID=0,anscount,totalchoice,tq,questionid,previd;
QuizTable quizTable;
LinearLayout rc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_activity_b);
qs = getIntent().getStringExtra("questions");
tq = Integer.parseInt(qs);
prevBT.setEnabled(false);
quizTable = new QuizTable(this);
quizTable.openToRead();
quizTable.openToWrite();
Nquest=quizTable.getNQuestions();
Pquest=quizTable.getPQuestions();
lastid=quizTable.getLastId();
firstid=quizTable.getFirstId();
previd=quizTable.getpreviousid();
Nitem=Nquest.get(questionid);
Pitem=Pquest.get(previd);
setQuestionView();
nextBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(questionid<Integer.parseInt(lastid)){
Nitem=Nquest.get(questionid);
prevBT.setEnabled(true);
setQuestionView();
}
else{
Intent intent = new Intent(QuizActivityB.this, TestAnalysisActivity.class);
startActivity(intent);
finish();
}}
});
prevBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(questionid<Integer.parseInt(lastid)){
Pitem=Pquest.get(previd);
questionid=previd;
setQuestionView1();
}
if(questionid==Integer.parseInt(lastid))
{
Pitem=Pquest.get(previd);
questionid=previd;
setQuestionView1();
}
}
});
}
private void setQuestionView()
{
txtQuestion.setText(Nitem.getquestions());
op1=(Nitem.getOption1());
op2=(Nitem.getOption2());
op3=(Nitem.getOption3());
op4=(Nitem.getOption4());
op5=(Nitem.getOption5());
ansc=Nitem.getAnscount();
tc=(Nitem.getTc());
questionid=(Nitem.getqID());
if(questionid==Integer.parseInt(firstid))
{
prevBT.setEnabled(false);
}
totalchoice=Integer.parseInt(tc);
anscount=Integer.parseInt(ansc);
System.out.println("QUESTIONID="+questionid);
if(anscount==1)
{
rc.removeAllViews();
addRadioButtons();
}
else if(anscount>1)
{
rc.removeAllViews();
addCheckButtons();
}}
private void setQuestionView1() {
// TODO Auto-generated method stub
if(questionid==Integer.parseInt(firstid))
{
prevBT.setEnabled(false);
}
txtQuestion.setText(Pitem.getquestions());
op1=(Pitem.getOption1());
op2=(Pitem.getOption2());
op3=(Pitem.getOption3());
op4=(Pitem.getOption4());
op5=(Pitem.getOption5());
ansc=Pitem.getAnscount();
tc=(Pitem.getTc());
questionid=(Pitem.getqID());
totalchoice=Integer.parseInt(tc);
anscount=Integer.parseInt(ansc);
System.out.println("PREVIOUSID="+ questionid);
if(anscount==1)
{
rc.removeAllViews();
addRadioButtons();
}
else if(anscount>1)
{
rc.removeAllViews();
addCheckButtons();
}
}
We you press Next it means it is obvious to increment questionID hence :
nextBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
questionid++; // MISSING IN UR CODE
if(questionid<Integer.parseInt(lastid)){
Nitem=Nquest.get(questionid);
prevBT.setEnabled(true);
setQuestionView();
}
else{
Intent intent = new Intent(QuizActivityB.this, TestAnalysisActivity.class);
startActivity(intent);
finish();
}}
});

Read and Write on SQLite Database in Android app_project

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();

Categories

Resources