I am facing a strange(for me) problemm of not being able to delete the last char of a stringbuffer string. I am building an app in which i have many checkboxes and i want to take multiple values so thats why i used the stringbuffer to append the checkboxes names.
Code:
int length = iceCreamPreference.length();
if (length>0){
iceCreamPreference = iceCreamPreference.deleteCharAt(length - 1);
}
Toast.makeText(SweetsLayoutActivity.this,
"Quantity: " + quantityNumberFinal +
"\nIce Cream Flavors: " + iceCreamPreference.toString() +
"\nIce Scream Scoops: " + quantityIceCreamNumberFinal +
"\nSyrups: " + syrupPreference.toString(), Toast.LENGTH_LONG).show();
Where i build the StringBuffer:
private void checkWhatIceCreamSelected() {
iceCreamPreference = new StringBuffer();
if (chocolate.isChecked()){
iceCreamPreference.append(chocolate.getText().toString() + ", ");
}
if (strawberry.isChecked()){
iceCreamPreference.append(strawberry.getText().toString() + ", ");
}
if (vanilla.isChecked()){
iceCreamPreference.append(vanilla.getText().toString() + ", ");
}
if (banana.isChecked()){
iceCreamPreference.append(banana.getText().toString() + ", ");
}
if (cookies.isChecked()){
iceCreamPreference.append(cookies.getText().toString() + ", ");
}
if (pistachio.isChecked()){
iceCreamPreference.append(pistachio.getText().toString() + ", ");
}
if (cheeseCake.isChecked()){
iceCreamPreference.append(cheeseCake.getText().toString() + ", ");
}
if (oreo.isChecked()){
iceCreamPreference.append(oreo.getText().toString() + ", ");
}
if (mango.isChecked()){
iceCreamPreference.append(mango.getText().toString() + ", ");
}
if (caramel.isChecked()){
iceCreamPreference.append(caramel.getText().toString() + ", ");
}
if (pineapple.isChecked()){
iceCreamPreference.append(pineapple.getText().toString() + ", ");
}
if (sorbet.isChecked()){
iceCreamPreference.append(sorbet.getText().toString() + ", ");
}
}
The Result:
HERE
I would like to have the last "," comma removed.
Any suggestions will be highly appreciated!!!
The last char in the your StringBuffer will be a space, so you need to delete the last two characters to get rid of the final comma.
You can use the comma before the name and put a logic so that it doesn't append comma before first data entry. So code will be
Declare a boolean variable
boolean comma=false;
Then do code like following
private void checkWhatIceCreamSelected() {
iceCreamPreference = new StringBuffer();
if (chocolate.isChecked()){
if(comma!=false)
{
iceCreamPreference.append( ", ");
}
iceCreamPreference.append(chocolate.getText().toString());
comma=true;
}
//do same for all other if
}
Related
db=helper.getReadableDatabase();
cursor=db.query(DBHelper.TABLE, new String[]{DBHelper.CONTACT_NO}, null, null, null, null, null);
String listContact[]=fromCursorToStringArray(cursor);
Log.d("Array",Arrays.toString(listContact));
String sms = "This is custom message" + "\n" + "IMEI : " + mngr.getDeviceId() + "\n" + "Location : " + provider + "\n" + Arrays.toString(listContact) + contact_name;
try
{
android.telephony.SmsManager smsmanager = android.telephony.SmsManager.getDefault();
for(int i=0; i<listContact.length; i++)
{
smsmanager.sendTextMessage(listContact[i], null, sms, null, null);
Log.d("index", listContact[i]);
}
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
When I seen in Log it is give me all contact number in array but while I am concat in string at that time contact number does not display in message
String sms = "This is custom message" + "\n" + "IMEI : " + mngr.getDeviceId() + "\n" + "Location : " + provider + "\n" + Arrays.toString(listContact) + contact_name;
Its because of the brackets.
I have created function for remove brackets will work. Its working my side
private String subString(String sms)
{
String temp = "";
for(int i=1;i<(sms.length()-1);i++)
{
temp += sms.charAt(i);
}
return temp;
}
First you put your array to String Variable then after Concat with your message.
String temp=Arrays.toString(listContact);
String sms = "This is custom message" + "\n" + "IMEI : " + mngr.getDeviceId() + "\n" + "Location : " + provider + "\n" + temp + contact_name;
Some times Android cant directly Convert and concat operation simontenously.
Try it hope it will help you.
or
Second thing is check your Contactlist cherecter length becouse there are charecter limit in message. so if contactlist length exceed max allowed length it became media so check this scenario also.
I am using this code to show missed calls in my application while I am using Call class to define an object each time then store it in test how Can I print all objects in test list in my application?
List<Call> callList = new ArrayList<Call>();
while (c.moveToNext()) {
Call call = new Call();
call.setNumber(c.getString(c.getColumnIndex(CallLog.Calls.NUMBER)));
/* if (c.getInt(c.getColumnIndex(CallLog.Calls.TYPE)) == CallLog.Calls.OUTGOING_TYPE) {
call.setOut(true);
} else {
call.setOut(false);
}*/
call.setName(c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME)));
call.setTime(c.getLong(c.getColumnIndex(CallLog.Calls.DATE)));
call.setDuration(c.getLong(c.getColumnIndex(CallLog.Calls.DURATION)));
if ( c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME))!= null)
{
continue;
}
callList.add(call);
}
c.close();
}
you can override toString() method on Call class like:
#Override
public String toString() {
return Name+" "+Time+" "+Duration;
}
and print your list in for statement like:
for (int i = 0 ; i < callList.size() ; i++)
Log.d("value is" , callList.get(i).toString());
You can just iterate through the list and print the elements :
List<Call> callList = new ArrayList<Call>();
for(Call call : callList){
System.out.print("Name - " +call.getName() +
"Number - "+call.getNumber() +
"Time - "+call.getTime() +
"Duration - "call.getDuration());
}
you must override toString in your Call class like this
#Override
public String toString() {
return "Call{" +
"Name=" + Name+
", Time='" + Time+ '\'' +
", Duration='" + Duration+ '\'' +
'}';
}
and then use this
System.out.println("callList: " +Arrays.toString(callList.toArray()));
I am retrieving all records from database and saving all records in array list.when i show array list records ,repeated data displayed,i don't know what's the prolblem??
Calling this function in view_record class:
public ArrayList<tuple> getdata() { // TODO Auto-generated method stub
tuple obj=new tuple();
Cursor c = ourDatabase.query(DATABASE_TABLE, PROJECTION_ALL, null, null, null, null, null);
if(c == null) {
return null;
}
ArrayList <tuple> data = new ArrayList<tuple>();
// String result = " ";
int i=0;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
obj.ROWID= c.getString(c.getColumnIndexOrThrow(KEY_ROWID));
obj.CNAME= c.getString(c.getColumnIndexOrThrow(KEY_CNAME));
obj.SNAME= c.getString(c.getColumnIndexOrThrow(KEY_SNAME));
obj.FAMILY= c.getString(c.getColumnIndexOrThrow(KEY_FAMILY));
obj.LOCATION= c.getString(c.getColumnIndexOrThrow(KEY_LOCATION));
obj.IMAGE1= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE1));
obj.IMAGE2= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE2));
obj.IMAGE3= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE3));
data.add(i, obj);
i++;
}
c.close();
return data; }
My view_record class
public class view_record extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.db_view);
TextView tv=(TextView) findViewById(R.id.tvSqlinfo);
ImageView img=(ImageView) findViewById(R.id.img_view);
db_handler info=new db_handler(this);
info.open();
// Log.d("abc", "adb");
ArrayList <tuple> data=info.getdata();
Log.d("abc", "adb");
String result="";
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
tv.setText(result);
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
info.close(); } }
I want to view as follows :
" 1 cname sname family location "
" 2 cname sname family location "
But i am getting
" 2 cname sname family location "
" 2 cname sname family location "
Means last record displayed two times.
and one more thing ,i want to get all records where cname=something,getting error while doing it so
you are not making a new project in your for loop. That is whay you are getting same results. just do...
on start of for loop add this line obj=new tuple();
Answer to your Second Question
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
tv.setText(Html.fromHtml(result));
Can someone tell me what is wrong with coding below. Why I can not update next positions?
public static void deleteItemsFromProduct(long nomer) {
cursor_child = DataSourceChild.queryAllinChild();
if (cursor_child != null) {
par = new String[]{String.valueOf(nomer)};
db_child.delete(DBHelperChild.TABLE_ITEMS_AND_PRICES, DBHelperChild.COLUMN_NOMER + "=?", par);
Prod.setProdId(nomer);
cv_child = new ContentValues();
cv_child.put(DBHelperChild.COLUMN_NOMER, Prod.getProdId());
par = new String[]{String.valueOf(nomer+1)};
int updCount = db_child.update(DBHelperChild.TABLE_ITEMS_AND_PRICES, cv_child, DBHelperChild.COLUMN_NOMER + "=?", par);
Log.d(LOG_TAG, "updated rows count = " + updCount);
if (cursor_child.moveToFirst()) {
Log.d(LOG_TAG, "--- Left in the table for items and prices: ---");
do {
Log.d(LOG_TAG,
"item id = " + cursor_child.getInt(item_and_price_idColIndex)
+ ", item name = " + cursor_child.getString(item_ColIndex)
+ ", item price = " + cursor_child.getInt(price_ColIndex)
+ ", product nomer = " + cursor_child.getInt(nomer_ColIndex));
} while (cursor_child.moveToNext());
} else {
}
} else {
Log.d(LOG_TAG, "Cursor is null");
// закрываем курсор
cursor_child.close();
}
}
The idea is to delete set of items in the list while getting id (nomer) from another list. This code updates only the next id nomer after deleted but not others down the list.
Thank you.
I have a database with the columns: id, pdate, pvalue1, pvalue2. First I make a query with a cursor:
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "_id","pdate","pvalue1","pvalue2"},
"pdate >= ? AND pdate <= ?", new String[] { datefrom, dateto }, null, null, null);
This gives me some rows, for example if pdate = 20120318, then pvalue1 = 58, pvalue2=29. These are strings so I can give a value of "XX" to pvalue2. I would like to sum the pvalue1 between the given datefrom and dateto and group them by pdate where pvalue2 = XX. My problem is that I cannot put this condition into the query (with that its working, like "pvalue2 = XX"..), because I need the other datas too.
if (c.moveToFirst())
{
do{
if (c.getString(3).equals("XX")){
Log.i("XX", c.getString(1) + " " + c.getString(2)) + " " + c.getString(3));
}
else {
Log.i("NotXX", c.getString(1) + " " + c.getString(2)) + " " + c.getString(3));
}
while (c.moveToNext());
}
}
It is okay so far, so I can log the datas with this where pvalue2 = XX and NotXX and get something like this:
(pdate,pvalue1,pvalue2) 20120317,48,29;------;20120317,21,54;-------20120317,11,XX;-----20120318,79,71;-------20120318,21,XX;
What I would like to do?
First: Grouping the sums (pvalue1) by pdate and indicate it if pvalue2 is XX or notXX, so somethnig like this:
20120317,NotXX,69 (since 48+21=69) -------- 20120317,XX,11 -------- 20120318,NotXX,79 -------- 20120318,XX,21
After this I would like to substract the XX sum from the NotXX sum for every day. I would like to get:
20120317,58 (since 69-11) ------- 20120318,58 (since 79-21)
How sould I do this?
Thank you very much in advance!
My problem is that I cannot put this condition into the query
You are probably wrong. You can add something like (syntax may contain errors)
"select sum(select pdate from DATABASE_TABLE where pdata > x and pdate < y) as sum"
to the projection argument and you get that result as a column named sum. The only problem is that there is no support for ? in projection (at least I have not tried it but I guess it would not work)
If that's not what you want then there is very likely a different way. SQLite is very powerful.
Edit:
Would that be what you want? It's not done in SQL but it would print the sum you want for each day.
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "_id","pdate","pvalue1","pvalue2"},
"pdate >= ? AND pdate <= ?", new String[] { datefrom, dateto }, null, null, "pdate");
boolean first = true;
if (c != null) {
String currentDate = null;
int sum = 0;
while (c.moveToNext()) {
String date = c.getString(1);
int value1 = c.getInt(2);
String value2 = c.getString(3);
if (!date.equals(currentDate)) {
if (!first) {
Log.d("TAG", "The result for " + currentDate + " is: " + sum);
} else {
Log.d("TAG", "Date has changed, but we don't have data yet.");
}
first = false;
currentDate = date;
sum = 0;
}
if ("XX".equals(value2)) {
Log.d("TAG", "new line: " + date + ", " + value1 + ", " + value2 + " -");
sum -= value1;
} else {
Log.d("TAG", "new line: " + date + ", " + value1 + ", " + value2 + " +");
sum += value1;
}
}
if (!first) {
Log.d("TAG", "The last result: " + currentDate + " is: " + sum);
}
c.close();
}
Edit2: This might work when you want it done by the database.
Cursor c = ourDatabase.rawQuery(
"SELECT pdate, sum(sum2) AS sum1 FROM " +
"(" +
" SELECT pdate, pvalue1, pvalue2, -sum(pvalue1) AS sum2 " +
" FROM " + DATABASE_TABLE +
" WHERE pvalue2='XX' GROUP BY pdate" +
" UNION " +
" SELECT pdate, pvalue1, pvalue2, sum(pvalue1) AS sum2 " +
" FROM " + DATABASE_TABLE +
" WHERE pvalue2!='XX' GROUP BY pdate" +
") " +
" WHERE pdate>=? AND pdate<=? " +
" GROUP BY pdate",
new String[] { datefrom, dateto });
if (c != null) {
while (c.moveToNext()) {
String date = c.getString(0);
int value1 = c.getInt(1);
Log.d("TAG", "The result for " + date + " is: " + value1);
}
c.close();
}