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()]);
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'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?
A very strange porblem. I'm tring to update contacts name by this rule:
- if a contact's name start with "bit" + space ("bit ") so -> update the contact's name to name.substring(4, name.length()), and that means that the contact name will update without the "bit ".
when I use name.substring from number that lower them 4 (I think until the space in contact's name) its working perfectly. When I use from the 4 character onwards the contact's name multiply. For exmaple, when i use name = name.substring(4, name.length()) while name equal to "bit Lili" its update to:
Lili Lili.
private void updateContact(String name) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[] {name};
Cursor phoneCur = managedQuery(ContactsContract.Data.CONTENT_URI,null,where,params,null);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
if ((null == phoneCur)) {//createContact(name, phone);
Toast.makeText(this, "no contact with this name", Toast.LENGTH_SHORT).show();
return;} else {ops.add(ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name.substring(4,name.length()))
.build());
}
phoneCur.close();
try {cr.applyBatch(ContactsContract.AUTHORITY, ops);}
catch (RemoteException e) {e.printStackTrace();}
catch (OperationApplicationException e) {e.printStackTrace();}}
Thanks!
Not a certain answer but it suppose to work the issue you have is with the
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME //This specific part has a problem with the new update function
,name.substring(4,name.length()))
So my fix proposal is to change it to family name and given name change these as you need based on your question you want to remove the given name so it's a fix for that
public static boolean updateContactName(#NonNull Context context, #NonNull String name) {
if (name.length() < 4) return true;
String givenNameKey = ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME;
String familyNameKey = ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME;
String changedName = name.substring(4, name.length());
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
String where = ContactsContract.Data.DISPLAY_NAME + " = ?";
String[] params = new String[]{name};
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(givenNameKey, changedName)
.withValue(familyNameKey, "")
.build());
try {
context.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
I am trying to catch values from the database in to a array list. and i want to get only the latitude and the longitude to create the markers.
here is my gettemple() function in db handler class
public ArrayList<kovil> Get_Temple(String temple_type, String Limit) {
try {
temple_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TEMPLE +"WHERE KEY_TMPTYPE=" + temple_type +"LIMIT" + Limit;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
System.out.print("CALLED");
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
kovil Kovil = new kovil();
Kovil.setID(Integer.parseInt(cursor.getString(0)));
Kovil.settemplename(cursor.getString(1));
Kovil.settempletype(cursor.getString(2));
Kovil.setlatitude(cursor.getString(3));
Kovil.setlongitude(cursor.getString(4));
Kovil.setimage_name(cursor.getString(5));
Kovil.setyear_build(cursor.getString(6));
Kovil.setaddress(cursor.getString(7));
Kovil.setcity(cursor.getString(8));
Kovil.setemail(cursor.getString(9));
Kovil.setwebsite(cursor.getString(10));
Kovil.settelephone1(cursor.getString(11));
Kovil.settelephone2(cursor.getString(12));
Kovil.setDescription(cursor.getString(13));
// Adding contact to list
temple_list.add(Kovil);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return temple_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_temples", "" + e);
}
return temple_list;
}
this will return the temple_list array in the same class.
private final ArrayList<kovil> temple_list = new ArrayList<kovil>();
and trying to call the Get_Temple() function in view map class
dbhand.Get_Temple((getIntent().getExtras().getString("temple_type")), getIntent().getExtras().getString("notemples"));
for (int i=0; i< Integer.parseInt(getIntent().getExtras().getString("notemples"));i++) {
//displaytemples(9.662502, 80.010239, "mugan kovil");
}
and i am trying to display the markers using this class
public boolean displaytemples(double lati, double longi, String templename){
MarkerOptions marker = new MarkerOptions().position(new LatLng(lati, longi)).title(templename);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon));
//marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(marker);
return true;
}
I want to catch only the latitude and the longitude from the array list and using that for loop i want to pass the latitude and the longitude to the displaytemples ().
can any one help me to write the for loop which will catch only the latitude and the longitude and pass it to the displaytemples() function. thank you...
To be honest, your code makes me scared... But that's different problem. The only thing I would point out - is please do not fetch DB from the main thread. You are blocking UI this way :( . Look at AsyncTask or some other ways to offload DB operations off the main thread..
As for your problem - you can try something like this:
ArrayList<kovil> data = dbhand.Get_Temple(getIntent().getExtras().getString("temple_type"),
getIntent().getExtras().getString("notemples"));
for (kovil temple: data) {
displaytemples(Double.parseDouble(temple.getlatitude(),
temple.getlongitude(),
temple.gettemplename());
}
I am getting an array from parse.com. I am using an array, to retrieve an array:
fightList.whereContainedIn("objectId", itemListCard);
fightList.findInBackground(new FindCallback<ParseObject>() ....
My first array; itemListCard is in a specific order. After I findInBackground, my array from online, (objectId), is completely out of order. This is because I am getting it from Parse.com, so it is added to the array as it is retrieved. I need to:
1. Re-order array objectId to match itemListCard or
2. Retrieve objectId in order of itemListCard
Java code:
HomeItemList = new ArrayList<HomeItem>();
fightList.whereContainedIn("objectId", itemListCard);
fightList.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objectId, ParseException e) {
if (e == null) {
for (int i = 0; i < objectId.size(); i = i + 2) {
HomeItem homeItem = new HomeItem();
homeItem.setHomeItemID(k);
k++;
//set Red Array
homeItem.setHomeItemRedName(objectId.get(i).getString("Name"));
homeItem.setHomeItemRedAge(objectId.get(i).getString("Age"));
homeItem.setHomeItemRedRecord(objectId.get(i).getString("Record"));
homeItem.setHomeItemRedHeight(objectId.get(i).getString("Height"));
homeItem.setHomeItemRedWeight(objectId.get(i).getString("Weight"));
homeItem.setHomeItemRedCity(objectId.get(i).getString("Location"));
homeItem.setHomeItemRedExp(objectId.get(i).getString("Experience"));
//set blue Array
homeItem.setHomeItemBlueName(objectId.get(i+1).getString("Name"));
homeItem.setHomeItemBlueAge(objectId.get(i+1).getString("Age"));
homeItem.setHomeItemBlueRecord(objectId.get(i+1).getString("Record"));
homeItem.setHomeItemBlueHeight(objectId.get(i+1).getString("Height"));
homeItem.setHomeItemBlueWeight(objectId.get(i+1).getString("Weight"));
homeItem.setHomeItemBlueCity(objectId.get(i+1).getString("Location"));
homeItem.setHomeItemBlueExp(objectId.get(i+1).getString("Experience"));
HomeItemList.add(homeItem);
}
HomeListAdapter = new HomeListAdapter(getApplicationContext(), 0, HomeItemList);
adapter.addSection(" Fight Card ", HomeListAdapter);
} else {
progressDialog.dismiss();
Log.d("Display Card", "Error parsing Card");
Log.d("Card Error:", e.getMessage());
Toast.makeText(databaseFightCard.this, "Could not retrieve parse info. Try again later", Toast.LENGTH_LONG).show();
}
listView.setAdapter(adapter);
progressDialog.dismiss();
}
});
Note
The for loop is counting by 2 because this is the structure I am going for:
objectId[0] vs objectId[1]
objectId[2] vs objectId[3]
objectId[4] vs objectId[5]
objectId[6] vs objectId[7]
....and so on
Hence the need for a specific order.
You can control the order in which the items are returned using orderByAscending() and orderByDescending().
In your case:
fightList.whereContainedIn("objectId", itemListCard);
fightList.orderByAscending("objectId");
fightList.findInBackground(new FindCallback<ParseObject>() ....
See Query Constraints section of the the Parse Android Guide.