如何将自定义库中单击的图像Uri传递给另一个活动?

时间:2012-02-04 17:14:53

标签: android android-intent gallery

这让我不眠...... 我正在制作幻灯片类应用。让我们说包名是com.myapp.slideshow 用户可以创建一个新的幻灯片,其中包含以前存储在SD卡应用程序私人文件夹中的图片(类似root / Android / data / com.myapp.slideshow / files / immagini /)

因此,我无法通过ACTION_GET_CONTENT使用内置图库,因此我创建了自己的图库活动类。

所以回顾一下我有SlideshowEditor.java,用户点击一个按钮来访问IMGALLERYactivity.java,在那里他们可以点击画廊幻灯片对象中的图片并据称返回到带有选中图片Uri的SlideshowEditor.java。 / p>

我的代码存在的问题是,当我运行应用程序时(我通过eclipse直接在设备上测试)我似乎没有得到Uri,并且得到一个nullpointer异常,这会停止应用程序。

以下是我使用的代码:

SlideshowEditor.java

       // set IDs for each type of media result
   private static final int PICTURE_ID = 1;
   private static final int MUSIC_ID = 2;
   private static final int VIDEO_ID = 3;       
   private static final int TAKE_PICTURE_ID = 4;

   // called when an Activity launched from this Activity returns
   @Override
   protected final void onActivityResult(int requestCode, int resultCode, 
      Intent data)
   {
      if (resultCode == RESULT_OK) // if there was no error
      {
         Uri selectedUri = data.getData(); 

         // if the Activity returns an image
         if (requestCode == PICTURE_ID || 
            requestCode == TAKE_PICTURE_ID || requestCode == VIDEO_ID )
         {
            // determine media type
            MediaItem.MediaType type = (requestCode == VIDEO_ID ?     
               MediaItem.MediaType.VIDEO : MediaItem.MediaType.IMAGE);

            // add new MediaItem to the slideshow
            slideshow.addMediaItem(type, selectedUri.toString());

            // refresh the ListView 
            slideshowEditorAdapter.notifyDataSetChanged();
         } // end if
         else if (requestCode == MUSIC_ID) // Activity returns music
            slideshow.setMusicPath(selectedUri.toString());
      } // end if
   } // end method onActivityResult

   // called when the user touches the "Done" Button
   private OnClickListener doneButtonListener = new OnClickListener()
   {
      // return to the previous Activity
      @Override
      public void onClick(View v)
      {
         finish();
      } // end method onClick
   }; // end OnClickListener doneButtonListener

   // called when the user touches the "Add Picture" Button
   private OnClickListener addPictureButtonListener = new OnClickListener()
   {
      // launch image choosing activity
      @Override
      public void onClick(View v)
      {

         Intent intent = new Intent(SlideshowEditor.this, IMGALLERYactivity.class);
////         String imgfolder = (Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Android" + File.separator + "data" + File.separator + "com.myapp.slideshow" + File.separator + "files" + File.separator + "immagini" + File.separator).toLowerCase();
       //  Uri startDir = Uri.fromFile(new File("Environment.getExternalStorageDirectory().getAbsolutePath()"));
////         intent.setDataAndType(Uri.parse(imgfolder), "image/*");
         ///intent.setType("image/*");
         ///intent.Output();
         ////startActivity(intent);
         startActivityForResult(intent, PICTURE_ID);
      } // end method onClick
   }; // end OnClickListener addPictureButtonListener

IMGALLERYactivity.java

public class IMGALLERYactivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.imgallery);

   Gallery g = (Gallery) findViewById(R.id.gallery);    g.setAdapter(new ImageAdapter(this, ReadSDCard()));

   g.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent,
         View v, int position, long id) {
           Toast.makeText(IMGALLERYactivity.this, "" + position, Toast.LENGTH_SHORT).show();

           Intent i = new Intent(IMGALLERYactivity.this, SlideshowEditor.class);                 
           i.putExtra("PICTURE_ID", position);                 
           setResult(Activity.RESULT_OK, i);
           finish();           
    //     Intent resultIntent = new Intent(); 
    //     // TODO Add extras or a data URI to this intent as appropriate. 
    //     setResult(Activity.RESULT_OK, resultIntent); 
    //     finish();           

       }    }); }

private List<String> ReadSDCard() { List<String> tFileList = new ArrayList<String>();

//It have to be matched with the directory in SDCard

//File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Android" + File.separator + "data" + File.separator
+ "com.deepsabrina.sabrinadeep" + File.separator + "files" + File.separator + "immagini");

File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Android" + File.separator + "data" + File.separator
+ "com.deepsabrina.sabrinadeep" + File.separator + "files" + File.separator + "immagini" + File.separator);

File[] files=f.listFiles();

for(int i=0; i<files.length; i++) {  File file = files[i];  /*It's assumed that all file in the path    are in supported type*/  tFileList.add(file.getPath()); }

return tFileList; }

public class ImageAdapter extends BaseAdapter {    int mGalleryItemBackground;    private Context mContext;    private List<String> FileList;

   public ImageAdapter(Context c, List<String> fList) {
       mContext = c;
       FileList = fList;
       TypedArray a = mContext.obtainStyledAttributes(R.styleable.HelloGallery);
       mGalleryItemBackground = a.getResourceId(
       R.styleable.HelloGallery_android_galleryItemBackground,0);
       a.recycle();    }

   public int getCount() {
       return FileList.size();    }

   public Object getItem(int position) {
       return position;    } 

   public long getItemId(int position) {
       return position;    }

   public View getView(int position, View convertView,
     ViewGroup parent) {
       ImageView i = new ImageView(mContext);

       Bitmap bm = BitmapFactory.decodeFile(
         FileList.get(position).toString());
       i.setImageBitmap(bm);

       i.setLayoutParams(new Gallery.LayoutParams(150, 100));
       i.setScaleType(ImageView.ScaleType.FIT_XY);
       i.setBackgroundResource(mGalleryItemBackground);

       return i;    } }

public TypedArray obtainStyledAttributes(int theme) {   // TODO Auto-generated method stub  return null; } }

我做错了什么? 任何帮助都会非常感激,可能会有代码更正,因为我刚开始熟悉Android,虽然我对java有中等的知识。


编辑:

谢谢Brian!我能够根据位置获取所选项目的路径,按照建议设置get item(),然后创建var like:String pippo = parent.getItemAtPosition(position).toString();至少我向前迈了一步......但是我仍然无法将它传递给SlideshowEditor.class。这就是我在onitemclicklistener上放置IMGALLERYactivity类的原因:

public void onItemClick(AdapterView<?> parent,
     View v, int position, long id) {
       String pippo = parent.getItemAtPosition(position).toString();


      Intent data = new Intent(IMGALLERYactivity.this, SlideshowEditor.class);                 
      data.putExtra("PICTURE_ID", pippo);                 
      setResult(RESULT_OK, data);
      finish();            


   } 

在SlideshowEditor.class上我有

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

      if (resultCode == RESULT_OK) // if there was no error
      {

          Uri selectedUri = Uri.parse(data.getDataString());         
          //Uri selectedUri = data.getData(); 

         // if the Activity returns an image
         if (requestCode == PICTURE_ID || 
            requestCode == TAKE_PICTURE_ID || requestCode == VIDEO_ID )
         {
            // determine media type
            MediaItem.MediaType type = (requestCode == VIDEO_ID ?     
               MediaItem.MediaType.VIDEO : MediaItem.MediaType.IMAGE);

            // add new MediaItem to the slideshow
            slideshow.addMediaItem(type, selectedUri.toString());

            // refresh the ListView 
            slideshowEditorAdapter.notifyDataSetChanged();
         } // end if
         else if (requestCode == MUSIC_ID) // Activity returns music
            slideshow.setMusicPath(selectedUri.toString());
      } // end if
   } // end method onActivityResult  

整个过程以

开始
Intent intent = new Intent(SlideshowEditor.this, IMGALLERYactivity.class);

         startActivityForResult(intent,PICTURE_ID);                                                                                   

我一直得到nullpointerexception。我尝试使用eclipse调试,我的理解是当我创建意图时,就会在IMGALLERY活动中拍摄nullpointerexception,但是我不打赌它,因为eclipse调试对我来说似乎很混乱......但是我在SlideshowEditor.class上的onactivityresult上切换了一个断点,它看起来像nullpointer异常在它到达那个点之前被镜头。我知道你不做私人咨询,但是我现在已经开始了3天的时间了解这个问题,在我完全疯了之前,任何帮助都会对我有所帮助lol

这是logcat的结果:

  

02-06 19:26:40.080:E / AndroidRuntime(10661):致命异常:主要   02-06 19:26:40.080:E / AndroidRuntime(10661):   java.lang.RuntimeException:传递结果失败   ResultInfo {who = null,request = 1,result = -1,data = Intent {   cmp = com.deitel.enhancedslideshow / .SlideshowEditor(有额外内容)}}到   活动   {com.deitel.enhancedslideshow / com.deitel.enhancedslideshow.SlideshowEditor}:   java.lang.NullPointerException:uriString 02-06 19:26:40.080:   E / AndroidRuntime(10661):at   android.app.ActivityThread.deliverResults(ActivityThread.java:2918)   02-06 19:26:40.080:E / AndroidRuntime(10661):at   android.app.ActivityThread.handleSendResult(ActivityThread.java:2970)   02-06 19:26:40.080:E / AndroidRuntime(10661):at   android.app.ActivityThread.access $ 2000(ActivityThread.java:132)02-06   19:26:40.080:E / AndroidRuntime(10661):at   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1068)   02-06 19:26:40.080:E / AndroidRuntime(10661):at   android.os.Handler.dispatchMessage(Handler.java:99)02-06   19:26:40.080:E / AndroidRuntime(10661):at   android.os.Looper.loop(Looper.java:150)02-06 19:26:40.080:   E / AndroidRuntime(10661):at   android.app.ActivityThread.main(ActivityThread.java:4277)02-06   19:26:40.080:E / AndroidRuntime(10661):at   java.lang.reflect.Method.invokeNative(Native Method)02-06   19:26:40.080:E / AndroidRuntime(10661):at   java.lang.reflect.Method.invoke(Method.java:507)02-06 19:26:40.080:   E / AndroidRuntime(10661):at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839)   02-06 19:26:40.080:E / AndroidRuntime(10661):at   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)02-06   19:26:40.080:E / AndroidRuntime(10661):at   dalvik.system.NativeStart.main(Native Method)02-06 19:26:40.080:   E / AndroidRuntime(10661):引起:java.lang.NullPointerException:   uriString 02-06 19:26:40.080:E / AndroidRuntime(10661):at   android.net.Uri $ StringUri。(Uri.java:420)02-06 19:26:40.080:   E / AndroidRuntime(10661):at   android.net.Uri $ StringUri。(Uri.java:410)02-06 19:26:40.080:   E / AndroidRuntime(10661):在android.net.Uri.parse(Uri.java:382)02-06   19:26:40.080:E / AndroidRuntime(10661):at   com.deitel.enhancedslideshow.SlideshowEditor.onActivityResult(SlideshowEditor.java:87)   02-06 19:26:40.080:E / AndroidRuntime(10661):at   android.app.Activity.dispatchActivityResult(Activity.java:4108)02-06   19:26:40.080:E / AndroidRuntime(10661):at   android.app.ActivityThread.deliverResults(ActivityThread.java:2914)

1 个答案:

答案 0 :(得分:0)

所以你唯一要添加到你的Intent的是:

Intent i = new Intent(IMGALLERYactivity.this, SlideshowEditor.class);                 
i.putExtra("PICTURE_ID", position);                 

但是你要尝试从onActivityResult()方法中得到一些你从未输入过的Intent:

Uri selectedUri = data.getData();

int position = data.getIntExtra("PICTURE_ID", 0);

哪个...可能不会有很多好处。你可以把URI作为额外的。

i.putExtra("PICTURE_URI", uriOfSelectedItem);

然后在onActivityResult()中将 拉出来。