I am working on a button to email all users that have an email within the sqlite database. At the moment i have got the button working successfully, but can only call a single email address that is linked to the rows id.
Below is the code where i call upon the email and then send.
view.findViewById(R.id.btn_save).setOnClickListener(new OnClickListener() {
public void onClick(View view ) {
Mail m = new Mail("gmail#gmail.com", "password");
int arg = 0;
String[] toArr = {user_eMail.get(arg)};
m.setTo(toArr);
m.setFrom("gmail#gmail.com");
m.setSubject("This email is never going to work");
m.setBody("If you can read this email, please call me immediately because this never should have worked.");
try {
if(m.send()) {
Toast.makeText(getActivity(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
});
How do i go about changing the "int arg = 0" into calling all ids in the database? If you need any other code just let me know.
ok, since user_eMail is an ArrayList
private ArrayList<String> user_eMail = new ArrayList<String>();
.setTo() method must receive an array of emails separated by ","
create a method to extract an array from the database (for example getEmailsFromDB()) containing the emails: {"email1#gmail.com", "email2#gmail.com", "email3#gmail.com", "email4#gmail.com", "email5#gmail.com"};
and use:
m.setTo(getEmailsFromDB())
other option, the method returns from Database a String containing all the emails separated by "," , like "email1#gmail.com, email2#gmail.com, email3#gmail.com, email4#gmail.com, email5#gmail.com";
String[] user_eMail = getEmailsFromDB().split(",");
m.setTo(user_eMail);
Related
Creating an app on Android studio, have a registration page working which updates the User table on back4app - it also creates a session table with sessionID associated with the account. I'm trying to make it so once the username and password have been confirmed and added the user is brought to a new page and more details are further taken and added to the row in the same User table.
My code for the section looks like
private void addPersonalDetailsToDatabase(String firstname,
String lastname,
String dob,
String addressline1,
String addressline2,
String postcode,
String livealone,
String havecarers) {
ParseObject userList = new ParseObject("User");
userList.put("firstname", firstname);
userList.put("lastname", lastname);
userList.put("dob", dob);
userList.put("addressline1", addressline1);
userList.put("addressline2", addressline2);
userList.put("postcode", postcode);
userList.put("livealone", livealone);
userList.put("havecarers", havecarers);
userList.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(PersonalDetailsForm.this, "Successful", Toast.LENGTH_SHORT).show();
openPDConfirmed();
} else {
Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
However when I run this code and enter the details it creates a new User table with a brand new row which isn't then accessed by the sessionID.
What I'm trying to do is to add these new columns and their contents to the original user table for the user that has just logged in. Is there any errors in my code or any way that I could add new columns to an already existing row.
Try ParseObject userList = new ParseObject("_User"); or ParseUser userList = new ParseUser();
I've been working with Xamarin for a few weeks now and i'm trying to find the best practices for using SQLite ORM queries.I have a log in page which is launched first before users can access the app.I have the database created before this first activity comes to the screen and administrator log in details inserted into the user's table as soon as the tables are created.The point is,the admin is meant to log in and import an xml file containing all of the other user's personal information.This information is read from the file and saved to sqlite as well.
Next,the other users can log in after their details have been imported and saved successfully.My challenge is,at the point of logging in,i would like to verify the details as follows:
1.Compare the entered username with a single username from the db
**2.Check the password entered to see if it matches the username entered **
I'm currently using a select query to pull up all the passwords from the database,before comparing the two strings(from the db and from the edit text field).If it's a large db however,reading all the data will be quite expensive.How do i go about this?
How do i also look up the password for that username?
Below is my code:
namespace sample.NameSpace
{
[Activity (MainLauncher = true)]
public class MainActivity : Activity
{
Button login = FindViewById<Button> (Resource.Id.login);
try{
login.Click += (object sender, EventArgs e) => {
if (TextUtils.IsEmpty(userName.Text.ToString())) {
makeToast();
} else if (TextUtils.IsEmpty(password.Text.ToString())) {
makeToast();
} else {
returningUser = userName.Text.ToString().Trim();
returningUserPassword = password.Text.ToString().Trim();
}
//Check to see if the name is in the db already
List<string> allUsers = GetAllUserNames();
//Loop through the list of names and compare the retrieved username with the name entered in the text field
string retrievedDbName ="";
foreach(string name in allUsers )
{
retrievedDbName = name .Trim();
}
//Verify name
if(retrievedDbName .Equals(returningUser))
{
Toast.MakeText(this,
"Login Successful !", ToastLength.Short).Show();
Intent intent = new Intent (this, typeof(HomeActivity));
StartActivity (intent);
}
else
{
Toast.MakeText(this, "User Name or Password does not match", ToastLength.Short).Show();
}
};
} catch(Exception e){
logger.Exception (this, e);
}
public List<string>GetAllUserNames()
{
List<UserInfoTable> allUserNames = new List<UserInfoTable> ();
allUserNames = dataManager.GetSingleUserName ();
string name = "";
foreach(var UserName in allUserNames)
{
Console.WriteLine ("Usernames from db :" + name.ToString());
}
return allUserNames;
}
Then the DataManager class:
public List<UserInfoTable> GetSingleUserName()
{
UserInfoTable user = new UserInfoTable ();
using (var db = dbHandler.getUserDatabaseConnection ()) {
var userName = db.Query<UserInfoTable> ("select * from UserInfoTable where user_name = ?", user.USER_NAME);
return userName;
}
}
public bool CheckLogin(string user, string password)
{
bool valid = false;
using (var db = dbHandler.getUserDatabaseConnection ()) {
var user = db.Query<UserInfoTable> ("select * from UserInfoTable where user_name = ? and password = ?", user, password);
if (user != null) valid = true;
}
return valid;
}
I am trying to add or update information in an SQLite database in Android.
The database takes a Lesson note id and a student id. If the lesson note id is 0, then a new entry is being made.
Here is what is in my Dbhelper class (for inserting, the update is fairly similar):
public boolean insertLessonNotes(LessonNotesData lData)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues lessonValues = new ContentValues();
//values.put(LESSON_ID, lData.getLessonID()); // Lesson ID
//values.put(ST_ID, lData.getStudentID()); // Student ID
//values.put(LESSON_IMAGE_ID, lData.getImageID()); // Lesson Image ID
//values.put(LESSON_IMAGE_NOTE, lData.getImageNote()); // Note attached to image
lessonValues.put(LESSON_ID, lData.getLessonID());
lessonValues.put(ST_ID, lData.getStudentID());
lessonValues.put(DATE, lData.getDate()); // Date note added
lessonValues.put(LESSON_READING, lData.getReadingNote()); // reading notes
lessonValues.put(LESSON_PHONICS, lData.getPhonicsNote()); // phoncis notes
lessonValues.put(LESSON_SPELLING, lData.getSpellingNote()); // spelling notes
lessonValues.put(LESSON_WRITING, lData.getWritingNote()); // writing notes
lessonValues.put(LESSON_COMMENTS, lData.getCommetns()); // comments notes
lessonValues.put(LESSON_HOMEWORK, lData.getHomework()); // homework notes
// Inserting Row
db.insert(TABLE_LESSON_NOTES, null, lessonValues);
db.close();
return true;
}
This is my lessonNotes class (where the information is entered and saved)
LessonNotesData lNote = new LessonNotesData(id_To_Update, student_id, lessonDate.getText().toString(), readNote.getText().toString(), phonNote.getText().toString(), spellNote.getText().toString(), writeNote.getText().toString(), commentNote.getText().toString(), homeworkNote.getText().toString());
Bundle extras = getIntent().getExtras();
int studentID = extras.getInt("studentId");
int lessonID = extras.getInt("lessonID");
Toast.makeText(getApplicationContext(), "LessonID is:(lessonNotes3) "+String.valueOf(lessonID), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "StudentID is: (lessonNotes3) "+String.valueOf(studentID), Toast.LENGTH_SHORT).show();
//Bundle studentId = getIntent().getExtras();
if (lessonID != 0) {
if (studentID > 0) {
if (mydb.updateLessonNotes(lNote)) {
//Update was successful
Toast.makeText(getApplicationContext(), "Updated successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.LessonNotesList.class);
intent.putExtra("studentId",studentID);
startActivity(intent);
} else {
//Update did not complete correctly
Toast.makeText(getApplicationContext(), "Update unsuccessful, Please try again", Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertLessonNotes(lNote)) {
Toast.makeText(getApplicationContext(), "New Lesson note created", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Error creating lesson note! Please try again", Toast.LENGTH_SHORT).show();
}
//Return user to lessonNotesList where ListView should now show new lesson note
Intent intent = new Intent(getApplicationContext(), com.example.ltss.dyslexia.app.LessonNotesList.class);
intent.putExtra("studentId",studentID);
startActivity(intent);
}
}
Whenever I try to add or update anything in the system, I get this from the debug log:
04-02 20:02:33.925 26789-26789/com.example.ltssdyslexiaapp D/Items to add:﹕ com.example.ltss.dyslexia.app.LessonNotesData#42602bf8
Any ideas as to what this is or how I can fix it?
Thanks
Actually its not an error at all its just a Log output, its a DEBUG type of Log. You colud try to log the same adding line android.util.Log.d("hello","world"); to any method you want. And 'com.example.ltss.dyslexia.app.LessonNotesData#42602bf8' means that LessonNotesData has no toString() method and thats why you see #42602bf8 - its an instance address in memory or hash.
In my application i want to get sms/mms from device and display the messages in listview.By using the following code to get the all sms from device.
public void readSmsFromDevice() {
preferences = PreferenceManager
.getDefaultSharedPreferences(BackgroundService.this);
final_msg_time = preferences.getLong("msgtime", 0);
Uri uriSMSURI = Uri.parse("content://sms/");
String[] projection = { "address", "body", "date", "type" };
String where = "date" + ">" + final_msg_time;
Cursor cur = getContentResolver().query(uriSMSURI, projection, where,null, "date");
while (cur.moveToNext()) {
if(ProfileFragment.stop)
{
break;
}else{
try {
//
Message mess1=new Message();
try{
String _id = cur.getString(cur.getColumnIndex("_id"));
mess1.setId(_id);
}catch(Exception e)
{
mess1.setId("null");
}
try{
String number = cur.getString(cur.getColumnIndex("address"));
number = number.replaceAll("[\\W]", "");
if (number.trim().length() > 10) {
mess1.setNumber(number.substring(number.length() - 10,
number.length()));
mess1.setAddress(number.substring(number.length() - 10,
number.length()));
} else {
mess1.setNumber(number);
mess1.setAddress(number);
}
}
catch(Exception e){}
mess1.setBody(cur.getString(cur.getColumnIndex("body")));
String type = cur.getString(cur.getColumnIndex("type"));
Long millisecond = Long.parseLong(cur.getString(cur
.getColumnIndex("date")));
String dateString = DateFormat.format("yyyy/MM/dd hh:mm:ss a",
new Date(millisecond)).toString();
mess1.setDate_millis(millisecond);
mess1.setDate(dateString);
mess1.setType(type);
mess1.setmessagetype("sms");
messages.add(mess1);
} catch (Exception e) {}
}
}
cur.close();
}
By using this method i am getting all sms from device.But my question is how to differenciate group message.In group message one message sent different contact numbers(senders).So in normal message application group message displayed in separate column and single message displayed in separate column.So my application also i have to display the messages like message application.So in this cursor how to identify group message?Is there any column is available to identify group message?So please suggest me how to do taht.Thanks In Advance.....
the thread THREAD_ID column will give you all the messages in the same conversation. You can then use the address column to differentiate the senders of the messages in the group message.
You should also use the Telephony class that was introduced in API 19 instead of the content resolver. https://developer.android.com/reference/android/provider/Telephony.html
i have created an app which insert data to sql server. i made column NAME as unique key.
i want that if i enter same name by edittext to insert...it should give a toast message.
but it's not happening. i cann't understand where i have made error.
in connection to server there is no problem. the only thing is i have to display Toast msg if i entered same name again.
my code is.......
public void onClick(View v) {
// TODO Auto-generated method stub
String myloc=loc.getText().toString();
String myname=name.getText().toString();
String myphone=phone.getText().toString();
initilize();
ResultSet rs;
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("SELECT * FROM FORM1");
List<Map<String,String>>data=null;
data=new ArrayList<Map<String,String>>();
while(rs.next()){
Map<String,String>datanum=new HashMap<String,String>();
datanum.put("a", rs.getString("NAME"));
data.add(datanum);
}
if(data.contains(myname)){
Toast.makeText(c, myname+" Already stored: please choose different one", Toast.LENGTH_LONG).show();
}
else{
insert(myname,myphone,myloc);
}
}catch(Exception e){
Log.e("ERROR", e.getMessage());
}
}
plzz guys...help me someone...
With data.contains(myname) you are trying to check if there is myname of type String in your data varible, but, in fact, your data have type List<Map<String,String>>, so when you are invoking contains(Object object) method passing a String, you are performing equals operation between Map<String,String> and String, which clearly would always result false. So I would suggest you either write something like this
List<String> data = new ArrayList<String>();
while(rs.next()) {
data.add(rs.getString("NAME"));
}
if(data.contains(myname)){
Toast.makeText(c, myname+" Already stored: please choose different one", Toast.LENGTH_LONG).show();
}
or there is a better way, just change your query to SELECT * FROM FORM1 WHERE NAME = myname and check if your result set is empty.