android- convert arraylist to one string in custom format - java

i have data in sqlit database so i use it to store categoreis and items
and i get it in arraylist like this:
public ArrayList showDataItems(String id_cate){
ArrayList<Items> arrayListItems = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cr = db.rawQuery("select * from items where id_cate = "+id_cate,null);
cr.moveToFirst();
while (cr.isAfterLast() == false){
String item_id = cr.getString(0);
String ItemName = cr.getString(1);
String Item_quantity = cr.getString(2);
String icon = cr.getString(3);
int isDone = Integer.parseInt(cr.getString(5));
arrayListItems.add(new Items(item_id,ItemName,Item_quantity,R.drawable.shopicon,icon,isDone));
cr.moveToNext();
}
return arrayListItems;
}
so i need to get this data and convert it to string and share it to other application like whatsapp in custom format for example :
1- first one *
2- second one *
3-....
so i use this code for send data
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT,"hello world");
intent.setType("text/plain");
startActivity(Intent.createChooser(intent,"send items i need all
data here"));
so we can use string builder or some thing to get data in one string
please help me!

As you said, there is a StringBuilder class who can help formatting strings.
Here are the java docs
From StringBuilder, see the append(..) method. For your example:
int size = list.size();
for(int i = 0; i< size-1;i++){
stringBuilder.append(i+1).append("- ").append(list.get(i)).append('\n');
}
stringBuilder.append(size).append("- ").append(list.get(size-1));
The last call to append is different from the firstone by not appending the end line

Related

Why Im getting this error? java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to java.lang.String

When exporting my array list item, Im getting this error. In the first place it works but when updating my code adding data on my array it crashed my app and this error appear, do you have any idea why this happening?
java.lang.ClassCastException: android.text.SpannableStringBuilder
cannot be cast to java.lang.String
I'm getting error in this line 312 after if statement -
mEdit1.putString("Status_" + i,list_items.get(i));
I've already tried put empty string on my list like this
""+list_items.get(i));
but it's not working :(
ArrayList<String> list_items = new ArrayList<String>(); //declared global
ArrayAdapter arrayAdapter; //declared global
public boolean export_data()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putString("Status_","");
mEdit1.apply();
mEdit1.putInt("Status_size", list_items.size());
for(int i=0;i<list_items.size();i++)
{
mEdit1.remove("Status_" + i);
if (list_items.get(i) !=null){
mEdit1.putString("Status_" + i,list_items.get(i));
String[] separated = list_items.get(i).split(":");
mEdit1.putString("Status_" + i, separated[0]);
}
else{
Toast.makeText(getApplicationContext(), "List is Empty", Toast.LENGTH_SHORT).show();
}
}
return mEdit1.commit();
}
Adding item on ArrayAdapter
public void refreshInbox(){
arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
ContentResolver cResolver = getContentResolver();
Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,"date desc");
int indexBody = smsInboxCursor.getColumnIndex("body");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
do{
String strbody = smsInboxCursor.getString( smsInboxCursor.getColumnIndex("body") );
if(strbody.contains("Notifier,") && strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
String[] sep = separate.split(" : ");
String sep1 = sep[1];
String finals = separate.replace(sep1, "<u>"+"<b>" + sep1 +"<b>"+ "</u>");
arrayAdapter.add(Html.fromHtml(finals));
}
else if(strbody.contains("Notifier,") && !strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
arrayAdapter.add(separate);
}
}while (smsInboxCursor.moveToNext());
}
Assuming you want to keep displaying HTML in your list view, the problem is that the objects that ArrayAdapter is adding list_items are not Strings. That means, you have to change how you define the list_items variable from String to a more generic character sequence type:
ArrayList<CharSequence> list_items = new ArrayList<>();
The CharSequence interface does not have a "split" method though. To be able to use "split", you'll need to call toString to get a regular string:
String[] separated = list_items.get(i).toString().split(":");
It would also help if you used the type parameter with your ArrayAdapter. Using the type parameter would have made it harder (if not impossible) to make this mistake.
ArrayAdapter<CharSequence> arrayAdapter;
... inside the method ...
arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, list_items);
list_items.get(i));
Looks like you might be attempting to put an unusual type of string into the list...
see: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
I'm not an android dev but I suspect there are some "useful" shortcuts it provides in an attempt to make your life easier, that would probably trip you up.
Groovy's default string was a GString rather than a String. That tripped me up a number of times before I got used to it.
The error is with this line in refreshInbox()
arrayAdapter.add(Html.fromHtml(finals));
Html.fromHtml does't return String but instead it retuns Spanned
But you need to pass String to add() on adapter
To fix this convert it to String
adapter.add(Html.fromHtml(finals).toString()); // this will return plain text without html tags
or
adapter.add(finals); // this will be having HTML tags from this you can set text on views later

Passing empty string to db helper

I'm having some real problems passing a single string from my main activity to my db helper class. Here is my main activity method which I am returning a string 'answerSetId':
public String showNextRandomQuestion3() {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAllAnswersByQuestion1();
//Get the question/text/answer Strings
List<String> questionStrings = listList.get(0); //question Strings
List<String> answerSetIds = listList.get(4);
//Generate random index
Random r = new Random();
int rand = Math.abs((r.nextInt() % questionStrings.size()));
//get answer description for randomly selected question
String questionString = questionStrings.get(rand);
String answerSetId = answerSetIds.get(rand);
questionView.setText(questionString);
return answerSetId;
}
I specifically want to use this 'answerSetId' in one method in my db helper class (as part of a query). Here is my current code - but it is capturing an empty string '[]':
public List<List<String>> getAnswers(String answerSetId) {
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
System.out.println(answerSetId);
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[]{TDESCR, ADESCR};
String selection = ASID+"=?";
String[] selectionArgs = new String[]{String.valueOf(answerSetId)};
Cursor c = db.query(TABLE_ANSWERS, columns, selection, selectionArgs, null, null, null);
if (c.moveToFirst()) {
do {
String textdescr = c.getString(c.getColumnIndex(TDESCR));
String answersdescr = c.getString(c.getColumnIndex(ADESCR));
array1.add(textdescr);
array2.add(answersdescr);
} while (c.moveToNext());
}
List< List<String> > listArray2 = new ArrayList< List<String> >();
listArray2.add(array1);
listArray2.add(array2);
return listArray2;
}
You can see that I want to use this method to retrun some more array data based on the query using the 'answerSetId' string - you'll also see where I have added a system print out which gives the empty value '[]'. But am only bothered about actually capturing the 'answerSetId' value from my main activity at this point.
How best to achieve this?
the arrays of data I will then pass onto my 'showNextAnswer()' method:
public String showNextAnswers() {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAnswers(answerSetId);
//Get the question/text/answer Strings
List<String> textDescrs = listList.get(0); //question Strings
// List<String> answerDescrs = listList.get(1); //text strings
// System.out.println(answerSetId);
answerView3.setText(textDescrs.toString());
String textDescriptions = textDescrs.toString();
// String regex = "\\[|\\]";
// textDescriptions = textDescriptions.replaceAll(regex, "");
//Separate out the question/answer of text description associated with the randomly selected question
StringTokenizer textDescr = new StringTokenizer(textDescriptions, ",");
String first = textDescr.nextToken();
// String second = textDescr.nextToken();
// String third = textDescr.nextToken();
// String fourth = textDescr.nextToken();
subQuestionView1.setText(first);
// subQuestionView2.setText(second);
// subQuestionView3.setText(third);
// answerView3.setText(fourth);
// System.out.println(textDescr);
return null;
}
FYI - I call 'showNextRandomQuestion3()' from an onClick method when user clicks to go to a next question - a new random question and the related answers to that new question will appear each click:
NextQuestionButton.setOnClickListener(new OnClickListener(){;
#Override
public void onClick(View v) {
showNextRandomQuestion3();
showNextAnswers();
countQuestions();
}});
It looks like the solution is very simple. You just capture the return value of showNextRandomQuestion3(), since it returns answerSetId.
You will need to add a String parameter to the showNextAnswers() method to take the String that was returned from showNextRandomQuestion3().
So in your click event, you would do this:
NextQuestionButton.setOnClickListener(new OnClickListener(){;
#Override
public void onClick(View v) {
String answerSetId = showNextRandomQuestion3(); //get return value
showNextAnswers(answerSetId); //give the ID here
countQuestions();
}});
Then, just add the parameter to showNextAnswers(), and you're done!
public String showNextAnswers(String answerSetId) {
SQLDatabaseHelper db = new SQLDatabaseHelper(this);
//get the data from the database
List<List<String>> listList = db.getAnswers(answerSetId); //This will work now!
//.................

Getting one column of SQLite DB to ListView not working in Android

I'm trying to retrieve a column (a database column where names are saved) and puting them to a listview. I have a class called Data with "getters" and "setters".
The following code is placed in a DBHandler class which extends SQLiteOpenHelper. This code is called from the MainActivity.java where the listview is meant to be updated with an onClickButton event.
public String[] getNames (int a, int b) {
String[] names = new String[] {};
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " WHERE " + KEY_ONE + " = ? AND " + KEY_TWO + " = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(a), String.valueOf(b)});
if (cursor.moveToFirst()) {
int i = 0;
do {
Data myData = new Data();
names [i] = cursor.getString(1); //Names in cursor
++i;
} while (cursor.moveToNext());
}
return names;
}
In the MainActivity.java I call the following code before updating and notifying the update of the listview adapter:
values = db.getNames (1, 1);
I don't know why but this isn't working, it throws many errors with String lengths and crashes the app when I click the button that is suposed to enter the onClickButton.
Thanks
Follow the laalto answer and at last convert your ArrayList to Array like below:
String[] arrRecords = names.toArray(new String[names.size()]);
String[] names = new String[] {};
...
names [i] = cursor.getString(1); //Names in cursor
You're assigning to an empty array which causes ArrayIndexOutOfBoundsException.
Consider using a list such as ArrayList where you can append your values, e.g.
List<String> names = new ArrayList<String>();
...
names.add(cursor.getString(1));
If you really need to return a String[], you can convert the list with toArray():
String[] arr = new String[names.size()];
names.toArray(arr);
return arr;
Also, when posting questions that involve exceptions, always include the exception stacktrace from logcat in the question itself.
Why use like this
String[] names = new String[] {}; //no size
names [i] = cursor.getString(1); //it can work?
Use ArrayList<String>
List<String> names = new ArrayList<String>(); //declare
names.add(<column-val>); //add column value to list

How to convert String to ArrayList

I need your help about retreive data from mysql db. I cant add string to array list.
my list declare
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
here my code
report_data = json.getJSONArray(TAG_REPORT_DATA);
for (int i = 0; i < report_data.length(); i++) {
//storing variable
JSONObject c = report_data.getJSONObject(i);
String reportID = c.getString(TAG_REPORT_ID);
String userID = c.getString(TAG_UID);
String projectName = c.getString(TAG_PROJECT_NAME);
String localWork = c.getString(TAG_LOCATION);
String timeStart = c.getString(TAG_TIME_START);
String timeEnd = c.getString(TAG_TIME_END);
Log.d(TAG_LOCATION, localWork);
// add data to Arraylist
reportList.add(new HandleListReport(reportID, userID, projectName, localWork, timeStart, timeEnd));
my problem my listReport missing string data. Logcat show reportList ---> []
thanks for answer!
create a list of string
List<String> list ......
list.add(String)
then list.toArray() method
http://docs.oracle.com/javase/6/docs/api/java/util/List.html#toArray(T[])
it seems you are trying to store object of HandleListReport in arraylist. In that case use the following to initiate
ArrayList<HandleListReport> reportList = new ArrayList<HandleListReport>();
It seems that the length of variable report_data is 0, so the element does not add the list.

creating an object in java

i have a simple doubt in android programming. I am not familiar with java coding.so it might be a simple problem.
In the first two lines I am retrieving an array, which i passed from another activity to this activity...Then i am creating an array list . I am creating an object in the 4th line. Now comes the problem ...
I have to run a for loop to get the url value, which i have to pass it in the BaseFeedParser class. but i cant use the 4th line, i.e creating the object inside the loop because it will create a new object each time... which should not happen ... how can i fix this probelm?
Intent myintent = getIntent();
String[] ActiveURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
BaseFeedParser parser = new BaseFeedParser(url);
// fetching all active URLs
for (int i = 0; i < ActiveURL.length + 1; i++) {
url = ActiveURL[i];
messages.addAll(parser.parse());
}
// now getting the titles out of the messages for display
for (Message msg : messages) {
titles.add(msg.getTitle());
}
Thanks in advance ...
There are some problems in your java code :
Intent myintent = getIntent();
//variables are named in camel case, starting with a lower case letter
String[] activeURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
//we will use parser later, see below
//BaseFeedParser parser = new BaseFeedParser(url);
// fetching all active URLs
//it's very easy to loop through a table in java / C / C++
//learn the pattern, it's the simplest, you got confused with the final index
for (int i = 0; i < activeURL.length ; i++) {
//here you don't change the former object url was referencing,
//you are saying that you give the name url to another object in the array
//it doesn't create any new item, change giving them a name to use them
url = activeURL[i];
//create a new parser for each url, except if they can be recycled
//i.e they have a property setUrl
messages.addAll( new BaseFeedParser(url).parse());
}
// now getting the titles out of the messages for display
for (Message msg : messages) {
titles.add(msg.getTitle());
}
Indeed, you could even shorten the whole thing by
Intent myintent = getIntent();
String[] activeURL = myintent.getStringArrayExtra("URL");
List<String> titles = new ArrayList<String>();
// fetching all active URLs
//use a for each loop
for ( String url : activeURL ) {
//loop through messages parsed from feed to add titles
for (Message msg : new BaseFeedParser(url).parse() ) {
titles.add(msg.getTitle());
}
}
if you don't need the List of Message you called messages.

Categories