简体   繁体   中英

Pass data with (Intent putextra) in listactivity not working

i have listactivity forming 5 rows each row when clicked open new activity ,

i set separate class for each one (to customize it ) so i have 5 class:as (City1,City2,City3,and so on )

in each row class i have many views , one of them button when clicked open customized infinite gallery ,

i want to pass this infinite gallery to 5 row classes by use putextra intent

but when run the app PRESS BUTTON TO OPEN INFINITE GALLERY it gave ( force close )

, i have little experiance in android development ,

would you please help me , any advice will be appreciated , thanks

my code : GalleryCity class

 public class GalleryCity extends Activity {
  static String city;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);

     Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
      // Set the layout to use
      setContentView(R.layout.main);
      if (customTitleSupported) { 
 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title); 
    TextView tv = (TextView) findViewById(R.id.tv); 
         Typeface face=Typeface.createFromAsset(getAssets(),"BFantezy.ttf");     
         tv.setTypeface(face);
         tv.setText("My Pictures"); 
            } 

      Intent intent = getIntent(); 
      city = intent.getStringExtra("galleryimags"); 

      InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);
      galleryOne.setAdapter(new InfiniteGalleryAdapter(this)); 
      galleryOne.setSelection(galleryOne.getCount()/2);            
                     }
                     }


   class InfiniteGalleryAdapter extends BaseAdapter { 
      private Context mContext;
      public InfiniteGalleryAdapter(Context c, int[] imageIds) { 
      this.mContext = c; } 

       public int getCount() { 
      return Integer.MAX_VALUE; } 

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

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

    private LayoutInflater inflater=null; 
    public InfiniteGalleryAdapter(Context a) { 
       this.mContext = a; 
       inflater = (LayoutInflater)mContext.getSystemService (
            Context.LAYOUT_INFLATER_SERVICE); 
       getImagesforCity(); 
        } 

      private int[] images;
      private void getImagesforCity() {
        if(GalleryCity.city.equalsIgnoreCase("City1")){ 
         int[] imagestemp = {
               R.drawable.one_1, R.drawable.one_1, 
                R.drawable.one_1

                  }; 
        images=imagestemp;

                        }
        if(GalleryCity.city.equalsIgnoreCase("City2")){
         int[] imagestemp = {
        R.drawable.one_2, R.drawable.one_2, 
             R.drawable.one_2   }; 
       images=imagestemp;

                                  }

        if(GalleryCity.city.equalsIgnoreCase("City3")){
          int[] imagestemp = {
        R.drawable.one_3, R.drawable.one_3, 
             R.drawable.one_3   }; 
        images=imagestemp;

                       }
        if(GalleryCity.city.equalsIgnoreCase("City4")){
          int[] imagestemp = {
        R.drawable.one_4, R.drawable.one_4, 
             R.drawable.one_4   }; 
        images=imagestemp;

                         }
        if(GalleryCity.city.equalsIgnoreCase("City5")){
            int[] imagestemp = {
        R.drawable.one_5, R.drawable.one_5, 
             R.drawable.one_5   }; 
       images=imagestemp;

                          }
                   }
       public class ViewHolder{ 
      public TextView text; 
      public ImageView image; } 

      private String[] name = { "in the cafe", "im in park", "nice place", };

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

             int itemPos = (position % images.length); 

        try { i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable 
                     ()).setAntiAlias(true); } 

       catch (OutOfMemoryError e) { Log.e("InfiniteGalleryAdapter", "Out of memory
                    creating imageview. Using empty view.", e); } 

       View vi=convertView; 
       ViewHolder holder; 
    if(convertView==null){ 
     vi = inflater.inflate(R.layout.gallery_items, null); 
      holder=new ViewHolder(); holder.text=(TextView)vi.findViewById
                    (R.id.textView1); 
      holder.image=(ImageView)vi.findViewById(R.id.image); 
         vi.setTag(holder); } 

      else holder=(ViewHolder)vi.getTag(); 
      holder.text.setText(name[itemPos]); 

      final int stub_id=images[itemPos]; 
      holder.image.setImageResource(stub_id); 

         return vi; } 

      private ImageView getImageView() { 

        ImageView i = new ImageView(mContext); 

               return i; } 

                        }
    class InfiniteGallery extends Gallery {

   public InfiniteGallery(Context context) {
    super(context);
      init();
            }

public InfiniteGallery(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
                   }

public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
               }

private void init(){
    setSpacing(25);
    setHorizontalFadingEdgeEnabled(false);
                   }

public void setResourceImages(int[] name){
    setAdapter(new InfiniteGalleryAdapter(getContext(), name));
    setSelection((getCount() / 2));
                  }
                    }

in each row class (City1,City2,City3,and so on ):

i put this code :

 public void handleClick(View v){


    Intent intent = new Intent(this, GalleryCity.class);
    intent.putExtra("galleryimags",city);
    startActivity(intent);                           

            }

                }

also please advice me how to set different images String names for each: ( City1,City2,City3,City4,City5 ) classes.

such as :

   private String[] name = { "in the cafe", "im in park",
                                 "nice place", };   

this is stack trace :

 04-20 18:29:17.421: E/AndroidRuntime(5007): FATAL EXCEPTION: main
 04-20 18:29:17.421: E/AndroidRuntime(5007): java.lang.RuntimeException: Unable to
 start activity ComponentInfo{com.test.city/com.test.city.GalleryCity}:
 java.lang.NullPointerException
 04-20 18:29:17.421: E/AndroidRuntime(5007):
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
 04-20 18:29:17.421: E/AndroidRuntime(5007):
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at android.app.ActivityThread.access$1500(ActivityThread.java:117)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
 04-20 18:29:17.421: E/AndroidRuntime(5007):
 at android.os.Handler.dispatchMessage(Handler.java:99)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at android.os.Looper.loop(Looper.java:123)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at android.app.ActivityThread.main(ActivityThread.java:3687)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at java.lang.reflect.Method.invokeNative(Native Method)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at java.lang.reflect.Method.invoke(Method.java:507)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at dalvik.system.NativeStart.main(Native Method)
 04-20 18:29:17.421: E/AndroidRuntime(5007):
 Caused by: java.lang.NullPointerException
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at com.test.city.InfiniteGalleryAdapter.getImagesforCity(GalleryCity.java:71)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at com.test.city.InfiniteGalleryAdapter.<init>(GalleryCity.java:66)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at com.test.city.GalleryCity.onCreate(GalleryCity.java:43)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
 04-20 18:29:17.421: E/AndroidRuntime(5007): 
    ... 11 more

UPDATE : APPLY CHANGES TO GallerCity as following :

  public class GalleryCity extends Activity {
 static String city;

    /** Called when the activity is first created. */
   @Override
      public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

    Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
    // Set the layout to use
    setContentView(R.layout.main);
    if (customTitleSupported) { 
 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title); 
         TextView tv = (TextView) findViewById(R.id.tv); 
     Typeface face=Typeface.createFromAsset(getAssets(),"BFantezy.ttf");     
         tv.setTypeface(face);
         tv.setText("My Pictures"); 
            } 

    Intent intent = getIntent(); 
    city = intent.getStringExtra("galleryimags"); 

    InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);

    galleryOne.setAdapter(new InfiniteGalleryAdapter(this,intent.getStringExtra
                          ("galleryimags"))); 
    galleryOne.setSelection(galleryOne.getCount()/2);            
     }
      }

  class InfiniteGalleryAdapter extends BaseAdapter { 
  private Context mContext;

   String city ="";  
  public InfiniteGalleryAdapter(Context c, String city) {  
     this.mContext = c;     
     this.city=city;       }  


   public int getCount() { 
return Integer.MAX_VALUE; } 

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

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

   private LayoutInflater inflater=null; 
   public InfiniteGalleryAdapter(Context a) { 
  this.mContext = a; 
     inflater = (LayoutInflater)mContext.getSystemService
             (Context.LAYOUT_INFLATER_SERVICE);                        
       getImagesforCity(); 
           } 

      private int[] images;


   private void getImagesforCity() {
  if(city.equalsIgnoreCase("City1")){  
    int[] imagestemp = {
            R.drawable.one_1, R.drawable.one_1, 
            R.drawable.one_1

    }; 
    images=imagestemp;

            }
 if(city.equalsIgnoreCase("City2")){  
    int[] imagestemp = {
            R.drawable.one_2, R.drawable.one_2, 
            R.drawable.one_2   }; 
    images=imagestemp;

            }

 if(city.equalsIgnoreCase("City3")){  
    int[] imagestemp = {
            R.drawable.one_3, R.drawable.one_3, 
            R.drawable.one_3   }; 
    images=imagestemp;

            }
 if(city.equalsIgnoreCase("City4")){  
    int[] imagestemp = {
            R.drawable.one_4, R.drawable.one_4, 
            R.drawable.one_4   }; 
    images=imagestemp;

            }
 if(city.equalsIgnoreCase("City5")){  
    int[] imagestemp = {
            R.drawable.one_5, R.drawable.one_5, 
            R.drawable.one_5   }; 
    images=imagestemp;

          }
        }
 public class ViewHolder{ 
 public TextView text; 
 public ImageView image; } 

   private String[] name = { "in the cafe", "im in park", "nice place", };

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

   int itemPos = (position % images.length); 

   try { i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable
                   ()).setAntiAlias(true); } 

  catch (OutOfMemoryError e) { Log.e("InfiniteGalleryAdapter", "Out of memory
              creating imageview. Using empty view.", e); } 

     View vi=convertView; 
     ViewHolder holder; 
   if(convertView==null){ 
 vi = inflater.inflate(R.layout.gallery_items, null); 
 holder=new ViewHolder(); holder.text=(TextView)vi.findViewById(R.id.textView1); 
 holder.image=(ImageView)vi.findViewById(R.id.image); 
 vi.setTag(holder); } 

      else holder=(ViewHolder)vi.getTag(); 
      holder.text.setText(name[itemPos]); 

      final int stub_id=images[itemPos]; 
      holder.image.setImageResource(stub_id); 

        return vi; } 

    private ImageView getImageView() { 

     ImageView i = new ImageView(mContext); 

      return i; } 

            }
    class InfiniteGallery extends Gallery {

  public InfiniteGallery(Context context) {
    super(context);
    init();
           }

public InfiniteGallery(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
                 }

public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
              }

private void init(){
    setSpacing(25);
    setHorizontalFadingEdgeEnabled(false);
              }
public void setResourceImages(String name){
    setAdapter(new InfiniteGalleryAdapter(getContext(), name));
    setSelection((getCount() / 2));
                }
            }

First thing after apply changes i had red line error on this part:

  public void setResourceImages(int[] name){
    setAdapter(new InfiniteGalleryAdapter(getContext(), name));
    setSelection((getCount() / 2));
          }
          }
  red mark under :
     setAdapter(new InfiniteGalleryAdapter(getContext(), name));

then changed to this (so no red line error appear ) :

    public void setResourceImages(String name){
    setAdapter(new InfiniteGalleryAdapter(getContext(), name));
    setSelection((getCount() / 2));
 }
     }

AFTER that i run app it gave force close when click button which open gallery ,

following logcat log as this:

  04-21 23:31:32.394: E/AndroidRuntime(27795): FATAL EXCEPTION: main
  04-21 23:31:32.394: E/AndroidRuntime(27795): java.lang.NullPointerException
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
    at com.test.city.InfiniteGalleryAdapter.getView(GalleryCity.java:126)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
    at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:192)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.View.measure(View.java:8366)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.View.measure(View.java:8366)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.View.measure(View.java:8366)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.View.measure(View.java:8366)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.View.measure(View.java:8366)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.ViewRoot.performTraversals(ViewRoot.java:844)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.os.Handler.dispatchMessage(Handler.java:99)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.os.Looper.loop(Looper.java:123)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at android.app.ActivityThread.main(ActivityThread.java:3687)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at java.lang.reflect.Method.invokeNative(Native Method)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at java.lang.reflect.Method.invoke(Method.java:507)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
  04-21 23:31:32.394: E/AndroidRuntime(27795): 
   at dalvik.system.NativeStart.main(Native Method)

the error in log cat in this line :

   04-21 23:31:32.394: E/AndroidRuntime(27795): 
     at com.test.city.InfiniteGalleryAdapter.getView(GalleryCity.java:126)

which match this line in code block:

     int itemPos = (position % images.length); 

did you try something like

Intent myIntent = new Intent();
myIntent.putExtra("key", "value");
startActivity(myIntent); 

I don't think it's a problem with your Intent. You can check it by debugging or just put Log.d("intentExtra", city); after getting the String extra from intent to check if it really gets it. I think it does.

What you need to do and there's no such thing in your code is to set an adapter to you InfiniteGallery (which is an extension of typical Gallery ), so it knows where to get the images from.

First you have to instantiate your adapter by calling something like:

InfiniteGalleryAdapter mAdapter = new InfiniteGalleryAdapter(this, imageIds)

( int[] imageIds is an array of ids, I don't know where you get it from)

And then set it to your gallery by:

galleryOne.setAdapter(mAdapter) .

UPDATE: Try the following code for your CityGallery class:

InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);
        galleryOne.setAdapter(initializeImages()); 
        galleryOne.setSelection(galleryOne.getCount()/2);            





    }

    private InfiniteGalleryAdapter initializeImages() {
        InfiniteGalleryAdapter galleryAdapter = null;

        String city = getIntent().getStringExtra("cityname");
        tv.setText("My "+city+" Pictures"); 

        if(city.equalsIgnoreCase("City1")){
            int[] tempimages = { R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher };  
            String[] name = { "Image 1","Image 2", "Image 3"};  

            galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);
        }else if(city.equalsIgnoreCase("City2")){
            int[] tempimages = { R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher };  
            String[] name = { "Image 4","Image 5", "Image 6"};  

            galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);


        }else if(city.equalsIgnoreCase("City3")){
            int[] tempimages = { R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher };  
            String[] name = { "Image 7","Image 8", "Image 9"};  

            galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);

        }else if(city.equalsIgnoreCase("City4")){
            int[] tempimages = { R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher };  
            String[] name = { "Image 10","Image 11", "Image 12"};  

            galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);

        }else if(city.equalsIgnoreCase("City5")){
            int[] tempimages = { R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher };  
            String[] name = { "Image 13","Image 14", "Image 15"};  

            galleryAdapter=new InfiniteGalleryAdapter(this, tempimages, name);
        }
        return galleryAdapter;





    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM