【问题标题】:How do i pass Uri of image clicked in custom gallery to another activity?如何将自定义图库中单击的图像的 Uri 传递给另一个活动?
【发布时间】:2012-02-04 17:14:53
【问题描述】:

这让我无法入睡... 我正在创建一个幻灯片类型的应用程序。假设包名是 com.myapp.slideshow 用户可以创建一个新的幻灯片,其中包含以前存储在 SD 卡应用程序的私有文件夹中的图片(例如 root/Android/data/com.myapp.slideshow/files/immagini/)

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

所以回顾一下,我有 SlideshowEditor.java,用户单击一个按钮以访问 IMGALLERYactivity.java,他们可以在其中单击从画廊幻灯片对象中选择图片,并据称返回到 SlideshowEditor.java 与选择的图片 Uri。

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

这是我正在使用的代码:

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 有一定的了解。


编辑:

谢谢布赖恩!我能够根据位置获取所选项目的路径,按照您的建议设置 get item(),然后创建 var,例如: 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);                                                                                   

我不断收到空指针异常。我尝试使用 eclipse 调试,我的理解是,当我创建意图时,nullpointerexception 是在 IMGALLERYactivity 中拍摄的,但我不会打赌,因为 eclipse 调试对我来说似乎很混乱......但是我切换了一个断点在 SlideshowEditor.class 的 onactivityresult 中,看起来 nullpointer 异常在到达该点之前就被触发了。我知道你不做私人咨询,但我从 3 天以来一直在努力解决这个问题,任何帮助都会真正帮助我,在我完全发疯之前,哈哈

这是 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):在 android.app.ActivityThread.deliverResults(ActivityThread.java:2918) 02-06 19:26:40.080: E/AndroidRuntime(10661): 在 android.app.ActivityThread.handleSendResult(ActivityThread.java:2970) 02-06 19:26:40.080: E/AndroidRuntime(10661): 在 android.app.ActivityThread.access$2000(ActivityThread.java:132) 02-06 19:26:40.080:E/AndroidRuntime(10661):在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1068) 02-06 19:26:40.080: E/AndroidRuntime(10661): 在 android.os.Handler.dispatchMessage(Handler.java:99) 02-06 19:26:40.080:E/AndroidRuntime(10661):在 android.os.Looper.loop(Looper.java:150) 02-06 19:26:40.080: E/AndroidRuntime(10661):在 android.app.ActivityThread.main(ActivityThread.java:4277) 02-06 19:26:40.080:E/AndroidRuntime(10661):在 java.lang.reflect.Method.invokeNative(Native Method) 02-06 19:26:40.080:E/AndroidRuntime(10661):在 java.lang.reflect.Method.invoke(Method.java:507) 02-06 19:26:40.080: E/AndroidRuntime(10661):在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 02-06 19:26:40.080: E/AndroidRuntime(10661): 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 02-06 19:26:40.080:E/AndroidRuntime(10661):在 dalvik.system.NativeStart.main(本机方法)02-06 19:26:40.080: E/AndroidRuntime(10661):引起:java.lang.NullPointerException: uriString 02-06 19:26:40.080: E/AndroidRuntime(10661): 在 android.net.Uri$StringUri.(Uri.java:420) 02-06 19:26:40.080: E/AndroidRuntime(10661):在 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):在 com.deitel.enhancedslideshow.SlideshowEditor.onActivityResult(SlideshowEditor.java:87) 02-06 19:26:40.080: E/AndroidRuntime(10661): 在 android.app.Activity.dispatchActivityResult(Activity.java:4108) 02-06 19:26:40.080:E/AndroidRuntime(10661):在 android.app.ActivityThread.deliverResults(ActivityThread.java:2914)

【问题讨论】:

    标签: android android-intent gallery


    【解决方案1】:

    所以你要添加到 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() 的另一边拉出那个

    【讨论】:

    • 谢谢。我现在明白为什么我不返回任何东西了。我认为 data.getdata() 会抓住我需要传递的东西......所以,请让我问你:首先,传递位置是否正确,以便将点击的图片 uri 传递给 SlideshowEditor班级?因为我看到你提到了 PICTURE_URI,但我不知道如何在 IMGALLERYactivity 类的图库对象幻灯片上点击图片时检索它。您能详细说明您对我的代码的解决方案吗?
    • 你比我更了解你的代码:)。如果是我,通常我的adapter.getItem() 实现会返回对列表中相应项目的引用。你的返回位置。如果您这样做是为了让getItem() 返回 URI,那么您可以使用您的适配器来获取正确的项目并将其插入到 Intent 中。如果我所说的对您来说没有多大意义,我建议您使用 ListView 和 ListAdapter。
    • Brian,如果可以的话,我该如何私下联系你?
    • 对不起,我不能做私人咨询。我更愿意在这里回答问题,希望能帮助很多人。
    • 我希望获得有关如何制作它的建议,以便 getitem() 返回 URI。经过 10 多个小时的深入研究,我不知道如何在图库或网格视图上检索所选图像的 URI。我看到有类似 getitematposition 的东西,但我找不到任何关于其内容列的文档。必须有一种简单的已知方法来从画廊或网格视图上的选定图像中获取 URI?
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    相关资源
    最近更新 更多