How to do pass the values from one class to other class

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

How to do pass the values from one class to other class

Postby rakesh86shankar » Tue Jan 26, 2010 12:19 pm

hi i am new to android and i want to know how to pass the values from one class to other class.Any sample programs would be helpful

Regards
P.RakeshShankar
rakesh86shankar
Developer
Developer
 
Posts: 38
Joined: Fri May 29, 2009 9:51 am

Top

Postby Johan Degraeve » Tue Jan 26, 2010 4:01 pm

Bundles are what you need.
In fact for every class you create a method toBundle and fromBundle
If a class A has fields of type another class B, you do the same for that other class

so in A.toBundle you use B.toBundle for every field in B, which may again contain other class or primitive datatypes.

in fromBundle you do the inverse.

Then how to use that bundle is a bit explained here : the_common_way_to_use_an_object_in_different_activities-t9227.html#30144
regards,

Johan
Johan Degraeve
Experienced Developer
Experienced Developer
 
Posts: 55
Joined: Tue Oct 27, 2009 1:50 pm
Location: Belgium

Postby nikoladj » Fri Jan 29, 2010 7:53 pm

You can use static final

Something like this

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. final public class MyShare{
  2.  
  3.     static String myString;
  4.  
  5.     MyApp(){
  6.  
  7.     }
Parsed in 0.031 seconds, using GeSHi 1.0.8.4



You can set value to it from anywhere with
MyShare.myString="something";

and read it like this

newVar=MyShare.myString;

It works..

There is one more way i found out


Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import android.app.Application;
  2.  
  3.  
  4.  
  5. class MyApp extends Application {
  6.  
  7.  
  8.  
  9.           private String myString;
  10.  
  11.  
  12.  
  13.           public String getString(){
  14.  
  15.             return myString;
  16.  
  17.           }
  18.  
  19.           public void setString(String s){
  20.  
  21.             myString = s;
  22.  
  23.           }
  24.  
  25.         }
Parsed in 0.031 seconds, using GeSHi 1.0.8.4


And you read and set it with functions:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. MyApp appState = ((MyApp)getApplicationContext());
  2.  
  3.                     appState.setString("testing");
Parsed in 0.034 seconds, using GeSHi 1.0.8.4


But you need to set in manifest.xml-> application-->name to MyApp or what ever you name the class in order to work.
nikoladj
Junior Developer
Junior Developer
 
Posts: 13
Joined: Fri Jan 29, 2010 7:44 pm

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 5 guests