getDatabase called recursively sqlite insert and getReadableDatabase() - java

I just started with my first App and I am trying to create a table settings, which should contain an entry PIN. after that I want to run the method getPIN() to get the value of this setting.
The problem is, that I get always the error "getDatabase called recursively". As I just started with this, I have no idea how to fix it. I've seen a lot of used to have the same problem, but the solutions doesn't work for me.
Could you please help me to understand what I'm doing wrong.
The contacts table was part of a tutorial I followed before, that´s the reason it's still in there.
Thank you.
This is my Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION =3;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = " contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null ," +
"name text not null, email text not null, pass text not null);";
private static final String TABLE_SETTINGS = "create table settings (id integer primary key not null ," +
"setting text not null, value integer not null);";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null,DATABASE_VERSION );
}
#Override
public void onCreate(SQLiteDatabase db){
String ssetting = "PIN";
db.execSQL(TABLE_CREATE);
db.execSQL(TABLE_SETTINGS);
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "Select * from settings";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put("id",count);
values.put("setting", ssetting);
values.put("value", 0);
db.insert("settings", null, values);
db.close();
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
String query = "DROP TABLE IF EXISTS"+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
public int insertContact(Contact c){
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "Select * from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID,count);
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_EMAIL, c.getEmail());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
return 0;
}
public String searchPass(String uname)
{
db = this.getReadableDatabase();
String query = "select name, pass from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a,b;
b="not found";
if (cursor.moveToFirst()){
do {
a = cursor.getString(0);
b = cursor.getString(1);
if (a.equals(uname)) {
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
db.close();
return b;
}
public int getPIN()
{
db = this.getReadableDatabase();
int pin=1;
String query = "select id, setting, value from settings where setting='PIN'";
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
do {
pin = cursor.getInt(2);
break;
}
while(cursor.moveToNext());
}
db.close();
return pin;
}
}
and the MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int pin = helper.getPIN();
if (pin==0){
Intent i = new Intent(MainActivity.this, Loginpin.class);
startActivity(i);
}
if (pin==1) {
Intent i = new Intent(MainActivity.this, Setuppin.class);
startActivity(i);
}
//pin = helper.getPIN();
}
public void b_newOnClick(View v) {
if (v.getId() == R.id.blogin)
{
EditText user = (EditText) findViewById(R.id.tfuser);
String su = user.getText().toString();
EditText pass = (EditText) findViewById(R.id.tf_pw);
String spass = pass.getText().toString();
String password = helper.searchPass(spass);
if(spass.equals(password))
{
Intent i = new Intent(MainActivity.this, Welcome.class);
i.putExtra("username", su);
startActivity(i);
}
else{
Toast.makeText(MainActivity.this, "Password incorrect", Toast.LENGTH_LONG).show();
}
}
}
public void onSignClick(View v) {
if (v.getId() == R.id.bsign) {
Intent i = new Intent(MainActivity.this, SignUp.class);
startActivity(i);
}
}
}
Thank you so much.
regards, S
Kilimanscharo

Don't call getWritableDatabase() or getReadableDatabase() from your SQLiteOpenHelper lifecycle methods such as onCreate() or onUpgrade() that are in turn triggered by a call to get...Database(). Instead, use the SQLiteDatabase object that is given as a parameter to these methods.
Specifically, remove this line from your onCreate():
db=this.getWritableDatabase();

Related

How to move data to SQLite?

Code
public class SettingsContacts extends AppCompatActivity {
private RecyclerView contactsList;
private List<ContactsHelper> contacts = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
private ContactsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_contacts);
contactsList = (RecyclerView) findViewById(R.id.usersList);
//Add the data first
addDataToList();
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
//and then create a object and pass the lis
mAdapter = new ContactsAdapter(contacts);
contactsList.setHasFixedSize(true);
contactsList.setLayoutManager(linearLayoutManager);
contactsList.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
public void addDataToList() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
}
}
This displays all the contacts in the users phone in an activity... How do i move the data into a table in SQLite?
Progress so far:
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL);";
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_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);
}
Helper
public class ContactsHelper {
private String Name;
private String PhoneNumber;
public ContactsHelper() {
}
public ContactsHelper(String Name, String PhoneNumber) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
}
I've got to this point but I don't know how to proceed because I have so far only worked with adding/modifying data by clicking a button or similar to that.
How do I move the complete data to SQLite and when new contact is added obviously it wont get added to table automatically so when I add a feature like swipe to refresh I want the new contact to be added to the data as well?
Solution:
Add this method in your DatabaseHelper class:
public void insertData(String contactName, String phoneNumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
then, Firstly, make DatabaseHelper global object in your SettingsContacts class:
public DatabaseHelper database;
Add this in youronCreate()
database = new DatabaseHelper(SettingsContacts.this);
then after this, add the below line in addDataToList() method as shown:
Add this line:
database.insertData(name, phoneNumber)
as shown in below code (Write Here):
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new ContactsHelper(name, phoneNumber));
phoneCursor.close();
....... (Write Here)
}
}
That's it.
Hope it works.
To see if the data is already inserted, you can check the count of your table:
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHandler.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Write the above method in you Database Handler class.
Then, in your activity after calling insertData(..), you can write like:
int count = database.getCount();
Log.e("Count From DB: ", String.valueOf(count));

Any Idea on how I can stop adding multiple entry's of ID's into a database with this code?

I'm trying to figure a way of allowing users NOT to be able to add the same ID twice as if I wanted to delete one of the users and he shared the ID with another it would delete both.
So far I have found no help doing so does anyone have an idea?
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText IdText;
private EditText NameText;
private EditText AgeText;
private EditText WeightText;
private EditText HeightText;
private EditText ReachText;
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IdText = (EditText) findViewById(R.id.IdText);
NameText = (EditText) findViewById(R.id.NameText);
HeightText = (EditText) findViewById(R.id.HeightText);
AgeText = (EditText) findViewById(R.id.AgeText);
WeightText = (EditText) findViewById(R.id.WeightText);
ReachText = (EditText) findViewById(R.id.ReachText);
button = (Button) findViewById(R.id.button);
dbHandler = new MyDBHandler(this);
AddData();
}
public void AddData() {
button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((IdText.getText().toString()).isEmpty()) {
IdText.setError("Please fill out your name");
return;
} else if ((NameText.getText().toString()).isEmpty()) {
NameText.setError("Please fill out your ID");
return;
} else if ((AgeText.getText().toString()).isEmpty()) {
AgeText.setError("Please fill out your Age");
return;
} else if ((HeightText.getText().toString()).isEmpty()) {
HeightText.setError("Please fill out your Height in centimeters");
return;
} else if ((WeightText.getText().toString()).isEmpty()) {
WeightText.setError("Please fill out your weight in kilos");
return;
} else if ((ReachText.getText().toString()).isEmpty()) {
ReachText.setError("Please fill out your reach in inches");
return;
} else {
boolean isInserted = dbHandler.insertData(IdText.getText().toString(),
NameText.getText().toString(),
AgeText.getText().toString(),
HeightText.getText().toString(),
WeightText.getText().toString(),
ReachText.getText().toString());
if (isInserted == true)
Toast.makeText(MainActivity.this, "Fighter added", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
}
}
);
}
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Fighters.db";
public static final String TABLE_PRODUCTS = "Fighter";
public static final String COLUMN_ID = "ID1";
public static final String COLUMN_NAME = "Name";
public static final String COLUMN_AGE = "Age";
public static final String COLUMN_WEIGHT = "Weight";
public static final String COLUMN_HEIGHT = "Height";
public static final String COLUMN_REACH = "Reach";
SQLiteDatabase db;
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_PRODUCTS + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,ID1 TEXT,Name TEXT,Age INTEGER,Weight INTEGER,Height TEXT,Reach TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
this.onCreate(db);
}
//Add new row to the database
public boolean insertData(String id1, String name, String age, String weight, String height, String reach) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id1);
contentValues.put(COLUMN_NAME, name);
contentValues.put(COLUMN_AGE, age);
contentValues.put(COLUMN_WEIGHT, weight);
contentValues.put(COLUMN_HEIGHT, height);
contentValues.put(COLUMN_REACH, reach);
long result = db.insert(TABLE_PRODUCTS, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_PRODUCTS, null);
return res;
}
public boolean updateData(String id1,String name, String age, String weight, String height, String reach) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id1);
contentValues.put(COLUMN_NAME, name);
contentValues.put(COLUMN_AGE, age);
contentValues.put(COLUMN_WEIGHT, weight);
contentValues.put(COLUMN_HEIGHT, height);
contentValues.put(COLUMN_REACH, reach);
db.update(TABLE_PRODUCTS, contentValues, "ID1 = ?", new String[] {id1 });
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_PRODUCTS, "ID1 = ?", new String[] {id});
}

ANDROID SQLITE DATABASE insert [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
the database class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String CONTACTS_TABLE_NAME = "contacts";
public static final String CONTACTS_COLUMN_ID = "id";
public static final String CONTACTS_COLUMN_NAME = "name";
public static final String CONTACTS_COLUMN_EMAIL = "email";
public static final String CONTACTS_COLUMN_STREET = "street";
public static final String CONTACTS_COLUMN_CITY = "place";
public static final String CONTACTS_COLUMN_PHONE = "phone";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean insertContact (String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
res.moveToNext();
}
return array_list;
}
the activity class
public class MainActivity extends AppCompatActivity {
Button login;
EditText student_id;
EditText password;
TextView message;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
login = (Button) findViewById(R.id.button);
student_id = (EditText) findViewById(R.id.student_id);
password = (EditText) findViewById(R.id.password);
message=(TextView)findViewById(R.id.logResult);
message.setText("");
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pass = password.getText().toString();
int id = Integer.parseInt(student_id.getText().toString());
int result= db.numberOfRows();
if (result == 1) {
message.setText("Invalid User");
} else {
message.setText("valid User" );
}
}
});
}
But,When the button is pressed the insertion in not occur and app close
where is the problem?? help?????????????? I want to insert data in database when the app is created how?
your call is outside of the onclick , first try:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.insertContact("jon","9595749944","r#hotmail.com","a","usa");
}
});

Android: How to display string on textview from console

I'm trying to display string on the textview. I'm succesfully able to print it on the console from database, but I'm not able to figure out how to print all the strings on different different textviews. Here is my code:
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
EditText search;
Button insert;
TextView txt1, txt2, txt3, txt4, txt5;
DatabaseHandler db;
List<History> history;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHandler(this);
search = (EditText) findViewById(R.id.search_word);
insert = (Button) findViewById(R.id.insert);
txt1 = (TextView) findViewById(R.id.txt1);
txt2 = (TextView) findViewById(R.id.txt2);
txt3 = (TextView) findViewById(R.id.txt3);
txt4 = (TextView) findViewById(R.id.txt4);
txt5 = (TextView) findViewById(R.id.txt5);
insert.setOnClickListener(this);
history = db.getAllHistory();
}
public void onClick(View v) {
db.addHistory(new History(search.getText().toString(), null));
Toast.makeText(getApplicationContext(),
"Inserted: " + search.getText().toString(), Toast.LENGTH_LONG)
.show();
}
#Override
protected void onStart() {
super.onStart();
List<History> history = db.getAllHistory();
for (History cn : history) {
String log = "Search Strings: " + cn.getName();
Log.d("Search Strings: ", log);
}
}
}
This is my activity in which I'm bringing my all database value on onStart() function. Now here I have to set all the data coming from database on the textview. Here is my DabaseHandler class in which I'm taking out each row.
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "historyManager";
private static final String TABLE_HISTORY = "histories";
private static final String KEY_NAME = "history";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_HISTORY_TABLE = "CREATE TABLE " + TABLE_HISTORY + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_HISTORY_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
onCreate(db);
}
void addHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
db.insert(TABLE_HISTORY, null, values);
db.close();
}
History getHistory(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HISTORY, new String[] { KEY_NAME },
"=?", new String[] { String.valueOf(id) }, null, null, null,
null);
if (cursor != null)
cursor.moveToFirst();
History history = new History(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return history;
}
public List<History> getAllHistory() {
List<History> historyList = new ArrayList<History>();
String selectQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
History contact = new History();
contact.setName(cursor.getString(0));
historyList.add(contact);
} while (cursor.moveToNext());
}
return historyList;
}
public int updateHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, history.getName());
return db.update(TABLE_HISTORY, values, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
}
public void deleteHistory(History history) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HISTORY, KEY_NAME + " = ?",
new String[] { String.valueOf(history.getName()) });
db.close();
}
public int getHistoryCount() {
String countQuery = "SELECT * FROM " + TABLE_HISTORY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
Please help in getting data printed on the textview. On the Log.d I can see all my data coming, one after another. But I'm not able to print all the data.
It's answer for "Thank You for that. Can you tell me how to set the data which I have printed in MainActivity on onStart() method (Log.d("")). If you can give me the code for that, that will be much easier for me."
try this:
List<String> listNames = new ArrayList<String>();//global variable
List<History> history = db.getAllHistory();
for (History cn : history) {
listNames.add(cn.getName());
}
or, if have in History field date try is, after easy will sort:
Map<String, Date> historyMap = new HashMap<String, Date>();
List<History> history = db.getAllHistory();
for (History cn : history) {
historyMap.put(cn.getName, cn.getDate);
}
You need make ListView in which will show your data from DB.Because you have many items datas getting from db.
I suggest to the next version:
In xml file you creat:
<ListView
android:id="#+id/list_names"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
...>
You need create Adapter for your list with next xml resource:
<TextView
android:id="#+id/text_name"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
In java code:
in onCreate:
ListView list = (ListView) findViewById(R.id.list);
OurAdapter adapter = new OurAdapter(..., List<String> yourListWithName);
list.setAdapter(adapter);
if you want a more detailed description of the code tell me.
For add last item in top you need next, create spec. internal class :
class Holder implements Comparable<Holder> {
String key;
Double value;
public int compareTo(Holder another) {
return another.value.compareTo(value);
}
}
and use him how:
List<this.Holder> listSortforLastInTop = new ArrayList<this.Holder>();
and
for(...){
Holder holder = new Holder();
holder.key=...;
older.value=..;
listSortforLastInTop.add(holder);
}

problem in database in android

hi i am an SEO and i am in currently practicing android development of my own. i studied about database storing in android developers site and found an example code that to be in a notepad.
I tried using it in my project. In my project i have placed 2 edit boxes with a OK button, when the OK button is clicked the data in the edit box gets stored and it is shown in a new page.
the following is the code of my project's main class file,
{
b = (Button)findViewById(R.id.widget30);
et1 = (EditText)findViewById(R.id.et1);
et2 = (EditText)findViewById(R.id.et2);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title = extras.getString(NotesDbAdapter.KEY_ET1);
String body = extras.getString(NotesDbAdapter.KEY_ET2);
mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);
if (title != null) {
et1.setText(title);
}
if (body != null) {
et2.setText(body);
}
}
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(et1.getText().toString().length() == 0 && et2.getText().toString().length() == 0)
{
et.setVisibility(View.VISIBLE);
alertbox();
}
else
{
main.this.finish();
Intent myIntent = new Intent(v.getContext(), T.class);
startActivityForResult(myIntent, 0);
}
}
});
}
public void alertbox()
{
et = new TextView(this);
Builder alert =new AlertDialog.Builder(main.this);
alert.setTitle("Alert");
alert.setMessage("Required all fields");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
}
});
AlertDialog alert1 = alert.create();
alert1.show();
}
}
the following is the code of the DataBaseAdapter
public class NotesDbAdapter {
public static final String KEY_ET1 = "a";
public static final String KEY_ET2 = "b";
public static final String KEY_ROWID = "_id";
private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table notes (_id integer primary key autoincrement, "
+ "title text not null, body text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "notes";
private static final int DATABASE_VERSION = 2;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public NotesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public NotesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(String a, String b) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ET1, a);
initialValues.put(KEY_ET2, b);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_ET1,
KEY_ET2}, null, null, null, null, null);
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_ET1, KEY_ET2}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String a, String b) {
ContentValues args = new ContentValues();
args.put(KEY_ET1, a);
args.put(KEY_ET2, b);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
when i run the project the new page is opening but the data's entered is not shown there.
what is to be the error. pls teach me
You are going to need to get an instance of your database adapter
NotesDbAdapter adapter = new NotesDbAdapter(this); //pass activity context as a param
then you need to use the open method of the new database object to open the database
adapter.open();
now call the store method
String str = myEditText.getText().toString();
String str1 = "random other string";
adapter.createNote(str, str1);
I notice that your createNote method takes two params. I dont know where you want to get the other data from, so I just used 'random other string'. Sub in the data you want to store as appropriate.
Finally you will need to close the database:
adapter.close();
And you have successfully stored the information. See this for help on how to use the console to view the data that you have entered into the database. (See specifically the sqlite3 portion of the page) Alternatively you could write some code to display it on the screen after retrieving it. You are going to need to read about cursors if you want to retrieve info. See here for some information on that.

Categories

Resources