How to get a value from listview with multidimensional array? - java

So I have a multidimensional array for my listview, it constructed like this:
String[][] listControls = {
{"Shutdown Host","10"},
{"Close Connection","1"}};
Let say the first String is the text I want to display in the list view, and the other one is a id/message to send via socket (lets say it a secret value).
I coded the Adapter like this:
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.layout_listview);
for(int i = 0; i < listControls.length; i++) {
adapter.add(listControls[i][0]);
}
listView = (ListView) findViewById(R.id.controls_listView);
listView.setAdapter(adapter);
listView.setClickable(true);
And I constructed the click listener of an item:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj = listView.getItemAtPosition(position);
//What should I add here? to get specific value from the array?
//Integer cmdId = Integer.parseInt( ... );
}
});
From the click listener, i want to get the other value, e.g. If I clicked "Close Connection" in list view, I want to get the "1" value from it and put it into a variable.
Thanks in advance for the help.

Write custom adapter for your case. Use HashMap which is always better.
HashMap<String, Integer> map = new LinkedHashMap<>();
map.add("Shut Down Host", 0);
map.add("Close connection", 1);
And most importantly use RecyclerView.
Tutorial for RecyclerView https://developer.android.com/guide/topics/ui/layout/recyclerview

What you could do is
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = listControls[position][1]
}
This will, of course work only if you have access to listControls. If not, I'd opt for creating an object SomethingWithCode(String text, Int code)[or just Pair in kotlin] and creating a custom adapter.
Hope this helps!
Also, you probably don't need multidimensional array for it, if you're always passing just two values(refer to object with string and int parameters)

Related

SetText () method does not work if the element its associated with an onItemSelected () element of a Spinner

I have an activty which has an EditText and a Spinner, in which when selecting an element of the Spinner, the selected element must be displayed in the EditText. Until then everything goes well. But if I want to assign a value to that EditText, outside of the onItemSelected method proper to the Spinner, it simply does not show the string I assigned it with the setText method.
deps = new ArrayList<>();
cargarDeps();
deps.add("");
adapterSPDep = new ArrayAdapter<String>(this, R.layout.lista_sp, deps);
spDep.setAdapter(adapterSPDep);
spDep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
auxDep = (String) adapterView.getItemAtPosition(pos);
txtDep.setText(auxDep);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// txtDep.setText(auxDep);
}
});
that code its in the onCreate of my activity, my method "cargaDeps()" is linked to a webservice which obtains all the departments that exists, which I save in the ArrayList "deps". In the onItemSelected () method of the Spinner is where I assign what my EditText is selected. But when I call this method:
public void rellenar(String[] campos) {
txtNum.setText(campos[4]);
txtFecha.setText(campos[1]);
txtHora.setText(campos[2]);
txtDes.setText(campos[3]);
txtTipo.setText(campos[4]);
txtDep.setText(auxDep);
txtReporta.setText(campos[6]);
txtAtiende.setText(campos[7]);
}
in txtDep.setText (auxDep); no value is assigned.
Make a global String value and assign the value you want to get from the spinner to the String value.

Android Firebase RecyclerView Adapter Remove Views

I am facing a Firebase RecyclerView problem where I cannot remove unwanted CardViews from my RecyclerViews. In my code I check the city's name and the guide's chosen city to match them. It populates guide's details only if the guide's city matches the picked city, but it also shows empty cardview with default layout.
guideDataRef = FirebaseDatabase.getInstance().getReference().child("Guides");
public void recycler() {
super.onStart();
try {
//Guide RecyclerView
Query guideQuery = guideDataRef.orderByKey();
guideQuery.keepSynced(true);
FirebaseRecyclerOptions guideOptions =
new FirebaseRecyclerOptions.Builder<UserModelClass>().setQuery(guideQuery, UserModelClass.class).build();
guideAdapter = new FirebaseRecyclerAdapter<UserModelClass, guideViewHolder>(guideOptions) {
#Override
protected void onBindViewHolder(#NonNull guideViewHolder holder, final int position, #NonNull final UserModelClass model) {
String pickedcity = model.getPickedCity();
String postname = (String) cityName.getText();
if(pickedcity.equals(postname)) {
final String guide_key= getRef(position).getKey();
holder.setGuideName(model.getName());
holder.setGuideSurname(model.getSurName());
holder.setGuideImage(getApplicationContext(), model.getPhotoURL());
// holder.mView.setVisibility(View.VISIBLE);
//Guide Click listener
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent guideHireIntent = new Intent(getApplication(), GuideHireActivity.class);
guideHireIntent.putExtra("guide_id", guide_key);
finish();
startActivity(guideHireIntent);
}
});
}
}
#NonNull
#Override
public guideViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout_guides, parent, false);
return new guideViewHolder(view);
}
#Override
public void onError(DatabaseError e){
Toast.makeText(getApplicationContext(), "Error by stopping ", Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return super.getItemCount();
}
#Override
public void onDataChanged() {
super.onDataChanged();
notifyDataSetChanged();
}
};
guideAdapter.notifyDataSetChanged();
guideRecyclerView.setAdapter(guideAdapter);
guideAdapter.startListening();
} catch (DatabaseException e) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
}
}
enter image description here
enter image description here
I can change the adapter visibility to gone if it does not match with the requirements but the problem is that after making it's visibility gone it is still there holding the place (but invisible - there's still an empty space). How can I avoid populating an item from the recycler view completely, instead of making it invisible if the requirements do not match?
You're not showing what guideDataRef is in your code, so I'm assuming that it's just aDatabaseReference object for everything beneath a \Guides node.
If you're doing that, you're going to get a call for onBindViewHolder for every child at that particular location. This means that you're going to be asked to make a view for every child. You cannot choose whether or not a view will appear for that item.
It looks like you're assuming that your if statement in onBindViewHolder method will skip over those items. But what's actually happening is that you're simply allowing an empty view to occupy that spot in the list.
Instead, you should come up with a query that generates only the items of interest to your list. This means you'll have to tell Firebase to filter for children that meet your criteria.
You can also read the entire contents of the location, manually filter out the items you don't want, and build a list of items you do want. You can then build an custom adapter with that list, and it can then become the input to a ListView or even better to a RecyclerView.

How to Select an Array By Selected List Position in Android

I have one string array to hold some options and 470 string array to hold this option's values I use a spinner to populate a options string array. I want to select an array from between 470 arrays according to selected option. For example if i select 2. option i want to print values2 array to screen. How can i do. I dont want to use 470 if then else blocks.
final String[] options={"option0","option1","option2","option3"...};
final String[] values0={"kjhk","kjhkhkhk","asfasd"};
final String[] values1={"gvctc","ononnnın","njbsalna"};
final String[] values2={"aasd","qwert","asadad"};
.
.
final String[] values470{"ljlj","ljljl","opıuo"};
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, final int position,long id) {
}
If you really want to setup your data by hand.
Here's a quick & dirty solution based on your provided information and data structure :
Map<String,List<String>> optionToValueMap=new HashMap<>();
List<String>values= new ArrayList<>();
values.add("1");
values.add("2");
optionToValueMap.put("option0",values);
// get values for 'option0'
for (String value:optionToValueMap.get("option0")){
}
I am not sure this is perfect solution but it can do what you want.
final String[] options={"option0","option1","option2","option3"...};
final String[] values0={"kjhk","kjhkhkhk","asfasd"};
final String[] values1={"gvctc","ononnnın","njbsalna"};
final String[] values2={"aasd","qwert","asadad"};
//form an two dimensional array
final String[][] values={values0,values1,values2};
OnSpinner Clickevent
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, final int position,long id) {
//here you get an particular array.
String[] array=values[position];
}

How to make listView say one thing, but pass through different data

So this question is a little hard to explain, but basically what i want is to have an array list for a listview, but change the title on the listview. So that when the user sees the listview it says one thing, but passes through different information.
Here's my code:
//the string names
String names[] = { "item1", "item2"};
i have 2 classes called item1.java and item2.java
when one listitem is clicked it sets a class equal to the activity name and opens it like this:
protected void onListItemClick(ListView lv, View v, int position, long id){
super.onListItemClick(lv, v, position, id);
String openClass = names[position];
try{
Class selected = Class.forName("com.example.example." + openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
But in the listview i don't want it to say "item1" and "item2"....is there any way to make like an alias or something?
Sorry if my question is hard to understand i tried my best to explain what i need help with let me know if you have any questions about my question(: thanks for the help
You do this the same way you make any custom adapter, such as one that should display images instead of or in addition to some text.
For example, if your adapter is an ArrayAdapter, you create a subclass, override getView(), and do what you want in there to format your rows the way that you want.
You can override toString() to do this. See following example
public static class Alias {
String originalValue;
public Alias(String s) {
this.originalValue = s;
}
#Override
public String toString() {
return "What are you want to show";
}
}
String names[] = {"item1", "item2"};
Alias array[] = new Alias[names.length];
Alias array[0] = new Alias(names[0]);
Alias array[1] = new Alias(names[1]);
ArrayAdapter<Alias> adapter = new ArrayAdapter<Alias>(this, resId, array);
This will show "What are you want to show" in every listview whatever the value is.

Using a Spinner value in a calculation

Wondering if i can get some help with a problem i'm having? I have searched for the answer on here, and although i found a few relevant topics i'm still really struggling...
Below you can see that i'm using a Spinner asking the user to select either Large, Med or Small.
The selection is then issued to a TextView.
What i now want to do is assign a value to the 3 selections, Large = 6, Med = 4, Small =2.
Next there will be a EditText box for the user to add their own value.
Then i want to put the two values into a calculation (say * them in this example) putting the answer into a TextView.
Any help here would be great.
Many Thanks
Will
String[] items = { "Large", "Med", "Small" };
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.plugfan);
Factor = (TextView) findViewById(R.id.Factor);
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
items);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
Factor.setText(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
Factor.setText("");
}
A quick way to solve this (not the smartest one) is to have a paralell array:
int[] itemValues = { 6, 4, 2 };
In the method onItmeSelected you can setText using the itemValue, instead of items.
If you want a more OO-solution a new class that returns a list of Strings to use as a model for your spinner might be a beter solution (an enumeration might solve it too).

Categories