android onActivityResult未返回片段类中的文件路径

nom7f22z  于 2023-04-28  发布在  Android
关注(0)|答案(1)|浏览(135)

我试图从我的android设备中选择一个文件,我启动意图,当在弹出窗口中单击特定按钮(pasirinktiFela按钮)时,我可以选择我的文件,然后我试图通过Log.d()查看选择的内容,但它没有显示结果。
下面是我的片段类KorepetitoriuiPatvirtintiMokiniai,它有onActivityResult方法。

public class KorepetitoriuiPatvirtintiMokiniai extends Fragment {

    private RecyclerView recyclerView;
    private ArrayList<KorepetitoriuiPatvirtintasMokinysKortele> arrayList;
    private KorepetitoriuiPatvirtintiMokiniaiCardAdapter adapter;
    private TextView emptyRecycler;

    public KorepetitoriuiPatvirtintiMokiniai() {
        // Required empty public constructor
    }

    public static KorepetitoriuiPatvirtintiMokiniai newInstance() {
        KorepetitoriuiPatvirtintiMokiniai fragment = new KorepetitoriuiPatvirtintiMokiniai();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_korepetitoriui_patvirtinti_mokiniai, container, false);

        recyclerView = view.findViewById(R.id.recyclerKorepetitoriuiPatvirtintiMokiniai);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        emptyRecycler = view.findViewById(R.id.neraMokiniuKorepetitoriui);

        arrayList = new ArrayList<KorepetitoriuiPatvirtintasMokinysKortele>();

        GautiPatvirtintusMokiniusTask task = new GautiPatvirtintusMokiniusTask(prisijungti.currentKorepetitorius.getId());
        task.execute();

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1 && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            String path = uri.getPath();
            Log.d("file", path);
        }
    }

    public class GautiPatvirtintusMokiniusTask extends AsyncTask<Void, Void, Void> {
        private int korepetitoriausId;

        public GautiPatvirtintusMokiniusTask(int korepetitoriausId) {
            this.korepetitoriausId = korepetitoriausId;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                URL url = new URL("http://192.168.0.104/PHPscriptai/gautiKorepetitoriuiPatvirtintusMokinius.php?korepetitoriaus_id=" + korepetitoriausId);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Accept", "application/json");

                BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
                StringBuilder sb = new StringBuilder();
                String output;
                while ((output = br.readLine()) != null) {
                    sb.append(output);
                }
                conn.disconnect();

                String jsonString = sb.toString();
                JSONArray jsonArray = new JSONArray(jsonString);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    String vardasMokinio = obj.getString("pilnas_mokinio_vardas");
                    int mokinioId = obj.getInt("mokinio_id");

                    arrayList.add(new KorepetitoriuiPatvirtintasMokinysKortele(vardasMokinio, mokinioId));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (arrayList.isEmpty()) {
                emptyRecycler.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            } else {
                emptyRecycler.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
                adapter = new KorepetitoriuiPatvirtintiMokiniaiCardAdapter(arrayList, getContext());
                recyclerView.setAdapter(adapter);
            }
        }
    }
}

我的适配器类:

public class KorepetitoriuiPatvirtintiMokiniaiCardAdapter extends RecyclerView.Adapter<KorepetitoriuiPatvirtintiMokiniaiCardHolder> {

    private ArrayList<KorepetitoriuiPatvirtintasMokinysKortele> list;
    private Context context;
    private Dialog popup;

    public KorepetitoriuiPatvirtintiMokiniaiCardAdapter(ArrayList<KorepetitoriuiPatvirtintasMokinysKortele> list, Context context) {
        this.list = list;
        this.context = context;
    }

    @NonNull
    @Override
    public KorepetitoriuiPatvirtintiMokiniaiCardHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.korepetitoriaus_mokinys_item, parent, false);

        return new KorepetitoriuiPatvirtintiMokiniaiCardHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull KorepetitoriuiPatvirtintiMokiniaiCardHolder holder, int position) {
        KorepetitoriuiPatvirtintasMokinysKortele sarasas = list.get(position);
        popup = new Dialog(context);

        KorepetitoriuiPatvirtintiMokiniaiCardHolder.mokinioVardas.setText(sarasas.getVardasMokinio());

        KorepetitoriuiPatvirtintiMokiniaiCardHolder.parasyti.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, susirasyti.class);
                intent.putExtra("dabartinis_id", prisijungti.currentKorepetitorius.getId());
                intent.putExtra("gavejas_id", sarasas.getMokinioId());
                context.startActivity(intent);
            }
        });

        KorepetitoriuiPatvirtintiMokiniaiCardHolder.pridetiMedziaga.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View popupView = LayoutInflater.from(context).inflate(R.layout.popup_pasirinkti_faila, null);

                Button pasirinktiFaila = popupView.findViewById(R.id.pasirinktiFailaButton);
                Button uzdaryti = popupView.findViewById(R.id.uzdarytiIkeltiLanga);
                EditText pavadinimas = popupView.findViewById(R.id.pavadinimasPopup);
                Button ikeltiFaila = popupView.findViewById(R.id.ikeltiFaila);

                pasirinktiFaila.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("*/*");
                        ((Activity) context).startActivityForResult(intent, 1);
                    }
                });

                ikeltiFaila.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // TODO
                        // upload the file
                    }
                });

                uzdaryti.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popup.dismiss();
                    }
                });

                popup = new Dialog(context);
                popup.setContentView(popupView);
                popup.show();
            }
        });
    }
    
    @Override
    public int getItemCount() {
        return list.size();
    }
}

我的保持器类别:

public class KorepetitoriuiPatvirtintiMokiniaiCardHolder extends RecyclerView.ViewHolder{
    
        public static TextView mokinioVardas;
        public static Button parasyti, pridetiMedziaga;
    
        public KorepetitoriuiPatvirtintiMokiniaiCardHolder(@NonNull View itemView) {
            super(itemView);
    
            mokinioVardas = itemView.findViewById(R.id.vardasKorteleMokinioPatvirtintas);
            parasyti = itemView.findViewById(R.id.korepetitoriusParasyti);
            pridetiMedziaga = itemView.findViewById(R.id.korepetitoriusPridetiMedziaga);
        }
    }

我做错什么了吗?
试图通过在我的Android应用程序中单击按钮从我的Android设备中获取文件,并检查所选文件是否实际上是通过日志选择的,没有得到任何结果。

ulydmbyx

ulydmbyx1#

这样就行了,照这个改吧。

public class MainActivity extends AppCompatActivity {

ActivityResultLauncher<Intent> launcher;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn = findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            launcher.launch(intent);
        }
    });

    launcher = registerForActivityResult(
                    new ActivityResultContracts.StartActivityForResult(),
                    new ActivityResultCallback<ActivityResult>() {
                        @Override
                        public void onActivityResult(ActivityResult result) {
                            if(result.getResultCode() == Activity.RESULT_OK) {
                                    Intent data = result.getData();
                                    Uri uri = data.getData();
                                    String path = uri.getPath();
                                    Log.d("file", path);
                            }
                        }
                    }
    );

{\fnSimHei\bord1\shad1\pos(200,288)}
基本上,我已经使用ActivityResultLauncher和registerForActivityResult(),而不是如果弃用startActivityForResult().它工作正常,我得到的文件的路径,我从设备中选择.

相关问题