I want my activity to pass a value to another activity class that extends view. Can you please tell me a solution? I am new to Android Programming.
Better idea is..
class CustomView extends View{
YourData data;
public CustomView(YourData data, Context context){
this.data = data
}
}
and in Activity
new CustomView(data. this)
pass throgh constructor or getter/seller . nothing related to android .
use standard java tequnique to pass data to object .
you can't because intents are used to comunicate between activitys, receivers & services.
You can pass the activity reference in the view and use that to get the appropriate values.
class MyActivity extends Activity {
MyView v;
int i;
public void onCreate(){
v = new MyView(this);
}
}
class MyView extends View {
MyActivity activity;
public MyView(MyActivity act) {
this.activity = act;
}
public void someMethod() {
int valueFromActivity = activity.i;
}
}
In the main class (A.java)
Intent i = new Intent(A.this,B.class);
i.putExtra("val", the value that you want to pass);
startActivity(i);
in B.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Integer number = getIntent().getIntExtra("val", 0);
We will get the passes value in number
Related
So I have this "middle man" nonactivity class, where I want to get a string path from an activity class. Then, from my nonactivity class send that string path to a different activity?
Activity A
#Override
public void onCreate(Bundle savedInstanceState)
{
Intent imageToFactory = new Intent(this,NonActivity.class);
imageToFactory.putExtra("yourImage", user_image_path);//I already set user_image path
}
NonActivity
public class NonActivity
{
private Intent grabImagePath = new Intent();
private String grabImagePathString = getIntent.getStringExtra("yourImage");//this obviously gives an error but for the example
public String grabUserImage()
{
return grabImagePathString;
}
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
NonActivity nonActivity;
String example = nonActivity.grabUserImage();
}
So this method doesn't work for some reason, I think I have to use contexts some how but im not sure exactly how to use them, if anyone can help with examples or modify the example code i did below that'd be awesome!
You can build a static variable that can serve as message bridge, first thing you need to create a class and name it anything you like, in my case I will name the example class as Conn, then add a static HashMap.
public class Conn {
public static HashMap<String,String> storage = new HashMap<>();
}
To utilize this this class in your example:
Activity A
#Override
public void onCreate(Bundle savedInstanceState){
Conn.storage.put("yourImage",user_image_path_in_string);
}
Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
String example = Conn.storage.get("yourImage");
}
if you want to use third class ( here NonActivity.class ) for some reasons, just do it like this:
create globals class like this :
package helper;
public class Globals {
private static final Globals instance = new Globals();
private GlobalVariables globalVariables = new GlobalVariables();
private Globals() {
}
public static Globals getInstance() {
return instance;
}
public GlobalVariables getValue() {
return globalVariables;
}
}
and global variables class like this :
public class GlobalVariables {
public String grabImagePathString;
}
now in activity A::
Globals.getInstance().getValue(). grabImagePathString = "something......";
and in activity B::
String gtabImagePathString = Globals.getInstance().getValue(). grabImagePathString;
Good Luck
New to Android and having some trouble passing data from an activity to a view. I have a simple Android onCreate method for my Activity.
public class MyActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
int num = intent.getIntExtra(MainActivity.EXTRA_NUM, 0);
setContentView(R.layout.play_game); //this is a MyView class inside of a LinearLayout
//where I want to pass the value of num to MyView
MyView myView = (MyView) findViewById(R.id.myview);
myView.setNum(num);
}
}
public class MyView extends View {
protected int num;
protected int[] array;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init();
}
protected void init() {
setBackgroundResource(R.drawable.pic1);
array = new int[num];
}
public void setNum(int num) {
this.num = num;
}
}
However, I can't figure out how to pass a value to the MyView class (it extends View). I just want to send an integer value that the view class will get before starting the constructor.
Add a setter method to yours MyView class
public void setNum(int num)
{
this.num=num;
}
In MyActivity find yours view
MyView myView=(MyView) findViewById(R.id.ID_OF_YOURS_VIEW_IN_ACTIVITYS_LAYOUT);
Set yours value to yours view by passing it to setter method
myView.setNum(num);
Get your view id by findViewById() in oncreate() of MyActivity class
MyView mv=(MyView) findViewById(R.id.your-view-id);
Then set the value by a method getdata()
mv.getdata(value);
where getdata() method looks like
public void getdata(int value)
{
this.value=value;
}
after setContentView
MyView mv = (MyView) findviewById(R.id.myView);
mv.setData(int number);
You'll need to make setData public. Make sure you set the id of myview with
android:id="#+id/myView"
in xml.
You have several options :
Remove initialization of the array from init() or give it a default value for avoiding error as others suggested. It depends whether an array with a default value makes sense or not in your context. Finally inject the number with a setter.
You can also define a static method for setting the number from the activity before the view constructor get called (do it before inflating view with findViewById()). But generatly it is a bad practice and should be used in specific cases.
The real question may be : does the init() call makes sense in constructors and the array must be set at view construction? Can't it be initialized afterward?
I've 3 activities. First activity sets id, activity second is menu and activity third to show id.
But, third activity shows null id. Why?
a.class:
package a.b.c.model;
public class Profil {
private String pid;
public String getpId() {
return pid;
}
public void setpId(String id) {
this.pid = pid;
}
}
b.class:
package a.b.c;
import a.b.c.model;
public class bextends Activity {
Profil p = new Profil();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b);
p.setpId("TEST");
}
}
c.class:
package a.b.c;
import a.b.c.model;
public class c extends Activity {
Profil p = new Profil();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c);
final TextView tex = (TextView) findViewById(R.id.pid);
tex.setText(p.getpId());
}
}
d.class
package a.b.c.model;
public class d extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.d);;
}
}
UPDATE:
activity class
b -> d -> c
If you intend pid to be global to the Profil class, you should make the pid variable static. A static variable belongs to the class itself, and not the instance of said class.
So our fix would look as simple as private static String pid;, and making our getters and setters static as well.
If you wish for each Profil to be able to have its own pid, then you'll need to pass the correct instance of Profil to where it is needed. A new instance of a class is generally always created with the new keyword. So remember, if we see new there's a new instance, and any non static variables are not kept and are separate from other instances.
In c.class, p is a new object with pid == null. You need to pass it from b to c through a Bundle.
In your b.class your creating a new object and setting the value to the object means it is a local object and you can use with in the class reference only. In your c.class when ever your crating a new object means it is freshly created i.e it don't have any values in it.
When ever you created an object like below means, it always empty and it having only null values in it.
Profil p = new Profil();
So coming to your solution, you can achieve it by many ways based on your specifications / requirements /scope
one way is make your classes like below
a.class
package a.b.c.model;
public class Profil implements Serializable {
/** auto generated serial version id
*
*/
private static final long serialVersionUID = 1L;
private String pid;
public String getpId() {
return id;
}
public void setpId(String id) {
this.id = id;
}
}
b.class
package a.b.c;
import a.b.c.model;
public class bextends Activity {
Profil p = new Profil();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b);
p.setpId("TEST");
}
after some button action click (navigating from b to c) you can send your Serialized Profile object to B class to C and then you can use it
your intent should be like this
Intent i = new Intent(this, D.class);
i.putExtra("sampleObject", p);
startActivity(i);
In your 'D' activity you need to get the object which your sending form activity b.
d.class
package a.b.c.model;
public class d extends Activity {
Profil p = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.d);
p = (Profil)getIntent().getSerializableExtra("sampleObject");
}
}
your intent should be like this (D activity to C activity)
// this you can write in your navigation part probably in a button click
Intent i = new Intent(this, C.class);
i.putExtra("sampleObject", p);
startActivity(i);
After receiving object when ever your navigating from activity 'D' to activity 'C' you need to pass the updated object in the same way
Then your C class should be like this
C.class
package a.b.c;
import a.b.c.model;
public class c extends Activity {
Profil p = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c);
p = (Profil)getIntent().getSerializableExtra("sampleObject");
final TextView tex = (TextView) findViewById(R.id.pid);
tex.setText(p.getpId());
}
}
That's it :) now you can use the updated Profile object in your C class as well..
Note:: As i told earlier this is a basic approach.. there is too many alternative approaches will do the same operation better than this
I am working in android. I have two acitivities in my project. I have declared a public static variable in one activity like this:-
public static String name="KUNTAL";
In my second activity i am trying to use this variable, then it is generating error that this name variable is not exist.
Is this possible to use a variable anywhere in my project if it is declared as public ?
Please suggest me what mistake i have done.?
Thank you in advance...
public class Activity1 extends Activity {
public static String name="KUNTAL"; //declare static variable.
#Override
public void onCreate(Bundle savedInstanceState) {
}
}
public class Activity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Activity1.name; //way to access static variable using dot operator.
}
}
I think you must access them in a 'static way', i.e.:
String myVar= name; // wrong
String myVar= TheClassThatContainsName.name; // right
You can use the variable specified as public static in any Activity but you need to access that variable by using the Activity name where you Declared it.
For Accessing in Second Activity just use ;
Activity1.name ="Me";
means that name variable belongs to Activity1 and you are using in Acvity2
Declaring variables public static is not the recommended way of passing values between two activities. Use Intent object instead:
public class Activity1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
yourButton.setOnClicklistener(listener);
}
}
//On click of some button start Activity2:
View.onClicklistener listener = new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent mIntent = new Intent(Activity1.this,Activity2.class);
mIntent.putExtra("yourKey","yourValue");
startActivity(mIntent);
}
};
//and then in your activity2 get the value:
public class Activity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
String yourValue = getIntent().getExtras().getString("yourKey");
}
}
if you're using the same variable in more than one activity then make a class something like ActivityConsts{}, and declare and initialize this variable in there(in ActivityConsts). And access this variable from anywhere with the class name.
ex-
declare a class-
public class ActivityConsts {
//your String var
public static String name="KUNTAL";
}
now in your activity:
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
String yourStringVar = ActivityConsts.name;
}
}
There is no datatype specified for your variable. Use
public static String name="KUNTAL";
I have an activity which creates an object instance of my class:
file MyActivity.java:
public class MyActivity extends Activity {
TextView myView = (TextView)findViewById(R.id.myView);
...
Points myPoints new Points();
...
}
--------------------------------------------------------------
file Points.java:
private class Points {
...
HOW TO USE myView HERE ???
...
}
--------------------------------------------------------------
How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?
see you post, i've edited it , to fix the problem
hope it helps :=)
here is the Edit :
file MyActivity.java:
public class MyActivity extends Activity {
TextView myView ;
protected void onCreate(android.os.Bundle savedInstanceState) {
myView = (TextView)findViewById(R.id.myView);
Points myPoints = new Points(this);
myPoints.displayMsg("Hello World !!!");
}
}
--------------------------------------------------------------
file Points.java:
private class Points {
protected MyActivity context;
//add a constructor with the Context of your activity
public Points(MyActivity _context){
context = _context;
}
public void displayMsg( final String msg){
context.runOnUiThread(new Runnable() {
#Override
public void run() {
context.myView.setText(msg);
}
});
}
}
Your Points can't be a private class without being an inner class. So your code doesn't even compile...
Pass the view as parameter to the constructor of your Points class:
public class MyActivity extends Activity {
TextView myView = (TextView)findViewById(R.id.myView);
Points myPoints new Points(myView);
private class Points {
public Points(TextView view) {
// todo
}
}
}
You should do everything and pass back the value to the activity to handle UI instead of doing any UI related stuff in the point stuff.
You can pass the main Activity's context (using Points(getApplicationContext());) to the class as a constructor parameter. You could also pass the specific UI elements you want to manipulate.
A better way to do it, however, may be to have Points not know about the Activity. Have your Activity call Points methods and take the necessary actions based on the method output.
You could just pass the view to your class.
Points myPoints = new Points(myView);
private class Points
{
private TextView mTextView;
Points(TextView textView)
{
this.mTextView = textView;
}
}
i was in same trouble..
i found the simple way..
make a static variable and function ...
call from other class..
TestActivity.java
public class TestActivity extends Activity {
static EditText edit_text1;
public void onCreate(Bundle savedInstanceState)
{
.....
edit_text1 = (EditText) findViewById(R.id.edit_text1);
.....
}
public static void setMSG(String str)
{
edit_text1.setText(str);
}
}
Test2.java
TestActivity.setMSG("this is text");
Could work using an interface
file MyActivity.java:
public class MyActivity extends Activity implements Points.MyListener {
TextView myView;
... onCreate(...){
myView = (TextView)findViewById(R.id.myView);
Points myPoints = new Points();
//pass in MyActivity's instance of the listener
myPoints.addListener(this);
}
#Override
public void updateTextView(String message){
myView.setMessage(message);
}
}
file Points.java:
public class Points {
public Points(){
}
public interface MyListener{
void updateTextView(String message);
}
MyListener myListener;
public void addListener(MyListener listener){
myListener = listener;
}
public void updatePoints(){
//do some operations in calculatePoints()
String points = calculatePoints();
//update views using MyActivity's implementation of updateTextView()
myListener.updateTextView(points);
}
}
Doing it this way, events can be fired / messages sent, for lack of better terms, from the external class to update the Activity UI. This might be overkill if all sb need is to call a method in the Points class that returns something