2

I have a JSON file which is populated to an activity (Main.java).

This Activity shows 3 random images from the URL on my JSON entries.

What I want to do is: I have 13 different entries on the my JSON, whenever I click the shown random picture it goes to another activity (ProjectDetail.java) containing the picture,title,and description depends on the item I click based on its entry on the JSON.

What do I have in is by using extra by I don't know exactly how to perform that since I'm using JSON. What should I add into my top_listener method on my Main class and what should I add into my ProjectDetail class?

Main.java

   public class Main extends Activity {
            /** Called when the activity is first created. */
            
            ArrayList<Project> prjcts=null;
            private ImageThreadLoader imageLoader = new ImageThreadLoader();
            private final static String TAG = "MediaItemAdapter";
            
            
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                
                prjcts = new ArrayList<Project>();
                WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
                Map<String, String> params = new HashMap<String, String>();
                params.put("var", "");
                String response = webService.webGet("", params);
                
                try
                {
                    Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
                    List<Project> lst= new Gson().fromJson(response, collectionType);
                    for(Project l : lst)
                    {
                        prjcts.add(l);
                        ConstantData.projectsList.add(l);
                    }
                }
                catch(Exception e)
                {
                    Log.d("Error: ", e.getMessage());
                }
                
                final Button project = (Button) findViewById(R.id.btn_projectslist);
                final Button infos = (Button) findViewById(R.id.btn_infos);
                final Button contact = (Button) findViewById(R.id.btn_contact);
                project.setOnClickListener(project_listener);
                infos.setOnClickListener(infos_listener);
                contact.setOnClickListener(contact_listener);
                
                ImageView image1;
                ImageView image2;
                ImageView image3;
                
                try {
                    image1 = (ImageView)findViewById(R.id.top1);
                    image2 = (ImageView)findViewById(R.id.top2);
                    image3 = (ImageView)findViewById(R.id.top3);
                  } catch( ClassCastException e ) {
                    Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
                    throw e;
                  }
        
        
                  Bitmap cachedImage1 = null;
                  Bitmap cachedImage2 = null;
                  Bitmap cachedImage3 = null;
                  
                  //randomize the index of image entry
                  
                  int max = prjcts.size();
                  List<Integer> indices = new ArrayList<Integer>(max);
                  for(int c = 0; c < max; ++c)
                  {
                      indices.add(c);
                  }
                  
                  int arrIndex = (int)((double)indices.size() * Math.random());
                  int randomIndex1 = indices.get(arrIndex);
                  indices.remove(arrIndex);
                  
                  
                  int randomIndex2 = indices.get(arrIndex);
                  indices.remove(arrIndex);
                  
                
                  int randomIndex3 = indices.get(arrIndex);
                  indices.remove(arrIndex);
                  
             
                  
                  setImage(cachedImage1, image1, prjcts.get(randomIndex1));
                  setImage(cachedImage2, image2, prjcts.get(randomIndex2));
                  setImage(cachedImage3, image3, prjcts.get(randomIndex3));
                  
                  image1.setOnClickListener(top_listener);
                  image2.setOnClickListener(top_listener);
                  image3.setOnClickListener(top_listener);
            }
           
            
            
            public void setImage(Bitmap cachedImage, final ImageView image, Project pro)
            {
                //Bitmap cachedImage1 = null;
                try {
                    cachedImage = imageLoader.loadImage(pro.smallImageUrl, new ImageLoadedListener() 
                    {
                        public void imageLoaded(Bitmap imageBitmap)
                        {
                            image.setImageBitmap(imageBitmap);
                            //notifyDataSetChanged();                
                        }
                    });
                } catch (MalformedURLException e) {
                    Log.e(TAG, "Bad remote image URL: " + pro.smallImageUrl, e);
                }
                if( cachedImage != null ) {
                    image.setImageBitmap(cachedImage);
                  }
            }
            
            
            private OnClickListener top_listener = new OnClickListener() {
                public void onClick(View v) {
                            Intent top = new Intent(Main.this, InfosActivity.class);
                            startActivity(top);
                }
                };

ProjectDetail.java

public class ProjectDetail extends Activity implements OnClickListener{
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.project);
        
        Button weitersagen = (Button) findViewById(R.id.btn_weitersagen);
        weitersagen.setOnClickListener(this);
 
        Button sms = (Button) findViewById(R.id.btn_sms_spenden);
        sms.setOnClickListener(this);
        
        int position = getIntent().getExtras().getInt("spendino.de.ProjectDetail.position");
        Project project = ConstantData.projectsList.get(position);
      

      try {
          ImageView projectImage = (ImageView)findViewById(R.id.project_image);
          Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(project.bigImageUrl).getContent());
          projectImage.setImageBitmap(bitmap); 
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } 

      TextView project_title = (TextView)findViewById(R.id.txt_project_title);
      project_title.setText(project.project_title);
      
      TextView organization_title = (TextView)findViewById(R.id.txt_organization_title);
      organization_title.setText(Html.fromHtml("von " +project.organization_title));

      TextView project_description = (TextView)findViewById(R.id.txt_project_description);
      project_description.setText(Html.fromHtml(project.project_description));
        
    }
     

I also have this ConstantData.java, the index which holds my JSON properties:

 public class ConstantData{

   public static String project_title = "project title";
   public static String organization_title = "organization title";
   public static String keyword = "keyword";
   public static String short_code = "short code";
   public static String project_description = "description";
   public static String smallImageUrl = "smallImageUrl";
   public static String bigImageUrl = "bigImageUrl";
   public static String price= "price";
   public static String country= "country";



    public static ArrayList<Project> projectsList = new ArrayList<Project>();
    
    
    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeString(project_title);
        out.writeString(organization_title);
        out.writeString(keyword);
        out.writeString(short_code);
        out.writeString(project_description);
        out.writeString(smallImageUrl);
        out.writeString(bigImageUrl);
        out.writeString(price);
        out.writeString(country);
    }

    public static final Parcelable.Creator<ConstantData> CREATOR
            = new Parcelable.Creator<ConstantData>() {
        public ConstantData createFromParcel(Parcel in) {
            return new ConstantData(in);
        }

        public ConstantData[] newArray(int size) {
            return new ConstantData[size];
        }
    };
    
    private ConstantData(Parcel in) {
        project_title = in.readString();
        organization_title = in.readString();
        keyword = in.readString();
        short_code = in.readString();
        project_description = in.readString();
        smallImageUrl = in.readString();
        bigImageUrl = in.readString();
        price = in.readString();
        country = in.readString();
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
hectichavana
  • 1,436
  • 13
  • 41
  • 71

3 Answers3

6

You could make the class ConstantData serializable by extending from Parcelable and implementing a couple of methods (see the documentation). Then you could pass a constantData instance as an extra by doing

intent.putExtra("jsonData", constantDataInstance);

and retrieving it from the other activity (in it's onCreate() method) with

getIntent().getExtras().getParcelable("jsonData");

Otherwise you could just past as extra every field independently, but it would be a mess. This way is not only more easy to read and everything, but "well designed".

ferostar
  • 7,074
  • 7
  • 38
  • 61
  • 1
    I've edited my ConstantData, pls have a look.. then with what should change the constantDataInstance? thx – hectichavana Apr 28 '11 at 15:24
  • For what i can see, you are placing your json data in ConstantData's array so you are not using any of it's other instance variables. You should parse the json and put every object inside a variable. Then, you pass to the intent the constantDataInstance that, being serializable, it carries all info with it. – ferostar Apr 28 '11 at 16:12
  • I see, can you provide me an example anyway? Thanks – hectichavana Apr 29 '11 at 07:57
  • Well, let's say you parse your json data to a string array. Then, you can do intent.putExtra("whatever", array[0]); for every object in the array and then you retrieve it with getIntent().getExtras().getString("whatever"); – ferostar Apr 29 '11 at 12:40
3

To pass information from one activity to another when you start the new one you do the following:

    Intent top = new Intent(Main.this, InfosActivity.class);
    Bundle b = new Bundle();
    b.putString("key1", "value2");
    b.putString("key2", "value2");
    b.putString("key3", "value3");
    top.putExtras(b);
    startActivity(top);

Then in the newly started activity, in the onCreate() put the following:

    Bundle b = getIntent().getExtras();
    b.get("key1");
    b.get("key2");
    b.get("key3");

This will get the values from the previous activity by using the key you provided.

For more complex objects you should extend Parcelable (probably what you'll need) and then use:

b.putParcelable("Key4", yourParcelableObject);

And in your onCreate()

b.getParcelable("Key4");

I hope this helps.

NotACleverMan
  • 12,107
  • 12
  • 47
  • 67
  • 1
    the first method is by inserting the values manually right? The thing is, my value is already declared on the JSON. For example: "short_code":"81190" and I believe there has soemthing to do with my ConstantData class, any idea? – hectichavana Apr 28 '11 at 13:45
  • I don't really understand what you're looking for, sorry. If you want to pass an entire ConstantData object just make your class extend Parcelable, and then use the b.putParceable() method. – NotACleverMan Apr 28 '11 at 13:58
  • 1
    thx. Let's say I need to set the extra (for example key1) into a TextView thru setText, what should I put as the argument on this method? projtitle.setText(); – hectichavana Apr 28 '11 at 15:00
  • "I need to set the extra (for example key1) into a TextView thru setText" I don't get it. Do you need to set the Extra, or do you need to put text into a textview? They are two completely separate things. – NotACleverMan Apr 28 '11 at 15:14
  • 1
    the text for the textview should be fetched from the extra – hectichavana Apr 28 '11 at 15:18
  • String projectTitle1 = b.getString("key1"); textView1.setText(projectTitle1); – NotACleverMan Apr 28 '11 at 15:20
  • 1
    thank you. I decided to use the Parcelable method, could you pls have a look into my edited ConstantData above. Ehmm with what should I replace 'yourParcelableObject'? – hectichavana Apr 28 '11 at 15:37
  • You should replace "yourParceableObject" with your ConstantData object. For example: ConstantData cd1 = new ConstantData(); b.putParcelable("key4", cd1); I've never made a parcelable class the way you did there. If it doesn't work you should look at this example: http://stackoverflow.com/questions/2139134/how-to-send-an-object-from-one-android-activity-to-another-with-intent-putextra/2141166#2141166 – NotACleverMan Apr 28 '11 at 15:56
  • 1
    I still dont get the idea about my ConstantData object, because I don't have any of them inside my Constant Data and the example your provide doesn't have the object declared as well. Declaring ConstantData cd1 = new ConstantData(); on my Main activity only give me errors. – hectichavana Apr 28 '11 at 16:10
  • I don't know your objects, but you should. I don't mean to offend you at all, but it seems like passing data between activities, especially in this case, is too advanced for you. In my answers I was taking for granted that you knew how to declare your own objects. I think you should look up some more java and maybe make a normal java project to get used to it before you start transfering this to android. I'm sorry i can't help more. – NotACleverMan Apr 28 '11 at 16:22
0

Use gson to parse the json to Java. Then you can use Wagon to move the extras around with ease.

GSON: https://github.com/google/gson

Wagon: https://github.com/beplaya/Wagon

beplaya
  • 281
  • 2
  • 8