I have a spinner that has an item and a sub item, it's populated programatically with hashmaps. I need to be able to grab a value out of the selected item by its key. I've gotten as far as getting the entire hashmap out but I can't figure out how to get just the one value based on the key I need.
JSONArray recordsArray = json.getJSONArray("record");
for (int i = 0; i < recordsArray.length(); i++) {
JSONObject record = recordsArray.getJSONObject(i);
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("code", record.getString("id") + " - " + record.getString("heading"));
datum.put("description", record.getString("body"));
spinneritems.add(datum);
adapter.notifyDataSetChanged();
spinner.setSelection(0);
populateList();
}
The above code shows how I populate my spinner, I then need to grab the value in the populateList() method.
Spinner was populated by an array of hashmaps. I used
String spinnerItem = spinneritems.get(spinner.getSelectedItemPosition()).get("key");
to get the value out of the hashmap at the index in the array I needed
Related
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<>();
}
I want to get all items from a dynamo db table. i have written a query in java as below and it works. but the problem is that it doesn't add all the columns to the AttributeValue Map. it has only the first column (key). so what i do here is searching every item by key in the loop. so it is not efficient if your table has millions of data as i search every item in the loop. what can i do to avoid this situation ?
note: 'name' is the first column in the table. (primary key)
i tried to get the 'count' as i did like 'name' but it doesn't return anything for 'count' but null.
Table table = dynamoDb.getTable(DYNAMODB_TABLE_NAME);
ScanRequest scanRequest = new ScanRequest(DYNAMODB_TABLE_NAME);
ArrayList<DeviceResponse>deviceResponses=new ArrayList<>();
Map<String, AttributeValue> exclusiveStartKey = null;
do {
final ScanResult scanResult = client.scan(scanRequest);
List<Map<String, AttributeValue>> items = scanResult.getItems();
for (int i = 0; i < items.size(); i++) {
Map<String, AttributeValue> map = items.get(i);
AttributeValue value = map.get("name");
String name = value.getS();
Item item = table.getItem("name", name); //Searching item
int count = item.getInt("count"); //getting count from item
DeviceResponse deviceResponse = new DeviceResponse();
deviceResponse.setName(name);
deviceResponse.setCount(count);
deviceResponses.add(deviceResponse);
}
exclusiveStartKey = scanResult.getLastEvaluatedKey();
// Reusing same request object, just setting the start key
scanRequest.setExclusiveStartKey(exclusiveStartKey);
} while(exclusiveStartKey != null);
return deviceResponses;
i tried to get the 'count' as i did like 'name'
No you didn't. This code where you get name:
AttributeValue value = map.get("name");
String name = value.getS();
Is not equivalent to this code where you attempt to get count:
Item item = table.getItem("name", name); //Searching item
int count = item.getInt("count"); //getting count from item
You are taking the name field, and then executing another query against the database for some reason. All the attributes are in the Map<String, AttributeValue> map object. If you wanted to get an attribute named count the same way you got the attribute named name then the code would be the following:
AttributeValue value = map.get("count");
int count = value.getN();
Or just simplify it like so:
int count = map.get("count").getN();
I'm attempting to get the values for the "filterInputParameters" array within the serviceResponseValue map. Right now I have attempted to iterate through the map but could only obtain the first level of data such as the displayName and I need to go one-two levels deeper for the values in filterInputParamters array. Please let me know if you need more information.
Dart Code:
var jsonString = response;
var dropDown = querySelector("#asset");
Map jsonObject = JSON.decode(jsonString) as Map;
dropDownList = jsonObject["serviceResponseValue"] as List<Map>;
LinkedHashMap<String, Map> dataMap = new LinkedHashMap<String, Map>();
//the one causing issues and returning null
var ddValues2 = dropDownList
//extract the 'displayValue'
.map((e2) => e2['filterInputParameters']['value']);
//create a set to eliminate duplicates
//.toSet().toList()
//sort the result
//..sort();
ddValues2.forEach((e2) {
print(e2);
});
Map jsonObject = JSON.decode(jsonString) as Map;
print(jsonObject["serviceResponseValue"][0]["filterInputParameters"]);
In JSON [ ] indicate a List and { } a Map.
You access a list element by passing a numeric index (xxx[5] to get the 6th item)
and a String to access a Map item (xxx["serviceResponeValue"]).
Your JSON starts with
{ // the outer element is a map
"serviceResponseValue":[ // this map item can be accessed with a
// string index"serviceResponseValue"
// after the colon `:` starts the associated value, a list
// the first item can be accessed using [0]
{ // which contains a map
...
"filterInputParameters":[ // this item of the map is returned by ["filterInputParameters"]
{
"id":"8a4984e047d0e40d0147d0e410020008",
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.
Here's what I'm trying to do:
- Retrieve a Map of key-value pairs from a SharedPreferences object (User#, Name)
- write those key-value pairs into an ArrayList such that I can
- use them to populate a ListView with each row containing BOTH the key and the value like so:
User 1 - Joe R.
User 2 - Frank B.
etc
UPDATE:
so after taking a good long look at the SimpleAdapter class, and talking with some wiser more knowledgable folks - I'm a lot closer than I was... but still not all the way there.
here's what I have now:
public class LogHistory extends ListActivity {
static final ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
private static final String KEY = null;
private static final String VALUE = null;
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.log_history);
SharedPreferences logPrefs = getSharedPreferences(LoginField.PREFSNAME, 0);
Map<String, ?> logMap = logPrefs.getAll();
for (Map.Entry<String, ?> e : logMap.entrySet()) {
HashMap<String, String> row = new HashMap<String, String>();
String mKey = e.getKey();
String mValue = (String) e.getValue();
row.put(KEY, mKey);
row.put(VALUE, mValue);
list.add(row);
// FOR DEBUGGING PURPOSES
makeToast(mKey);
makeToast(mValue);
}
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
R.layout.list_item,
new String[] { KEY, VALUE },
new int[] {R.id.item1, R.id.item2}
);
setListAdapter(adapter);
This sort of works - but only half way... what I get as a result is a list of the VALUES in both columns...
HOWEVER the makeToast function returns the proper values for both the KEY and the VALUE - so the problem must be in the SimpleAdapter method yes??
assistance would be great - homework is due tonight! :-0
You need to search for "custom listview", "listview custom adapter" and those things. "two line listview item layout"...
See this example. There are others on Google.
Basically, you can create a ArrayList<Hashmap<String,String>>, which is your data container. You add values to that creating as many HashMap<String, String> objects as you need and using list.add(yourHashMap), where list is the ArrayList.
At the end you feed that to a SimpleAdapter (there are other methods, but this works without much trouble).
Check the docs to see how each thing works exactly.
You are nulling your index keys. Put a name into those final Strings.
This sort of works - but only half way... what I get as a result is a list of the VALUES in both columns...
HOWEVER the makeToast function returns the proper values for both the KEY and the VALUE - so the problem must be in the SimpleAdapter method yes??
As I said, no. When you do this:
row.put(KEY, mKey);
row.put(VALUE, mValue);
You are not providing a meaninful difference between KEY and VALUE, because both are null. It's something like putting all things into the same column.
Your mistake into reasoning that is because the Toast test you created yourself test only the correctness of the values, not the columns:
makeToast(mKey);
makeToast(mValue);
In that you test only the values. ;) You assume that the columns are right, and that the mistake could only be in the values, which is exactly the opposite.
First rule of dealing with computers: computers never assume LOL. ;-)