This is a recipe app with categories and sub categories. I want to know is there any other command to open different activities besides position command. Because I have a problem when searching it becames alphabetical order, when i click the item it give me different result because the position is changing. I dont know what is the problem of my code is it the search function or the position command to open different new activities.
MainAdapter.class
public class MainAdapter extends FirebaseRecyclerAdapter<MainModel,MainAdapter.myViewHolder> {
private Context context;
/**
* Initialize a {#link RecyclerView.Adapter} that listens to a Firebase query. See
* {#link FirebaseRecyclerOptions} for configuration options.
*
* #param options
*/
public MainAdapter(#NonNull FirebaseRecyclerOptions<MainModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull MainAdapter.myViewHolder holder, int position, #NonNull MainModel model) {
holder.categoryName.setText(model.getName());
holder.categoryDesc.setText(model.getDescription());
Glide.with(holder.categoryImage.getContext())
.load(model.getImage())
.placeholder(R.drawable.common_google_signin_btn_icon_dark)
.error(R.drawable.common_google_signin_btn_icon_dark_normal)
.into(holder.categoryImage);
context = holder.itemView.getContext();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent;
switch (position){
case 0:
intent = new Intent(context, ChickenActivity.class);
break;
case 1:
intent = new Intent(context, PorkActivity.class);
break;
case 2:
intent = new Intent(context, BeefActivity.class);
break;
case 3:
intent = new Intent(context, SeafoodActivity.class);
break;
default:
intent = new Intent(context, VegetableActivity.class);
break;
}
context.startActivity(intent);
}
});
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_item,parent,false);
return new myViewHolder(view);
}
class myViewHolder extends RecyclerView.ViewHolder{
ImageView categoryImage;
TextView categoryName, categoryDesc;
public myViewHolder(#NonNull View itemView) {
super(itemView);
categoryImage = (ImageView)itemView.findViewById(R.id.categoryImage);
categoryName = (TextView)itemView.findViewById(R.id.categoryName);
categoryDesc = (TextView)itemView.findViewById(R.id.categoryDesc);
}
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
MainAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
FirebaseRecyclerOptions<MainModel> options =
new FirebaseRecyclerOptions.Builder<MainModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("category"), MainModel.class)
.build();
mainAdapter = new MainAdapter(options);
recyclerView.setAdapter(mainAdapter);
}
#Override
protected void onStart() {
super.onStart();
mainAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
mainAdapter.stopListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search,menu);
MenuItem item = menu.findItem(R.id.search);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
txtSearch(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
txtSearch(query);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void txtSearch(String str)
{
FirebaseRecyclerOptions<MainModel> options =
new FirebaseRecyclerOptions.Builder<MainModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("category").orderByChild("name").startAt(str).endAt(str+"~"), MainModel.class)
.build();
mainAdapter = new MainAdapter(options);
mainAdapter.startListening();
recyclerView.setAdapter(mainAdapter);
}
}
Instead of tying the Activity to a number you should tie it to a tag or some identifier. For example, you have 3 items in the list Like:
[
{
name: "chickenwings"
},
{
name: "octopus"
},
{
name: "tomato"
}
]
Instead you can have additional information like the activity the item should correlate with, for example
[
{
name: "chickenwings",
category: "chicken"
},
{
name: "octopus",
category: "seafood"
},
{
name: "tomato",
category: "vegetable"
}
]
This will help you update your code like below
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent;
val category = model.getCategory()
switch (category){
case "chicken":
intent = new Intent(context, ChickenActivity.class);
break;
case "pork":
intent = new Intent(context, PorkActivity.class);
break;
case "beef":
intent = new Intent(context, BeefActivity.class);
break;
case "seafood":
intent = new Intent(context, SeafoodActivity.class);
break;
case "vegetable":
default:
intent = new Intent(context, VegetableActivity.class);
break;
}
context.startActivity(intent);
}
});
You can use "holder.getAdapterPosition" instead of "position" to solve this problem.
Related
I know how to add items to RecyclerView and show them, but let's say I add some dynamic items to the RecyclerView like this image
Here After click save button, it creates three rows in the RecyclerView like below image, which I don't want it creates three rows.
Instead I want to create one row, and when I clicked in that row then shows the three items like this image.
AddChecklist class
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
dbHelper = new DbHelper(this);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView(){
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
CheckBox checkBox = checklistView.findViewById(R.id.check_box);
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
}
else
checklistHelper.setStatus("0");
dbHelper.insertChecklist(checklistHelper.getStatus(), etChecklistItem.getText().toString(), DateTime.date(), DateTime.time(), System.currentTimeMillis());
}
finish();
break;
}
return true;
}
}
Adapter class
public class ChecklistItems extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
String content;
String status;
boolean isEditChecklist = false;
private ChecklistAdapter checklistAdapter;
DbHelper dbHelper;
List<ChecklistHelper> checks;
int id;
ChecklistHelper checklistHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
checks = dbHelper.getChecklists();
checklistAdapter = new ChecklistAdapter(checks);
recyclerView.setAdapter(checklistAdapter);
}
public class ChecklistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private boolean isEnableDelete = false;
List<ChecklistHelper> checkList;
public ChecklistAdapter(List<ChecklistHelper> checkList) {
this.checkList = checkList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.checklist_layout_child, parent, false);
return new ChecklistChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChecklistChildViewHolder checklistChildViewHolder = (ChecklistChildViewHolder) holder;
checklistChildViewHolder.updateVisibility(isEnableDelete);
checklistChildViewHolder.checkBox.setText(checkList.get(position).getContent());
checklistChildViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String txt = checklistChildViewHolder.checkBox.getText().toString();
if (b)
checklistChildViewHolder.checkBox.setText(lineThrough(txt));
else
checklistChildViewHolder.checkBox.setText(txt);
}
});
checklistChildViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dbHelper.deleteChecklist(id);
finish();
}
});
}
#Override
public int getItemCount() {
return checkList.size();
}
public void updateItems(boolean isEnableDelete){
this.isEnableDelete = isEnableDelete;
notifyDataSetChanged();
}
public class ChecklistChildViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
ImageView delete, edit;
ChecklistChildViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkbox_child);
delete = itemView.findViewById(R.id.delete_child);
edit = itemView.findViewById(R.id.edit_child);
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
public void updateVisibility(boolean isEnableDelete){
if (isEnableDelete) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
else {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(this);
// long id = getIntent().getIntExtra("id", 0);
switch (item.getItemId()) {
case R.id.edit:
isEditChecklist = true;
checklistAdapter.updateItems(true);
invalidateOptionsMenu();
break;
case R.id.save:
Toast.makeText(getApplicationContext(), "saved ", Toast.LENGTH_SHORT).show();
checklistAdapter.updateItems(false);
isEditChecklist = false;
finish();
break;
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Checklist");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Continue ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbHelper.deleteChecklist(id);
// checklistAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "checklist deleted", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
break;
}
return true;
}
}
Can someone look at my code its really simple created just to practice my skills. But the language spinner works but the gender spinner is buggy. It will work once i change the language then change the gender and then go back to the gender i originally wanted. Code is shown. Thanks. Have tried putting onItemSelected() for spinnerGen, it does not solve the issue. Researching about this since last night cant find any solution
public class MainActivity extends AppCompatActivity {
private Button btnGo, btnAbout;
private Spinner spinner, spinnerGen;
private EditText addName;
private ArrayList<String> options;
private ArrayList<String> optionsGen;
private String allOption = "";
private String genOption = "";
private String genOptionSec = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPage();
options = new ArrayList<>();
options.add("English");
options.add("Bengali");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, options);
spinner.setAdapter(adapter);
adapter.setNotifyOnChange(true);
adapter.notifyDataSetChanged();
optionsGen = new ArrayList<>();
optionsGen.add("Male");
optionsGen.add("Female");
ArrayAdapter<String> adapterGen = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, optionsGen);
spinnerGen.setAdapter(adapterGen);
adapterGen.setNotifyOnChange(true);
adapterGen.notifyDataSetChanged();
spinnerMethod();
}
private void initPage() {
btnGo = findViewById(R.id.btnGo);
btnAbout = findViewById(R.id.btnAbout);
spinner = findViewById(R.id.spinner);
spinnerGen = findViewById(R.id.spinnerGen);
addName = findViewById(R.id.addName);
}
public void spinnerMethod() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
allOption = spinner.getSelectedItem().toString();
switch (allOption) {
case "English" :
newMethodEnglish();
break;
case "Bengali" :
newMethodBengali();
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void newMethodEnglish() {
genOption = spinnerGen.getSelectedItem().toString();
switch (genOption) {
case "Male":
onClickEngMale(); //In these method Im just navigating to another activity
break;
case "Female":
OnClickEngFemale();
break;
default:
break;
}
}
public void OnClickEngFemale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String femaleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, EngFemale.class);
intent.putExtra("DataFemale", femaleData);
startActivity(intent);
}
});
}
public void onClickEngMale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String maleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, EngMale.class);
intent.putExtra("Data", maleData);
startActivity(intent);
}
});
}
public void newMethodBengali() {
genOptionSec = spinnerGen.getSelectedItem().toString();
switch (genOptionSec){
case "Male":
onClickBanMale();
break;
case "Female":
onClickBanFemale();
default:
break;
}
}
public void onClickBanMale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String maleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, BanMale.class);
intent.putExtra("DataBan", maleData);
startActivity(intent);
}
});
}
public void onClickBanFemale() {
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String femaleData = addName.getText().toString();
Intent intent = new Intent(MainActivity.this, BanFemale.class);
intent.putExtra("BanFemale", femaleData);
startActivity(intent);
}
});
}
}
I am creating a Chat App and I show the user their contacts. Right now the user can see the image name and status of all of their contacts. But when the user clicks on the contact I want them to go into the ChatActivity. Right now I am stuck because I don't know how to send them their.
I tried this
mAuth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
But it doesn't work the words setOnClickListener are red. Can someone please help ?
EDIT !!!!!!
I tried both of the below answers and neither helped me. When I put these blocks
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
SendUserToChatActivity();
}
}
private void SendUserToChatActivity() {
Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
And I am getting a red line under here Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
This is the updated code(I am still trying to find a way).
private View ContactsView;
private RecyclerView myContactsList;
private DatabaseReference ContacsRef, UsersRef;
private FirebaseAuth mAuth;
private String currentUserID;
public ContactsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ContactsView = inflater.inflate(R.layout.fragment_contacts, container, false);
myContactsList = (RecyclerView) ContactsView.findViewById(R.id.contacts_list);
myContactsList.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ContacsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
return ContactsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContacsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ContactsViewHolder> adapter
= new FirebaseRecyclerAdapter<Contacts, ContactsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ContactsViewHolder holder, int position, #NonNull Contacts model) {
String userIDs = getRef(position).getKey();
UsersRef.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
if(dataSnapshot.child("userState").hasChild("state")){
String state = (dataSnapshot.child("userState").child("state")).getValue().toString();
String date = (dataSnapshot.child("userState").child("date")).getValue().toString();
String time = (dataSnapshot.child("userState").child("time")).getValue().toString();
if(state.equals("online")){
holder.onlineIcon.setVisibility(View.VISIBLE);
}
else if(state.equals("offline")){
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
} else {
holder.userStatus.setText("offline");
}
if(dataSnapshot.hasChild("image")){
String userImage = dataSnapshot.child("image").getValue().toString();
String profileName = dataSnapshot.child("name").getValue().toString();
String profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(holder.profileImage);
}
else{
String profileName = dataSnapshot.child("name").getValue().toString();
String profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ContactsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
SendUserToChatActivity();
}
}
private void SendUserToChatActivity() {
Intent mainIntent = new Intent(getApplication(), MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
}
};
myContactsList.setAdapter(adapter);
adapter.startListening();
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView userName, userStatus;
CircleImageView profileImage;
ImageView onlineIcon;
public ContactsViewHolder(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);
}
}
Since you want recyclerView adapter clickable, you need to setOnClickListener in holder.itemView. Inside onBindViewHolder, add this
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ChatActivity.class);
i.putExtra("visit_user_id", userIDs);
i.putExtra("visit_user_name", profileName);
i.putExtra("visit_image", userImage);
startActivity(i);
}
});
Full Code
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
ContactsView = inflater.inflate(R.layout.fragment_contacts, container, false);
myContactsList = (RecyclerView) ContactsView.findViewById(R.id.contacts_list);
myContactsList.setLayoutManager(new LinearLayoutManager(getContext()));
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ContacsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
return ContactsView;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerOptions options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContacsRef, Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts, ContactsViewHolder> adapter
= new FirebaseRecyclerAdapter<Contacts, ContactsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ContactsViewHolder holder, final int position, #NonNull Contacts model) {
final String userIDs = getRef(position).getKey();
UsersRef.child(userIDs).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (dataSnapshot.child("userState").hasChild("state")) {
String state = (dataSnapshot.child("userState").child("state")).getValue().toString();
String date = (dataSnapshot.child("userState").child("date")).getValue().toString();
String time = (dataSnapshot.child("userState").child("time")).getValue().toString();
if (state.equals("online")) {
holder.onlineIcon.setVisibility(View.VISIBLE);
} else if (state.equals("offline")) {
holder.onlineIcon.setVisibility(View.INVISIBLE);
}
} else {
holder.userStatus.setText("offline");
}
if (dataSnapshot.hasChild("image")) {
userImage = dataSnapshot.child("image").getValue().toString();
profileName = dataSnapshot.child("name").getValue().toString();
profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
Picasso.get().load(userImage).placeholder(R.drawable.profile_image).into(holder.profileImage);
} else {
profileName = dataSnapshot.child("name").getValue().toString();
profileStatus = dataSnapshot.child("status").getValue().toString();
holder.userName.setText(profileName);
holder.userStatus.setText(profileStatus);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ChatActivity.class);
i.putExtra("visit_user_id", userIDs);
i.putExtra("visit_user_name", profileName);
i.putExtra("visit_image", userImage);
startActivity(i);
}
});
}
#NonNull
#Override
public ContactsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
};
myContactsList.setAdapter(adapter);
adapter.startListening();
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView userName, userStatus;
CircleImageView profileImage;
ImageView onlineIcon;
public ContactsViewHolder(#NonNull View itemView) {
super(itemView);
userName = itemView.findViewById(R.id.user_profile_name);
userStatus = itemView.findViewById(R.id.user_status);
profileImage = itemView.findViewById(R.id.users_profile_image);
onlineIcon = (ImageView) itemView.findViewById(R.id.user_online_status);
}
}
Looks like you only missing the proper import, you can press alt + enter on everything that is in red to import open small dialog and import it.
You can either import this:
import android.view.View.OnClickListener;
Or you can implement the click listener interface and avoid creating new click listener for every view like this:
class yourClass implements View.OnClickListener {
#Override
public void onClick(View v) {
//Views clicks go here
}
}
Edit:
You need to replace your first parameter in your intent and pass context.
Replace this:
Intent mainIntent = new Intent(ContactsFragment.this, MainActivity.class);
with this:
Intent mainIntent = new Intent(context, MainActivity.class);
Note that you will have to pass the context and not just the keyword "context", for example, you can pass your current activity like this:
Intent mainIntent = new Intent(MyActivityThatContainsThisFragment, MainActivity.class);
You must get the context of where it is at this moment in case it is a fragment.
Intent mainIntent = new Intent(**getContext()**, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
If you want to set click listener on list item then
import android.view.View.OnClickListener;
public static class ContactsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
...some other code
ContactsViewHolder(View itemView){
// some code
// setting click listener on complete row
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v){
Intent i = new Intent(v.getContext(),ChatActivity.class);
v.getContext().startActivity(i);
}
EDIT :
For your ChatLink,
Intent require 2 parameter to open activity i.e. Context and Destination class. So try this
class chatLink implements View.OnClickListener {
#Override
public void onClick(View v) {
//Resolve error
// you can also use class of fragment i.e. Fragment.this.getContext()
SendUserToChatActivity(v.getContext());
}
}
private void SendUserToChatActivity(Context ctx) {
Intent mainIntent = new Intent(ctx, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
I am filtering my recyclerview data with onQueryTextChange method, the filter is working fine, however when I am clicking on a element after filter, it still picks up the element that was placed before the filter. Could some one point me out what I am doing wrong here.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener
{
List<DataAdapter> DataAdapterClassList;
RecyclerView recyclerView;
EditText etSearch;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerViewAdapter recyclerViewadapter;
ProgressBar progressBar;
JsonArrayRequest jsonArrayRequest;
ArrayList<String> BankNames;
RequestQueue requestQueue;
String HTTP_SERVER_URL = "http://hiddenforsecurity.com?method=apiTest";
View ChildView;
int RecyclerViewClickedItemPOS;
LinearLayout lyt, icicBtn, hdfcBtn, axisBtn, sbiBtn, pnbBtn, yesBtn;
private static int firstVisibleInListview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataAdapterClassList = new ArrayList<>();
BankNames = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
lyt = (LinearLayout) findViewById(R.id.Layout1);
final Intent go = new Intent(MainActivity.this, StateList.class);
icicBtn = (LinearLayout) findViewById(R.id.icicBtn);
hdfcBtn = (LinearLayout) findViewById(R.id.hdfcBtn);
axisBtn = (LinearLayout) findViewById(R.id.axisBtn);
sbiBtn = (LinearLayout) findViewById(R.id.sbiBtn);
pnbBtn = (LinearLayout) findViewById(R.id.pnbBtn);
yesBtn = (LinearLayout) findViewById(R.id.yesBtn);
final Intent i = new Intent(this, StateList.class);
// JSON data web call function call from here.
JSON_WEB_CALL();
//RecyclerView Item click listener code starts from here.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
ChildView = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (ChildView != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked item value.
RecyclerViewClickedItemPOS = Recyclerview.getChildAdapterPosition(ChildView);
Toast.makeText(MainActivity.this, BankNames.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
//Printing RecyclerView Clicked item clicked value using Toast Message.
//i.putExtra("selectedbank", BankNames.get(RecyclerViewClickedItemPOS));
//startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
icicBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "ICICI BANK LIMITED");
startActivity(go);
}
});
axisBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "AXIS BANK");
startActivity(go);
}
});
hdfcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "HDFC BANK");
startActivity(go);
}
});
sbiBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "STATE BANK OF INDIA");
startActivity(go);
}
});
pnbBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "PUNJAB NATIONAL BANK");
startActivity(go);
}
});
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
go.putExtra("selectedbank", "YES BANK");
startActivity(go);
}
});
}
public void JSON_WEB_CALL(){
progressBar.setVisibility(View.VISIBLE);
jsonArrayRequest = new JsonArrayRequest(HTTP_SERVER_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setBankName(json.getString("BANK"));
//Adding subject name here to show on click event.
BankNames.add(json.getString("BANK"));
}
catch (JSONException e)
{
e.printStackTrace();
}
DataAdapterClassList.add(GetDataAdapter2);
}
progressBar.setVisibility(View.GONE);
recyclerViewadapter = new RecyclerViewAdapter(DataAdapterClassList, this);
recyclerView.setAdapter(recyclerViewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
Toast.makeText(MainActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
return false;
}
}
private List<DataAdapter> filter(List<DataAdapter> models, String query) {
query = query.toLowerCase();
final List<DataAdapter> filteredModelList = new ArrayList<>();
for (DataAdapter model : models) {
final String text = model.getBankName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
recyclerViewadapter = new RecyclerViewAdapter(filteredModelList, MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerView.setAdapter(recyclerViewadapter);
recyclerViewadapter.notifyDataSetChanged();
return filteredModelList;
}
}
RecyclerviewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
public DataAdapter dataAdapter;
List<DataAdapter> dataAdapters;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
dataAdapter = dataAdapters.get(position);
viewHolder.TextViewName.setText(dataAdapter.getBankName());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView TextViewName;
public ViewHolder(View itemView) {
super(itemView);
TextViewName = (TextView) itemView.findViewById(R.id.TextViewCard) ;
}
}
public void setFilter(List<DataAdapter> bankNames) {
dataAdapters = new ArrayList<>();
dataAdapters.addAll(bankNames);
notifyDataSetChanged();
}
}
Please have a look at these screenshot for better understanding of my query.
When I click on a item before filter, Toast displays correct data.
Unfiltered Screenshot
When I click on a item after filtering, Toast still displays the data from the above screenshot, where as it was supposed to show HDFC BANK.Filtered Screenshot
Its because you are changing dataset in list view but later on in Toast you reffer to BankNames which is different dataset.
In your example list has ony 1 element due to filters. While you click it, clicked index will be in fact 0, not x as you would require and later on you are picking 0 indexed bank from BankNames not from filtered result set.
To get things right, use the same dataset for list view and data fetch.
You can do that, by simply creating filteredBankNames collection that will contain currently filtered results, and pass that to your list view. In the same time, in on click event, pick bank name from filteredBankNames as well insteed of BankNames
So for example:
// make this not final local variable, but a field in activity so you can remember filtered items
final List<DataAdapter> filteredModelList = filter(DataAdapterClassList, newText);
if (filteredModelList.size() > 0) {
recyclerViewadapter.setFilter(filteredModelList);
return true;
} else {
and with Toast
Toast.makeText(MainActivity.this, filteredModelList.get(RecyclerViewClickedItemPOS), Toast.LENGTH_SHORT).show();
I need an answer on how to create an add button to add listview item, and a delete button to delete last added item. Look at my code. I made an add button but that item exists only for a few seconds and every time I close that page (go to other activity in usermode) it is deleted. Please let me know how can I fix this code and how can I write code for delete button. I need to know how to delete last made item. Thanks for your help in advance. I am looking forward to reply.
public class dodaj extends Activity {
ListView lv;
SearchView sv;
EditText txtinput;
ArrayList<String> arrayList;
String[] recepies={};
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dodaj);
registerClickCallback();
lv=(ListView) findViewById(R.id.listView);
sv=(SearchView) findViewById(R.id.searchView);
txtinput=(EditText)findViewById(R.id.txtinput);
Button addbutton=(Button)findViewById(R.id.addbutton);
Button buttondel=(Button) findViewById(R.id.buttondel);
arrayList= new ArrayList<>(Arrays.asList(recepies));
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
String newItem=txtinput.getText().toString();
arrayList.add(newItem);
adapter.notifyDataSetChanged();
}
});
buttondel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v ) {
int i = arrayList.size()-1;
arrayList.remove(arrayList.get(i));
}
});
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arrayList);
lv.setAdapter(adapter);
sv.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
private void registerClickCallback(){
lv=(ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
TextView textView= (TextView) viewClicked;
if(position==0){
goToMojRecept1();
}else if(position==1){
goToMojRecept2();
}else if(position==2){
goToMojRecept3();
}else if(position==3){
goToMojRecept4();
}else if(position==4) {
goToMojRecept5();
}
}
});
}
private void goToMojRecept5() {
Intent intent = new Intent(this, MojRecept5.class);
startActivity(intent);
}
private void goToMojRecept4() {
Intent intent = new Intent(this, MojRecept4.class);
startActivity(intent);
}
private void goToMojRecept3() {
Intent intent = new Intent(this, MojRecept3.class);
startActivity(intent);
}
private void goToMojRecept2() {
Intent intent = new Intent(this, MojRecept2.class);
startActivity(intent);
}
private void goToMojRecept1() {
Intent intent = new Intent(this, MojRecept1.class);
startActivity(intent);
}