get the string[] in android from list - java

I have to develop an one android application.
Here i have to get the list of items and set that list of item value in android spinner.
So i have using following code:
if (getIntent().getExtras() !=null) {
retailerNamesList = (ArrayList<RetailerNames>) getIntent().getExtras().getSerializable("RetailerName");
for (int i=0;i<retailerNamesList.size();i++) {}
mRetailerNameAdapter = new RetailerNamesAdapter(WatchList.this,retailerNamesList);
retailerlist.setAdapter(mRetailerNameAdapter);
}
Here i get the list of arraylist values in that spinner.but i have to split these values and set it in android spinner.please help me.how can i do ???
EDIT:
In the above code am getting the output like:
[com.example.RetailerNames#41216470]
But i need to get the output like:
String[] period_timings={"0-2 days","Within a Week","Within a Month"};
That list have to split and get the values in string[].How can i write the code for these ??? please provide me solution for these ???

for (int i=0;i<retailerNamesList.size();i++){
retailerNamesList.get(i);
}
or if you really have to create an array of it then
final int nameListSize = retailerNamesList.size();
String []names = new String[nameListSize];
for (int i=0;i<nameListSize ;i++){
names[i] = retailerNamesList.get(i);
}
// use the string array names to set wherever u need.

Related

Android get ArrayList from Room Database in adapter class

I have a Room Database table with multiple columns (PartsTable). I need to fetch only one column from the table that contains one word String and I'm using a subset of a table as per google docs (PartsTuple).
Now I need to create a function that will or something else that will return the ArrayList of fetched data, which I can access in my adapter class. I am able to return the data and see it in a console log (from the main fragment where I get data from ViewModel), but I just can't seem to make it work on a function that will return the said list of data which I could then access from a different class.
Code from DAO:
#Query("SELECT keyword FROM partsTable")
LiveData<List<PartsTuple>> getTuple();
Code from repo:
public LiveData<List<PartsTuple>> getPartsTuple() {
return partsKeyword;
}
Code from view model:
public LiveData<List<PartsTuple>> getPartsTuple() {
return partsKeyword;
}
Fragment class where I display data in a log:
mViewModel.getPartsTuple().observe(getViewLifecycleOwner(), new Observer<List<PartsTuple>>() {
#Override
public void onChanged(List<PartsTuple> partTuple) {
Log.d(TAG, "vraceno: " + partTuple.toString());
}
});
, and data from the log
D/PartsFragment: vraceno: [part1, parts3, part_2]
Code from adapter class where I compare strings and highlight them.
ArrayTEST arrayTEST = new ArrayTEST();
ArrayList<String> values = arrayTEST.getWordFromHardcodedList();
String text = note.getPartsSubtitle();
Spannable textSpannable = new SpannableString(text);
for (int j = 0; j < values.size(); j++) {
//word of list
String word = String.valueOf(values.get(j));
//find index of words
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1; i++) {
//find the length of word for set color
int last = i + word.length();
textSpannable.setSpan(new BackgroundColorSpan(Color.parseColor("#1a0cab8f")),
i, last, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textSpannable.setSpan(new ForegroundColorSpan(Color.RED),
i, last, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
if (note.getPartsSubtitle().trim().isEmpty()) {
tvTEXT.setVisibility(View.GONE);
} else {
tvTEXT.setText(textSpannable);
}
The part that I'm having trouble with is this, where I need to get a list of data from database and not hardCoded like this
arrayTEST.getWordFromHardcodedList();
Now I need to access this list of data from my adapter class since if there is a match I wanna highlight the parts from the list of parts in my main recycler view where all the data is shown. I can do this when I type the list manually but it needs to be dynamic based on user input.
Thanks in advance
In your adapter class add a field for this list - I'll call it highlightedParts. Observe getPartsTuple() as you do, and set the data you get to highlightedParts. Then you need to create a custom setter for highlightedParts and every time it gets called, update elements of the RecyclerView to highlight the desired items. For updating, you can use notifyDataSetChanged() method. There are other, more optimized variations for only updating a specific item or item range, but you're going to have to update entire dataset.
Ended up using shared preferences with Gson.
In app gradle add
implementation 'com.google.code.gson:gson:2.8.6'
Save the data to SP in a fragment:
SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("shared_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(myListOfData);
editor.putString("partsKEY", json);
editor.apply();
Load the array in the adapter class:
SharedPreferences sharedPreferences = context.getSharedPreferences("shared_preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("partsKEY", null);
Type type = new TypeToken<ArrayList<NoteTupleTest>>() {
}.getType();
partsArrayList= gson.fromJson(json, type);
if (partsArrayList== null) {
partsArrayList= new ArrayList<>();
}

ParseQuery: convert from list of prices in database to strings android

​Hi All,
I am trying to build a scrolling custom listview that displays a list of products ordered by Price ascending. However I just realized I was storing the prices as strings which means $1000.00 comes before $2.01 because it is a character and not a number. I have converted my data to a "Number" on Parse and believe the best type to retrieve it is a double (can anyone comment on that for dollar amounts). The problem is I need to keep it as a number convert it to a string and then pass it to the listview for display on a text field. Initially i had
PPI.setProductprice((String) product.get("Price"));
like this:
// Locate the class table named "Products" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Products");
// Locate the column named "Price" in Parse.com and order list
// by ascending
query.orderByAscending("Price");
ob = query.find();
for (ParseObject product : ob) {
// Locate images in PrimaryPhoto column
ParseFile productimage = (ParseFile) product.get("PrimaryPhoto");
ProductPopulation PPI = new ProductPopulation();
PPI.setProductname((String) product.get("Name"));
PPI.setProductbrand((String) product.get("Brand"));
PPI.setProductprice((String) product.get("Price"));
PPI.setProductimage(productimage.getUrl());
productpopulationlist.add(PPI);
I then tried putting it into an array of doubles an iterating through it to convert to strings.
My last attempt which probably doesn't make sense was to change it like this:
PPI.setProductprice((Double) product.getDouble("Price"));
I am fairly knew to Android and any help you can give me would be appreciated.
Thanks in advance.
OK so i do not get the context here but what you can do is save the price as a string and when extracting it you could call Integer.parseInt(String intvalue); on the string to convert the value back to int then you can do all operations you ought to do. you can get a disordered array from the server and arrange it at device level that will save you some time and logic.
I don't know what is the ProductPopulation class you use to populate the list, so I can not say what exactly is the best way in your case, but in general a list can be ordered by means of the Collections.sort() method (see the method documentation).
You could sort the list before you add it to your list view. To sort a list the way you need, you must provide a comparator, than obtains the required values (fields or method results) from the objects that comprise your list, compares the obtained values and returns -1, 0, or 1, depending on the comparison result.
It could look somewhat like this:
for (...) {
ItemClass newObject = new ItemClass(); // new list item
// ...here add the values to the list item...
theList.add(newObject); // add the new item to the list
}
// now sort the list before adding it to the list viewer
Collections.sort(theList, new Comparator<ItemClass>() {
#Override
public int compare(ItemClass o1, ItemClass o2) {
// obtain and compare the values you need
return Double.compare(o1.getDouble(), o1.getDouble());
// you could also do something like
// Double.compare(
// Double.parseDouble(o1.getString()),
// Double.parseDouble(o2.getString()));
// but it would be much slower
}
});
// now add the sorted list to the viewer
listViewer.setList(theList);

JAVA-How to get all keys from an array that start with a certain string?

I am trying to get some values from config file. I have lot of keys and want to get only certain values. These values have keys starting with same initial name with a slight variation towards the end.
can Someone help me quickly?
assuming when you say key you mean value (as in values in an array),
final String PREFIX = "yourPrefix";
for(String value : valueList) {
if(value.startwith(PREFIX)) {
<do whatever...>
}
here is the link to the java Doc
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#startsWith(java.lang.String)
I am assuming you are scanning the config file for Strings that have similar prefixes. Why not try scanning them in grouped instead of scanning them in all in one hashmap. If you know already the specified prefixes try creating an arraylist for each prefix and while scanning receive the given prefix and add it accordingly.
StringTokenizer s = new StringTokenizer ("Configuration File : Server_intenties = keyId_11503, keyId_11903 : Server_passcodes = keyCode_1678, keyCode_9893", " ");
ArrayList<String> keyCode = new ArrayList();
ArrayList<String> keyId = new ArrayList();
while(s.hasMoreTokens){
String key = s.nextToken
if(key.contains("keyId")){
keyId.add(key);
}
if(key.contains("keyCode")){
keyCode.add(key);
}
}
System.out.println(keyCode);
System.out.println(keyId);

How to pass a list of values into a crystal report

I have a list of integer values(employee IDs) which i need to pass to a Crystal Report.
I am using a Action class to pass these values.
So far i have succeeded with passing a single value but i couldn't find a way to pass a list of values.
Fields fields = new Fields();
Values vals1 = new Values();
ParameterFieldDiscreteValue pfieldDV1 = new ParameterFieldDiscreteValue();
pfield1.setName("fromDate");
pfieldDV1.setValue(start_Date);
vals1.add(pfieldDV1);
pfield1.setCurrentValues(vals1);
fields.add(pfield1);
CrystalReportViewer viewer = new CrystalReportViewer();
//some code to set CrystalReportViewer settings
viewer.setParameterFields(fields);
By this way i was able to get the fromDate value into the Crystal Report.
Does any one know how to get a this kind of list
int employeeList[]
Or a
String[] empListOptions
Thanks in advance.
foreach (string in string_array)
{
param.Value = string;
report.ParameterFields[parameter].CurrentValues.Add(param);
}
Found here: http://www.logicaltrinkets.com/wordpress/?p=227

how to add Set<String> value to the List in the for loop?

I would like to iterate the Value of the accountset List<AccountTO> and set to AccountID.
Actually in the accountset I am getting the values : 100,101,102 I would like to add the values to the List<AccounTO> and set them to AccountID and pass it to the Service call. Is there any that I can go with or else any other procedure.
for(String s :group.getAccounts().keySet())
{
System.out.println("===="+s.lastIndexOf("-"));
System.out.println("sub"+s.substring(0,s.lastIndexOf("-")));
accountSet.add(s.substring(0, s.lastIndexOf("-")));
}
If I understand the question correctly it should be fairly simple :
List<AssetAllocationTO> someList = new ArrayList<AssetAllocationTO>();
for (String string : group.getAccounts().keySet()){
AssetAllocationTO al = new AssetAllocationTO();
al.setAccountID(string);
someList.add(al);
}

Categories