This is the Method by which I insert the row in my application's database. But its insert only one row. So what I have to do add multiple rows in database. This code I had used for the new User Registration in my application.
Thanks in advance.....
public void addProductToCart(String username, String password,
String email, String contact, String bloodgroup, String city, String state) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(colUsername, username);
contentValues.put(colPassword, password);
contentValues.put(colEmail, email);
contentValues.put(colContact, contact);
contentValues.put(colBloodgroup, bloodgroup);
contentValues.put(colCity, city);
contentValues.put(colState, state);
db.insert(USERTABLE, colUsername, contentValues);
db.close();
context.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, "You have registered successfully.",
Toast.LENGTH_LONG).show();
context.finish();
}
});
}
I don't think there is something else that android supports, but my solution will be to build for that a new class with the Fields you need, and then pass as parameter to the addProductToCart method a list of all the objects you want to put. Inside the method do for loop until you get to the end of the list.
It is not possible to register multiple users at a time, if u want to add more number of users at a time use the back-end process in you database class.
try to add the values in your code instead of using the user Interface. If you set a on click function to a button then call the method as many times u want with the values you prefer.
Like this,
db.addProductToCart(username1,password1,email1, contact1,bloodgroup1,city1,state1);
db.addProductToCart(username2,password2,email2, contact2,bloodgroup2,city2,state2);
db.addProductToCart(username3,password3,email3,contact3,bloodgroup3,city3,state3);
Related
I made a simple login activity. I use Sqlite for this. Everything working well but i cant find who login into activity. I cannot access the user's id.
Is there any documentation or video for this ?
My Login Button Code :
public void girisyap(View view){
String acc= editTextAcc.getText().toString().trim();
String pass=editTextPass.getText().toString().trim();
DatabaseHelper db=new DatabaseHelper(this);
if (TextUtils.isEmpty(acc))
{ editTextAcc.setError("Bu Bölüm Boş Bırakılamaz!"); return; }
if (TextUtils.isEmpty(pass))
{ editTextPass.setError("Bu Bölüm Boş Bırakılamaz!"); return; }
if(db.checkUser(acc,pass)){
Intent intent = new Intent(this,AnaSayfa.class);
startActivity(intent);
}
else
Toast.makeText(this, "Wrong Login", Toast.LENGTH_SHORT).show();
}
Checkuser Database Code :
public boolean checkUser(String Kayitadi,String Kayitsifre){
String[] columns ={Table_Id};
SQLiteDatabase db =this.getWritableDatabase();
String selection=Kayit_Name+" =?"+" and "+Kayit_Pass+" =?";
String[] selectionArgs ={ Kayitadi,Kayitsifre };
Cursor cursor =db.query(Table_Name,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount=cursor.getCount();
cursor.close();
db.close();
if(cursorCount>0){
return true;
}
return false;
}
This codes catch is there any user in database. But i need to find who did login. What's his id.
As i mentioned in the comment section of this question you have 2 choises, either implement Auth0 to get your users ID after they log in or move to Firebase.
But if you just want to show the users email when they log in you can just pass a putExtra to your intent to the other activity, so when the user is succefull login you can have the email of the user. check this snippet
When the login is success (acc and pass are correct, you are going to another Activity where it suposes to say Hello "user_email") so, to do this is very simple, just add a putExtra before launching your other Activity, with this you can send data from one Activity to another.
if(db.checkUser(acc,pass)){
Intent intent = new Intent(this,AnaSayfa.class);
intent.putExtra("user_email",here your select_method_or_where_you_get_the_email);
startActivity(intent);
}
Note: you can use this putExtra to pass your users account
intent.putExtra("user_email",acc.toString());
if it is already an String do not put toString();
now , to get your email from the other activity, just do this
Intent iin= getIntent();
Bundle b = iin.getExtras();
if(b!=null)
{
String n =(String) b.get("user_email");
}
happy coding.
I'm having a very strange issue on my Android app wherein when I am inserting a value to a DB table, the first entry is disappearing somehow. However, any subsequent entries are appearing fine.
To be a little more specific, part of my application allows users to create a simple log where they enter some text and when they save it, it shows up on a list of log entries. However, when I try to insert the very first entry to an empty table, that entry is not being displayed, nor does the database indicate there is any data when I query for a count.
Interestingly enough, when I look at the return of the database insert call (SQLiteDatabase.insert()) I see a valid row number returned. In fact, when I look at any log entry I've saved to the database, the row number is correctly incrementing. As per the docs, my understanding is that if a non-negative number is returned, the insert was successful.
Here is the code that takes the result of the EditText from my AlertDialog, creates a new log entry, and calls the insert method:
newPainLogEntryDialog.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//make new pain log entry
PainLog painLog = new PainLog();
painLog.setPainEntry(input.getText().toString());
painLog.setPainDateTime(Calendar.getInstance());
Database.init(PainLogTab.this.getActivity());
Database.createPainLog(painLog);
updatePainLogList();
//display success to user
Toast.makeText(PainLogTab.this.getActivity(),
"Log entry saved", Toast.LENGTH_SHORT).show();
}
});
The code for Database.createPainLog():
public static long createPainLog(PainLog painLog) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_PAINLOG_ENTRY, painLog.getPainEntry());
cv.put(COLUMN_PAINLOG_DATETIME, painLog.getPainDateTimeString());
return getDatabase().insert(PAINLOG_TABLE, null, cv);
}
And the last call before the Toast message is updatePainLogList(), which gets all the DB entries:
public void updatePainLogList(){
Database.init(PainLogTab.this.getActivity());
final List<PainLog> painLogs = Database.getAllPainLogs();
painLogListAdapter.setPainLogs(painLogs);
Log.d(getClass().getSimpleName(), "number of painLogs found: " + painLogs.size());
getActivity().runOnUiThread(new Runnable() {
public void run() {
// reload content
PainLogTab.this.painLogListAdapter.notifyDataSetChanged();
if(painLogs.size() > 0){
getView().findViewById(android.R.id.empty).setVisibility(View.INVISIBLE);
}else{
getView().findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
});
}
And for completion sake, the body of the getAll() and its accompanying method getCursor():
public static Cursor getPainLogCursor() {
String[] columns = new String[] {
COLUMN_PAINLOG_ID,
COLUMN_PAINLOG_ENTRY,
COLUMN_PAINLOG_DATETIME
};
return getDatabase().query(PAINLOG_TABLE, columns, null, null, null, null,
null);
}
public static List<PainLog> getAllPainLogs() {
List<PainLog> painLogs = new ArrayList<PainLog>();
Cursor cursor = Database.getPainLogCursor();
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
PainLog painLog = new PainLog();
painLog.setId(cursor.getInt(IDX_PAINLOG_ID));
painLog.setPainEntry(cursor.getString(IDX_PAINLOG_ENTRY));
painLog.setPainDateTime(cursor.getString(IDX_PAINLOG_DATETIME));
painLogs.add(painLog);
}
}
cursor.close();
return painLogs;
}
Now with some code I can explain what debugging steps I have taken thus far. As mentioned above, when I look at the return of the DB insert, I get a positive, non-zero number. However, when I try to print the number of logs in the immediately following update method (no deletes or anything get called en route), it displays 0, and indeed if I follow the Cursor I find that it never enters the loop which adds logs to the list which is displayed, also indicating it is not picking up the entry.
I have tried to set the DB insert in a transaction so that I can manually commit, but this does not help either. What makes this more interesting to me is that I have similar functionality elsewhere in my app where I save user preferences and display them in a list, and this does not suffer from the same problem...I have compared against this code and couldn't find any differences that would cause it.
To sum it up, my question is two-fold: why is only my first insert on an empty table showing up as not there, while all following ones are fine?; why am I getting a valid return from the database insert and yet immediately following the insert when I query for that data it is missing?
Thanks in advance for any help you can provide :)
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
This skips the first row in cursor. moveToFirst() moves to the first row and moveToNext() moves to the next one, skipping the first one.
You can replace this with just while (cursor.moveToNext()). When you get your cursor from a query, it is placed at index -1 first i.e. at the row before the first one.
if (cursor.moveToFirst()) {
while (cursor.moveToNext()) {
This would be the best solution for it....
I have a problem, I created database for all activities, and in each activity I should insert information to database, so for the first activity , the insert is done , for the second activity I update the row with new insertion to complete all information and so on, my problem is that I don't know how to refer to the last row, I mean what should I do that make the update for the second activity occurs to the last row that has been insert in the first activity, do you have any suggestions ???
Well you can just use the primary key. When you insert something into the database you get as a return value the primary key. You can add this to the Intent that opens the other Activity and that way refer back to the row you previously inserted.
Edit:
I don't know if you are working with and SQLiteDatabase Object or with a ContentProvider, but in any case the code would be pretty much the same. In this example I will work directly with an SQLiteDatabase Object, even though using ContentProviders is in most cases the better alternative.
In your first Activity:
// When you perform an insert you get the id of the row which was just inserted.
long id = sqliteDatabase.insert("some_table", null, contentValues);
// The id will be -1 if an error occured
if(id >= 0) {
...
}
...
// When you start your second Activity you can add the id to the Intent
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
// The String is a tag with which you can later retrieve the id from the Intent.
// Note that you should never hardcode String like that, use constants in your app.
intent.putExtra("rowId", id);
In the onCreate Method of your second Activity you can retrieve the id:
#Override
protected void onCreate (Bundle savedInstanceState) {
// Check if the Activity has been created for the first time
if(savedInstanceState == null) {
// Retrieve the Intent with which the Activity was started
Intent intent = getIntent();
long id = intent.getLongExtra ("rowId", -1);
// If id is valid proceed
if(id >= 0) {
Cursor cursor = sqliteDatabase.query("some_table", columns, "_id = ?",
new String[] { String.valueOf(id) }, null, null, null, null);
// Check if Cursor is valid and if yes read your data.
if(cursor != null) {
...
}
}
}
}
The best way to do this would be to add a column to your database which will hold the time the row was inserted. Then when you need the latest row, query for the one with the most current time. An example SQL string would be:
SELECT * FROM my_table WHERE 1 ORDER BY time_stamp LIMIT 1
I have a class that contains:
#Override
public void onClick(View createView) {
switch (createView.getId()) {
case R.id.save_button:
Appointments add = new Appointments();
add.addAppointment(TITLE);
add.addAppointment(TIME);
break;
}
}
I want to be able to call the addAppointment method which is in another class:
public void addAppointment(String string) {
// Insert a new record into the Appointment data source.
// You would do something similar for delete and update.
SQLiteDatabase db = events.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TITLE, string);
values.put(TIME, string);
db.insertOrThrow(TABLE_NAME, null, values);
}
I have tried this way, but when I click the onclick , the program crashes
#Override
public void onClick(View createView) {
switch (createView.getId()) {
case R.id.save_button:
Appointments add = new Appointments();
add.addAppointment(TITLE, TIME); //Send both together
break;
}
}
I want to be able to call the addAppointment method which is in another class:
public void addAppointment(String title, String time) { // Change method header to accept both Strings here
// Insert a new record into the Appointment data source.
// You would do something similar for delete and update.
SQLiteDatabase db = events.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("title", title); // second param is what you passed in for first param of method
values.put("time", time); // second param here is whatever you passed in for second param of method
db.insertOrThrow(TABLE_NAME, null, values);
}
I don't know what TITLE and TIME are because I don't see them declared or initialized anywhere but inside the vaules.put() should be (key, value) so you make the key something descriptive about the value and the value obviously just that. Normally all caps represent a constant so just something to think about to keep up with standards
write method with two parameters 1st.calling method one after other with one parameter won't give you both values.
add.addAppointment(TITLE,TIME);
I am in process of developing an Android tablet app using sqllite 3.7.4 which would
perform following:
Fetches information from the UI
Performs some logic and store related information to the sqlite database
The stored information has to be send immediately OR at schedule
interval (ex. at 5:00 on xyz date) over the network
Currently, we have developed a dispacher mechanism (thread ), which constantly polls the database for new information inserted in the database. The thread fetches the information and send to the network module.
But, I feel this is not the correct approach as
Polling every time is a overhead. There can be times when there is nothing to execute
It is not real time , because we poll after every 5 seconds
So
Is there a way to send a trigger to my network module as soon as information is updated in database?
Or any better way to achieve this task?
Thanks in advance.
This question is about one year ago, but i think this is a common problem. This is how i handled the Database changes:
In my Adapter ( SQL ADAPTER) i have methods for updating / deleting or inserting data into the Database obviously. Like this method:
public long addProduct(String code, String name ... String gid, String gdate) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CODE, code);
initialValues.put(KEY_NAME, name);
...
initialValues.put(KEY_CHECK, this.checkfalse);
initialValues.put(KEY_GID, gid);
---------
Intent i = new Intent("data_inserted");
i.putExtra("date", date);
sendBroadcast(i);
---------
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
After the change happened it will send an broadcast intent. To fetch this first register your Broadcast Receiver in your onCreate Method (uploaderClass or whatever). This will look like this:
registerReceiver(Updated, new IntentFilter("data_inserted"));
And this Method to handle the following actions!
private final BroadcastReceiver Updated= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
doSomething(); // Data was inserted upload it
}
};
EDIT :
To fetch only new items from database, I sign new products. I have a colum "info" which can contain Strings like "upload", "update" or "delete". Then i fetch all Items from the database which contain these special strings and upload them. After that i set them to null or an empty String. Whatever you wish. Hope i explained it not to complicated :)
You can create your own database listener whenever something is updated to the database it will fetch the information and send to the network. I think will clear some idea for implementing this thing.
Now we can use Room to achieve this.
database.getInvalidationTracker().addObserver(new InvalidationTracker.Observer(tableToObserve) {
#Override
public void onInvalidated(#NonNull Set<String> tables) {
}
});
database is an instance of RoomDatabase, which is the base class for all Room databases. All classes that are annotated with "#Database" (which is the way to use the Room Libary) must extend this class.
In the creator method of InvalidationTracker.Observer, you can pass in an array of String (or in the form of varargs) to indicate the tables you'd like to observe, if any update happen to those tables, the callback method onInvalidated is invoked.
Some links to refer to:
https://developer.android.com/reference/android/arch/persistence/room/InvalidationTracker.html#addObserver(android.arch.persistence.room.InvalidationTracker.Observer)
hope so this will help you
private Handler h;
// in create time
h = new Handler();
// call where you want
h.postDelayed(myRunnable2, 1000); // after 1000 millisecond this function call automatically
// this function
private Runnable myRunnable2 = new Runnable() {
public void run() {
// do some thing
h.postDelayed(myRunnable2, 1000);
}
};