2016-08-05 193 views
1

我有一個使用URI的ArrayList,以便能夠遍歷圖像並每次更新一個ImageView。當我接近這樣做時,我得到一個NullPointerException異常,我相信它與相機旋轉我的屏幕(摧毀該活動),當它出現採取前面提到的圖片。如何保存屏幕上的ArrayList <Uri>旋轉?

這與onSaveInstanceState和onResume--有什麼不同? 124

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference 
at plaidshorts.rafael.myapplication.Person1Screen$5.onClick(Person1Screen.java:124) 
at android.view.View.performClick(View.java:5209) 
at android.view.View$PerformClick.run(View.java:21174) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5477) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

線路是:相機或畫廊

mainView.setImageURI(happyList.get(0)); 

我dispatchTakePictureIntent提示兩次(見開頭的循環)。然後OnActivityResult接受URI並將其添加到happyList(在onCreate中實例化)。

private void dispatchTakePictureIntent() { 
    pictureCounter = -1; 
    for(int i = 0; i < 2; i++) { 
     pictureCounter++; 
     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
      // Create the File where the photo should go 
      File photoFile = null; 
      try { 
       photoFile = createImageFile(); 
       outputFileUri = Uri.fromFile(photoFile); 
      } catch (IOException ex) { 
       Log.w("error","IOException"); 
      }catch (NullPointerException nullEx) { 
       Log.w("error","NullPointerException"); 
      } 
      // Camera. 
      final List<Intent> cameraIntents = new ArrayList<Intent>(); 
      final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
      final PackageManager packageManager = getPackageManager(); 
      final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); 
      for (ResolveInfo res : listCam) { 
       final String packageName = res.activityInfo.packageName; 
       final Intent intent = new Intent(captureIntent); 
       intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); 
       intent.setPackage(packageName); 
       intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); 
       cameraIntents.add(intent); 
      } 
      // Filesystem. 
      final Intent galleryIntent = new Intent(); 
      galleryIntent.setType("image/*"); 
      galleryIntent.setAction(Intent.ACTION_GET_CONTENT); 
      // Chooser of filesystem options. 
      final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source"); 
      // Add the camera options. 
      chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()])); 
      startActivityForResult(chooserIntent, REQUEST_TAKE_PHOTO); 
     } 
    } 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == RESULT_OK) { 
      if (requestCode == REQUEST_TAKE_PHOTO) { 
       final boolean isCamera; 
       if (data == null) { 
        isCamera = true; 
       } else { 
        final String action = data.getAction(); 
        if (action == null) { 
         isCamera = false; 
        } else { 
         isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
        } 
       } 
       Uri selectedImageUri; 
       if (isCamera) { 
        selectedImageUri = outputFileUri; 
       } else { 
        selectedImageUri = data == null ? null : data.getData(); 
       } 
       // mainView.setImageURI(selectedImageUri); 
       // Log.d("Before adding", selectedImageUri.toString()); 
       happyList.add(selectedImageUri); 
      } 
     } 
    } 
+0

你可以發佈你的代碼以及NPE的logcat嗎? –

+2

將數據存儲在** onSaveInstanceState()**中,並將數據恢復到** onRestoreInstanceState()**中。欲瞭解更多信息,請點擊https://developer.android.com/training/basics/activity-lifecycle/recreating.html –

+0

@MehrajMalik我理解這些概念(主要是),但我不確定如何「存儲」我的ArrayList 並恢復它 – rafvasq

回答

1

存儲區的onSaveInstanceState中的(數據)

@Override 
public void onSaveInstanceState (Bundle outState) { 
    // TODO Auto-generated method stub 
    super.onSaveInstanceState(outState); 
    outState.putSerializable("array", arrayDetails); 
} 

把這些代碼行中onCreate()方法的活動來獲得對取向變化的ArrayList。

if (savedInstanceState != null) { 
     arrayDetails = (ArrayList<yourListType>)savedInstanceState.getSerializable("array"); 
} 
+0

在這種情況下什麼是arrayDetails? 我是否需要製作一個onResume? – rafvasq

+0

'arrayDetails'是您想要在屏幕上旋轉保存的ArrayList 。 – user392117

1
ArrayList<URI> uris = .. 
//inStop of your application 
SharedPreference sp = context.getSharePreference("imagineThis",0); 
SharedPreference.Editor ed = sp.edit(); 
byte i =0; 
for(Uri u : uris){ i++; 
    ed.put(String.valueOf(i), u.toString());} 
ed.commit(); 
//in onrestart of your app 
uris.clear();//provided is not null; 
SharedPreference sp = context.getSharePreference("imagineThis",0); 
SharedPreference.Editor ed = sp.edit(); 
for(String s : ((Map<String,String>)sp.getAll()).values()){ 
    uris.add(Uri.parse(s)); 
} 
ed.clear(); 
ed.commit(); 

我認爲你是很好的,現在

+1

ed命名不佳,:) – David

1

嘿,你可以簡單地覆蓋onRetainNonConfigurationInstance在您的活動,並返回你的ArrayList對象,並在你的onCreate()方法檢查,如果你的對象爲空或不是,如果其零使用getLastNonConfigurationInstance()來檢索對象

//PseudoCode 
onRetainNonConfigurationInstance() { 

return arraylistObject; 

} 

oncreate(Bundle onSavedInstance){ 

if(arraylistObject == null){ 

arraylistObject = (cast properly)getLastNonConfigurationInstance(); 

} 

} 

這是最簡單的一個,但使用片段保存狀態橫跨建議旋轉