How to pass data from activity to a class? - java

How can i send data from an activity to a class ?
I tried to pass a String using getter but this gives me the initial value of the variable , but my String's value changes in my onCreate. Any ideas how can i pass it to my class ?
Here is some code :
public class MainActivity extends AppCompatActivity {
private String global ;
public String getGlobal() {
return global;
}
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
global = String.valueOf(parent.getItemAtPosition(position));
}
});
}
And here is my class
public class SimpleVar {
MainActivity mainActivity = new MainActivity() ;
String data = mainActivity.getGlobal; }
Any help will be much appreciated. Thank you in advance !

global is not actually "global"
Each instance of the Activity has its own string, and the OS can decide to kill your Activity at any time and recreate it, so therefore don't rely on a variable from an Activity within another class.
Secondly, never ever make a new Activity. That is no longer tied to the Activity that you would eventually click the button on.
It's hard to determine what you really need, but this is more correct.
public class SimpleVar {
String data;
}
With the Activity sending data to it
private SimpleVar var;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
var = new SimpleVar();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
var.data = String.valueOf(parent.getItemAtPosition(position));
}
});
}
If you need that object elsewhere, you need to pass it around to those classes from this Activity

try to make constructor for your class
public class SimpleVar {
private String data;
public SimpleVar(String data) {
this.data = data;
}
public void setData(String data) {
this.data = data;
}
}
then in your activity new the class and then set data to it

You should not create new mainactivity in your class.
When on instantiating the class pass to it a reference to Activity in which the class was created. Reference to Activity should be kept in a weakreference. Then You can make a getter in the Activity and call it from Your class.
Or You can do the opposite - keep reference to the instantiated object in the Activity. Use setter from the activity to pass new values to the object.

Related

How to register and reference callback interface?

When I need a callback from Activity B back to Activity A I usually make the reference variable in Activity B 'static'. I realize that if the user rotates the device the Life Cycle methods will remove my reference.
Is this the only drawback and is there a better way to register without a static reference. Is it better to simply put all data in the Application class ? - Thank you.
public class MainActivity extends Activity implements InterfaceMainActivityTwo {
static Main2Activity main2Activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main2Activity = new Main2Activity();
main2Activity.setDataListener(this);
}
#Override
public void getDataMainActivityTwo(String string) {
tvTextData.setText(string);
}
}
public class Main2Activity extends Activity {
static InterfaceMainActivityTwo mGetDataInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void getDataSaveBtn(View v) {
if (mGetDataInterface != null)
mGetDataInterface.getDataMainActivityTwo(fullName);
else
Toast.makeText(this, "IS NULL.INTERFACE NOT INITIALIZED !!!!", Toast.LENGTH_SHORT).show();
}
/////////// interface setup
interface InterfaceMainActivityTwo {
void getDataMainActivityTwo(String string);
}
public void setDataListener(InterfaceMainActivityTwo listener) {
this.mGetDataInterface = listener;
}
}
You should never need a callback between two activities. You're doing something wrong if you do. If you need to pass data from A to B, pass it in the bundle. If you need to pass it back from B to A, use startActivityForResult and pass it in the result. If you need to share data between many activities, it should be held in some globally accessible data structure, either in memory or on disk.

Struggling to writing my object to Parcelable

I am trying to send an object from one activity to another, so hence I am using parcelable, and while I have created code to send it and receive it,(the code for this is at the bottom) it seems that I need some code to be able to actually write the object to the parcel.
Error While Passing An Object From An Activity To Another (Using Parcelable)
I believe what I need to do is similar to the answer given in this, so I need a writeToParcel method, which I have done in the code below. (Although at dest.writeValue(this); is where I get an error) says StackOverFlowError
I believe i may also need public static final Parcelable.Creator... although don't completely know how to write it (I have tried to write one roughly and its the bit in comments)
Also I don't know if I need a bit that would be like public Clubs (Parcel source)...
Any help would be greatly appreciated. Thanks
public class Clubs implements Parcelable{
public void setEvent(String eventType, String date) {
this.eventType = eventType;
this.date = date;
}
//contains lots of defined variables and various methods that
//aren't relevant for my question and would take up lots of room
//all like the one above.
//public static final Parcelable.Creator CREATOR
//= new Parcelable.Creator() {
// public Parcel createFromParcel(Parcel in) {
// return (in);
// }
//};
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this);
}
}
My onItemClick class that puts the object into the parcel, and starts the new activity
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Clubs mymeeting = db.get(map.get(position));
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable("mymeeting", mymeeting);
i.putExtras(b);
i.setClass(ListSample.this, DynamicEvents.class);
startActivity(i);
}
The start of my new activity code that will be edit later once it send the object across correctly
public class DynamicEvents extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(20);
textView.setText(" " + b.getParcelable("mymeeting").toString());
// Set the text view as the activity layout
setContentView(textView);
}
}
Rewrite writeToParcel method as
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(eventType);
dest.writeString(date);
}
You may not be allowed to write Custom Java Object directly. Either write standard data values individually or make your object serializable and use method writeSerializable on Parcel object.

Passing string from class to main activity

I'm trying to pass something from one class to my MainActivity, but it doesn't seem to work, I don't understand why.
I have my GPS Tracker on another class (not the MainActivity) in order to reuse it.
When the location changes, I want my other class to call a method from within the MainActivity to update my UI.
I summarized my code like that :
My MAIN ACTIVITY :
public class MainActivity extends Activity implements OnClickListener {
TextView tv;
EditText et;
Button btun;
int arg0;
int stuff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
et = (EditText) findViewById(R.id.et);
btun = (Button) findViewById(R.id.btun);
btun.setOnClickListener(this);
}
private void setter(int stuff) {
tv.setText(stuff);
}
public void setText(int _stuff) {
_stuff = stuff;
setter(_stuff);
}
#Override
public void onClick(View v) {
Getter get = new Getter();
get.getInfo(Integer.parseInt(et.getText().toString()));
}
The other Class :
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I end up having a NullPointerException in my LogCat
at :
- tv.setText(stuff);
- setter(_stuff);
- main.setText(_getString);
- get.getInfo(Integer.parseInt(et.getText().toString()));
and I don't really know why, and above all, how to fix it.
I'll appreciate any help !
(PS : My GPS tracker thingy is working fine, it's just about invoking my setter() method.
Instantiaing an Object of MainActivity doesn't automatically call onCreate method but this method is called when you start an activity using Intent; And using the same intent you can pass extra values. For example:
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("key", value);
context.startActivity(intent);
and then in your main activity onCreate method:
String value = getIntent.getStringExtra("key");
Edit:
In your case why don't you change your void getInfo(int getString) to return a String value i.e.
public class Getter {
...
...
public String getInfo(int getString) {
_getString = getString * 8;
return Integer.toString(_getString);
}
}
and then in onClick event of MainActivity bind this returned text to TextView
It's maybe because the MainActivity's onCreate()-Method hasn't been called. Therefore the tv is still null causing the NullPointerException
One problem is here. main is an Activity, but it should be the MainActivity calling this object.
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
_getString = getString * 8;
main.setText(_getString);
}
}
I cannot really make out what you are trying to achieve in the Getter class, but either:
1: Pass the Activity instance to the object
public class Getter {
int _getString;
MainActivity _main = null;
public Getter(MainActivity main) {
_main = main;
}
public void getInfo(int getString) {
_getString = getString * 8;
_main.setText(_getString);
}
}
#Override
public void onClick(View v) {
Getter get = new Getter(this);
get.getInfo(Integer.parseInt(et.getText().toString()));
}
or
2: set the text in the Activity and only get the value from the Getter (My choice)
public class Getter {
int _getString;
MainActivity main = new MainActivity();
public void getInfo(int getString) {
return getString * 8;
}
}
#Override
public void onClick(View v) {
Getter get = new Getter();
int info = get.getInfo(Integer.parseInt(et.getText().toString()));
setText(Integer.toString(info));
}
Use Application Class or create a separate Class and declare a static variable in it. Use getter & setter methods to get the value. To update the Textview in mainacivity from other class pass the texview reference variable from main activity and put null check condition in other class if textview is not null then update the value.

Java hierarchy inside an android listner

In my android application I want to solve the following scenario.
class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutBuilder objLB=new LayoutBuilder(this);
objLB.createSpinner();
}
public void spinnerItemSelectedEvent(AdapterView<?> parent, View view,
int pos, long id)
{
}
}
class LayoutBuilder {
private Activity objActivity;
public LayoutBuilder(Activity a) {
objActivity = a;
}
public void createSpinner() {
final Spinner objSPItem = new Spinner(objActivity);
objSPItem.setOnItemSelectedListener(
new Spinner.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id)
{
// Do some common activity
objActivity.spinnerItemSelectedEvent(parent,view,pos,id);
// calling this for do some additional task
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
objActivity.spinnerItemSelectedEvent()
}
}
and the problem is when i try to access spinnerItemSelectedEvent(parent,view,pos,id) from the 'onItemSelected' listner inside createSpinner method
I got the following error.
The method spinnerItemSelectedListener(AdapterView, View, int, long) is undefined for the type Activity
but out side the listner the access to the method works ok(neglect parameter list). What is the reason behind that? is any alternate way exist for solving this? plz help
Activity in android represents a screen. You are making a variable objActivity of type Activity whereas it should be of type Login where the function spinnerItemSelectedEvent() is declared. Change the following lines:
private Activity objActivity;
to
private Login objActivity;
and your code should run.
EDIT
Have a BaseActivity and let all your other activities extend this BaseActivity. To make the function spinnerItemSelectedEvent() reusable declare it in the BaseActivity and you can use it the way you are trying to do it now.
Example:
class BaseActivity extends Activity{
public void spinnerItemSelectedEvent(AdapterView<?> parent, View view,
int pos, long id){ }
}
class Login extends BaseActivity{
public void spinnerItemSelectedEvent(AdapterView<?> parent, View view,
int pos, long id){ //Local implementation of the function}
}
class LayoutBuilder {
private BaseActivity objActivity;
}
The problem is that inside LayoutBuilder, you have declared objActivity to be an Activity. Declare it to be a Login and all should be fine:
class LayoutBuilder {
private Login objActivity;
public LayoutBuilder(Login a) {
objActivity = a;
}
. . .
EDIT
If you want your LayoutBuilder class to be reusable by other activities, then one way to do this is via an interface declaration. For instance:
public interface SpinnerSelectionHandler {
void spinnerItemSelectedEvent(AdapterView<?> parent, View view,
int pos, long id);
}
Then declare Login as:
public class Login extends Activity implements SpinnerSelectionHandler {
. . .
Finally, redefine LayoutBuilder to take a SpinnerSelectionHandler in its constructor:
class LayoutBuilder {
private Activity objActivity;
private SpinnerSelectionHandler selectHandler;
public LayoutBuilder(Activity a, SpinnerSelectionHandler handler) {
objActivity = a;
selectHandler = handler;
}
And then replace
objActivity.spinnerItemSelectedEvent(parent,view,pos,id);
with
spinnerHandler.spinnerItemSelectedEvent(parent,view,pos,id);
Plus, if you don't need the Activity reference for anything else, you can get rid of it from the LayoutBuilder class.

Best way to store list of activities to be called from another activity

I have following goal: From a list in main activity that extends ListActivity, I want to start other activities.
This is the code of the main activity:
public class SelectionWidgetsExampleActivity extends ListActivity {
private Class[] demos = {ListViewDemo.class, ChecklistDemo.class};
private ArrayAdapter<Class> aa;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
aa = new ArrayAdapter<Class>(this, android.R.layout.simple_list_item_1, demos);
setListAdapter(aa);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this, demos[position]);
startActivity(intent);
}
}
My question is
How would you solve the issue of having list of classes to be executed outside the code of the main activity?
My first idea was to put it into xml resource file as string array. I can then easily create array of Strings from the resource, but don't know how to convert the string to the class - I need something like:
SomeJavaClass.getMeClassFromString(demos[position])
Do you need Class#forName(String className)?
It will solve your issue.
But what's wrong with your initial (posted) solution? I'd rather keep it than use dynamic class loading, only would changed modifiers of demos to private static final.

Categories