I am trying to create an ObservableList() to use with my Tableview. The StringData type is a class containing two SimpleStringProperty var. I want to create this list and bind each variable to an specific position of a List. Something like this:
public class DownloadService implements Runnable {
//List that will be updated
public List<SimpleStringProperty> dList = new ArrayList<SimpleStringProperty>();
public class MainScreenController implements Initializable {
//List that populates TV
private ObservableList<DataString> data = FXCollections.observableArrayList();
//tableview
#FXML
private TableView<DataString> tbl_table;
DownloadService download;
...}
public class DataString{
public final SimpleStringProperty state;
public final SimpleStringProperty sinc;
public SimpleStringProperty stateProperty() {
return state;
}
public void setState(String status) {
state.set(status);
}
public SimpleStringProperty sincProperty() {
return sinc;
}
public void setSinc(String sinc) {
this.sinc.set(sinc);
}
}
On MainScreenController I try to do this:
DataString s = new DataString();
s.state.bind (download.dList.get(data.size()));
s.sinc.bind (download.dList.get(data.size()));
data.add(s);
tbl_table.setItems(data);
However, I cannot update the content of data when I update the list on DownloadService. I believe it should update the value of the column associated with the state and sinc variable everytime DownloadService updated the content of the list in each position. I am doing something wrong or is there another way to bind a StringProperty to a position on the list?
Thanks!
You are binding to the specific object inside the list, not to the position. If using SimpleStringProperty in dList isn't strict requirement, than you can use Bindings.stringValueAt():
StringBinding binding = Bindings.stringValueAt(dList, index);
s.state.bind(binding);
If you really need SimpleStringProperty, you can implement custom StringBinding, something like this:
class CustomStringBinding extends StringBinding {
private ObservableList<SimpleStringProperty> op;
private int index;
public CustomStringBinding(ObservableList<SimpleStringProperty> list, int index) {
this.op = list;
this.index = index;
super.bind(op, op.get(index));
}
#Override
public void dispose() {
super.unbind(op, op.get(index));
}
#Override
protected String computeValue() {
try {
return op.get(index).get();
} catch (IndexOutOfBoundsException ex) {
// log
}
return null;
}
#Override
public ObservableList<?> getDependencies() {
return FXCollections.singletonObservableList(op);
}
}
Related
This Is Main Fragment
Fragment:
private void getStock() {
dialog.show();
Retrofit retrofit = RetrofitClient.getRetrofitInstance();
apiInterface api = retrofit.create(apiInterface.class);
Call<List<Blocks>>call = api.getVaccineBlocks();
call.enqueue(new Callback<List<Blocks>>() {
#Override
public void onResponse(Call<List<Blocks>>call, Response<List<Blocks>> response) {
if (response.code() == 200) {
block = response.body();
spinnerada();
dialog.cancel();
}else{
dialog.cancel();
}
}
#Override
public void onFailure(Call<List<Blocks>> call, Throwable t) {
dialog.cancel();
}
});
}
private void spinnerada() {
String[] s = new String[block.size()];
for (int i = 0; i < block.size(); i++) {
s[i] = block.get(i).getBlockName();
final ArrayAdapter a = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, s);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spinner.setAdapter(a);
}
}
This Is Blocks Model
model:
package com.smmtn.book.models;
import java.io.Serializable;
public class Blocks implements Serializable {
public String id;
public String blockName;
public String blockSlug;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBlockName() {
return blockName;
}
public void setBlockName(String blockName) {
this.blockName = blockName;
}
public String getBlockSlug() {
return blockSlug;
}
public void setBlockSlug(String blockSlug) {
this.blockSlug = blockSlug;
}
}
here i need onitemclick with blockslug please any one can help, am new to android so i need some example.when on click i want take blockslug and load another method with that blockslug,like will get data from u "http://example.com/block/"+blockslug
i want to get blockslug from selected block
i hope guys i will get help
and sorry for my bad English,
First of all, you need to implement setOnItemSelectedListener. Refer to this https://stackoverflow.com/a/20151596/9346054
Once you selected the item, you can call them by making a new method. Example like below
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
final String itemSelected = parent.getItemAtPosition(pos).toString();
showBlockSlug(itemSelected);
}
And then, at the method showBlockSlug() , you can call Retrofit.
private void showBlockSlug(final String blockslug){
final String url = "http://example.com/block/"+ blockslug;
//Do your stuff...
}
I am trying to create my custom configuration object from Map using model mapper. Everything gets mapped properly excepts the fields property which is coming fro Generic super class.
My target object is
public class ADParserConfig extends CustomParserConfig<ADParserConfigField> {
private String pattern;
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
This extends generic class CustomParserConfig
public class CustomParserConfig<T extends CustomParserConfigField> {
protected List<T> fields;
protected String timeStampField;
public List<T> getFields() {
return fields;
}
public void setFields(List<T> fields) {
this.fields = fields;
}
public String getTimeStampField() {
return timeStampField;
}
public void setTimeStampField(String timeStampField) {
this.timeStampField = timeStampField;
}
}
Where CustomParserConfigField is
public class CustomParserConfigField {
protected String name;
protected Integer index;
protected String type;
protected String format;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
}
I am trying to map Map using below function
ADParserConfig adParserConfig = getConfig(map,ADParserConfig.class);
public <T extends CustomParserConfig> T getConfig(Map<String,Object> configObject, Class<T> classType){
ModelMapper modelMapper = new ModelMapper();
return modelMapper.map(configObject,classType);
}
Everything excepts fields gets mapped properly for the below map.
{fields=[{name=timeStamp, type=timestamp, format=dd/mm/yyyy HH:MM:SS a}, {name=logName, type=string}], pattern=(?<timeStamp>\d{2}\/\d{2}\/\d{4}\s\d{2}:\d{2}:\d{2}\s[AMPMampm]{2})?\s(LogName=(?<logName>[\w\s\W]+))?\sSourceName=(?<sourceName>[\w\s\W]+)\sEventCode=(?<eventCode>[0-9]*), timeStampField=timestamp}
Please help. Why is issue happens only for fields object ? Do I need to specify something else in mapper configurations ?
It looks like a bug and it had been fixed by #370
I've use Filterable inside my RecyclerView. What I wanted to do is, to filter the recyclerview from edittext. Below is my actual code.
public class NavDrawerAdapter_v2 extends RecyclerView.Adapter<NavDrawerAdapter_v2.ViewHolder> implements Filterable{
private static final int TYPE_ITEM = 0;
private ArrayList<String> menu_list;
private ArrayList<String> filtered_menu_list;
Context mContext;
public static class ViewHolder extends RecyclerView.ViewHolder {
int Holderid;
TextView shopName, shopLevel;
public ViewHolder(View itemView,int ViewType) {
super(itemView);
shopName = (TextView) itemView.findViewById(R.id.rowText);
shopLevel = (TextView) itemView.findViewById(R.id.rowLevel);
if(ViewType == TYPE_ITEM) {
Holderid = 0;
}
}
}
public NavDrawerAdapter_v2(Context mContext, ArrayList<String> menu_list){
this.menu_list = menu_list;
this.filtered_menu_list = menu_list;
this.mContext = mContext;
}
#Override
public NavDrawerAdapter_v2.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_ITEM) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.drawer_item_row,parent,false); //Inflating the layout
return new ViewHolder(v,viewType);
}
return null;
}
#Override
public void onBindViewHolder(NavDrawerAdapter_v2.ViewHolder holder, int position) {
if (holder.Holderid == 0) {
String getShopName = menu_list.get(position).split("-")[0];
String getShopLevel = menu_list.get(position).split("-")[1];
holder.shopName.setText(getShopName);
holder.shopLevel.setText(getShopLevel);
}
}
#Override
public int getItemCount() {
return menu_list == null ? 0 : menu_list.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemViewType(int position) {
return TYPE_ITEM;
}
public boolean okay(){
return true;
}
#Override
public Filter getFilter() {
return new UserFilter(this, menu_list);
}
private static class UserFilter extends Filter {
private final NavDrawerAdapter_v2 adapter;
private final ArrayList<String> originalList;
private final ArrayList<String> filteredList;
private UserFilter(NavDrawerAdapter_v2 adapter, ArrayList<String>originalList) {
super();
this.adapter = adapter;
this.originalList = new ArrayList<>(originalList);
this.filteredList = new ArrayList<>();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
filteredList.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
filteredList.addAll(originalList);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (String getValue : originalList) {
if (getValue.contains(filterPattern)) {
filteredList.add(getValue);
}
}
}
results.values = filteredList;
results.count = filteredList.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
adapter.filtered_menu_list.clear();
adapter.filtered_menu_list.addAll((ArrayList<String>) results.values);
adapter.notifyDataSetChanged();
}
}
}
But, in my fragment. I can't call adapter.getFilter(). What is wrong here?
If you want EditText for searchView purposes, you need to add change listener for EditText, as explained in the link : android on Text Change Listener
When the text changed, you should call
adapter.getFilter().filter(newText);
Alternatively, you should try to implement searchview in action bar with recyclerView. Todo this, implement getFilter() method inside your RecyclerView adapter. You can use the getFilter() method implemented in the link https://stackoverflow.com/a/10532898/1308990 .
menu.xml:
<item android:id="#+id/menuSearch"
android:title="search"
android:icon = "#android:drawable/ic_menu_search"
app:actionViewClass = "android.support.v7.widget.SearchView"
app:showAsAction = "always|collapseActionView"></item>
Inside onCreateOptionsMenu() method, write following codes :
MenuItem item = menu.findItem(R.id.menuSearch);
//SearchView searchView = (SearchView) item.getActionView();
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//Called when the query text is changed by the user.
#Override
public boolean onQueryTextChange(String newText) {
Log.d("soda in MainActivity","onQueryTextChange method is called.");
mutfagimFragment.adapter.getFilter().filter(newText);
return false;
}
});
When the user changes the text, check whether the onQueryTextChange() method is called by monitoring the logs. If it is not called, try to put the above codes inside onPrepareOptionsMenu() method rather than onCreateOptionsMenu() method.
Following your example, I'm pretty sure you were assigning the object to a RecyclerView.Adapter variable instead of to a NavDrawerAdapter_v2 variable inside the Activity.
RecyclerView.Adapter adapter = new NavDrawerAdapter_v2(menuList);
instead of
NavDrawerAdapter_v2 adapter = new NavDrawerAdapter_v2(menuList);
NavDrawerAdapter_v2 extends from RecyclerView.Adapter but at the same time implements Filterable.
If you assign the object to a RecyclerView.Adapter variable you will still be able to call getItemCount(), onBindViewHolder() and onCreateViewHolder() (since they are abstract methods from RecyclerView.Adapter)
The bad part is that you won't be able to call getFilter() because it belongs to the Filterable interface.
I want to store many details (like name, email, country) of the particular person using the same key in hashtable or hashmap in java?
hashMap.put(1, "Programmer");
hashMap.put(2, "IDM");
hashMap.put(3,"Admin");
hashMap.put(4,"HR");
In the above example, the 1st argument is a key and 2nd argument is a value, how can i add more values to the same key?
You can achieve what you're talking about using a map in each location of your map, but it's a little messy.
Map<String, Map> people = new HashMap<String, Map>();
HashMap<String, String> person1 = new HashMap<String, String>();
person1.put("name", "Jones");
person1.put("email", "jones#jones.com");
//etc.
people.put("key", person1);
//...
people.get("key").get("name");
It sounds like what you might really want, though, is to define a Person class that has multiple properties:
class Person
{
private String name;
private String email;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
//plus getters and setters for other properties
}
Map<String, Person> people = new HashMap<String, Person>();
person1 = new Person();
person1.setName("Jones");
people.put("key", person1);
//...
people.get("key").getName();
That's the best I can do without any information about why you're trying to store values in this way. Add more detail to your question if this is barking up the wrong tree.
I think what you are asking
let us assume you we want to store String page, int service in the key and an integer in the value.
Create a class PageService with the required variables and define your HashMap as
Hashmap hmap = .....
Inside pageService, what you need to do is override the equals() and hashcode() methods. Since when hashmap is comparing it checks for hashcode and equals.
Generating hashcode and equals is very easy in IDEs. For example in eclipse go to Source -> generate hashcode() and equals()
public class PageService {
private String page;
private int service;
public PageService(String page, int service) {
super();
this.page = page;
this.service = service;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public int getService() {
return service;
}
public void setService(int service) {
this.service = service;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((page == null) ? 0 : page.hashCode());
result = prime * result + service;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PageService other = (PageService) obj;
if (page == null) {
if (other.getPage() != null)
return false;
} else if (!page.equals(other.getPage()))
return false;
if (service != other.getService())
return false;
return true;
}
}
The following class is very generic. You can nest ad infinitum. Obviously you can add additional fields and change the types for the HashMap. Also note that the tabbing in the toString method should be smarter. The print out is flat.
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class HierarchicalMap
{
private String key;
private String descriptor;
private Map<String,HierarchicalMap>values=new HashMap<String,HierarchicalMap>();
public String getKey()
{
return key;
}
public void setKey(String key)
{
this.key = key;
}
public void addToSubMap(String key, HierarchicalMap subMap)
{
values.put(key, subMap);
}
public String getDescriptor()
{
return descriptor;
}
public void setDescriptor(String descriptor)
{
this.descriptor = descriptor;
}
public HierarchicalMap getFromSubMap(String key)
{
return values.get(key);
}
public Map<String,HierarchicalMap> getUnmodifiableSubMap()
{
return Collections.unmodifiableMap(values);
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("HierarchicalMap: ");
sb.append(key);
sb.append(" | ");
sb.append(descriptor);
Iterator<String> itr=values.keySet().iterator();
while(itr.hasNext())
{
String key= itr.next();
HierarchicalMap subMap=this.getFromSubMap(key);
sb.append("\n\t");
sb.append(subMap.toString());
}
return sb.toString();
}
How to read variable length String from a C struct using Javolution API?
For example the code below is used to get a fixed size String-
public final UTF8String data= new UTF8String(100);
Can anyone give me an example for reading variable length String.
This is what we have and we are learning as well:
public class EvDasTestResults extends AbstractServiceJavolutionObject
{
public final Signed32 result = new Signed32();
public final UTF8String description;
public EvDasTestResults(int size)
{
description = new UTF8String(size);
}
}
public abstract class AbstractServiceJavolutionObject extends Struct
{
#Override
public ByteOrder byteOrder()
{
return ByteOrder.nativeOrder();
}
#Override
public boolean isPacked()
{
return true;
}
}