I want to save multiple files to my database one by one.
And what happen here using my codes is this:
What I want to happen is like this one:
here is my code:
//Arraylist for getting the multiple brand code
ArrayList<String> content = new ArrayList<String>();
for (int j=0; j<checkSelected.length; j++) {
if(checkSelected[j]==true) {
String values = BrandListAdapter.mListItems.get(j);
//content.add(values);
Cursor rSubBrand = databaseHandler.getReport_SubBrandCode(values);
String SubBrandCode = rSubBrand.getString(rSubBrand.getColumnIndex(Constants.SUBBRAND_CODE));
content.add(SubBrandCode);
//Casting and conversion for SubBrand Code
String subBrand = content.toString();
//SAVE SUBBRAND
databaseHandler.SaveSubBrand(new Cons_iReport (ReportCode, subBrand));
Toast.makeText(getApplicationContext(), subBrand, Toast.LENGTH_LONG).show();
}
}
Mistakes:
content.add(SubBrandCode);
do you know how to remove the '[ ]' in the saved data? (e.g. [AC001]) All I want to save is the AC001 only.
Solutions:
Call clear() method of ArrayList before adding new values into it.
Its giving you [AC001] as you are subBrand by doing content.toString();. Don't convert it to string, instead use content.getString(position) and it will give you String value.
Related
I have an myArrayList which is to be stored and restored back in its saved sorted order. But the code does not do that. Why?
ArrayList<String> myArrayList
// save:
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor edit;
edit = prefs.edit();
edit.putStringSet("mydata", new LinkedHashSet<String>(myArrayList));
edit.commit();
// read:
myArrayList = new ArrayList<String>(PreferenceManager
.getDefaultSharedPreferences(getBaseContext()).getStringSet(
"mydata", new LinkedHashSet<String>()));
adapterAppList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
myArrayList);
Is there any better way I can store the value of myArrayList and restored back to its original saved sorted order?
HashSet is not keeping orders, it is ordering for quickest find to it. You can convert list to json and save as string.
When you need to it, you can convert it to ArrayList from json with keeped ordering.
Example:
String listAsString = new Gson().toJson(arrayList); //list to string
List<String> arrayList = Arrays.asList(new Gson().fromJson(listAsString,String[].class)) //string to list
dont forget add library to build.gradle:
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
You can serialize arrayList like string:
1 with gson
public ArrayList<String> convertToArrayList(String json) {
if (TextUtils.isEmpty(json)){
return null; // or new ArrayList<>()
}
Type type = new TypeToken<ArrayList<String>>(){}.getType();
return new Gson().fromJson(json, type);
}
public String convertFromArrayList(ArrayList<String> list) {
if (list == null){
return null;
}
return new Gson().toJson(list);
}
2 without gson
public ArrayList<String> convertToArrayList(String st) {
if (!TextUtils.isEmpty(st)){
String[] str = st.split(",");
if (str.length > 0){
return new ArrayList<>(Arrays.asList(str));
}
}
return null;
}
public String convertFromArrayList(ArrayList<String> list) {
if (list!=null && !list.isEmpty()){
return TextUtils.join(",", list);
}
return null;
}
Yes, you are right, the order is not stored in string set, coz it is a set (duh).
When I was bugged with this, I got the serializing solution where, you can serialize your string.
Read this only if you haven't read about serializing, else go down and read my hack
In order to store array items in order, we can serialize the array into a single string (by making a new class ObjectSerializer (copy the code from – www.androiddevcourse.com/objectserializer.html , replace everything except the package name))
Entering data in Shared preference :
the rest of the code on line 38 -
Put the next arg as this, so that if data is not retrieved it will return empty array(we cant put empty string coz the container/variable is an array not string)
Coming to my Hack :-
Merge contents of array into a single string by having some symbol in between each item and then split it using that symbol when retrieving it.
If you are worried about splitting just look up "splitting a string in java".
[Note: This works fine if the contents of your array is of primitive kind like string, int, float, etc. It will work for complex arrays which have its own structure, suppose a phone book, but the merging and splitting would become a bit complex. ]
PS: I am new to android, so don't know if it is a good hack, so lemme know if you find better hacks.
My Android Application, I want to put new data in a table created in SQLite database, but before that I want to avoid duplication. The way I want to do is first of all to retrieve the data from database and then I save it in a unidimensional String array, and then I run the array to check if the data i want to add into database is in that string, if yes then the data will not be reinserted, if no, then the data is inserted.
My main problem is to get all of those data and to put them into string array: below are my code which is giving only the last item in the database:
Cursor time_from_db=sqLite_database_helper_class.getting_all_call_logs_from_database();
int i,n=time_from_db.getCount();
String[] call_times_array=new String[n];
while (time_from_db.moveToNext()){
for (i=0;i<n;i++) {
call_times_array[i] = time_from_db.getString(4);
}
}
for (i=0;i<n;i++){
text_view_call_log_id=(TextView)findViewById(R.id.text_view_call_log_id);
text_view_call_log_id.setText(call_times_array[i]+"\n\n");
}
Whenever I run this code, is showing that the record saved in that string array is the last one from the database while is a database containing 500 records. So please, kindly help me!
text_view_call_log_id.setText(call_times_array[i]+"\n\n");
This code will only show the last item as you are not appending it correctly. Please use the following code to append correctly.
String result = "";
for (i=0;i<n;i++){
result += call_times_array[i]+"\n\n";
}
text_view_call_log_id= (TextView)findViewById(R.id.text_view_call_log_id);
text_view_call_log_id.setText(result);
For retrieving data from cursor replace your while loop as follows
int i=0;
while (time_from_db.moveToNext()){
call_times_array[i] = time_from_db.getString(4);
i++;
}
Actually, you should append strings all you want to get.
Cursor time_from_db=sqLite_database_helper_class.getting_all_call_logs_from_database();
int i,n=time_from_db.getCount();
String[] call_times_array=new String[n];
while (time_from_db.moveToNext()){
for (i=0;i<n;i++) {
call_times_array[i] = time_from_db.getString(4);
}
}
String result = "";
for (i=0;i<n;i++){
result += call_times_array[i]+"\n\n";
}
text_view_call_log_id=(TextView)findViewById(R.id.text_view_call_log_id);
text_view_call_log_id.setText(result );
try this one?
int i,n=time_from_db.getCount();
String[] call_times_array=new String[n];
int numIndex = 0;
while (time_from_db.moveToNext()){
call_times_array[numIndex] = time_from_db.getString(4);
++numIndex;
}
String result = "";
for (i=0;i<n;i++){
result += call_times_array[i]+"\n\n";
}
text_view_call_log_id=(TextView)findViewById(R.id.text_view_call_log_id);
text_view_call_log_id.setText(call_times_array[i]+"\n\n");
I am trying to learn retrofit and I have made successful attempts at posting data and now I am trying to retrieve JSON array which looks as follows:
{
"result": "success",
"message": "All Questions Have Been Selected",
"question": {
"all_question_ids": ["1","2","3"]
}
}
I am using the following getter
public ArrayList getAll_question_ids(){
return all_question_ids;
}
I am retrieving using Retrofit as follows
if (resp.getResult().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = pref.edit();
Log.d("Question_IDs", "getAllQuestionID() = " + response.body().getQuestion().getAll_question_ids() );
editor.putString(Constants.All_QUESTION_IDS,((resp.getQuestion().getAll_question_ids().toString())));
editor.apply();
}
progress.setVisibility(View.INVISIBLE);
It is here that I am stuck, as I am retrieving the array ok but I am unsure how to loop out the Array which is now stored in Shared Preferences.
When I place a toast to show me how the IDs are coming across, my toast confirms the data as [1,2,3]
The goal is to add a dynamic button and the individual ID, i.e button 1, button 2 etc every-time the loop is iterated.
I have tried the following:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
for (int i =0; i < questionNumber.length(); i++) {
try {
/*Dynamically create new Button which includes the question name
*/
AppCompatButton btn_question = new AppCompatButton(getActivity());
/*LayoutParams (int width, int height,float weight)
As LayoutParams is defaulted in px, I have called a method called dpToPX to make sure
the dynamically added EditText is the same size on all devices.
*/
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpToPx(280), dpToPx(45), 1);
btn_question.setBackgroundColor(Color.parseColor("#3B5998"));
btn_question.setTextColor(Color.WHITE);
// btn_question.setText(String.valueOf(x));
btn_question.setText("Question "+ pref.getString(Constants.All_QUESTION_IDS,""));
btn_question.setGravity(Gravity.CENTER);
//generate unique ID for each new EditText dynamically created
View.generateViewId();
//Log.d("TEST VALUE", "Question1 generated ID = " + btn_question.generateViewId());
params.setMargins(0, dpToPx(10), 0, dpToPx(10));
btn_question.setPadding(0, 0, 0, 0);
btn_question.setLayoutParams(params);
allEds.add(btn_question);
mLayout.addView(btn_question);
} catch (Exception e) {
Log.d(TAG, "Failed to create new edit text");
}
}
However the above is adding the value as it appears in the array e.g [1,2,3] which is obviously not what I want.
I have added a photo in case my explanation isn't clear. I want a button with 1 number added to it each time the loop iterates but I am unable to figure this out.
I have looked through lots of resource but cannot find an answer that is relevant to my problem, although, if there is, I am not familiar enough to recognise a similar issue.
If someone can offer some assistance, I would appreciate it!
When you call editor.putString(Constants.All_QUESTION_IDS,((SOMETHING.toString())));, what is actually stored depends on the implementation of the toString method in the type of SOMETHING (in this case String[]). So avoid doing that. Instead, since you're already using Gson or Jackson (or others), store the question_idsas JSON:
final String jsonIds = gson.toJson (resp.getQuestion().getAll_question_ids());
editor.putString(Constants.All_QUESTION_IDS, jsonIds);
Your actual stored value no longer depends on the implementation of something that you don't control (String[].toString). It is a valid JSON array and regardless of what tool/library you use to read it back, it's valid.
Now, to read back the stored data:
final String storedJson = pref.getString(Constants.All_QUESTION_IDS, null);
if (null == storedJson) {
// TODO: No question ids found
}
final String[] ids = gson.fromJson (storedJson, String[].class);
for (int i = 0; i < ids.length; i++) {
// make your buttons
}
This is a problem of saving and then reading out a List of items (in this case, String instances).
You've chosen to save the list by calling editor.putString() with a value of getAll_question_ids().toString(). That toString() call is going to return a string representation of your list, or, in other words, a String instance with the value [1, 2, 3]. At this point, you no longer have a List proper, but a String that looks like a list.
This is all technically fine, but it means you have to take this into account when you're trying to read out that list.
You've written this to read the list back out:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
Once this line executes, questionNumber will be a String instance with the value [1, 2, 3]. Again, this is fine, but now we come to the key point: we have to convert this String back into a List.
If you know for sure that the values in this list won't have commas in them, you can do it easily:
Trim the braces off the string using substring()
Create a String[] using split()
Convert your array to a list using Arrays.asList() (you could even skip this step since iterating over an array is just as easy as iterating over a list)
Put that together and you get:
String questionNumber = pref.getString(Constants.All_QUESTION_IDS, "");
questionNumber = questionNumber.substring(1, questionNumber.length() - 1);
String[] array = questionNumber.split(", ");
List list = Arrays.asList(array);
At this point, you can iterate over your array or list:
for (String value : list) {
...
btn_question.setText("Question " + value);
...
}
now i've got simple setter and getter of string array. I want to use setter to put some retrevied json info + same text to array. When i use belowe code:
met.setPlacepic(new String[]{"http://dfsdfsdfsf/" + json.getString("source")});
it looks like setter put only one string to array, despite there is many more data.
Declaration is simple
public String[] placepic
and the setter is also simple:
public void setPlacepic(String[] placepic) {
this.placepic = placepic;
}
Anybody knows reason of this?
If the number of strings is fixed (you know exactly how many element you would have in the array), then you could use String Arrays:
String[] placepic = new String[20]; //20 strings
//Then, in your loop:
placepic[i] = yourData;
If you do NOT know how many strings in your data, You should use List:
List<String> placepicList= new ArrayList<String>();
//Then, in your loop:
placepicList.add(yourData);
//Then after the loop, you get the array
String[] placepic = placepicList.toArray(new String[placepicList.size()]);
In my Application i am saving Contacts in SharedPreferences but the array which i am passing is also including open braces and double Quotes in the string.
like this ["contactnumber1","contactnumber2","contactnumber3".......]
but i need the string to be like this
contactnumber1,contactnumber2,contactnumber3....
so that i can use this contactnumbers string to directly place it in sms app and send alert msg with click of a button.
please help me with this
Code:
String[] arrayOfString=localMultiAutoCompleteTextview.getText().toString().split(",");
// Create a JSONArray to store all numbers
JSONArray numberArray=new JSONArray();
// Loop through the multiautocomplete textview value array
for(int i=0; i < arrayOfString.length; i++)
{
// Check whether the string contains '%'
if(arrayOfString[i].contains("%"))
{
// Add numbers to the array
numberArray.put(arrayOfString[i].split("%")[1]);
}
}
// Store the complete number array in preference as String
sp=getActivity().getSharedPreferences("sdat", 2);
ed=sp.edit();
ed.putString("snum", numberArray.toString());
ed.commit();
// To read the numbers after saving
String display = sp.getString("snum", new JSONArray().toString());
System.out.println(display);
Toast.makeText(getActivity(),"Contacts Saved:"+display,Toast.LENGTH_SHORT ).show();
}
});
The following line is a regex which matches quotes and brackets, and removes them from the string. Just call replaceAll and it will go through your string, find the following characters: '[', ']', '"' and remove them from the string.
strWithoutQuotesAndBraces = strWithQuotesAndBraces.replaceAll("(["[\\]])", "");