-3

I am trying to developing an app in which an alertdialog must open on button click in recylcerview and these are the error I am getting :

21 06:50:20.817 1037-1037/com.example.hephaestus.shadowpets4 
E/AndroidRuntime: FATAL EXCEPTION: main                                                                         
java.lang.IllegalStateException: You need to use a Theme.AppCompat 
theme (or descendant) with this activity.                                                                             
      at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
      at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
      at android.support.v7.app.AppCompatDialog.setContentView(AppCompatDialog.java:83)
      at android.support.v7.app.AlertController.installContent(AlertController.java:225)
      at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
      at android.app.Dialog.dispatchOnCreate(Dialog.java:351)
      at android.app.Dialog.show(Dialog.java:256)
      at com.example.hephaestus.shadowpets4.Adapters.TrainerAdapter$1.onClick(TrainerAdapter.java:84)
      at android.view.View.performClick(View.java:4084)
      at android.view.View$PerformClick.run(View.java:16966)
      at android.os.Handler.handleCallback(Handler.java:615)
      at android.os.Handler.dispatchMessage(Handler.java:92)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:4745)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:511)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
      at dalvik.system.NativeStart.main(Native Method)
Koopakiller
  • 2,838
  • 3
  • 32
  • 47
Atul kumar
  • 97
  • 3
  • 13
  • The logcat is clearly suggesting you what to do next: `You need to use a Theme.AppCompat theme (or descendant) with this activity` – Phantômaxx Aug 21 '17 at 09:08
  • You need to use a Theme.AppCompat theme (or descendant) with this activity. at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359) at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328) at – Rihan Husain Aug 21 '17 at 09:50
  • Possible duplicate of [You need to use a Theme.AppCompat theme (or descendant) with this activity](https://stackoverflow.com/questions/21814825/you-need-to-use-a-theme-appcompat-theme-or-descendant-with-this-activity) – Ajil O. Aug 21 '17 at 11:21
  • could you tell me where changes can be made so that it can work? – Atul kumar Aug 21 '17 at 14:43

1 Answers1

1

After researching a lot i found the answer to my problem order to use alert dialog in your activity we should use activity instead of context while creating the alert dialog and we should use application context while using fragment , these changes must be made in the adapter(as I'm using it with the recylcerview ) as well as in the activity in which it's executed , these could be understand by this example : the following is an example of implementing alert dialog box with recyclerview in an fragment

  public class AdoptpetAdapter extends RecyclerView.Adapter<AdoptpetAdapter.ViewHolder> {
     private Context context;
     private List<Pet> petList;
    public AdoptpetAdapter(Context context,List<Pet> petList)
    {
        this.context=context;
        this.petList=petList;
    }
    @Override
    public AdoptpetAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_pet,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
            holder.petName.setText(petList.get(position).getPetName());
            holder.petCost.setText(petList.get(position).getPetCost());
        Picasso.with(context).load(petList.get(position).getPetImage()).into(holder.imageView);
        holder.btn_Contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  LayoutInflater li =LayoutInflater.from(context);
               View promptsView = li.inflate(R.layout.petenquiryform,null);
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setView(promptsView);
                  TextView msg_Title =(TextView)promptsView.findViewById(R.id.txt_petEnquirytitle);
                    msg_Title.setText("Enquiry about "+" "+petList.get(position).getPetName());
                EditText txt_message =(EditText) promptsView.findViewById(R.id.txt_message);
                 builder.setCancelable(false)
                         .setPositiveButton("Send", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         })
                         .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         });
                   AlertDialog alertDialog = builder.create();
                    alertDialog.show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return petList.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder
    {
        private ImageView imageView;
        private TextView petCost,petName;
        private Button btn_Contact;

        public ViewHolder(View itemView) {

            super(itemView);
            imageView=(ImageView)itemView.findViewById(R.id.img_pet);
            petCost=(TextView)itemView.findViewById(R.id.txt_petprice);
            petName=(TextView)itemView.findViewById(R.id.txt_petname);
            btn_Contact=(Button)itemView.findViewById(R.id.btn_contactSeller);
        }
    }
}

In order to implement it in fragment you just have to do the following code

    public class Pets extends Fragment {
    List<Pet> petList;
    RecyclerView recyclerView;
    ProgressDialog pDialog;
    AdoptpetAdapter adapter;




    public Pets() {
        // 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_pets, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView=(RecyclerView)view.findViewById(R.id.list_pets);
         initviews();
    }
    private void initviews()
    {
        pDialog = new ProgressDialog(getContext());
        pDialog.setMessage("Loading,Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
        try
        {
            Glide.with(this).load(R.drawable.ic_menu_gallery).into((ImageView) recyclerView.findViewById(R.id.img_pet));

        }
        catch (Exception ex)
        {

        }
        petList=new ArrayList<>();
        adapter=new AdoptpetAdapter(getContext(),petList);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(),2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        loadJson();
    }
    private void loadJson()
    {
          try
          {
              Retrofit retrofit = new Retrofit.Builder().baseUrl(APIUrl.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
              APIService service=retrofit.create(APIService.class);
              Call<Response> call =service.getPetList();
               call.enqueue(new Callback<Response>() {
                   @Override
                   public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
                       List<Pet>data=response.body().getPetList();
                       recyclerView.setAdapter(new AdoptpetAdapter(getActivity(),data));
                       recyclerView.smoothScrollToPosition(0);
                       pDialog.hide();
                   }

                   @Override
                   public void onFailure(Call<Response> call, Throwable t) {
                       pDialog.dismiss();


                   }
               });
          }
          catch (Exception ex)
          {
               pDialog.hide();

          }
    }
}

**While implementing it in Activity it should be changed as following , the following is the code for the adapter and implementing alert dialog box in it **

public class TrainerAdapter extends RecyclerView.Adapter<TrainerAdapter.ViewHolder> {
    private Activity activity;
    private List<Trainer> trainerList;
    public TrainerAdapter(Activity activity,List<Trainer> trainerList)
    {
        this.activity=activity;
        this.trainerList=trainerList;
    }
    @Override
    public TrainerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_trainer,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.trainerName.setText(trainerList.get(position).getTrainerName());
        holder.trainerLocation.setText(trainerList.get(position).getTrainerPhone());
        holder.btnEnquiretrnr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater li = LayoutInflater.from(activity);
               View promptsView = li.inflate(R.layout.trainerenquiryform,null);
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                 builder.setView(promptsView);
                 builder.setCancelable(false)
                         .setPositiveButton("Send", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         })
                         .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialog, int which) {

                             }
                         });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });

    }

    @Override
    public int getItemCount() {
        return trainerList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView trainerName,trainerLocation;
        private Button btnEnquiretrnr;
        public ViewHolder(View itemView) {
            super(itemView);
            trainerName=(TextView)itemView.findViewById(R.id.txt_Trainername);
            trainerLocation=(TextView)itemView.findViewById(R.id.txt_trainerLocation);
            btnEnquiretrnr=(Button)itemView.findViewById(R.id.btn_enquireTrnr);
        }
    }
}

In order to implement it into activity this is how we should implement it

   public class Trainers extends AppCompatActivity {
        RecyclerView trainersList;
        List<Trainer> list;

        ProgressDialog pDialog;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_trainers);
            pDialog = new ProgressDialog(this);
            pDialog.setCancelable(false);
            pDialog.setMessage("Loading,Please wait....");
            pDialog.show();
            trainersList =(RecyclerView)findViewById(R.id.list_trainers);
            trainersList.setHasFixedSize(true);

            RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
            trainersList.setLayoutManager(layoutManager);
            loadData();

        }

        private void loadData()
        {
            try {
                Retrofit retrofit = new Retrofit.Builder().baseUrl(APIUrl.BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
                APIService service = retrofit.create(APIService.class);
                Call<Response> call = service.getTrainers();
                call.enqueue(new Callback<Response>() {
                    @Override
                    public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
                        list=response.body().getTrainerList();
                        TrainerAdapter trainerAdapter=new TrainerAdapter(Trainers.this,list);
                        trainersList.setAdapter(trainerAdapter);
                        pDialog.hide();
                    }

                    @Override
                    public void onFailure(Call<Response> call, Throwable t) {

                    }
                });
            }
             catch (Exception ex)
             {

                }
            }
        }

I hope these answers many people queries like i had

Atul kumar
  • 97
  • 3
  • 13