ZXingScannerView in another class than Main - java

I want to create a QR scan code system using ZXingScannerView, but i want to use this interface not in base class. I decided to create a xml file when I have just ZXingScannerView and I call functions on this, but it's not working.
This is my class when I run my Code Scanner by button click:
package com.example.elistazakupow3;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import Models.ShoppingList;
public class FragmentShoppingList extends Fragment {
protected View view;
private RecyclerView myRecyclerView;
private ArrayList<ShoppingList> lstShoppingList;
Button scan_button;
#Nullable
#Override
public View onCreateView(#NonNull final LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_shopping_list, container,false);
myRecyclerView = view.findViewById(R.id.myRC);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
MyRecyclerViewAdapter recyclerViewAdapter = new MyRecyclerViewAdapter(lstShoppingList);
myRecyclerView.setAdapter(recyclerViewAdapter);
//Scanner
scan_button = view.findViewById(R.id.scan_button);
scan_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CodeScanner();
}
});
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
lstShoppingList = new ArrayList<>();
lstShoppingList.add(new ShoppingList("Na wigiliÄ™","Nie wiem","23.04.1998"));
}
}
And my CodeScanner class
package com.example.elistazakupow3;
import android.app.AlertDialog;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class CodeScanner extends FragmentShoppingList implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
public CodeScanner(){
mScannerView = getActivity().findViewById(R.id.scaner);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onPause(){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
// Toast.makeText(getContext(), "Contents = " + result.getText() + ", Format = " + result.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
AlertDialog.Builder bd = new AlertDialog.Builder(getActivity());
bd.setTitle("Wynik skanowania");
bd.setMessage(result.getText());
AlertDialog pokazKod = bd.create();
pokazKod.show();
}
}

You can't show a Fragment in that manner. Read this and try to follow it in your code.
Move this to onResume:
mScannerView.setResultHandler(this);
mScannerView.startCamera();
You're supposed to create a new ZXingScannerView and return it in your CodeScanner's onCreateView, the idea is that instead of inflating an XML, you're instantiating ZXingScannerView as your whole UI. Instead of mScannerView = getActivity().findViewById(R.id.scaner);, do something like this in your CodeScanner fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mScannerView= new ZXingScannerView(requireContext());
return mScannerView;
}

Related

error: non-static method show() cannot be referenced from a static context in FragmentActivity crashes

The sourcecode of the project is given below
non-static method show(FragmentManager,String) cannot be referenced from a static context
my AdminHomeActivity and the AdminComplaintDetailsFragment classes are given below.
Full project source codeof error
Main project source code
AdminHomeFragment.java
package com.example.ecomplaint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class AdminHomeFragment extends Fragment {
ListView listview;
public static ArrayList arrayList;
FirebaseDatabase rootNode;
DatabaseReference reference;
public static CustomRow adapter;
public static ArrayList adapterData;
FloatingActionButton mainbutton,registerbutton,logoutbutton;
Animation fabOpen,fabClose,rotateForward,rotateBackward;
boolean isOpen=false;
DatabaseReference referenceExpert;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_admin_home,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ProgressBar simpleProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
mainbutton=(FloatingActionButton) view.findViewById(R.id.floatingActionButton);
registerbutton=(FloatingActionButton) view.findViewById(R.id.registerbutton);
logoutbutton=(FloatingActionButton) view.findViewById(R.id.logout_button);
fabOpen= AnimationUtils.loadAnimation(getContext(),R.anim.from_buttom_anim);
fabClose= AnimationUtils.loadAnimation(getContext(),R.anim.to_buttom_anim);
rotateForward= AnimationUtils.loadAnimation(getContext(),R.anim.rotate_open_anim);
rotateBackward= AnimationUtils.loadAnimation(getContext(),R.anim.rotate_close_anim);
mainbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animatefab();
}
});
registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(),RegistrationActivity.class);
startActivity(i);
}
});
logoutbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getContext(),MainActivity.class));
}
});
listview=view.findViewById(R.id.list);
listview.setItemsCanFocus(false);
arrayList = new ArrayList<Complaint>();
adapterData = new ArrayList<Complaint>();
adapter = new CustomRow(getContext(), arrayList);
listview.setAdapter(adapter);
simpleProgressBar.setVisibility(View.VISIBLE);
//arrayList.add(new Complaint("123","this is title","akhil","19bce1564","ragging","rahul","registered"));
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(!arrayList.isEmpty()){
arrayList.clear();
}
for(DataSnapshot dataSnapshot:snapshot.getChildren()){
Complaint complaint=dataSnapshot.getValue(Complaint.class);
// if(complaint.getComplaintFrom().getEmail().equals(FirebaseAuth.getInstance().getCurrentUser().getEmail())){
//get all users complaint
arrayList.add(complaint);
// }
adapter.notifyDataSetChanged();
listview.requestLayout();
simpleProgressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Complaint present = (Complaint) arrayList.get(position);
AdminComplaintDetailsFragment admincomplaintDetailsFragment= new AdminComplaintDetailsFragment(present);
AdminComplaintDetailsFragment.show(((FragmentActivity)getContext()).getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());
//Toast.makeText(getContext(), "hii", Toast.LENGTH_SHORT).show();
}
});
}
private void animatefab(){
if (isOpen){
mainbutton.startAnimation(rotateForward);
registerbutton.startAnimation(fabClose);
logoutbutton.startAnimation(fabClose);
registerbutton.setClickable(false);
logoutbutton.setClickable(false);
isOpen=false;
}
else{
mainbutton.startAnimation(rotateBackward);
registerbutton.startAnimation(fabOpen);
logoutbutton.startAnimation(fabOpen);
registerbutton.setClickable(true);
logoutbutton.setClickable(true);
isOpen=true;
}
}
}
AdminComplaintDetailsFragment.java
package com.example.ecomplaint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Locale;
/**
* A simple {#link Fragment} subclass.
* Use the {#link ComplaintDetailsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AdminComplaintDetailsFragment extends BottomSheetDialogFragment {
FirebaseDatabase rootNode;
DatabaseReference reference;
String[] items = {"Under investigation","Reviewing complaint","Investigation complete","Case Closed"};
AutoCompleteTextView autoCompleteTxt;
ArrayAdapter<String> adapterItems;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
Complaint present;
public AdminComplaintDetailsFragment() {
// Required empty public constructor
}
public AdminComplaintDetailsFragment(Complaint present){
this.present=present;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment ComplaintDetailsFragment.
*/
// TODO: Rename and change types and number of parameters
public static AdminComplaintDetailsFragment newInstance(String param1, String param2) {
AdminComplaintDetailsFragment fragment = new AdminComplaintDetailsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_complaint_details, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(present.getStatus().equals("registered")){
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
present.setStatus("Seen");
HashMap hashMap=new HashMap();
hashMap.put("status","Seen");
reference.child(present.complaintID).updateChildren(hashMap);
Log.i("this",reference.child("complaintID").child(present.complaintID).child("status").toString());
}
TextView title=view.findViewById(R.id.details_title);
title.setText(present.getTitle());
TextView name=view.findViewById(R.id.details_name);
name.setText(present.getName());
TextView regno=view.findViewById(R.id.details_regno);
regno.setText(present.getRegno());
TextView incident=view.findViewById(R.id.details_info);
incident.setText(present.getIncident_info());
TextView ComplaintFrom=view.findViewById(R.id.complaintFrom);
ComplaintFrom.setText(present.getComplaintFrom().getName());
TextView status=view.findViewById(R.id.details_status);
status.setText(present.getStatus().toUpperCase(Locale.ROOT));
autoCompleteTxt = view.findViewById(R.id.auto_complete_txt);
adapterItems = new ArrayAdapter<String>(getContext(),R.layout.list_item,items);
autoCompleteTxt.setAdapter(adapterItems);
autoCompleteTxt.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Complaints");
present.setStatus(item);
HashMap hashMap=new HashMap();
hashMap.put("status",item);
reference.child(present.complaintID).updateChildren(hashMap);
Log.i("this",reference.child("complaintID").child(present.complaintID).child("status").toString());
status.setText(present.getStatus().toUpperCase(Locale.ROOT));
//Toast.makeText(getContext(),"Item: "+item,Toast.LENGTH_SHORT).show();
}
});
}
}
The show method on AdminComplaintDetailsFragment is not static which is what you are doing via AdminComplaintDetailsFragment.show.
Use the variable admincomplaintDetailsFragment that you've initialized.
Change
AdminComplaintDetailsFragment.show(((FragmentActivity)getContext()).getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());
to
admincomplaintDetailsFragment.show(requireActivity.getSupportFragmentManager(), admincomplaintDetailsFragment.getTag());

how to move from a fragment to a new activity when i clicked an item of recyclerview?

I am using recyclerview in fragment dynamically, now i want to open new activity on click of items with the same object / item.
AllCoursesFeagment.java
package com.example.learningapp.ui.NavigationDrawer.AllCourses;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Adapters.AllCoursesMyAdapter;
import com.example.learningapp.Interface.APIinterface;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import com.example.learningapp.Responses.CourseListResponse;
import com.example.learningapp.RetrofitAPIs.RetrofitAPI;
import com.example.learningapp.utility.ConstantData;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AllCoursesFragment extends Fragment {
private RecyclerView recyclerView;
private List<CourseListModel> courseListModelList;
public AllCoursesFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static AllCoursesFragment newInstance() {
return new AllCoursesFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_all_courses,null);
recyclerView = view.findViewById(R.id.allCourseList_RV);
APIinterface apIinterface = RetrofitAPI.getClient().create(APIinterface.class);
Call<CourseListResponse> call = apIinterface.getAllCourses(ConstantData.AppKey);
call.enqueue(new Callback<CourseListResponse>() {
#Override
public void onResponse(Call<CourseListResponse> call, Response<CourseListResponse> response){
if (response.isSuccessful()){
courseListModelList = response.body().getCourseList();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new AllCoursesMyAdapter(getActivity(),courseListModelList));
}
}
#Override
public void onFailure(Call<CourseListResponse> call, Throwable t) {
Toast.makeText(getActivity(),"Something went wrong",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AllCoursesMyAdapter.java
This is my adapter class.
package com.example.learningapp.Adapters;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.learningapp.Activities.CheckoutActivity;
import com.example.learningapp.Models.CourseListModel;
import com.example.learningapp.R;
import java.util.List;
public class AllCoursesMyAdapter extends RecyclerView.Adapter<AllCoursesMyAdapter.RecyclerVH> {
Context context;
List<CourseListModel> courseListModelList;
public AllCoursesMyAdapter(Context context, List<CourseListModel> courseListModelList) {
this.context = context;
this.courseListModelList = courseListModelList;
}
#NonNull
#Override
public RecyclerVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.single_row_design_allcourses,parent,false);
return new RecyclerVH(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerVH holder, int position) {
final CourseListModel courseListModel = courseListModelList.get(position);
holder.courseTitle.setText(courseListModel.getCourseName());
holder.courseDesc.setText(courseListModel.getCourseDescription());
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
private void moveToNewActivity () {
Activity activity = new Activity();
Intent i = new Intent(activity, CheckoutActivity.class);
context.startActivity(i);
((Activity) context).overridePendingTransition(0, 0);
}
#Override
public int getItemCount() {
return courseListModelList.size();
}
public class RecyclerVH extends RecyclerView.ViewHolder {
TextView courseTitle,courseDesc;
Button buyBtn;
public RecyclerVH(#NonNull View itemView) {
super(itemView);
courseTitle = itemView.findViewById(R.id.course_title);
courseDesc = itemView.findViewById(R.id.course_desc);
buyBtn = itemView.findViewById(R.id.btn_buycourse);
}
}
}
I'm gettng crashed when i clicked item
holder.buyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
moveToNewActivity();
//Toast.makeText(context,"Item Clicked"+position,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, CheckoutActivity.class);
intent.putExtra("coursetitle",courseListModel.getCourseName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
Here i am using a stored list of objects and now i want to move to the new activity when i clicked on an item with given position, but i am not able to do that.
private void moveToNewActivity () {
Activity activity = new Activity(); //this is wrong, delete this
...
}
you can't and shouldn't create an instance of an activity like this, it's something the OS has to schedule and handle for you.
you already seem to have context defined somewhere, so that means:
private void moveToNewActivity () {
Intent i = new Intent(context, CheckoutActivity.class);
context.startActivity(i);
...
}
so that means:
#Override
public void onClick(View v) {
moveToNewActivity();
}

passing string from an activity to a fragment

Hi ive been going through questions and found a solution to pass a string from an activity (not the fragment activity) to a fragment. i want to pass a document ID on click from RestaurantsList.class to Mainsfragment.class, inside my onclick.
The error message i get is the following:
Attempt to invoke virtual method 'android.content.Intent android.app.Activity.getIntent()' on a null object reference
here is my code for the activity:
package com.example.hostapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RelativeLayout;
import com.example.hostapp.Adapters.RestaurantAdapter;
import com.example.hostapp.Adapters.categoryCardAdapter;
import com.example.hostapp.MenuFragments.MainsFragment;
import com.example.hostapp.Models.Restaurant;
import com.example.hostapp.Models.categoryCard;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class RestaurantList extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference restaurantref = db.collection("restaurants");
private RestaurantAdapter adapter;
String categoryid = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant_list);
setUpRecyclerView();
}
private void setUpRecyclerView() {
//Get intent
if (getIntent() != null)
categoryid = getIntent().getStringExtra("categoryid");
if (!categoryid.isEmpty() && categoryid != null) {
Query query = restaurantref.whereEqualTo("categoryid", categoryid).orderBy("name");
final FirestoreRecyclerOptions<Restaurant> options = new FirestoreRecyclerOptions.Builder<Restaurant>().setQuery(query, Restaurant.class).build();
adapter = new RestaurantAdapter(options);
RecyclerView recyclerView = findViewById(R.id.restaurant_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListerner(new RestaurantAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
Restaurant restaurant = documentSnapshot.toObject(Restaurant.class);
Intent foodlist = new Intent(RestaurantList.this, Foodlist.class);
Bundle bundle = new Bundle();
bundle.putString("restaurantid", documentSnapshot.getId());
MainsFragment m4 = new MainsFragment();
m4.setArguments(bundle);
//foodlist.putExtra("restaurantid", documentSnapshot.getId());
startActivity(foodlist);
}
});
}
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
here is my code for the fragment:
package com.example.hostapp.MenuFragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.hostapp.Adapters.FoodAdapter;
import com.example.hostapp.Models.FoodModel;
import com.example.hostapp.R;
import com.example.hostapp.RestaurantList;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class MainsFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private FoodAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mains, container, false);
String restaurantNumber = getArguments().getString("restaurantid");
Query menuref = db.collectionGroup("Foods").whereEqualTo("menuid", restaurantNumber);
FirestoreRecyclerOptions<FoodModel> options = new FirestoreRecyclerOptions.Builder<FoodModel>().
setQuery(menuref, FoodModel.class)
.build();
adapter = new FoodAdapter(options);
RecyclerView recyclerView = view.findViewById(R.id.recycler_mains);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(adapter);
return view;
}
private void setUpRecyclerView() {
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
I had the same experience like this. Here is how I handled it:
1, Pass your data from RestaurantList activity to your foodlist activity via intent.putExtra();
Intent foodlist = new Intent(RestaurantList.this, Foodlist.class);
foodlist.putExtra("restaurantid", documentSnapshot.getId());
startActivity(foodlist);
2, Get the value by getIntent() from Foodlist activity;
String id = getIntent().getStringExtra("restaurantid");
3, Pass your data to the Adapter where you are initializing the adapter. (sth like this :)
YourAdapter adapter = new YourAdapter(getSupportFragmentManager(), tabLayout.getTabCount(),id);
4, Get the data in constractor of adapter (you have to create a global variable and fill it in constructor) and create a bundle in getItem() method and pass the data to it and set arguments to the fragment (like below code)
public class YourAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
String id;
public AdapterPagerShift(FragmentManager fm, int NumOfTabs, String id) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.id = id;
}
#Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putString("restaurantid", documentSnapshot.getId());
switch (position) {
case 0:
MainsFragment main = new MainsFragment();
main.setArguments(bundle);
return main;
case 1:
//...
case 2:
//...
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
5, Get the data by using below code in your MainsFragment class :
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String id = getArguments().getString("restaurantid");
}
Hope it helps!

app getting crashed when trying to use setOnClickListener

main activity
import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void button(View v)
{
FragmentManager fragmentManager=getFragmentManager();
frag1 f1=new frag1();
f1.show(fragmentManager,"TAG");
}
}
fragment
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class frag1 extends DialogFragment implements View.OnClickListener{
Button button;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag1,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button= (Button) getActivity().findViewById(R.id.button);
button.setOnClickListener((View.OnClickListener) getActivity());
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"working",Toast.LENGTH_LONG).show();
}
}
This is a code for a simple dialog box.
Here's a link where I learnt it from. It works completely fine if I just create the dialog box with calling the button.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.frag1,container,false);
button= (Button) View.findViewById(R.id.button);
button..setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity(),"working",Toast.LENGTH_LONG).show();
}
});
return view;
}
Change your line from
button.setOnClickListener((View.OnClickListener) getActivity());
to
button.setOnClickListener(this);
Also, use
getSupportFragmentManager() to instead of getFragmentManager()
and import
import android.support.v4.app.FragmentManager;

Add Function for each bottom from Bottomsheet

I have set of different buttons in my list view:
This is my app:
MyBottomSheetDialogFragment:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sasank on 26-11-2016.
*/
public class MyBottomSheetDialogFragment extends BottomSheetDialogFragment {
String mString;
private RecyclerView mRecyclerView;
private VerticalListAdapter mVerticalListAdapter;
static MyBottomSheetDialogFragment newInstance(String string) {
MyBottomSheetDialogFragment f = new MyBottomSheetDialogFragment();
Bundle args = new Bundle();
args.putString("string", string);
f.setArguments(args);
return f;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mString = getArguments().getString("string");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bottom_sheet_modal_list, container, false);
mRecyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
List<Model> list = new ArrayList<Model>();
list.add(new Model(R.drawable.ic_call_black_24dp, "Call"));
list.add(new Model(R.drawable.ic_chat_black_24dp, "Chat"));
list.add(new Model(R.drawable.ic_android_black_24dp, "Android"));
list.add(new Model(R.drawable.ic_location_on_black_24dp, "Location"));
list.add(new Model(R.drawable.ic_call_black_24dp, "Call"));
list.add(new Model(R.drawable.ic_chat_black_24dp, "Chat"));
list.add(new Model(R.drawable.ic_android_black_24dp, "Android"));
list.add(new Model(R.drawable.ic_location_on_black_24dp, "Location"));
mVerticalListAdapter = new VerticalListAdapter(getContext(), list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mVerticalListAdapter);
}
}
My verticalListAdapter.
package com.example.user.bottomsheet_android;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class VerticalListAdapter extends RecyclerView.Adapter<VerticalListAdapter.MyViewHolder>{
private Context mContext;
private List<Model> mModelList;
public VerticalListAdapter(Context context, List<Model> list) {
this.mContext = context;
this.mModelList = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.modal_list_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.txtView.setText(mModelList.get(position).getName());
holder.imgView.setImageDrawable(mContext.getResources().getDrawable(mModelList.get(position).getImgId()));
}
#Override
public int getItemCount()
{
return mModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView txtView;
public ImageView imgView;
public MyViewHolder(View view) {
super(view);
txtView = (TextView) view.findViewById(R.id.txtView);
imgView = (ImageView) view.findViewById(R.id.imgView);
}
}
}
My goal is to add function for each button that is showed in the bottom sheet.
For any clarification please leave a comment.
In your onBindViewHolder method, I would put an onClickListener, and then use either a switch-case structure or several different if-elseif statements. For example, the switch-case would look something like:
holder.txtView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
switch (holder.getAdapterPosition()) {
case 1:
// do call related things here
.
.
.
break;
case 2:
// do chat related things here
.
.
.
break;
}
}
}
and so on. You could implement something similar with if statements

Categories

Resources