How to get informations about checkboxes from ReyclerView in fragment - java

I need to get informaions about item from recyclerView. I try do something like this to get in but this didnt work, any ideas?? I think that calling CheckBox is useless and i dont need it. but now i dont have any idea how to do it.
private void handlerForChannels() {
list = ChannelsManager.getInstance().getChannelList();
mAdapter = new SettingsCustomAdapter(context, posit, list);
verticalGridView.setAdapter(mAdapter);
textView.setText(R.string.title_channels);
button.setText(R.string.select_all);
final SparseBooleanArray mChecked = new SparseBooleanArray();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAdapter.getItemViewType(SETTINGS_CHANNELS);
mAdapter.getItemId(getId());
CheckBox cb;
int count = list.size();
cb = (CheckBox) view.findViewById(R.id.checkBox_for_recycle);
for (int i = 0; i < count; i++) {
mChecked.put(i, cb.isChecked());
}
mAdapter.notifyDataSetChanged();
}
});
button.setNextFocusLeftId(R.id.select_all);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
button1.setText(R.string.cancel_text);
button1.setNextFocusLeftId(R.id.select_all);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) activity).closeSettingsDrawerFragment();
}
});
button2.setText(R.string.ok_text);
button2.setNextFocusLeftId(R.id.ok_button);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}

Add a new Array into your adapter with booleans, to set the checkboxes true or false:
//...
public ArrayList<Boolean> checkBoxesState;
//...
public mAdapter(Context context, ArrayList<String> posit, ArrayList<String> list, ArrayList<Boolean> checkBoxesState /* <- add this one*/) {
//...
this.checkBoxesState = checkBoxesState;
}
Than you set if they get checked or don't:
#Override
public void onBindViewHolder(final NotaViewHolder viewHolder, final int position) {
//...
viewHolder.checkBox.setChecked(checkBoxesState.get(position));
}
Now you probably already know how to check them but for those who stumble into this too, here's how:
//create adapter
mAdapter = new mAdapter(context, posit, list, checkBoxesStates /* <- fill with false booleans */ );
recyclerView.setAdapter(mAdapter);
//check them all
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i <= mAdapter.getItemCount(); i++) {
checkBoxesStates.add(i, true);
mAdapter.notifyItemChanged(0); //this updates the adapter
}
}
});
Edit:
You have to create your checkbox in the ViewHolder, something like this:
public class NotaViewHolder extends RecyclerView.ViewHolder {
//...
CheckBox checkBox;
public NotaViewHolder(final View itemView) {
super(itemView);
//...
checkBox = (CheckBox) itemView.findViewById(R.id.rowCheckBox);
//...
}
}

the best way to do this:
1. in your adapter add some code:
private boolean isAllCheckBoxSelected;
public void setAllCheckBoxesSelected(boolean isSelected){
isAllCheckBoxSelected = isSelected;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
...
holder.mCheckBox.setChecked(isAllCheckBoxSelected);
...
}
2. in your fragment call where you need
mAdapter.setAllCheckBoxesSelected(true or false);

Related

on back pressed I want to go previous activity from adapter

I have an activity which is connected with an adapter. In the activity, I include adapter layout. when I click on the button than adapter layout open but when I press back button in adapter layout than automatically reached main activity. I want that when I press back button in adapter than go to previous activity.
activity code is below
public class TestFragment extends Fragment {
private Button btnA,
btnB,
btnC,
btnD,
btnSubmit,
btnNext,
btnPrev,
btnFlag;
private TextView tvQuestion,
tvLayout;
private int totalItem;
private int listItem = 0;
private ArrayList < mcqQuestion > quesList = new ArrayList < >();
private int score = 0;
private boolean isLoading = true;
private RelativeLayout rlMcqProgress;
private FirebaseAuth mAuth;
private boolean allAnswered = false;
private RecyclerView rvQuesLayout;
private RecyclerView.LayoutManager layoutManager;
private QuestionLayoutRecyclerAdapter adapter;
private LinearLayout llQuestionAll;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference("tax").child("Questions");
public TestFragment() {
// Required empty public constructor
}#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_test, container, false);
btnA = view.findViewById(R.id.btn_mcq_A);
btnB = view.findViewById(R.id.btn_mcq_B);
btnC = view.findViewById(R.id.btn_mcq_C);
btnD = view.findViewById(R.id.btn_mcq_D);
btnSubmit = view.findViewById(R.id.btn_mcq_submit);
btnNext = view.findViewById(R.id.btn_mcq_next);
btnPrev = view.findViewById(R.id.btn_mcq_prev);
btnFlag = view.findViewById(R.id.btn_mcq_flag);
tvQuestion = view.findViewById(R.id.tv_mcq_question);
tvLayout = view.findViewById(R.id.tv_mcq_question_layout);
rvQuesLayout = view.findViewById(R.id.rv_layout_question_test);
rlMcqProgress = view.findViewById(R.id.rl_mcq_progress);
rlMcqProgress.setVisibility(View.VISIBLE);
llQuestionAll = view.findViewById(R.id.ll_test_all);
mAuth = FirebaseAuth.getInstance();
getFData();
btnA.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optA");
setButtonColor();
btnA.setBackgroundResource(R.color.sky_blue);
}
});
btnB.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optB");
setButtonColor();
btnB.setBackgroundResource(R.color.sky_blue);
}
});
btnC.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optC");
setButtonColor();
btnC.setBackgroundResource(R.color.sky_blue);
}
});
btnD.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
quesList.get(listItem).setSelAnswer("optD");
setButtonColor();
btnD.setBackgroundResource(R.color.sky_blue);
}
});
btnFlag.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
setFlagValue();
setFlagColor();
}
});
tvLayout.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
adapter.notifyDataSetChanged();
if (rvQuesLayout.getVisibility() == View.GONE || rvQuesLayout.getVisibility() == View.INVISIBLE) {
rvQuesLayout.setVisibility(View.VISIBLE);
llQuestionAll.setVisibility(View.GONE);
} else {
rvQuesLayout.setVisibility(View.GONE);
llQuestionAll.setVisibility(View.VISIBLE);
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
displayNextQues();
}
});
btnPrev.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
displayPrevQues();
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {#SuppressLint("SetTextI18n")#Override
public void onClick(View v) {
for (int i = 0; i < totalItem; i++) {
if (quesList.get(i).getSelAnswer().equals("none")) {
allAnswered = false;
score++;
break;
} else {
if (quesList.get(i).getSelAnswer().equals(quesList.get(i).getAnswer())) {
score++;
}
allAnswered = true;
}
}
if (allAnswered) {
Intent intent = new Intent(this, finalresult.class);
intent.putExtra("score", score);
intent.putExtra("questions", totalItem);
startActivity(intent);
} else {
Toast.makeText(this, "Answer all the questions", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void makeRecyclerView() {
layoutManager = new LinearLayoutManager(this);
//rvQuesLayout.setHasFixedSize(true);
rvQuesLayout.setLayoutManager(layoutManager);
adapter = new QuestionLayoutRecyclerAdapter(quesList);
rvQuesLayout.setAdapter(adapter);
adapter.setOnItemClickListner(new QuestionLayoutRecyclerAdapter.onItemClickListner() {#Override
public void onClick(int pos) {
listItem = pos;
if (listItem >= 0 && listItem < totalItem) {
makeAllDisplay();
rvQuesLayout.setVisibility(View.GONE);
llQuestionAll.setVisibility(View.VISIBLE);
}
}
});
}
private void setDisplay(int item) {
btnA.setText(quesList.get(item).getOptA());
btnB.setText(quesList.get(item).getOptB());
btnC.setText(quesList.get(item).getOptC());
btnD.setText(quesList.get(item).getOptD());
tvQuestion.setText(quesList.get(item).getQuestion());
}
private void getFData() {
myRef.addValueEventListener(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
String qtext = (String) messageSnapshot.child("qText").getValue();
String optA = (String) messageSnapshot.child("optA").getValue();
String optB = (String) messageSnapshot.child("optB").getValue();
String optC = (String) messageSnapshot.child("optC").getValue();
String optD = (String) messageSnapshot.child("optD").getValue();
String answer = (String) messageSnapshot.child("answer").getValue();
quesList.add(new mcqQuestion(qtext, optA, optB, optC, optD, answer, "none", false));
Log.d("TOTAL ITEM", String.valueOf(quesList.size()));
}
totalItem = quesList.size();
isLoading = false;
if (!isLoading) {
setDisplay(listItem);
rlMcqProgress.setVisibility(View.GONE);
tvLayout.setVisibility(View.VISIBLE);
}
makeRecyclerView();
}#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void setFlagValue() {
if (quesList.get(listItem).isFlag()) {
quesList.get(listItem).setFlag(false);
} else {
quesList.get(listItem).setFlag(true);
}
}
private void setFlagColor() {
if (quesList.get(listItem).isFlag()) {
btnFlag.setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.black));
btnFlag.setTextColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey));
} else {
btnFlag.setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey_light));
btnFlag.setTextColor(ContextCompat.getColor(Objects.requireNonNull(this), R.color.grey));
}
}
private void setButtonColor() {
btnA.setBackgroundResource(R.color.grey_light);
btnB.setBackgroundResource(R.color.grey_light);
btnC.setBackgroundResource(R.color.grey_light);
btnD.setBackgroundResource(R.color.grey_light);
}
private void displayNextQues() {
if (listItem < totalItem - 1) {
listItem++;
makeAllDisplay();
} else {
btnNext.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
}
}
private void makeAllDisplay() {
setDisplay(listItem);
setButtonColor();
setFlagColor();
switch (quesList.get(listItem).getSelAnswer()) {
case "optA":
btnA.setBackgroundResource(R.color.sky_blue);
break;
case "optB":
btnB.setBackgroundResource(R.color.sky_blue);
break;
case "optC":
btnC.setBackgroundResource(R.color.sky_blue);
break;
case "optD":
btnD.setBackgroundResource(R.color.sky_blue);
break;
default:
setButtonColor();
break;
}
}
private void displayPrevQues() {
btnNext.setVisibility(View.VISIBLE);
if (listItem > 0 && listItem < totalItem) {
listItem--;
makeAllDisplay();
} else {
Toast.makeText(this, "Cannot GO back!!", Toast.LENGTH_SHORT).show();
}
}
}
and the adapter code is below
public class QuestionLayoutRecyclerAdapter extends RecyclerView.Adapter < QuestionLayoutRecyclerAdapter.FlagViewHolder > {
private ArrayList < mcqQuestion > quesList;
private onItemClickListner onItemClickListner;
public void setOnItemClickListner(QuestionLayoutRecyclerAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(int pos); //pass your object types.
}
public QuestionLayoutRecyclerAdapter(ArrayList < mcqQuestion > quesList) {
this.quesList = quesList;
}
#NonNull#Override
public FlagViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(layout.question_layout, parent, false);
FlagViewHolder flagViewHolder = new FlagViewHolder(view, quesList);
return flagViewHolder;
}
#SuppressLint("ResourceAsColor")#Override
public void onBindViewHolder(#NonNull final FlagViewHolder holder, int position) {
mcqQuestion question_id = quesList.get(position);
holder.tvQuestionNumber.setText("Question " + (position + 1));
if (question_id.isFlag()) {
holder.ivFlag.setImageResource(drawable.right2);
} else {
holder.ivFlag.setImageResource(drawable.white2);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
onItemClickListner.onClick(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return quesList.size();
}
public static class FlagViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView ivFlag;
TextView tvQuestionNumber;
ArrayList < mcqQuestion > quesList;
public FlagViewHolder(#NonNull View itemView, ArrayList < mcqQuestion > quesList) {
super(itemView);
ivFlag = itemView.findViewById(id.iv_layout_flag);
tvQuestionNumber = itemView.findViewById(id.tv_layout_question_number);
itemView.setOnClickListener(this);
this.quesList = quesList;
}
#Override
public void onClick(View v) {
int quesClick = getAdapterPosition();
}
}
}
Try this
#Override
public void onBackPressed()
{
Intent intent = new Intent(this, ActivityWhereYouWantToGo.class);
startActivity(intent);
}
As per you code, you are not navigation to another screen you are only changing the Visibility. On back press, you can check which view is currently displaying and handle accordingly.
#Override
public void onBackPressed() {
if (findViewById(R.id.your_view).visibility == View.Visible) {
//change your visibility
rvQuesLayout.setVisibility(View.VISIBLE);
llQuestionAll.setVisibility(View.GONE);
//reverse the things you did in makeAllDisplay() method
} else {
super.onBackPressed();
}
}

how to delete cardview in a recycler view and its json data

I want to delete card in a RecyclerView after selecting it.data in the RecyclerView is JSON data
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if(response.isSuccessful()) {
JsonObject responseObject = response.body();
if (responseObject.has("data")) {
JsonArray arrayobject = responseObject.getAsJsonArray("data");
ArrayList<User_Details_Model> myorder = getGeneral(arrayobject.toString());
viewRequestControllerCallback.hitsuccess1(myorder);
Here is a good resource to detect which cardView is clicked. After clicking a cardView you can delete it:
Recyclerview-listener
public interface OnItemClickListener {
void onItemClick(ContentItem item);
}
public void bind(final ContentItem item, final OnItemClickListener listener) {
...
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onItemClick(item);
}
});
}
this is the adapter
public void onBindViewHolder(#NonNull final UserViewHolder holder, final int
position) {
final User_Details_Model product = user_details.get(position);
Log.d("######",user_details.toString());
holder.tv1.setText(product.getDriverId());
holder.tv2.setText(product.getDriverName());
holder.tv3.setText(product.getVehicleId());
holder.tv4.setText(product.getVehicleType());
holder.tv5.setText(product.getOilType());
holder.button_ok.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int pos=holder.getAdapterPosition();
if (position==pos){
getdetails();
user_details.remove(pos);
}
}
}

Trying to call method from MainActivity in Another Activity it is me leading to error

I have Recycler ListView which I show in MainActivity and the first item it is as selected, I have done to click for another items but the last stays clicked and when I try to take this recycler view to show me in next Activity it doesn't work.
The first item it is selected but I have a click method which when click an image makes as selected but when I click a new image this works but the first item stays as selected so continues for others images. I want only a image to be selected.
I don't want to write twice the same code.
Is it good if I have a class only for this method which I can use everytime I want.
The id of recycler view list it is the same on both xml's.
If you have any suggestion for my question please let me know.
This is the adapter for the RecyclerView.
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
This is the method in MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
This is the button which takes to another activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
Cursor data = mDatabaseHelper.getData();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("name", newEntry);
intent.putExtra("test", mSearchUrl.get(0));
startActivityForResult(intent, 2);
}
});
This is the another activity
public class ActivitySearchEngine extends Activity implements
SwipeRefreshLayout.OnRefreshListener {
public ImageView mHome;
public EditText searchPlugin;
public WebView webView;
Button btnSearch;
public ImageButton clearSearch, exitButton;
public ImageView favIcon;
public ProgressBar loadIcon;
String text;
SwipeRefreshLayout refreshLayout;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
private String selectedSearchUrl;
RecyclerView mListView;
MainActivity mainActivity = new MainActivity();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
mHome = findViewById(R.id.imgBtnHome);
searchPlugin = findViewById(R.id.etSearch);
webView = findViewById(R.id.webView);
clearSearch = findViewById(R.id.btnClearSearch);
btnSearch = findViewById(R.id.btnSearch);
favIcon = findViewById(R.id.imgViewFavIcon);
loadIcon = findViewById(R.id.progressBarIcon);
exitButton = findViewById(R.id.imgBtnStopLoad);
refreshLayout = findViewById(R.id.refreshLayout);
mListView = findViewById(R.id.lvEngines);
refreshLayout.setOnRefreshListener(this);
mDatabaseHelper = new DatabaseHelper(this);
mainActivity.intSearch(); // Here it is the error
Activity.ActivitySearchEngine}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("test");
searchPlugin.setText(selectedName);
loadIcon.setVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("www.bing.com/search?=" + selectedName);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
favIcon.setImageBitmap(icon);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadIcon.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
try {
if (loadIcon.getVisibility() == View.VISIBLE) {
loadIcon.setVisibility(View.GONE);
favIcon.setVisibility(View.VISIBLE);
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
exitButton.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRefresh();
}
});
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
searchPlugin.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
processButtonByTextLength();
}
});
mHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText(null);
finish();
}
});
clearSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText("");
}
});
public void processButtonByTextLength() {
String inputText = searchPlugin.getText().toString();
if(inputText.length() > 0) {
btnSearch.setVisibility(View.VISIBLE);
mHome.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.VISIBLE);
loadIcon.setVisibility(View.GONE);
exitButton.setVisibility(View.GONE);
} else if(inputText.length() == 0) {
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
clearSearch.setVisibility(View.GONE);
}
}
#Override
public void onRefresh() {
webView.reload();
refreshLayout.setRefreshing(false);
}
}
This is the photo with RecyclerView at MainActivity.class
Photo of another Activity

How to reset data or set default data on a RecyclerView item when it is added to the recyclerView?

I have a textView that holds a number value that when the add button is clicked it adds one to it and when the subtract button is clicked it subtracts 1 from it. But when i add a new item to the recyclerView the number value will be automatically set to the last items value. So if the first item numberValue is 3 the second items number value will be 3 when it is added. I want the textView to automatically be 0 when a new item is added to the recyclerView
public class PlatesAdapter extends
RecyclerView.Adapter<PlatesAdapter.ViewHolder> {
//Declaring a List<> of Plates
private List<Plates> mPlatesList;
//Variable to hold total numberOfPlates being used
int amountOfPlates = 0;
String amountOfPlatesString;
//OnBindViewHolder
#Override
public void onBindViewHolder(PlatesAdapter.ViewHolder holder, int position) {
final TextView amountOfPlatesTextView = holder.amountOfPlatesTextView;
//BUTTONS add 1 or subtract 1 from amountOfPlates;
Button addAmountOfPlatesButton = holder.addButton;
Button subtractAmountOfPlatesButton = holder.subButton;
addAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addPlates();
amountOfPlatesString = Integer.toString(amountOfPlates);
amountOfPlatesTextView.setText(amountOfPlatesString);
}
});
subtractAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
subtractPlates();
amountOfPlatesString = Integer.toString(amountOfPlates);
amountOfPlatesTextView.setText(amountOfPlatesString);
}
});
}
public void addPlatesLayout(Plates plate) {
if (mPlatesList == null) mPlatesList = new ArrayList();
//plate.setPlateWeight(a);
mPlatesList.add(plate);
//notifyDataSetChanged();
notifyItemInserted(mPlatesList.size() - 1);
}
public int addPlates() {
amountOfPlates++;
return amountOfPlates;
}
public int subtractPlates() {
amountOfPlates--;
return amountOfPlates;
}
Just need to setText in OnBindViewHolder.
#Override
public void onBindViewHolder(PlatesAdapter.ViewHolder holder, int position) {
final TextView amountOfPlatesTextView = holder.amountOfPlatesTextView;
amountOfPlatesTextView.setText("0");
//BUTTONS add 1 or subtract 1 from amountOfPlates;
Button addAmountOfPlatesButton = holder.addButton;
Button subtractAmountOfPlatesButton = holder.subButton;
addAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addPlates();
amountOfPlatesString = Integer.toString(amountOfPlates);
amountOfPlatesTextView.setText(amountOfPlatesString);
}
});
subtractAmountOfPlatesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
subtractPlates();
amountOfPlatesString = Integer.toString(amountOfPlates);
amountOfPlatesTextView.setText(amountOfPlatesString);
}
});
}

Why my listview is empty?

I have a arraylist in which users can input their text. And it is displayed in the screen as a listview. That works, but when i try to get the values of the arraylist it says that: Invalid index 0, size is 0. So im guessing for some reason the listview isnt populating?
This is how I add values to the list:
public class ZaidejaiActivity extends ActionBarActivity implements View.OnClickListener{
public Button mBtnIstrinti;
public Button mBtnPrideti;
public Button mBtnPradeti;
public EditText mYrasytiVarda;
public ListView mZaidejai;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidejai);
mBtnPrideti = (Button) findViewById(R.id.pridėtiBtn);
mBtnPrideti.setOnClickListener(this);
mYrasytiVarda = (EditText) findViewById(R.id.VardoYrasymoBtn);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
// set the mZaidejai variable to your list in the xml
mZaidejai = (ListView) findViewById(R.id.sarašas);
mZaidejai.setAdapter(adapter);
mZaidejai.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// remove item from List.
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
list.remove(position);
AlertDialog.Builder builder = new AlertDialog.Builder(ZaidejaiActivity.this);
builder.setMessage("Delete?");
builder.setTitle("Confirm Action");
builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
adapter.notifyDataSetChanged();
}
//checked.clear();
});
builder.setNegativeButton("Cancel", null);
builder.create();
builder.show();
}
});
mBtnPradeti = (Button) findViewById(R.id.žaistiBtn);
mBtnPradeti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// count items
int i;
for (i = adapter.getCount() - 1; i >= 0; i--) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
}
});
}
#Override
public void onClick(View v) {
String input = mYrasytiVarda.getText().toString();
if(input.length() > 0)
{
// add string to the adapter, not the listview
adapter.add(input);
// no need to call adapter.notifyDataSetChanged(); as it is done by the adapter.add() method
}else{
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Klaida:");
alertDialog.setMessage("Blogai yrašytas vardas");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// here you can add functions
}
});
alertDialog.show();
}
}
EDIT
In this activity I want to get the values of the list:
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mZaidejas;
public TextView mKlausimas;
public Button mKitasKlausimas;
public Button mGryzti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
//show the first players name
mZaidejas = (TextView)findViewById(R.id.ZaidejoVardas);
mZaidejas.setText(list.get(0));
/** mGryzti = (Button)findViewById(R.id.GryztiMeniuBtn);
mKitasKlausimas = (Button)findViewById(R.id.KitasBtn);
mKitasKlausimas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
*/
Unfortunately your list==empty. So add some values on it.
list.add("ABC");
list.add("XYZ");
and then setAdapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
mZaidejai = (ListView) findViewById(R.id.sarašas);
mZaidejai.setAdapter(adapter);
Your not adding any values to it. And your list is empty and add some values to it like list.add("hyd");
list.add("city");
and pass those values to adapter
Rather doing
adapter.add(input);
Do
list.add(input);
adapter.notifyDataSetChanged();
So, as others have said you should change the adapter.add(input); on the onClick method to
list.add(input);
adapter.notifyDataSetChanged();
Also, on an unrelated matter, you should really move the list.remove(position); call to the following onClick method of the positive button, before the adapter.notifyDataSetChanged(); call, so it wont be removed if the user cancels the action :)
at the first time your list adapter is empty (getCount() = 0) and you do -1 in the for
mBtnPradeti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// count items
int i;
if (adapter.getCount() > 0)
{
for (i = adapter.getCount() - 1; i >= 0; i--) {
String obj = adapter.getItem(i);
// send items to other activity
Intent pradetiZaidima = new Intent(v.getContext(), ZaidimasActivity.class);
pradetiZaidima.putExtra("playerList", obj);
startActivity(pradetiZaidima);
}
}
}
});
and for this code :
mZaidejas.setText(list.get(0));
but on Create your list is empty !!!

Categories

Resources