Как получить фрагменты контекста из адаптеров

#android

#Android

Вопрос:

Я пытаюсь создать адаптер для фрагмента

создайте держатель для моего cardview. в коде для setOnClickListener появляется ошибка в startActivityForResult для отображения редактирования фрагмента

вот мой код

 @Override
public void onBindViewHolder(RvFragmentAdapter.MyViewHolder holder, final int position) {
    holder.tv_id.setText(array_id.get(position));
    holder.tv_username.setText(array_username.get(position));
    holder.tv_email.setText(array_email.get(position));
    holder.tv_nama.setText(array_nama.get(position));
    holder.tv_jenis_kelamin.setText(array_jenis_kelamin.get(position));
    holder.tv_no_hp.setText(array_no_hp.get(position));
    holder.tv_sertifikat.setText(array_sertifikat.get(position));
    holder.tv_no_kta.setText(array_no_kta.get(position));
    holder.tv_masa_berlaku.setText(array_masa_berlaku.get(position));
    holder.tv_no_reg.setText(array_no_reg.get(position));
    holder.tv_password.setText(array_password.get(position));
    holder.tv_level.setText(array_level.get(position));
    holder.tv_agama.setText(array_agama.get(position));
    holder.tv_tempat_lahir.setText(array_tempat_lahir.get(position));
    holder.tv_tgl_lahir.setText(array_tgl_lahir.get(position));
    holder.tv_area.setText(array_area.get(position));

    Glide.with(mContext)
            .load(array_url_gambar.get(position))
            .placeholder(R.drawable.ic_action_person)
            .apply(new RequestOptions().override(80, 100))
            .into(holder.iv_url_gambar);
    holder.cv_main.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(mContext, EditPersonilActivity.class);
            i.putExtra("id",array_id.get(position));
            i.putExtra("username",array_username.get(position));
            i.putExtra("email",array_email.get(position));
            i.putExtra("nama",array_nama.get(position));
            i.putExtra("jenis_kelamin",array_jenis_kelamin.get(position));
            i.putExtra("no_hp",array_no_hp.get(position));
            i.putExtra("sertifikat",array_sertifikat.get(position));
            i.putExtra("no_kta",array_no_kta.get(position));
            i.putExtra("masa_berlaku",array_masa_berlaku.get(position));
            i.putExtra("no_reg",array_no_reg.get(position));
            i.putExtra("password",array_password.get(position));
            i.putExtra("level",array_level.get(position));
            i.putExtra("agama",array_agama.get(position));
            i.putExtra("tempat_lahir",array_tempat_lahir.get(position));
            i.putExtra("tgl_lahir",array_tgl_lahir.get(position));
            i.putExtra("area",array_area.get(position));

            ((EditPersonilFragment)mContext).startActivityForResult(i,2);
        }
    });

}
 

и это код ошибки

 ((EditPersonilFragment)mContext).startActivityForResult(i,2);
 

это сообщение об ошибке

 error: incompatible types: Context cannot be converted to EditPersonilFragment
            ((EditPersonilFragment)mContext).startActivityForResult(i,2);
 

вот мой полный код моего адаптера

 package elnusa.co.smart.model;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import elnusa.co.smart.EditPersonilActivity;
import elnusa.co.smart.R;
import elnusa.co.smart.ui.home.EditPersonilFragment;
public class RvFragmentAdapter extends RecyclerView.Adapter<RvFragmentAdapter.MyViewHolder> {
    private Context mContext;
    private ArrayList<String> array_id, array_username, array_email, array_nama, array_jenis_kelamin,
            array_no_hp, array_sertifikat,array_no_kta, array_no_reg, array_masa_berlaku,
            array_password, array_level, array_agama, array_tempat_lahir, array_tgl_lahir,array_area,array_url_gambar;
    ProgressDialog progressDialog;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView tv_id, tv_username, tv_email, tv_nama, tv_jenis_kelamin, tv_no_hp, tv_no_kta,
                tv_no_reg,tv_sertifikat,tv_masa_berlaku, tv_password, tv_level, tv_agama, tv_tempat_lahir,
                tv_tgl_lahir, tv_area;
        ImageView iv_url_gambar;
        public CardView cv_main;

        public MyViewHolder(View view) {
            super(view);
            cv_main = itemView.findViewById(R.id.cv_main);
            tv_id = itemView.findViewById(R.id.id);
            tv_username = itemView.findViewById(R.id.username);
            tv_email = itemView.findViewById(R.id.email);
            tv_password = itemView.findViewById(R.id.password);
            tv_level = itemView.findViewById(R.id.level);
            tv_nama = itemView.findViewById(R.id.nama);
            tv_jenis_kelamin = itemView.findViewById(R.id.jenis_kelamin);
            tv_no_hp = itemView.findViewById(R.id.no_hp);
            tv_sertifikat = itemView.findViewById(R.id.sertifikat);
            tv_no_kta = itemView.findViewById(R.id.no_kta);
            tv_no_reg = itemView.findViewById(R.id.no_reg);
            tv_masa_berlaku = itemView.findViewById(R.id.masa_berlaku);
            tv_agama = itemView.findViewById(R.id.agama);
            tv_tempat_lahir = itemView.findViewById(R.id.tempat_lahir);
            tv_tgl_lahir= itemView.findViewById(R.id.tgl_lahir);
            tv_area= itemView.findViewById(R.id.area);
            iv_url_gambar = itemView.findViewById(R.id.gbr_profil);
            progressDialog = new ProgressDialog(mContext);

        }
    }

    public RvFragmentAdapter(Context mContext, ArrayList<String> array_id, ArrayList<String> array_username,
                     ArrayList<String> array_email, ArrayList<String> array_nama, ArrayList<String> array_jenis_kelamin,
                     ArrayList<String> array_no_hp, ArrayList<String> array_sertifikat, ArrayList<String> array_no_kta,
                     ArrayList<String> array_masa_berlaku, ArrayList<String> array_no_reg, ArrayList<String> array_password,
                     ArrayList<String> array_level, ArrayList<String> array_agama, ArrayList<String> array_tempat_lahir,
                     ArrayList<String> array_tgl_lahir,ArrayList<String> array_area, ArrayList<String> array_url_gambar) {
        super();
        this.mContext = mContext;
        this.array_id = array_id;
        this.array_username = array_username;
        this.array_email = array_email;
        this.array_nama = array_nama;
        this.array_jenis_kelamin = array_jenis_kelamin;
        this.array_no_hp = array_no_hp;
        this.array_sertifikat = array_sertifikat;
        this.array_no_kta = array_no_kta;
        this.array_masa_berlaku = array_masa_berlaku;
        this.array_no_reg = array_no_reg;
        this.array_password = array_password;
        this.array_level = array_level;
        this.array_agama = array_agama;
        this.array_tempat_lahir = array_tempat_lahir;
        this.array_tgl_lahir = array_tgl_lahir;
        this.array_area = array_area;
        this.array_url_gambar = array_url_gambar;

    }

    @Override
    public RvFragmentAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View itemView = layoutInflater.inflate(R.layout.template_rv,parent,false);
        return new RvFragmentAdapter.MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(RvFragmentAdapter.MyViewHolder holder, final int position) {
        holder.tv_id.setText(array_id.get(position));
        holder.tv_username.setText(array_username.get(position));
        holder.tv_email.setText(array_email.get(position));
        holder.tv_nama.setText(array_nama.get(position));
        holder.tv_jenis_kelamin.setText(array_jenis_kelamin.get(position));
        holder.tv_no_hp.setText(array_no_hp.get(position));
        holder.tv_sertifikat.setText(array_sertifikat.get(position));
        holder.tv_no_kta.setText(array_no_kta.get(position));
        holder.tv_masa_berlaku.setText(array_masa_berlaku.get(position));
        holder.tv_no_reg.setText(array_no_reg.get(position));
        holder.tv_password.setText(array_password.get(position));
        holder.tv_level.setText(array_level.get(position));
        holder.tv_agama.setText(array_agama.get(position));
        holder.tv_tempat_lahir.setText(array_tempat_lahir.get(position));
        holder.tv_tgl_lahir.setText(array_tgl_lahir.get(position));
        holder.tv_area.setText(array_area.get(position));

        Glide.with(mContext)
                .load(array_url_gambar.get(position))
                .placeholder(R.drawable.ic_action_person)
                .apply(new RequestOptions().override(80, 100))
                .into(holder.iv_url_gambar);
        holder.cv_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(mContext, EditPersonilActivity.class);
                i.putExtra("id",array_id.get(position));
                i.putExtra("username",array_username.get(position));
                i.putExtra("email",array_email.get(position));
                i.putExtra("nama",array_nama.get(position));
                i.putExtra("jenis_kelamin",array_jenis_kelamin.get(position));
                i.putExtra("no_hp",array_no_hp.get(position));
                i.putExtra("sertifikat",array_sertifikat.get(position));
                i.putExtra("no_kta",array_no_kta.get(position));
                i.putExtra("masa_berlaku",array_masa_berlaku.get(position));
                i.putExtra("no_reg",array_no_reg.get(position));
                i.putExtra("password",array_password.get(position));
                i.putExtra("level",array_level.get(position));
                i.putExtra("agama",array_agama.get(position));
                i.putExtra("tempat_lahir",array_tempat_lahir.get(position));
                i.putExtra("tgl_lahir",array_tgl_lahir.get(position));
                i.putExtra("area",array_area.get(position));

                ((EditPersonilFragment)mContext).startActivityForResult(i,1);
            }
        });

    }

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

Вот мой фрагмент

     package elnusa.co.smart.ui.home;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

import elnusa.co.smart.ListPersonilActivity;
import elnusa.co.smart.R;
import elnusa.co.smart.TambahPersonilActivity;
import elnusa.co.smart.model.RvFragmentAdapter;

public class EditPersonilFragment extends Fragment {

    SwipeRefreshLayout srl_main;
    RecyclerView rv_main;
    ArrayList<String> array_id, array_username, array_email, array_nama, array_jenis_kelamin,
            array_no_hp, array_sertifikat,array_no_kta, array_no_reg, array_masa_berlaku,
            array_password, array_level, array_agama, array_tempat_lahir, array_tgl_lahir, array_area,array_url_gambar;
    ProgressDialog progressDialog;


    private RvFragmentAdapter recycleViewAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_editpersonil, container, false);
        setHasOptionsMenu(true);
        srl_main    = view.findViewById(R.id.swipe_to_refresh_layout);
        rv_main     = view.findViewById(R.id.rv_main);
        progressDialog = new ProgressDialog(getActivity());

        rv_main.hasFixedSize();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        rv_main.setLayoutManager(layoutManager);


        srl_main.setOnRefreshListener(() -> {
            scrollRefresh();
            srl_main.setRefreshing(false);
        });
        scrollRefresh();
        return view;
    }

    public void scrollRefresh(){
        progressDialog.setMessage("Mengambil Data.....");
        progressDialog.setCancelable(false);
        progressDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getData();
            }
        },1200);
    }


    void initializeArray(){

        array_id = new ArrayList<>();
        array_username = new ArrayList<>();
        array_email = new ArrayList<>();
        array_nama = new ArrayList<>();
        array_jenis_kelamin = new ArrayList<>();
        array_no_hp = new ArrayList<>();
        array_sertifikat = new ArrayList<>();
        array_no_kta = new ArrayList<>();
        array_masa_berlaku = new ArrayList<>();
        array_no_reg = new ArrayList<>();
        array_password = new ArrayList<>();
        array_level = new ArrayList<>();
        array_agama = new ArrayList<>();
        array_tempat_lahir = new ArrayList<>();
        array_tgl_lahir = new ArrayList<>();
        array_area = new ArrayList<>();
        array_url_gambar = new ArrayList<>();

        array_id.clear();
        array_username.clear();
        array_email.clear();
        array_nama.clear();
        array_jenis_kelamin.clear();
        array_no_hp.clear();
        array_sertifikat.clear();
        array_no_kta.clear();
        array_masa_berlaku.clear();
        array_no_reg.clear();
        array_password.clear();
        array_level.clear();
        array_agama.clear();
        array_tempat_lahir.clear();
        array_tgl_lahir.clear();
        array_area.clear();
        array_url_gambar.clear();
    }

    public void getData(){
        initializeArray();
        AndroidNetworking.get("http://192.168.137.187/smart/user/getData.php")
                .setTag("Get Data")
                .setPriority(Priority.MEDIUM)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        progressDialog.dismiss();

                        try{
                            Boolean status = response.getBoolean("status");
                            if(status){
                                JSONArray ja = response.getJSONArray("result");
                                Log.d("respon","" ja);
                                for(int i = 0 ; i < ja.length() ; i  ){
                                    JSONObject jo = ja.getJSONObject(i);
                                    array_id.add(jo.getString("id"));
                                    array_username.add(jo.getString("username"));
                                    array_email.add(jo.getString("email"));
                                    array_nama.add(jo.getString("nama"));
                                    array_jenis_kelamin.add(jo.getString("jenis_kelamin"));
                                    array_no_hp.add(jo.getString("no_hp"));
                                    array_sertifikat.add(jo.getString("sertifikat"));
                                    array_no_kta.add(jo.getString("no_kta"));
                                    array_masa_berlaku.add(jo.getString("masa_berlaku"));
                                    array_no_reg.add(jo.getString("no_reg"));
                                    array_password.add(jo.getString("password"));
                                    array_level.add(jo.getString("level"));
                                    array_agama.add(jo.getString("agama"));
                                    array_tempat_lahir.add(jo.getString("tempat_lahir"));
                                    array_tgl_lahir.add(jo.getString("tgl_lahir"));
                                    array_area.add(jo.getString("area"));
                                    array_url_gambar.add(jo.getString("letak_gbr"));
                                }
                                recycleViewAdapter = new RvFragmentAdapter(getActivity(),array_id, array_username, array_email, array_nama, array_jenis_kelamin,
                                        array_no_hp, array_sertifikat,array_no_kta, array_no_reg, array_masa_berlaku,
                                        array_password, array_level, array_agama, array_tempat_lahir, array_tgl_lahir,array_area,array_url_gambar);
                                rv_main.setAdapter(recycleViewAdapter);
                            }else{
                                Toast.makeText(getActivity(), "Gagal Mengambil Data", Toast.LENGTH_SHORT).show();
                                recycleViewAdapter = new RvFragmentAdapter(getActivity(),array_id, array_username, array_email, array_nama, array_jenis_kelamin,
                                        array_no_hp, array_sertifikat,array_no_kta, array_no_reg, array_masa_berlaku,
                                        array_password, array_level, array_agama, array_tempat_lahir, array_tgl_lahir,array_area,array_url_gambar);
                                rv_main.setAdapter(recycleViewAdapter);
                            }
                        }
                        catch (Exception e){
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(ANError anError) {

                    }
                });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem mSearch = menu.findItem(R.id.action_search);
        SearchView mSearchView = (SearchView) mSearch.getActionView();
        mSearchView.setQueryHint("Search");
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String nama) {
                return false;
            }
            @Override
            public boolean onQueryTextChange(String nama) {
                initializeArray();
                AndroidNetworking.post("http://192.168.137.187/smart/user/pencarian.php")
                        .addBodyParameter("nama","" nama)
                        .setPriority(Priority.MEDIUM)
                        .build()
                        .getAsJSONObject(new JSONObjectRequestListener() {
                            @Override
                            public void onResponse(JSONObject response) {
                                progressDialog.dismiss();

                                try{
                                    Boolean status = response.getBoolean("status");
                                    if(status){
                                        JSONArray ja = response.getJSONArray("result");
                                        Log.d("respon","" ja);
                                        for(int i = 0 ; i < ja.length() ; i  ){
                                            JSONObject jo = ja.getJSONObject(i);
                                            array_id.add(jo.getString("id"));
                                            array_username.add(jo.getString("username"));
                                            array_email.add(jo.getString("email"));
                                            array_nama.add(jo.getString("nama"));
                                            array_jenis_kelamin.add(jo.getString("jenis_kelamin"));
                                            array_no_hp.add(jo.getString("no_hp"));
                                            array_sertifikat.add(jo.getString("sertifikat"));
                                            array_no_kta.add(jo.getString("no_kta"));
                                            array_masa_berlaku.add(jo.getString("masa_berlaku"));
                                            array_no_reg.add(jo.getString("no_reg"));
                                            array_password.add(jo.getString("password"));
                                            array_level.add(jo.getString("level"));
                                            array_agama.add(jo.getString("agama"));
                                            array_tempat_lahir.add(jo.getString("tempat_lahir"));
                                            array_tgl_lahir.add(jo.getString("tgl_lahir"));
                                            array_area.add(jo.getString("area"));
                                            array_url_gambar.add(jo.getString("letak_gbr"));
                                        }
                                        recycleViewAdapter = new RvFragmentAdapter(getActivity(),array_id, array_username, array_email, array_nama, array_jenis_kelamin,
                                                array_no_hp, array_sertifikat,array_no_kta, array_no_reg, array_masa_berlaku,
                                                array_password, array_level, array_agama, array_tempat_lahir, array_tgl_lahir,array_area,array_url_gambar);
                                        rv_main.setAdapter(recycleViewAdapter);
                                    }else{
                                        Toast.makeText(getActivity(), "Gagal Mengambil Data", Toast.LENGTH_SHORT).show();
                                        recycleViewAdapter = new RvFragmentAdapter(getActivity(),array_id, array_username, array_email, array_nama, array_jenis_kelamin,
                                                array_no_hp, array_sertifikat,array_no_kta, array_no_reg, array_masa_berlaku,
                                                array_password, array_level, array_agama, array_tempat_lahir, array_tgl_lahir,array_area,array_url_gambar);
                                        rv_main.setAdapter(recycleViewAdapter);
                                    }
                                }
                                catch (Exception e){
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onError(ANError anError) {

                            }
                        });
                return true;
            }
        });

        getActivity().getMenuInflater().inflate(R.menu.menu,menu);
        super.onCreateOptionsMenu(menu, inflater);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id==R.id.menu_add){
            Intent i = new Intent(getActivity(), TambahPersonilActivity.class);
            startActivityForResult(i,1);
        }
        if(id==R.id.menu_edit){
            Intent i = new Intent(getActivity(), ListPersonilActivity.class);
            startActivity(i);
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==2){
        if(resultCode==RESULT_OK){
            scrollRefresh();
        }else if(resultCode==RESULT_CANCELED){
            Toast.makeText(this, "Canceled", Toast.LENGTH_SHORT).show();
        }
    }
}

}





                                  
 

Комментарии:

1. Пожалуйста, отправьте полный код фрагмента и адаптера для инициализации

2. mContext.startActivityForResult(i,2);

3. Я добавил это @Ashish

4. ошибка: не удается найти символ mContext.startActivityForResult(i,1); @HB.

Ответ №1:

Пожалуйста, замените ((EditPersonilFragment)mContext).startActivityForResult(i,2); на startActivityForResult(i, 1);

Комментарии:

1. ошибка: не удается найти символ startActivityForResult(i,1);

2. или попробуйте использовать getActivity().startActivityForResult(i,2);

3. ошибка: не удается найти символ getActivity().startActivityForResult(i,1); @Setu Vignesh

Ответ №2:

Я нашел ответ после нескольких ошибок

Я добавил фрагмент EditPersonilFragment кода в свой адаптер

     public RvFragmentAdapter(Context mContext, EditPersonilFragment fragment, ArrayList<String> array_id, ArrayList<String> array_username,
                     ArrayList<String> array_email, ArrayList<String> array_nama, ArrayList<String> array_jenis_kelamin,
                     ArrayList<String> array_no_hp, ArrayList<String> array_sertifikat, ArrayList<String> array_no_kta,
                     ArrayList<String> array_masa_berlaku, ArrayList<String> array_no_reg, ArrayList<String> array_password,
                     ArrayList<String> array_level, ArrayList<String> array_agama, ArrayList<String> array_tempat_lahir,
                     ArrayList<String> array_tgl_lahir,ArrayList<String> array_area, ArrayList<String> array_url_gambar)
{
        super();
        this.mContext = mContext;
        this.fragment = fragment;
        this.array_id = array_id;
        this.array_username = array_username;
        this.array_email = array_email;
        this.array_nama = array_nama;
        this.array_jenis_kelamin = array_jenis_kelamin;
        this.array_no_hp = array_no_hp;
        this.array_sertifikat = array_sertifikat;
        this.array_no_kta = array_no_kta;
        this.array_masa_berlaku = array_masa_berlaku;
        this.array_no_reg = array_no_reg;
        this.array_password = array_password;
        this.array_level = array_level;
        this.array_agama = array_agama;
        this.array_tempat_lahir = array_tempat_lahir;
        this.array_tgl_lahir = array_tgl_lahir;
        this.array_area = array_area;
        this.array_url_gambar = array_url_gambar;

    }
 

и и редактирование кода personilfragment.это во фрагменте

 recycleViewAdapter = new RvFragmentAdapter(getActivity(),EditPersonilFragment.this, array_id, array_username, array_email, array_nama, array_jenis_kelamin,
                                                array_no_hp, array_sertifikat,array_no_kta, array_no_reg, array_masa_berlaku,
                                                array_password, array_level, array_agama, array_tempat_lahir, array_tgl_lahir,array_area,array_url_gambar);
                                        rv_main.setAdapter(recycleViewAdapter);