【问题标题】:Issue in loading fragment with the below mentioned issue加载片段时出现以下问题
【发布时间】:2018-03-07 12:21:43
【问题描述】:

当我使用意图获取数据或在通过异步改造进行 Api 调用时多次遇到以下问题时,我遇到了片段。虽然我在主线程中没有执行任何主要操作。

03-07 17:31:16.913 31144-31144/? I/art: Late-enabling -Xcheck:jni
03-07 17:31:17.033 31144-31144/com.komplete.insights I/MultiDex: VM with version 2.1.0 has multidex support
03-07 17:31:17.033 31144-31144/com.komplete.insights I/MultiDex: Installing application
03-07 17:31:17.033 31144-31144/com.komplete.insights I/MultiDex: VM has multidex support, MultiDex support library is disabled.
03-07 17:31:17.043 31144-31144/com.komplete.insights I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
03-07 17:31:18.153 31144-31144/com.komplete.insights W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-07 17:31:19.303 31144-31144/com.komplete.insights I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
03-07 17:31:20.133 31144-31144/com.komplete.insights I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
03-07 17:31:20.883 31144-31144/com.komplete.insights I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
03-07 17:31:21.633 31144-31144/com.komplete.insights I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
03-07 17:31:22.383 31144-31144/com.komplete.insights I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
03-07 17:31:22.773 31144-31171/com.komplete.insights D/OpenGLRenderer: Render dirty regions requested: true
03-07 17:31:22.783 31144-31144/com.komplete.insights D/Atlas: Validating map...
03-07 17:31:22.783 31144-31144/com.komplete.insights I/Choreographer: Skipped 182 frames!  The application may be doing too much work on its main thread.
03-07 17:31:23.623 31144-31171/com.komplete.insights I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BR.1.1.3_RB1.05.01.00.032.017_msm8916_64_LA.BR.1.1.3_RB1__release_AU (Ie228694f41)
                                                               OpenGL ES Shader Compiler Version: E031.25.03.04
                                                               Build Date: 09/29/15 Tue
                                                               Local Branch: mybranch14662643
                                                               Remote Branch: quic/LA.BR.1.1.3_rb1.32
                                                               Local Patches: NONE
                                                               Reconstruct Branch: AU_LINUX_ANDROID_LA.BR.1.1.3_RB1.05.01.00.032.017 + 26a3cba + 6f69ea6 + 8bc2bc8 + 649fcde + a52cccf + dbf281f + 15f0bf8 + 8d02f76 + 9b2cb1a + 25f3b04 + 7cd8c84 + b54906e + 675fd74 + 7c22ef4 + 79b094c 
03-07 17:31:23.623 31144-31171/com.komplete.insights I/OpenGLRenderer: Initialized EGL, version 1.4
03-07 17:31:23.643 31144-31171/com.komplete.insights D/OpenGLRenderer: Enabling debug mode 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: PartialUpdate status: Disabled
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Left Align: 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Width Align: 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Top Align: 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Height Align: 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Min ROI Width: 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Min ROI Height: 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Needs ROI Merge: 0
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Dynamic Fps: Enabled
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Min Panel fps: 45
03-07 17:31:23.643 31144-31171/com.komplete.insights I/qdutils: Max Panel fps: 60
03-07 17:31:24.193 31144-31144/com.komplete.insights I/Choreographer: Skipped 84 frames!  The application may be doing too much work on its main thread.
03-07 17:31:25.183 31144-31144/com.komplete.insights I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@2baca30c time:25778313
03-07 17:34:07.643 31144-31144/com.komplete.insights I/Timeline: Timeline: Activity_launch_request time:25940771
03-07 17:34:08.293 31144-31144/com.komplete.insights W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
03-07 17:34:08.383 31144-31144/com.komplete.insights I/zzbz: Making Creator dynamically
03-07 17:34:08.413 31144-31144/com.komplete.insights I/DynamiteModule: Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:18
03-07 17:34:08.413 31144-31144/com.komplete.insights I/DynamiteModule: Selected remote version of com.google.android.gms.maps_dynamite, version >= 18
03-07 17:34:08.433 31144-31144/com.komplete.insights W/ResourcesManager: Asset path '/system/framework/com.android.media.remotedisplay.jar' does not exist or contains no resources.
 03-07 17:34:08.433 31144-31144/com.komplete.insights W/ResourcesManager: Asset path '/system/framework/com.android.location.provider.jar' does not exist or contains no resources.
 03-07 17:34:08.453 31144-31144/com.komplete.insights I/art: DexFile_isDexOptNeeded failed to open oat file '/data/dalvik-cache/arm64/data@data@com.google.android.gms@app_chimera@m@00000003@DynamiteModulesB_GmsCore_prodlmp_xxhdpi_release.apk@classes.dex' for file location '/data/data/com.google.android.gms/app_chimera/m/00000003/DynamiteModulesB_GmsCore_prodlmp_xxhdpi_release.apk': Failed to open oat filename for reading: No such file or directory
 03-07 17:34:08.513 31144-31144/com.komplete.insights I/Google Maps Android API: Google Play services client version: 11910000
 03-07 17:34:08.523 31144-31144/com.komplete.insights I/Google Maps Android API: Google Play services package version: 11975248
 03-07 17:34:09.163 31144-31144/com.komplete.insights I/Choreographer: Skipped 88 frames!  The application may be doing too much work on its main thread.
03-07 17:34:09.523 31144-31144/com.komplete.insights I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@2e5c667b time:25942656
03-07 17:34:09.783 31144-31163/com.komplete.insights I/art: Background sticky concurrent mark sweep GC freed 63099(3MB) AllocSpace objects, 46(8MB) LOS objects, 13% free, 51MB/59MB, paused 4.235ms total 127.020ms
03-07 17:34:11.143 31144-31235/com.komplete.insights W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found.
03-07 17:34:11.153 31144-31235/com.komplete.insights I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
 03-07 17:34:11.153 31144-31235/com.komplete.insights I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 4
 03-07 17:34:11.163 31144-31235/com.komplete.insights I/art: DexFile_isDexOptNeeded failed to open oat file '/data/dalvik-cache/arm64/data@data@com.google.android.gms@app_chimera@m@00000001@GoogleCertificates_GmsCore_prodlmp_xxhdpi_release.apk@classes.dex' for file location '/data/data/com.google.android.gms/app_chimera/m/00000001/GoogleCertificates_GmsCore_prodlmp_xxhdpi_release.apk': Failed to open oat filename for reading: No such file or directory

片段交易代码:

ivEditProfile.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        getSupportActionBar().hide();
        EditProfileFragment editProfileFragment = new EditProfileFragment();              
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.main_frame, editProfileFragment);
        transaction.addToBackStack(null);
        transaction.commit();
        drawer.closeDrawer(GravityCompat.START);
    }
}); 

EditProfileFragment.java

这是我遇到问题的片段的代码。

public class EditProfileFragment extends Fragment {

RadioGroup radioGroup;
RadioButton radioMale, radioFemale;
Calendar birthDataCalendar = Calendar.getInstance();
CustomEditText etBirthDate;
CustomClearableEditText etName, etNumber, etAddress;
CircleImageView civProfile, civChoose;
CustomButton btnSave;
ImageView ivBack;
Bundle extra;
byte[] byteArray;
Bitmap bitmap;
private static final int REQUEST_CAMERA = 55;
private static final int SELECT_FILE = 66;
String token;
ApiInterface apiInterface;
String selection;
private MultipartBody.Part fileToUpload;


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

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    etName = view.findViewById(R.id.edit_profile_et_name);
    etNumber = view.findViewById(R.id.edit_profile_et_contact_no);
    etAddress = view.findViewById(R.id.edit_profile_et_address);
    radioMale = view.findViewById(R.id.edit_profile_radio_male);
    radioFemale = view.findViewById(R.id.edit_profile_radio_female);
    etBirthDate = view.findViewById(R.id.edit_profile_et_birth_date);
    civProfile = view.findViewById(R.id.edit_profile_civ_profile);
    civChoose = view.findViewById(R.id.edit_profile_civ_choose);
    ivBack = view.findViewById(R.id.edit_profile_iv_back);
    radioGroup = view.findViewById(R.id.radioGroup);
    btnSave = view.findViewById(R.id.edit_profile_btn_save);

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    // Change base URL to your upload server URL.
    apiInterface = new Retrofit.Builder()
            .baseUrl("https://demourl.com/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiInterface.class);

    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "font/myriadregular.ttf");
    radioMale.setTypeface(font);
    radioFemale.setTypeface(font);

    etName.setText(MainActivity.navName);
    etAddress.setText(MainActivity.navAddress);
    etNumber.setText(MainActivity.contactNumber);
    token = getActivity().getIntent().getStringExtra("token");

    civChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final CharSequence[] options = {"Camera", "Choose from Gallery", "Cancel"};

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogCustom);
            builder.setTitle("Add Photo from..");
            builder.setItems(options, new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Camera")) {
                        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        startActivityForResult(cameraIntent, REQUEST_CAMERA);
                    } else if (options[item].equals("Choose from Gallery")) {
                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, SELECT_FILE);
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
    });

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            birthDataCalendar.set(Calendar.YEAR, year);
            birthDataCalendar.set(Calendar.MONTH, monthOfYear);
            birthDataCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }
    };

    if (getActivity().getIntent().getStringExtra("signInProfileImage") == null) {

        extra = getActivity().getIntent().getExtras();
        if (extra != null) {
            byteArray = extra.getByteArray("signUpProfileImage");
            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            civProfile.setImageBitmap(bitmap);
        }

    } else {
        String imagePath = getActivity().getIntent().getStringExtra("signInProfileImage");
        Picasso.with(getActivity()).load(imagePath).into(civProfile);
    }

    etBirthDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(getActivity(), date, birthDataCalendar
                    .get(Calendar.YEAR), birthDataCalendar.get(Calendar.MONTH),
                    birthDataCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    ivBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getFragmentManager().getBackStackEntryCount() != 0) {
                getFragmentManager().popBackStack();
            }
        }
    });

    btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isValidName(etName.getText().toString())) {
                showErrorMessage("Enter Valid Name");
                etName.requestFocus();
            } else if (!isValidDate(etBirthDate.getText().toString())) {
                showErrorMessage("Select Valid Date");
                etBirthDate.requestFocus();
            } else if (!isValidAddress(etAddress.getText().toString())) {
                showErrorMessage("Enter Address");
                etAddress.requestFocus();
            } else if (!isValidContactNo(etNumber.getText().toString())) {
                showErrorMessage("Enter Valid contact Number");
                etNumber.requestFocus();
            } else if (isValidGenderSelected() == null) {
                showErrorMessage("Select Gender");
            } else {
                uploadData();
            }
        }
    });
}


private boolean isValidName(String name) {
    if (!TextUtils.isEmpty(name)) {
        Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
        Matcher ms = ps.matcher(name);
        boolean bs = ms.matches();
        if (!bs) {
            showErrorMessage("Enter Proper Name");
            return false;
        }
    } else if (TextUtils.isEmpty(name)) {
        showErrorMessage("Enter Name");
        return false;
    }
    return true;
}

public boolean isValidDate(String date) {

    if (TextUtils.isEmpty(date)) {
        showErrorMessage("Select Valid Date");
        return false;
    }
    return true;
}

public String isValidGenderSelected() {
    if (radioGroup.getCheckedRadioButtonId() != -1) {
        int id = radioGroup.getCheckedRadioButtonId();
        View radioButton = radioGroup.findViewById(id);
        int radioId = radioGroup.indexOfChild(radioButton);
        RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
        selection = (String) btn.getText();
        return selection;
    } else {
        showErrorMessage("Select Gender");
        return null;
    }
}

private boolean isValidContactNo(String contactNo) {
    if (TextUtils.isEmpty(contactNo)) {
        showErrorMessage("Enter Contact Number");
        return false;
    }
    return true;
}

public boolean isValidAddress(String address) {

    if (TextUtils.isEmpty(address)) {
        showErrorMessage("Enter valid Address");
        return false;
    }
    return true;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        for (Fragment fragment : getChildFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    if (REQUEST_CAMERA == requestCode && resultCode == RESULT_OK) {

        Bitmap bitmap = (Bitmap) data.getExtras().get("data");

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        if (bitmap != null) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        }
        String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "", null);


        File filesDir = getActivity().getFilesDir();
        File imageFile = new File(filesDir, "image" + ".jpg");

        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }
        RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), imageFile);

        fileToUpload = MultipartBody.Part.createFormData("profile_image", String.valueOf(imageFile), mFile);

        Uri.parse(path);

        Picasso.with(getActivity()).load(path).noPlaceholder().centerCrop().fit().into(civProfile);
    }

    if (requestCode == SELECT_FILE) {

        Toast.makeText(getActivity(), "Gallery clicked", Toast.LENGTH_SHORT).show();

        Uri selectedImageURI = data.getData();
        String filePath = getRealPathFromURIPath(selectedImageURI, getActivity());
        File file = new File(filePath);

        //RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        RequestBody mFile = RequestBody.create(MediaType.parse("image/*"), file);

        fileToUpload = MultipartBody.Part.createFormData("profile_image", file.getName(), mFile);

        try {
            InputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024 * 8];
            int bytesRead = 0;

            while ((bytesRead = inputStream.read(b)) != -1) {
                bos.write(b, 0, bytesRead);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Picasso.with(getActivity()).load(selectedImageURI).noPlaceholder().centerCrop().fit()
                .into((civProfile));
    }
}

private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
    Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) {
        return contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }
}

private void updateLabel() {
    String myFormat = "dd-MMM-yyyy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    etBirthDate.setText(sdf.format(birthDataCalendar.getTime()));
}

private void uploadData() {

    RequestBody name = RequestBody.create(MediaType.parse("text/plain"), etName.getText().toString());
    RequestBody date = RequestBody.create(MediaType.parse("text/plain"), etBirthDate.getText().toString());
    RequestBody gender = RequestBody.create(MediaType.parse("text/plain"), selection);
    RequestBody number = RequestBody.create(MediaType.parse("text/plain"), etNumber.getText().toString());
    RequestBody address = RequestBody.create(MediaType.parse("text/plain"), etAddress.getText().toString());

    Call<EditProfileExample> register = apiInterface.updateProfile(token, name, date, gender, number, address, fileToUpload);
    register.enqueue(new Callback<EditProfileExample>() {
        @SuppressLint("ResourceAsColor")
        @Override
        public void onResponse(Call<EditProfileExample> call, Response<EditProfileExample> response) {

            if (response.isSuccessful()) {
                showSuccessMessage("Profile Updated Successfully");
            }
        }

        @Override
        public void onFailure(Call<EditProfileExample> call, Throwable t) {
            showErrorMessage("Please Connect to Internet Connection");
            Log.d("onFailure", "Error " + t.getMessage());
        }
    });


}


@SuppressLint("ResourceAsColor")
private void showErrorMessage(String s) {
    TSnackbar snackbar = TSnackbar.make(getView(), s, TSnackbar.LENGTH_LONG);
    View v = snackbar.getView();
    v.setBackgroundResource(R.color.toast_red);
    TextView textView = (TextView) v.findViewById(com.androidadvance.topsnackbar.R.id.snackbar_text);
    textView.setTextColor(Color.WHITE);
    snackbar.show();
}


@SuppressLint({"ResourceAsColor", "ResourceType"})
private void showSuccessMessage(String s) {
    TSnackbar snackbar = TSnackbar.make(getView(), s, TSnackbar.LENGTH_LONG);
    View v = snackbar.getView();
    v.setBackgroundResource(Color.GREEN);
    TextView textView = (TextView) v.findViewById(com.androidadvance.topsnackbar.R.id.snackbar_text);
    textView.setTextColor(Color.WHITE);
    snackbar.show();
  }
}

【问题讨论】:

  • 你有什么问题?
  • @VinayakB 片段在某些时候没有打开并退出到以前的活动。黑屏出现 1-2 秒,然后返回到 logcat 中上述问题的单个片段的先前活动。我正在寻找的解决方案是:编舞:跳过 182 帧!应用程序可能在其主线程上做了太多工作。
  • 能否请您发布您的片段交易代码
  • @VinayakB 请参考编辑后的帖子
  • 这是来自活动还是来自片段?

标签: android android-layout android-fragments android-fragmentactivity


【解决方案1】:

改变

 FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

并确保您在片段类中使用import android.support.v4.app.Fragment

【讨论】:

    猜你喜欢
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多