I'm trying to validate two strings via TextUtils.isEmpty but i'm failing everytime.
Following is my code:
private void addArtist() {
//getting the values to save
String email = editTextName.getText().toString().trim();
String mobileno = editTextName1.getText().toString().trim();
//checking if the value is provided
if (TextUtils.isEmpty(email)){
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter email.", Toast.LENGTH_LONG).show();
}
else{
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseArtists.push().getKey();
//creating an Artist Object
Artist artist = new Artist(id, email, mobileno);
//Saving the Artist
databaseArtists.child(id).setValue(artist);
Toast.makeText(this, "Successful...", Toast.LENGTH_LONG).show();
}
}
Currently this code is working on string email, i want it to work with string mobileno also.Any help is appreciated.
Why don't you just try to use try catch block and inside it try to convert this string after you read from TextField control object into number if "Mobileno" variable should be int type? If it fails then you can in catch block make some other instructions to prevent from inserting it to field of specific object. Have you tried that?
Related
private void sendSMS(){
String phoneNo = number.getText().toString().trim();
String SMS = message.getText().toString().trim();
if (number.getText().toString().length() >= 4) {
if (!message.getText().toString().equals("")) {
SmsManager smsManager =sManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, SMS, null, null);
Toast.makeText(this, "Your SMS is sent successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter a message!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "The number is incorrect, it must contain at least 4 numbers!", Toast.LENGTH_SHORT).show();
}
}
I have this piece of code that works successfully! But I want now sent message to various numbers with separate ";".
For example, in the emulator I want enter in the numbers zone (1254;2058;153348) and the message has to be sent to all the contacts I have enter.
If phoneNo contains the following value: 1254;2058;153348
You can split your phone numbers to array with numbers.
Please see the following example:
String phoneNo = number.getText().toString().trim();
String []phoneNumbers = phoneNo.split(";");
After that you can iterate by every element in phoneNumbers array
I want just sent the same message at various numbers.
Why dont you split string on ; and than iterate through loop to send it one by one
I hope you understand what i mean
I created one table has studId, studName, place.I also want to create another table related to the first one that has studId, day, timeone, timeTwo. How can I do it? I'm a beginner in firebase
this method will add the data for firebase
private void addDate(){
String studName = userName.getText().toString().trim();
String place = spinnerPlace.getSelectedItem().toString();
if(!TextUtils.isEmpty(studName)){
String id = databaseStudentData.push().getKey();
StudentData studentData = new StudentData(id, studName, place);
databaseStudentData.child(id).setValue(studentData);
addDay(id);
Toast.makeText(this, "Data is saved", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this, "you Should Enter your name", Toast.LENGTH_LONG).show();
}
}
and here the data that i stored
enter image description here
There is no benefit in creating another table just for one attribute, what you can do is the following. Since you already did this:
String id = databaseStudentData.push().getKey();
StudentData studentData = new StudentData(id, studName, place);
databaseStudentData.child(id).setValue(studentData);
Now to add time under this table you can do the following:
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("time", time);
databaseStudentData.child(id).updateChildren(childUpdates);
This way you will have the following database:
id
studId : "id"
studName : "name"
studPlace : "place"
studTime : "time"
I have a json array of all names and contacts on my phone, looks something like this:
[{"name":"andy","phone_number":"+123"},{"name":"bob","phone_number":"+456"},{"name":"chris","phone_number":"+789"}]
I check the phone numbers against phone numbers in a db, if there's a match I want to show the name in the recycler view, if no match, then show just the number.
For example, +123, yes, it is in the db, so show andy in the cell in recyclerview. +789 is not in the db, so show +789 in the cell.
Here's what I'm working with so far: it works when there is a match, the if part, but I don't know how to deal with the else part (for when there is no match). If I uncomment my else code it always jumps straight to there.
public void onResponse(String response) {
try {
//name our JSONObject User_Private_Public_Obj, which is response from server
//the response from server will be like:
//{"private_review_ids":[{"reviewid":7,"username":"+123"},{"reviewid":14,"username":"+456"}]}
JSONObject User_Private_Public_Obj = new JSONObject(response);
//Now break up the response from server
//We want the JSON Array part, "private_review_ids"
JSONArray private_ids = User_Private_Public_Obj.getJSONArray("private_review_ids");
for
//get the number of objects in User_Private_Public_Obj
(int i = 0; i < private_ids.length(); i++)
{
//for each object in the array private_ids, name it obj
//each obj will consist of reviewid and username
JSONObject obj = private_ids.getJSONObject(i);
Review review = new Review();
//get the string from sharedpreferences, AllPhonesandNamesofContacts,
//it will be like [{"phone_number":"+123","name":"andy"}, etc...]
//we want this so we can display phone name in recyclerView, if it's a contact
SharedPreferences sharedPrefs = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String json_array = sharedPrefs.getString("AllPhonesandNamesofContacts", "0");
//convert the string above into a json array
JSONArray jsonArray = new JSONArray(json_array);
//set a string to the phone number from the DB,
//the phone number of the person who made the review
phoneNoInDB = obj.getString("username");
//set the setter to the phone number string, the string is
//the phone number of the person who made the review
review.setPhoneNumberofUserFromDB(phoneNoInDB);
//jsonArray is our All Phones and Names of Contacts array
int matching = jsonArray.length();
for (int n = 0; n < matching; n++) {
try {
//for every object in "All Phones and Names of Contacts" array...
JSONObject object = jsonArray.getJSONObject(n);
//if the review maker is a contact...that is,
//if the phone_number in AllPhonesandNamesofContacts equals
//the phone number in the DB
if (object.getString("phone_number").equals(phoneNoInDB)) {
//just for testing purposes...
Toast.makeText(NewActivity.this, object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
//then rip out the other part of the object, the name in
// AllPhonesandNamesofContacts
//of the person who made the review
review.setphoneNameonPhone(object.getString("name"));
//add the review to the sharedReviewList
reviewList.add(review);
}
/* else {
//just for testing...
Toast.makeText(NewActivity.this, " should be green" + object.getString("phone_number") + " = " + phoneNoInDB, Toast.LENGTH_LONG).show();
review.setphoneNameonPhone(object.getString("phone_number"));
//add the review to the sharedReviewList
//reviewList.add(review);
}*/
} catch (JSONException e) {
System.out.println("error in if else");
//Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
//set the adapter to show the random reviews
recyclerView.setAdapter(uAdapter);
This question already has answers here:
Convert ArrayList to String array in Android
(7 answers)
Closed 8 years ago.
I am trying to send an email, from a button click, to all emails stored in a sqlite database. I have been successful in selecting one email, but now i am trying to use a cursor to continue to send the email to all stored email addresses. Below is the button call and the method to retrieve the array of addresses from the database.
view.findViewById(R.id.btn_save).setOnClickListener(new OnClickListener() {
public void onClick(View view ) {
Mail m = new Mail("gmail#gmail.com", "pw");
String[] usereMail = getEmailsFromDB().split(",");;
m.setTo(usereMail);
m.setFrom("iwalker77#gmail.com");
m.setSubject("Never going to happen");
m.setBody("If you receive this email, the planets have aligned and i have somehow managed to get an email sent to all players in the database");
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);
}
}
private ArrayList<String> getEmailsFromDB() {
// TODO Auto-generated method stub
dataBase = mHelper.getReadableDatabase();
Cursor Cursor = dataBase.rawQuery("SELECT " + DbHelper.KEY_EMAIL + " FROM "
+ DbHelper.TABLE_NAME, null);
ArrayList<String> array = new ArrayList<String>();
while(Cursor.moveToNext()) {
String usereMail = Cursor.getString(Cursor.getColumnIndex(DbHelper.KEY_EMAIL));
array.add(usereMail);
}
Cursor.close();
return array;
}
});
The error i am receiving is on the line ' String[] usereMail = getEmailsFromDB().split(",");' and it is due to the error 'Type mismatch: cannot convert from ArrayList to String[]'. Is there any way round this? And if not, how should i change my approach?
Clearly the ArrayList<String> array and String[] are incompatible types
Use toArray to return an array of the type contained within the collection and match the expected return type for the method getEmailsFromDB
return list.toArray(new String[array.size()]);
I want to use a text file to populate a linked list using a Java SE app. The text file has the following format:
firstnamelastname mobile home office
I want to insert these lines as nodes in the linked list! then i want to search for a specific node from the linked list that has been populated from the text file !
using firstnamelastname as a key i want to compare it with the nodes data (data is to to splitted as to compare with the "key") after finding the specific node i want to split that nodes data using split(" "); and show the resultant !!!
i just want to know about hint doing it all I will be very thankful in advance please help me out !!!
i have generated a java source code but its not working as it always give me the last nodes data so check the blunder I made if its totally wrong give any of your idea!
try {
String fullname;
String mobile;
String home;
String mobile2;
String office;
Node current = first;
while (current.data != key) {
String splitter[] = current.data.split(" ");
fullname = splitter[0];
mobile = splitter[1];
home = splitter[2];
mobile2 = splitter[3];
office = splitter[4];
if (fullname == null ? key == null : fullname.equals(key)) {
mobilefield.setText(mobile);
homefield.setText(home);
mobilefield2.setText(mobile2);
officefield.setText(office);
} else {
throw new FileNotFoundException(
"SORRY RECORD NOT LISTED IN DATABASE");
}
break;
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage()
+ "\nPLEASE TRY AGAIN !", "Search Error",
JOptionPane.ERROR_MESSAGE);
}
(key is as=firstname+lastname;)
I would use an ArrayList (needs less memory, has better performance for most operations)
Code looks ok for me, but I would not not split the current.data for every entry.
I would use a test like
if(current.data.startsWith(key)){
String splitter[]=current.data.split(" ");
...
}
and only if this is true I would split the current.data because only in this case you need mobile *home* office