Android Studio, for Listview error working scrollview - java

for Android Studio with Java
Listview have not correctly scrollview, so mean I select first item in Listview but Selecting first item both another a item. So mean, showing me two item, one's my selected item another random a item
What can I do about this situation
for Listview, selected item not correctly work

Automatically selected item element in list view
please refer this 2 link, I hope you getting your solution
This is first link
This is second link

Map<Integer, String> Green = new HashMap<>();
Map<Integer, String> white = new HashMap<>();
checkBox_TumParca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox_TumParca.isChecked()){
for(int i=0;i<barkodlar.size();i++){
listemiz.getChildAt(i).setBackgroundColor(Color.GREEN);
Green.put(i,"Yeşil");
white.remove(i);
}
}else{
for(int i=0;i<barkodlar.size();i++){
listemiz.getChildAt(i).setBackgroundColor(Color.WHITE);
white.put(i,"Beyaz");
Green.remove(i);
}
}
}
});
ArrayList<Integer> posit = new ArrayList<>();
ArrayList<Integer> yesil = new ArrayList<>();
ArrayList<Integer> beyaz = new ArrayList<>();
listemiz.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
try {
String a=Green.get(position);
if (a!="Yeşil"){
listemiz.getChildAt(position).setBackgroundColor(Color.GREEN);
Green.put(position,"Yeşil");
white.remove(position);
}
else if (a=="Yeşil"){
listemiz.getChildAt(position).setBackgroundColor(Color.WHITE);
white.put(position,"Beyaz");
Green.remove(position);
}
}catch (Exception ex){
dialog("",ex.getMessage(),false);
}
}
});

Related

how I can hide the element with index 0 from dropdown list in spinner

Please tell me how can I hide the item at index 0 from the dropdown in the spinner in Android Studio? I am using this code, it works, but when I open the list, it shows at the bottom. That is, it is focused on the elements below. what do i need to change?
SpinnerName = (Spinner) v.findViewById(R.id.spinner1);
ArrayList<String> names = new ArrayList<>();
names.add(0, "SELECT");
names.add(1, "Name1");
names.add(2, "Name2");
final int listsize = names.size()-1;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, names){
#Override
public int getCount() {
return(listsize);
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerName.setAdapter(adapter);
adapter.setDropDownViewResource(R.layout.spinner_list);
SpinnerName.setSelection(listsize);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
....
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
SpinnerName.setSelection(listsize);
your problem is here! you are passing the total list size number and
that where you are doing wrong, because setSelection method use to
show default index of spinner.
you can simply do that SpinnerName.setSelection(1); that would give you the fist spinner item unless showing the names.add(0, "SELECT"); item

how to save the state of those items which have been selected in recyler view even after the app is closed

What I want to do is to show the same selected items on a recycler view even after the activity has been closed and only change items color when I again click on it. For now I have achieved changing the color on click but the state doesn't get saved?
This is my adapter:
public class LightsRecyclerViewAdapter extends
RecyclerView.Adapter<LightsRecyclerViewAdapter.ViewHolder> {
// private List<Integer> mViewColors;
private List<String> mAnimals;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
LightsRecyclerViewAdapter(Context context, List<String>
animals) {
this.mInflater = LayoutInflater.from(context);
this.mAnimals = animals;
}
// inflates the row layout from xml when needed
#Override
#NonNull
public ViewHolder onCreateViewHolder(#NonNull ViewGroup
parent, int viewType) {
View view = mInflater.inflate(R.layout.item, parent,
false);
return new ViewHolder(view);
}
// binds the data to the view and textview in each row
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int
position) {
// int color = mViewColors.get(position);
String animal = mAnimals.get(position);
// holder.myView.setBackgroundColor(color);
holder.myTextView.setText(animal);
}
// total number of rows
#Override
public int getItemCount() {
return mAnimals.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
View myView;
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
// myView = itemView.findViewById(R.id.colorView);
myTextView =
itemView.findViewById(R.id.tvAnimalName);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null)
mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public String getItem(int id) {
return mAnimals.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener
itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
And this is my activity:
public class DevicesList extends AppCompatActivity implements
LightsRecyclerViewAdapter.ItemClickListener{
private LightsRecyclerViewAdapter adapter,adapter1;
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_devices_list);
title = (TextView)findViewById(R.id.textGrid);
// data to populate the RecyclerView with
ArrayList<Integer> viewColors = new ArrayList<>();
viewColors.add(Color.BLUE);
viewColors.add(Color.YELLOW);
viewColors.add(Color.MAGENTA);
viewColors.add(Color.RED);
viewColors.add(Color.BLACK);
ArrayList<String> Lab1LightsList = new ArrayList<>();
Lab1LightsList.add("Light 1");
Lab1LightsList.add("Light 2");
Lab1LightsList.add("Light 3");
Lab1LightsList.add("Light 4");
Lab1LightsList.add("Light 5");
ArrayList<String> Lab1ACList = new ArrayList<>();
Lab1ACList.add("AC 1");
Lab1ACList.add("AC 2");
Lab1ACList.add("AC 3");
Lab1ACList.add("AC 4");
Lab1ACList.add("AC 5");
ArrayList<String> Lab2LightsList = new ArrayList<>();
Lab2LightsList.add("Light 1");
Lab2LightsList.add("Light 2");
Lab2LightsList.add("Light 3");
Lab2LightsList.add("Light 4");
Lab2LightsList.add("Light 5");
Lab2LightsList.add("Light 6");
ArrayList<String> Lab2ACList = new ArrayList<>();
Lab2ACList.add("AC 1");
Lab2ACList.add("AC 2");
Lab2ACList.add("AC 3");
Lab2ACList.add("AC 4");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.list1);
RecyclerView recyclerView1 =findViewById(R.id.list2);
LinearLayoutManager horizontalLayoutManagaer
= new LinearLayoutManager(DevicesList.this, LinearLayoutManager.HORIZONTAL, false);
LinearLayoutManager horizontalLayoutManager
= new LinearLayoutManager(DevicesList.this, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(horizontalLayoutManagaer);
recyclerView1.setLayoutManager(horizontalLayoutManager);
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("labno", 0);
if(intValue==0) {
adapter = new LightsRecyclerViewAdapter(this, Lab1LightsList);
adapter1 = new LightsRecyclerViewAdapter(this, Lab1ACList);
adapter.setClickListener(this);
adapter1.setClickListener(this);
recyclerView.setAdapter(adapter);
recyclerView1.setAdapter(adapter1);
}
if(intValue==1) {
adapter = new LightsRecyclerViewAdapter(this, Lab2LightsList);
adapter1 = new LightsRecyclerViewAdapter(this, Lab2ACList);
adapter.setClickListener(this);
adapter1.setClickListener(this);
recyclerView.setAdapter(adapter);
recyclerView1.setAdapter(adapter1);
}
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " +
adapter.getItem(position) + " on item position " + position,
Toast.LENGTH_SHORT).show();
view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
Please help on this.
Create one selected item position list and store it in prefs when an app goes to background or closed. Load that list when launching an app and compare that list in an adapter's onBindViewHolder's position parameter and marks it selected/unselected based on a comparison.
As per my understandings about your question, you want to save the state of the selected items even after the app is closed, and then you want to reload it whenever the app is launched again. You need to refer to this link Android Save Data
For the above solution, there can be various ways to save state, I am mentioning a few below:
Use SQLite Database to save the selected items. Then, whenever the app is loaded, fetch all the selected data from the DB and then mark them selected with whatever colour you want on the list.
You can also use Shared Preferences, to store the selection. And, same as above, you can reload the data when the app is launched.
You can also store the data in a specific format, maybe CSV, JSON, XML etc., in a file and save it either in Internal Storage or External Storage of the device. And when the app is launched, fetch all the selected values from the file and process accordingly.
You can also use a web server, Firebase Storage, or other cloud storage services to save the data and then fetch the data on new app launch.
Do note: All these techniques require you to save the state before the app is closed. So it is better to store the states, either on click of the item, or onPause method of the activity.
If you face any problems with these solutions, you can post another comment and I will give it a look.
Save these clicked item position in a hashmap in Shareprefence. suppose u close the activity after u coming back the activity just pass the saved list with ur data in adapter and compare the shareprefence list with ur data list if position or data match than make the itemview layout colored.
// save clicked item is a list and save it sharePreference.
List<Integer> clikedList = new ArrayList<>();
if (clicked item){
ClikedList.add(position)
}
String value = gson.toJson(list);
SharedPreferences prefs = context.getSharedPreferences("mylist",
Context.MODE_PRIVATE);
Editor e = prefs.edit();
e.putString("list", value);
e.commit();
// for getting cliked position list from SharePreference
SharedPreferences prefs = context.getSharedPreferences("mylist",
Context.MODE_PRIVATE);
String value = prefs.getString("list", null);
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
MyObject[] list = gson.fromJson(value, MyObject[].class);
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
// suppose clicked position 4 u get from shaved cliked list
in here u neddd to retreive cliked list position and clored those item
int select = 4;
if (select == position) {
holder.itemView.setBackgroundColor(Color.BLUE);
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
} else {
holder.itemView.setBackgroundColor(Color.parseColor("#214F4B"));
Toast.makeText(context, "" + position, Toast.LENGTH_SHORT).show();
}
holder.tv_title.setText(data.get(position));
}

How can I remove duplicates from a spinner in android

The code for the spinner is below, The spinners on my app tend to duplicate it's content sometimes for some weird reason. How do I prevent this from happening?:
Spinner spinnerG = (Spinner) findViewById(R.id.spGroup);
final ArrayAdapter<String> dataAdapterG = new ArrayAdapter<>
(this, R.layout.simple_spinner_item, groups);
dataAdapterG.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinnerG.setAdapter(dataAdapterG); //general basics //sets up the group spinner, filled with the groups list
spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
selectedGroup = groups.get(position);
studentsToShow.clear();
for(int i = 0; i < studList.size(); i++){
if(studList.get(i).getGroup().equals(selectedGroup)){
Students a = new Students();
a.setFirstName(studList.get(i).getFirstName());
a.setLastName(studList.get(i).getLastName());
a.setStudentID(studList.get(i).getStudentID());
a.setGroup(studList.get(i).getGroup());
studentsToShow.add(a); //when a new group is chosen the list of students in the selected group needs to be updated
} //this re uses the code earlier to make a list of student in the selected group
}
updateSpS(); //updates the student spinner
}
public void onNothingSelected(AdapterView<?> parent){
}
});
The spinner will duplicate if you have put this oncreate event. Put the spinner population code on the onResume method.
From the snippet shared with the question, its hard to guess why OP would have duplicate value. An educated guess is his onItemSelected() is being called multiple times.
Spinner's (in my personal view, is one of the worst android widget) onItemSelected() can be called multiple times for different reasons, one of the thing I would recommend to try this way -
class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
boolean userSelect = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (userSelect) {
// Your selection handling code here
userSelect = false;
if(view!=null){
selectedGroup = groups.get(position);
studentsToShow.clear();
for(int i = 0; i < studList.size(); i++){
if(studList.get(i).getGroup().equals(selectedGroup)){
Students a = new Students();
a.setFirstName(studList.get(i).getFirstName());
a.setLastName(studList.get(i).getLastName());
a.setStudentID(studList.get(i).getStudentID());
a.setGroup(studList.get(i).getGroup());
studentsToShow.add(a); //when a new group is chosen the list of students in the selected group needs to be updated
} //this re uses the code earlier to make a list of student in the selected group
}
updateSpS(); //updates the student spinner
}
}
}
}
And then set -
SpinnerInteractionListener listener = new SpinnerInteractionListener();
spinnerG.setOnTouchListener(listener);
spinnerG.setOnItemSelectedListener(listener);
This at the same time takes care unwanted callbacks of onItemSelected() without user touch and if any previous leaked listeners.

Obtaining a List from Parse without auto-selecting when obtained in Android Studio

The title says it all, I'm trying to do that because I obtain a list from parse and the user must choose one of them from a spinner and based on the user's choice it responds and sets another filter to another spinner. The problem I'm having (really not much of a deal, but it's something that I'd like to do) is that when the list gets obtained from Parse it automatically selects the first one it retrieves and fills all the spinners automatically (of course you can change it and it will work perfectly).
The question is, how do I retrieve a list from parse, add it into a spinner in a way that it doesn't fill everything by itself ?
Here's my piece of code where I obtain the list and add it into a spinner:
groupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Group Item Selected Ran");
final String spinI1 = groupSpinner.getSelectedItem().toString();
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("grupo", spinI1);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
int size = 0;
size = parseObjects.size();
String[] mod = new String[size];
for (int i = 0; i < parseObjects.size(); i++) {
mod[i] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i]);
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(HandsetLocation.this, android.R.layout.simple_spinner_item, mod);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
hospitalSpinner.setAdapter(spinnerArrayAdapter);
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Any help would be appreciated greatly!
At my phone so cannot properly indent the code but here it goes:
String[] mod = new String[size+1];
mod[0] = "select value";
for (int i = 0; i < parseObjects.size(); i++) {
mod[i+1] = parseObjects.get(i).getString("Hospital");
System.out.println(mod[i+1]);
}

how to change the string array of a spinner at runtimeHow to use the selected item of a spinner in an if statement (Android in eclipse)

Hi I have a spinner (spinner1) and when the user selects an item from it (example: "Canada" I want the spinner2 to populate with Provinces of "canada". I have tried the following but it doesnt work. I tried to do this by using:
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List list = new ArrayList();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
for some reason the items aren't being added to spinner2. please help
This code
if (spinner1.getSelectedItem().toString().equals("Canada"))
{
addItemsOnSpinner2();
}
will only run the first time the Activity is created since it is in your onCreate(). You need to add this code to your onItemSelected() for spinner1. So you first need to implement an OnItemSelected listener to that spinner.
spinner1.setOnItemSelected(new OnItemSelected()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id)
{
TextView tv = (TextView)v; // cast the View to a TextView
if ("Canada".equals(tv.getText().toString())
{
addItemsOnSpinner2();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Something like this should work. Although, you will probably be safer to use position instead of getting the text.
OnItemSelected Docs

Categories

Resources