Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 将文件路径从片段传递到活动,反之亦然_Android_Android Fragments - Fatal编程技术网

Android 将文件路径从片段传递到活动,反之亦然

Android 将文件路径从片段传递到活动,反之亦然,android,android-fragments,Android,Android Fragments,我正在制作自己的应用程序来练习Android编程。我正在制作一个由3个片段+一个摘要片段组成的向导,特别是在第三个片段中,用户必须拍摄两张图片,然后将其传递给摘要(以及之前片段中收集的先前数据)。我没有得到的是,我必须返回到主要活动,并传递图像路径,以便在单击按钮返回摘要片段时调用它们 代码如下: MainActivity.java public class MainActivity extends AppCompatActivity { private Button personal

我正在制作自己的应用程序来练习Android编程。我正在制作一个由3个片段+一个摘要片段组成的向导,特别是在第三个片段中,用户必须拍摄两张图片,然后将其传递给摘要(以及之前片段中收集的先前数据)。我没有得到的是,我必须返回到主要活动,并传递图像路径,以便在单击按钮返回摘要片段时调用它们

代码如下:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private Button personalData;
    protected String strUsername;
    private boolean isProfileReady;
    protected SharedPreferences loginData;

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

        TextView welcome = (TextView) findViewById(R.id.welcome);
        personalData = (Button) findViewById(R.id.data);
        personalData.setText("Profile Info");
        personalData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, WizardActivity.class);
                intent.putExtra("profileReady", isProfileReady);
                startActivityForResult(intent, 1);
            }
        });
        loginData = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        String value = loginData.getString("Username", null);
        if (value == null) {
            welcome.setText("Welcome guest!");
            personalData.setVisibility(View.INVISIBLE);
        } else {
            welcome.setText("Welcome " + loginData.getString("Username", strUsername) + "!");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            isProfileReady = true;
            personalData.setText("View Profile");
        }

    }
}
public class WizardActivity extends AppCompatActivity implements SummaryFragment.Images {

    //region Variables
    Button go;
    WizardOne wizOne;
    WizardTwo wizTwo;
    WizardThree wizThree;
    SummaryFragment summaryFragment;
    Bitmap frontBitmap, backBitmap;
    SharedPreferences wizardPrefs;
    Bundle bundle = new Bundle();

    int currentPage = 1;

    public static final String FRONT_BITMAP_KEY = "frontBitmap", BACK_BITMAP_KEY = "backBitmap";

    boolean isProfileReady;
    //endregion

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

        isProfileReady = getIntent().getBooleanExtra("profileReady", false);

        Toast.makeText(this, "profileReady : " + isProfileReady, Toast.LENGTH_SHORT).show();

        setContentView(R.layout.wizard_layout);
        go = (Button) findViewById(R.id.go);

        if (isProfileReady) {
            /*bundle.getParcelable("frontBitmap");
            bundle.getParcelable("backBitmap");*/
            currentPage = 4;
            go.setText("Home");
            summaryFragment = new SummaryFragment();
            summaryFragment.setArguments(bundle);
     getSupportFragmentManager().beginTransaction().add(R.id.activity_layout, summaryFragment).commit();
        } else {
            wizOne = new WizardOne();
            if (savedInstanceState == null)
                getSupportFragmentManager().beginTransaction().add(R.id.activity_layout, wizOne).commit();
        }

        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isProfileReady) {
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    nextFragment();
                }
            }
        });
    }

    public void nextFragment() {

        switch (currentPage) {

            case 1:
                if (wizOne.validate()) {
                    wizTwo = new WizardTwo();
                    changeFragment(wizTwo, R.id.activity_layout);
                    currentPage++;
                } else {
                    Toast.makeText(getApplicationContext(), "Fill the fields", Toast.LENGTH_SHORT).show();
                }
                break;

            case 2:
                if (wizTwo.validate()) {
                    wizThree = new WizardThree();
                    changeFragment(wizThree, R.id.activity_layout);
                    currentPage++;
                } else {
                    Toast.makeText(getApplicationContext(), "Fill the fields", Toast.LENGTH_SHORT).show();
                }
                break;

            case 3:
                if (wizThree.validate()) {
                    bundle.putParcelable("frontBitmap", wizThree.getFrontBitmap());
                    bundle.putParcelable("backBitmap", wizThree.getBackBitmap());
                    summaryFragment = new SummaryFragment();
                    summaryFragment.setArguments(bundle);
                    go.setText("Home");
                    changeFragment(summaryFragment, R.id.activity_layout);
                    currentPage++;
                }
                break;

            case 4:
                passImages();
                setResult(RESULT_OK);
                finish();
                break;

            default:
                break;

        }
    }


    public void changeFragment(ValidateFragment f, int resource) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(resource, f);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public Bitmap getFrontBitmap() {
        return frontBitmap;
    }

    public Bitmap getBackBitmap() {
        return backBitmap;
    }

    @Override
    public void onBackPressed() {

        if (currentPage > 1) {
            currentPage--;
            getSupportFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }

    }

    @Override
    public Bundle passImages() {
        bundle.getParcelable("frontBitmap");
        bundle.getParcelable("backBitmap");
        return bundle;
    }
}
WizardActivity.java

public class MainActivity extends AppCompatActivity {

    private Button personalData;
    protected String strUsername;
    private boolean isProfileReady;
    protected SharedPreferences loginData;

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

        TextView welcome = (TextView) findViewById(R.id.welcome);
        personalData = (Button) findViewById(R.id.data);
        personalData.setText("Profile Info");
        personalData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, WizardActivity.class);
                intent.putExtra("profileReady", isProfileReady);
                startActivityForResult(intent, 1);
            }
        });
        loginData = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        String value = loginData.getString("Username", null);
        if (value == null) {
            welcome.setText("Welcome guest!");
            personalData.setVisibility(View.INVISIBLE);
        } else {
            welcome.setText("Welcome " + loginData.getString("Username", strUsername) + "!");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            isProfileReady = true;
            personalData.setText("View Profile");
        }

    }
}
public class WizardActivity extends AppCompatActivity implements SummaryFragment.Images {

    //region Variables
    Button go;
    WizardOne wizOne;
    WizardTwo wizTwo;
    WizardThree wizThree;
    SummaryFragment summaryFragment;
    Bitmap frontBitmap, backBitmap;
    SharedPreferences wizardPrefs;
    Bundle bundle = new Bundle();

    int currentPage = 1;

    public static final String FRONT_BITMAP_KEY = "frontBitmap", BACK_BITMAP_KEY = "backBitmap";

    boolean isProfileReady;
    //endregion

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

        isProfileReady = getIntent().getBooleanExtra("profileReady", false);

        Toast.makeText(this, "profileReady : " + isProfileReady, Toast.LENGTH_SHORT).show();

        setContentView(R.layout.wizard_layout);
        go = (Button) findViewById(R.id.go);

        if (isProfileReady) {
            /*bundle.getParcelable("frontBitmap");
            bundle.getParcelable("backBitmap");*/
            currentPage = 4;
            go.setText("Home");
            summaryFragment = new SummaryFragment();
            summaryFragment.setArguments(bundle);
     getSupportFragmentManager().beginTransaction().add(R.id.activity_layout, summaryFragment).commit();
        } else {
            wizOne = new WizardOne();
            if (savedInstanceState == null)
                getSupportFragmentManager().beginTransaction().add(R.id.activity_layout, wizOne).commit();
        }

        go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isProfileReady) {
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    nextFragment();
                }
            }
        });
    }

    public void nextFragment() {

        switch (currentPage) {

            case 1:
                if (wizOne.validate()) {
                    wizTwo = new WizardTwo();
                    changeFragment(wizTwo, R.id.activity_layout);
                    currentPage++;
                } else {
                    Toast.makeText(getApplicationContext(), "Fill the fields", Toast.LENGTH_SHORT).show();
                }
                break;

            case 2:
                if (wizTwo.validate()) {
                    wizThree = new WizardThree();
                    changeFragment(wizThree, R.id.activity_layout);
                    currentPage++;
                } else {
                    Toast.makeText(getApplicationContext(), "Fill the fields", Toast.LENGTH_SHORT).show();
                }
                break;

            case 3:
                if (wizThree.validate()) {
                    bundle.putParcelable("frontBitmap", wizThree.getFrontBitmap());
                    bundle.putParcelable("backBitmap", wizThree.getBackBitmap());
                    summaryFragment = new SummaryFragment();
                    summaryFragment.setArguments(bundle);
                    go.setText("Home");
                    changeFragment(summaryFragment, R.id.activity_layout);
                    currentPage++;
                }
                break;

            case 4:
                passImages();
                setResult(RESULT_OK);
                finish();
                break;

            default:
                break;

        }
    }


    public void changeFragment(ValidateFragment f, int resource) {

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(resource, f);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    public Bitmap getFrontBitmap() {
        return frontBitmap;
    }

    public Bitmap getBackBitmap() {
        return backBitmap;
    }

    @Override
    public void onBackPressed() {

        if (currentPage > 1) {
            currentPage--;
            getSupportFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }

    }

    @Override
    public Bundle passImages() {
        bundle.getParcelable("frontBitmap");
        bundle.getParcelable("backBitmap");
        return bundle;
    }
}
向导3.java

public class WizardThree extends ValidateFragment {

    Button photos, deleteFirst, deleteSecond, button;
    TextView frontText, backText, textView;
    ImageView frontPhoto, backPhoto, imageView;
    static final int REQUEST_IMAGE_CAPTURE = 1;
    String path;
    File photo = null;
    Uri photoURI_1, photoURI_2, uri, uriOut;

    private Bitmap frontBitmap, backBitmap;

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

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_wizard_three, container, false);
        photos = (Button) v.findViewById(R.id.photos);
        photos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent capture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (capture.resolveActivity(getActivity().getPackageManager()) != null) {
                    try {
                        photo = createImgFile();
                    } catch (IOException e) {
                        Log.d("No,", " non funziona");
                    }
                    if (photo != null) {
                        uriOut = FileProvider.getUriForFile(WizardThree.this.getContext(), "com.example.android.fileprovider", photo);
                        capture.putExtra(MediaStore.EXTRA_OUTPUT, uriOut);
                        startActivityForResult(capture, REQUEST_IMAGE_CAPTURE);
                    }
                }
            }
        });
        frontText = (TextView) v.findViewById(R.id.frontText);
        frontPhoto = (ImageView) v.findViewById(R.id.frontPhoto);
        deleteFirst = (Button) v.findViewById(R.id.deleteFirst);
        deleteFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deletePhoto(frontPhoto, frontText, deleteFirst);
            }
        });
        backText = (TextView) v.findViewById(R.id.backText);
        backPhoto = (ImageView) v.findViewById(R.id.backPhoto);
        deleteSecond = (Button) v.findViewById(R.id.deleteSecond);
        deleteSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deletePhoto(backPhoto, backText, deleteSecond);
            }
        });
        return v;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if (frontPhoto.getDrawable() == null) {
                photoURI_1 = uriOut;
                frontBitmap = putPhoto(frontPhoto, frontText, deleteFirst, photoURI_1);
                checkButton();
            } else if (backPhoto.getDrawable() == null) {
                photoURI_2 = uriOut;
                backBitmap = putPhoto(backPhoto, backText, deleteSecond, photoURI_2);
                checkButton();
            }
        }
    }

    //region getBitmaps
    public Bitmap getFrontBitmap() {
        return frontBitmap;
    }

    public Bitmap getBackBitmap() {
        return backBitmap;
    }
    //endregion

    public Bitmap putPhoto(ImageView imageView, TextView textView, Button button, Uri uri) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() / 3, bitmap.getHeight() / 3, true);
        imageView.setImageBitmap(bitmap);
        textView.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.VISIBLE);
        button.setVisibility(View.VISIBLE);
        return bitmap;
    }

    public void checkButton() {
        if ((frontPhoto.getDrawable() != null) && (backPhoto.getDrawable() != null)) {
            photos.setEnabled(false);
        } else {
            photos.setEnabled(true);
        }
    }

    private File createImgFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imgName = "JPEG_" + timeStamp + "_";
        File storage = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File img = File.createTempFile(imgName, ".jpg", storage);
        path = img.getAbsolutePath();
        return img;
    }

    public void deletePhoto(ImageView imageView, TextView text, Button btn) {
        imageView.setImageDrawable(null);
        text.setVisibility(View.GONE);
        btn.setVisibility(View.GONE);
        checkButton();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public boolean validate() {
        if ((frontPhoto.getDrawable() == null) || (backPhoto.getDrawable() == null)) {
            Toast.makeText(getContext(), "Both photos are necessary", Toast.LENGTH_SHORT).show();
            return false;
        }
SummaryFragment.java

public class SummaryFragment extends ValidateFragment {

    //region Variables
    TextView getFName, getLName, getFisCode, getBirth, getCity, getProv, getZip, getCC, getIban, getMail;
    ImageView imgOne, imgTwo;
    String strFName, strLName, strFisCode, strBirth, strCity, strZip, strProv, strCC, strIban, strMail, path;
    SharedPreferences wizardPrefs;
    private Bitmap frontBitmap = null;
    private Bitmap backBitmap = null;
    Uri uri;
    Images callBack;
    //endregion

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        frontBitmap = getArguments().getParcelable("frontBitmap");
        backBitmap = getArguments().getParcelable("backBitmap");
    }

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

        //region findViewById
        getFName = (TextView) v.findViewById(R.id.getFName);
        getLName = (TextView) v.findViewById(R.id.getLName);
        getFisCode = (TextView) v.findViewById(R.id.getFisCode);
        getBirth = (TextView) v.findViewById(R.id.getBirth);
        getCity = (TextView) v.findViewById(R.id.getCity);
        getProv = (TextView) v.findViewById(R.id.getProv);
        getZip = (TextView) v.findViewById(R.id.getZip);
        getCC = (TextView) v.findViewById(R.id.getCC);
        getIban = (TextView) v.findViewById(R.id.getIban);
        getMail = (TextView) v.findViewById(R.id.getMail);
        imgOne = (ImageView) v.findViewById(R.id.imgOne);
        imgTwo = (ImageView) v.findViewById(R.id.imgTwo);
        //endregion

        wizardPrefs = this.getActivity().getSharedPreferences("USERDATA", Context.MODE_PRIVATE);
        getFName.setText(wizardPrefs.getString("Nome utente", strFName));
        getLName.setText(wizardPrefs.getString("Cognome utente", strLName));
        getFisCode.setText(wizardPrefs.getString("Codice Fiscale", strFisCode));
        getBirth.setText(wizardPrefs.getString("Data di nascita", strBirth));
        getCity.setText(wizardPrefs.getString("Città", strCity));
        getZip.setText(wizardPrefs.getString("CAP", strZip));
        getProv.setText(wizardPrefs.getString("Provincia", strProv));
        getCC.setText(wizardPrefs.getString("CC", strCC));
        getIban.setText(wizardPrefs.getString("IBAN", strIban));
        getMail.setText(wizardPrefs.getString("E-mail", strMail));
        imgOne.setImageBitmap(frontBitmap);
        imgTwo.setImageBitmap(backBitmap);

        return v;
    }

    @Override
    public boolean validate() {
        return false;
    }

    public Bitmap getFrontBitmap() {
        return frontBitmap;
    }

    public Bitmap getBackBitmap() {
        return backBitmap;
    }

    public interface Images {
        Bundle passImages();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            callBack = (Images) context;
        } catch (ClassCastException c) {
            throw new ClassCastException(context.toString() + "Exception thrown");
        }

    }

}
            return true;
        }

    }

有人能帮我弄清楚吗?

您已经有了活动结果,所以:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {
        isProfileReady = true;
        String imageOne = data.getStringExtra("imageOne");
    }
}
从SummaryFragment中,您需要执行以下操作:

Intent intent = new Intent();

intent.putExtra("ImageOne", imageOne);
setResult(RESULT_OK, intent);

finish();

您可以使用片段中的共享首选项,然后在活动中读取。这样,片段和活动之间就没有紧密耦合

从这里读一个很好的例子。

但是,如果我错了,请纠正我,我不能在任何非活动的内容中使用
setResult
方法。。另一方面,如果不使用它,我会在
data.getStringExtra()
处得到一个
NullPointerException
,对吗?@frensir您应该能够
这个.getActivity().setResult(…)