我知道之前已经问过这个问题,但他们并没有遇到我所处的相同情况.
我的问题我需要有我的PostPhotosActivity类retainInstance.我这样做的方式是把它变成一个片段.不幸的是我总是收到这个错误.
12-13 14:38:55.669: E/AndroIDRuntime(30234): FATAL EXCEPTION: main12-13 14:38:55.669: E/AndroIDRuntime(30234): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{Trade.ly.Tradely/Trade.ly.Tradely.PostPhotosActivity}: java.lang.classCastException: Trade.ly.Tradely.PostPhotosActivity cannot be cast to androID.app.Activity12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.app.ActivityThread.performlaunchActivity(ActivityThread.java:2106)12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.app.ActivityThread.access0(ActivityThread.java:141)12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.os.Handler.dispatchMessage(Handler.java:99)12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.os.Looper.loop(Looper.java:137)12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.app.ActivityThread.main(ActivityThread.java:5039)12-13 14:38:55.669: E/AndroIDRuntime(30234): at java.lang.reflect.Method.invokeNative(Native Method)12-13 14:38:55.669: E/AndroIDRuntime(30234): at java.lang.reflect.Method.invoke(Method.java:511)12-13 14:38:55.669: E/AndroIDRuntime(30234): at com.androID.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)12-13 14:38:55.669: E/AndroIDRuntime(30234): at com.androID.internal.os.ZygoteInit.main(ZygoteInit.java:560)12-13 14:38:55.669: E/AndroIDRuntime(30234): at dalvik.system.NativeStart.main(Native Method)12-13 14:38:55.669: E/AndroIDRuntime(30234): Caused by: java.lang.classCastException: Trade.ly.Tradely.PostPhotosActivity cannot be cast to androID.app.Activity12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.app.Instrumentation.newActivity(Instrumentation.java:1054)12-13 14:38:55.669: E/AndroIDRuntime(30234): at androID.app.ActivityThread.performlaunchActivity(ActivityThread.java:2097)12-13 14:38:55.669: E/AndroIDRuntime(30234): ... 11 more
这是发布所有错误的PostPhotosActivity.
public class PostPhotosActivity extends androID.app.Fragment {public static final String TAG = "PostPhotosActivity";String Title, price, description, maincat, subcat, pname, pemail, pphone, pmeet, imageUri;public static final String TEMP_PHOTO_file_name = "temp_photo.jpg";public static final int REQUEST_CODE_galLERY = 0x1;public static final int REQUEST_CODE_TAKE_PICTURE = 0x2;public static final int REQUEST_CODE_CROP_IMAGE = 0x3;private ImageVIEw mImageVIEw;private file mfileTemp;Parsefile file;double latitude;final String[] items = new String[] { "Take from camera", "Select from gallery" };double longitude;button button;@OverrIDepublic VIEw onCreateVIEw(LayoutInflater inflater, VIEwGroup container, Bundle savedInstanceState) { VIEw vIEw = inflater.inflate(R.layout.activity_post_photos, container,false); Bundle extras= getActivity().getIntent().getExtras(); if(extras!=null) { Title = extras.getString("Title"); // get the value based on the key price = extras.getString("PRICE"); // get the value based on the key description = extras.getString("DESCRIPTION"); // get the value based on the key maincat = extras.getString("MAINCAT"); // get the value based on the key subcat = extras.getString("SUBCAT"); // get the value based on the key pname = extras.getString("Pname"); // get the value based on the key pemail = extras.getString("PEMAIL"); // get the value based on the key pphone = extras.getString("PPHONE"); // get the value based on the key pmeet = extras.getString("PMEET"); // get the value based on the key latitude = extras.getDouble("lat"); longitude = extras.getDouble("long"); } button newPost = (button)vIEw.findVIEwByID(R.ID.post_data);newPost.setVisibility(VIEw.INVISIBLE);newPost.setonClickListener(new VIEw.OnClickListener() { public voID onClick(VIEw v) { // Perform action on click ParseGeoPoint point = new ParseGeoPoint(latitude, longitude); ParSEObject setPost = new ParSEObject("posts"); // Create an author relationship with the current user setPost.put("author", ParseUser.getCurrentUser()); // Get location setPost.put("location", point); setPost.put("Title", Title); setPost.put("Price", price); setPost.put("Description", description); setPost.put("MainCat", maincat); setPost.put("SubCat", subcat); setPost.put("Pname", pname); setPost.put("PEmail", pemail); setPost.put("PPhone", pphone); setPost.put("PMeet", pmeet); setPost.put("Photo", file); setPost.saveInBackground(); Intent intent = new Intent(getActivity(), Flow.class); startActivity(intent); }}); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), androID.R.layout.select_dialog_item, items); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Select Image"); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public voID onClick(DialogInterface dialog, int item) { // pick from // camera if (item == 0) { takePicture(); } else { // pick from file opengallery(); } } }); final AlertDialog dialog = builder.create(); mImageVIEw = (ImageVIEw) vIEw.findVIEwByID(R.ID.iv_photo); mImageVIEw.setonClickListener(new OnClickListener() { public voID onClick(VIEw v) { dialog.show(); } }); String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mfileTemp = new file(Environment.getExternalStorageDirectory(), TEMP_PHOTO_file_name); } else { mfileTemp = new file(getActivity().getfilesDir(), TEMP_PHOTO_file_name); } setRetainInstance(true); return vIEw;}private voID takePicture() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); try { Uri mImageCaptureUri = null; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { mImageCaptureUri = Uri.fromfile(mfileTemp); } else { /* * The solution is taken from here: https://stackoverflow.com/questions/10042695/how-to-get-camera-result-as-a-uri-in-data-folder */ mImageCaptureUri = InternalStorageContentProvIDer.CONTENT_URI; } intent.putExtra(androID.provIDer.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); intent.putExtra("return-data", true); startActivityForResult(intent, REQUEST_CODE_TAKE_PICTURE); } catch (ActivityNotFoundException e) { Log.d(TAG, "cannot take picture", e); }}private voID opengallery() { Intent photopickerIntent = new Intent(Intent.ACTION_PICK); photopickerIntent.setType("image/*"); startActivityForResult(photopickerIntent, REQUEST_CODE_galLERY);}private voID startCropImage() { Intent intent = new Intent(getActivity(), CropImage.class); intent.putExtra(CropImage.IMAGE_PATH, mfileTemp.getPath()); intent.putExtra(CropImage.SCALE, true); intent.putExtra(CropImage.ASPECT_X, 1); intent.putExtra(CropImage.ASPECT_Y, 1); startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);}@OverrIDepublic voID onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESulT_OK) { return; } Bitmap bitmap; switch (requestCode) { case REQUEST_CODE_galLERY: try { inputStream inputStream = getActivity().getContentResolver().openinputStream(data.getData()); fileOutputStream fileOutputStream = new fileOutputStream(mfileTemp); copyStream(inputStream, fileOutputStream); fileOutputStream.close(); inputStream.close(); startCropImage(); } catch (Exception e) { Log.e(TAG, "Error while creating temp file", e); } break; case REQUEST_CODE_TAKE_PICTURE: startCropImage(); break; case REQUEST_CODE_CROP_IMAGE: String path = data.getStringExtra(CropImage.IMAGE_PATH); if (path == null) { return; } //byte[] IData = path.getBytes(); Bitmap picture = BitmapFactory.decodefile(path); ByteArrayOutputStream stream = new ByteArrayOutputStream(); picture.compress(Bitmap.CompressFormat.JPEG, 100, stream); // get byte array here byte[] IData= stream.toByteArray(); file = new Parsefile("photo.jpg", IData); file.saveInBackground(); bitmap = BitmapFactory.decodefile(mfileTemp.getPath()); mImageVIEw.setimageBitmap(bitmap); button.setVisibility(VIEw.VISIBLE); break; } super.onActivityResult(requestCode, resultCode, data);}public static voID copyStream(inputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); }}}
表现
<activity androID:name="Trade.ly.Tradely.PostPhotosActivity" androID:label="@string/Title_activity_post_photos"> </activity>
在onClick上创建片段的类活动
public class PostActivity extends FragmentActivity implementsPageFragmentCallbacks, RevIEwFragment.Callbacks, ModelCallbacks { private VIEwPager mPager; private MyPagerAdapter mPagerAdapter; private boolean mEditingAfterRevIEw; private AbstractWizardModel mWizardModel = new SanDWichWizardModel(this); private boolean mConsumePageSelectedEvent; private button mNextbutton; private button mPrevbutton; String user_name; String uemail; private List<Page> mCurrentPageSequence; private StepPagerStrip mStepPagerStrip; public static final String TAG = "PostActivity"; double latitude, longitude; public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_post); Bundle extras = getIntent().getExtras(); if(extras !=null) { // Get the results user_name = extras.getString("name"); uemail = extras.getString("email"); } Bundle data = new Bundle(); if (!TextUtils.isEmpty(CustomerInfoPage.EMAIL_DATA_KEY)) { data.putString(CustomerInfoPage.EMAIL_DATA_KEY, uemail); mWizardModel.findByKey("Your Info").resetData(data); } GpsLocationTracker mGpsLocationTracker = new GpsLocationTracker(PostActivity.this); // Set GPS Location fetched address if (mGpsLocationTracker.canGetLocation()) { latitude = mGpsLocationTracker.getLatitude(); longitude = mGpsLocationTracker.getLongitude(); Log.i(TAG, String.format("latitude: %s", latitude)); Log.i(TAG, String.format("longitude: %s", longitude)); } else { mGpsLocationTracker.showSettingsAlert(); } if (savedInstanceState != null) { mWizardModel.load(savedInstanceState.getBundle("model")); } mWizardModel.registerListener(this); mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager()); mPager = (VIEwPager) findVIEwByID(R.ID.pager); mPager.setAdapter(mPagerAdapter); mStepPagerStrip = (StepPagerStrip) findVIEwByID(R.ID.strip); mStepPagerStrip.setonPageSelectedListener(new StepPagerStrip.OnPageSelectedListener() { @OverrIDe public voID onPageStripSelected(int position) { position = Math.min(mPagerAdapter.getCount() - 1, position); if (mPager.getCurrentItem() != position) { mPager.setCurrentItem(position); } } }); mNextbutton = (button) findVIEwByID(R.ID.next_button); mPrevbutton = (button) findVIEwByID(R.ID.prev_button); mPager.setonPagechangelistener(new VIEwPager.SimpleOnPagechangelistener() { @OverrIDe public voID onPageSelected(int position) { mStepPagerStrip.setCurrentPage(position); if (mConsumePageSelectedEvent) { mConsumePageSelectedEvent = false; return; } mEditingAfterRevIEw = false; updateBottombar(); } }); mNextbutton.setonClickListener(new VIEw.OnClickListener() { @Suppresslint("ValIDFragment") @OverrIDe public voID onClick(VIEw vIEw) { if (mPager.getCurrentItem() == mCurrentPageSequence.size()) { DialogFragment dg = new DialogFragment() { @OverrIDe public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setMessage(R.string.submit_confirm_message) .setPositivebutton( R.string.submit_confirm_button, new DialogInterface.OnClickListener() { public voID onClick( DialogInterface dialog, int ID) { String Title = mWizardModel .findByKey( "Post Info") .getData() .getString( TpdModel.Title_DATA_KEY); String price = mWizardModel .findByKey( "Post Info") .getData() .getString( TpdModel.PRICE_DATA_KEY); String description = mWizardModel .findByKey( "Post Info") .getData() .getString( TpdModel.DESCRIPTION_DATA_KEY); String maincat = mWizardModel .findByKey( "Main category") .getData() .getString( Page.SIMPLE_DATA_KEY); String subcat = mWizardModel .findByKey( "Sub category") .getData() .getString( Page.SIMPLE_DATA_KEY); String pname = mWizardModel .findByKey( "Your Info") .getData() .getString( CustomerInfoPage.name_DATA_KEY); String pemail = mWizardModel .findByKey( "Your Info") .getData() .getString( CustomerInfoPage.EMAIL_DATA_KEY); String pphone = mWizardModel .findByKey( "Your Info") .getData() .getString( CustomerInfoPage.PHONE_DATA_KEY); String pmeet = mWizardModel .findByKey( "Your Info") .getData() .getString( CustomerInfoPage.MEET_DATA_KEY); Intent i = new Intent( PostActivity.this, PostPhotosActivity.class); i.putExtra("Title", Title); i.putExtra("PRICE", price); i.putExtra("DESCRIPTION", description); i.putExtra("MAINCAT", maincat); i.putExtra("SUBCAT", subcat); i.putExtra("Pname", pname); i.putExtra("PEMAIL", pemail); i.putExtra("PPHONE", pphone); i.putExtra("PMEET", pmeet); i.putExtra("lat", latitude); i.putExtra("long", longitude); startActivityForResult(i, 0); } }) .setNegativebutton(androID.R.string.cancel, null).create(); } }; dg.show(getSupportFragmentManager(), "place_order_dialog"); } else { if (mEditingAfterRevIEw) { mPager.setCurrentItem(mPagerAdapter.getCount() - 1); } else { mPager.setCurrentItem(mPager.getCurrentItem() + 1); } } } }); mPrevbutton.setonClickListener(new VIEw.OnClickListener() { @OverrIDe public voID onClick(VIEw vIEw) { mPager.setCurrentItem(mPager.getCurrentItem() - 1); } }); onPageTreeChanged(); updateBottombar();}@OverrIDepublic voID onPageTreeChanged() { mCurrentPageSequence = mWizardModel.getCurrentPageSequence(); recalculateCutOffPage(); mStepPagerStrip.setPageCount(mCurrentPageSequence.size() + 1); // + 1 = // revIEw // step mPagerAdapter.notifyDataSetChanged(); updateBottombar();}private voID updateBottombar() { int position = mPager.getCurrentItem(); if (position == mCurrentPageSequence.size()) { mNextbutton.setText(R.string.finish); mNextbutton.setBackgroundResource(R.drawable.finish_background); mNextbutton.setTextAppearance(this, R.style.TextAppearanceFinish); } else { mNextbutton.setText(mEditingAfterRevIEw ? R.string.revIEw : R.string.next); mNextbutton .setBackgroundResource(R.drawable.selectable_item_background); TypedValue v = new TypedValue(); gettheme().resolveAttribute(androID.R.attr.textAppearanceMedium, v, true); mNextbutton.setTextAppearance(this, v.resourceID); mNextbutton.setEnabled(position != mPagerAdapter.getCutOffPage()); } mPrevbutton .setVisibility(position <= 0 ? VIEw.INVISIBLE : VIEw.VISIBLE);}@OverrIDeprotected voID onDestroy() { super.onDestroy(); mWizardModel.unregisterListener(this);}@OverrIDeprotected voID onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBundle("model", mWizardModel.save());}@OverrIDepublic AbstractWizardModel onGetModel() { return mWizardModel;}@OverrIDepublic voID onEditScreenAfterRevIEw(String key) { for (int i = mCurrentPageSequence.size() - 1; i >= 0; i--) { if (mCurrentPageSequence.get(i).getKey().equals(key)) { mConsumePageSelectedEvent = true; mEditingAfterRevIEw = true; mPager.setCurrentItem(i); updateBottombar(); break; } }}@OverrIDepublic voID onPageDataChanged(Page page) { if (page.isrequired()) { if (recalculateCutOffPage()) { mPagerAdapter.notifyDataSetChanged(); updateBottombar(); } }}@OverrIDepublic Page onGetPage(String key) { return mWizardModel.findByKey(key);}private boolean recalculateCutOffPage() { // Cut off the pager adapter at first required page that isn't completed int cutOffPage = mCurrentPageSequence.size() + 1; for (int i = 0; i < mCurrentPageSequence.size(); i++) { Page page = mCurrentPageSequence.get(i); if (page.isrequired() && !page.isCompleted()) { cutOffPage = i; break; } } if (mPagerAdapter.getCutOffPage() != cutOffPage) { mPagerAdapter.setCutOffPage(cutOffPage); return true; } return false;}public class MyPagerAdapter extends FragmentStatePagerAdapter { private int mCutOffPage; private Fragment mPrimaryItem; public MyPagerAdapter(FragmentManager fm) { super(fm); } @OverrIDe public Fragment getItem(int i) { if (i >= mCurrentPageSequence.size()) { return new RevIEwFragment(); } return mCurrentPageSequence.get(i).createFragment(); } @OverrIDe public int getItemposition(Object object) { // Todo: be smarter about this if (object == mPrimaryItem) { // Re-use the current fragment (its position never changes) return position_UNCHANGED; } return position_NONE; } @OverrIDe public voID setPrimaryItem(VIEwGroup container, int position, Object object) { super.setPrimaryItem(container, position, object); mPrimaryItem = (Fragment) object; } @OverrIDe public int getCount() { return Math.min(mCutOffPage + 1, mCurrentPageSequence == null ? 1 : mCurrentPageSequence.size() + 1); } public voID setCutOffPage(int cutOffPage) { if (cutOffPage < 0) { cutOffPage = Integer.MAX_VALUE; } mCutOffPage = cutOffPage; } public int getCutOffPage() { return mCutOffPage; } }}
解决方法:
您不能将PostPhotosActivity用作活动,因为它不是活动.它是片段,因为它扩展了Fragment而不是Activity.在你的清单中有这个是一个错误,并在意图上调用startActivityForResult
Intent i = new Intent(PostActivity.this,PostPhotosActivity.class);
导致抛出异常,因为Fragment不能被转换为Activity.
您可以在其他一些活动中将xml布局与此片段一起使用,或将片段更改为activity. xml布局示例:
<linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:orIEntation="horizontal" androID:layout_wIDth="match_parent" androID:layout_height="match_parent"> <fragment androID:ID="@+ID/post_photos_fragment" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" /></linearLayout>
然后在一些扩展Activity类调用setContentVIEw(R.layout.yourlayout)的活动中,你的片段将在你的活动中创建.
总结以上是内存溢出为你收集整理的片段无法转换为android.app.activity全部内容,希望文章能够帮你解决片段无法转换为android.app.activity所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)