How to pass data from activity to class - android

Here is my activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_engineer_recycler );
String value = "hello";
}
Here is my class file :
public class complaintAdapter{
//code here
}
Now can anyone help me how pass that "hello" from activity to class

There could be two solutions to this.
Solution 1
Using data from Activity during object creation like this.
Create a constructor in the class that could take the desired data like this
public class complaintAdapter{
private String _value;
public complaintAdapter(String value){
_value = value;
// use _value
}
}
This can be used in the activity like this.
Create a method in the class and call it using the data as a parameter.
String value = "hello";
complaintAdapter complaintAdapterObj = new complaintAdapter(value);
Solution 2
Using data from the activity in the method call like this.
Create a method in the class and call it using the data as a parameter.
public class complaintAdapter{
private String _value;
public void sendData(String value){
_value = value;
// use _value
}
}
This can be used in the activity like this
String value = "hello";
complaintAdapter complaintAdapterObj = new complaintAdapter();
complaintAdapterObj.sendData(value);

Create a constructor in your ComplaintAdapter class
public class ComplaintAdapter{
private String value;
public ComplaintAdapter(String value){
this.value = value;
}
}
Then when you create the object of this class pass the value to constructor
ComplaintAdapter adapter = new ComplaintAdapter(value);

To pass any value to class you should create an appropriate constructor. In this case you should do like this:
public class complaintAdapter {
private String value;
public complaintAdapter(String value) {
this.value = value;
}
}
Then you create an instance in your activity:
complaintAdapter adapter = new complaintAdapter(value);
P.S. As Java Code conventions rule says - any java class name should start with uppercase symbol so you better rename your class to ComplaintAdapter

Change it in this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_engineer_recycler );
String value = "hello";
ComplaintAdapter adapter = new ComplaintAdapter(value);
//access to value
adapter.getValue();
}
and change Class in this way:
public class ComplaintAdapter{
private String value;
public ComplaintAdapter(String value){
this.value = value;
}
public String getValue(){
return this.value;
}
}

Related

How do you pass information to and from a non activity class?

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

Give reference to string parameters in outer class method Android

I am calling some function of outer class from my activity and I want to give reference of parameters so that I can get updated value.
I m calling function like this:
My activity:
String var1;
ArrayList<String> var2;
OuterClass outerClass = new Outerclass();
outerClass.someMethod(var1, var2);
My outer Class function:
public void someMethod(String var1,ArrayList<String> var2) {
// after some operations
var1 = "somevale1";
var2 also have some value;
I need to access both of updated value in my activity without any return statement only from reference. But here I am getting error variable accessed from within inner class needs to be declare final but I cannot declare final.
What should I do to give reference just like TextView and EditText?
Try this,
Take a bean class, and put it into var1, var2 and then update in out class method and that updated values reflected into that bean object.
class CustomBean{
String var1;
ArrayList<String> var2;
}
OuterClass outerClass = new Outerclass();
outerClass.someMethod(Bean bean);
public void someMethod(String var1,ArrayList<String> var2) {
// after some operations
bean.var1 = "somevale1";
bean.var2 also have some value;
}
I think you can declare as global variables and make them final.
final String var1;
final Arraylist<String> var2;
You can't update values in such way, because you pass to method just references to where date is stored. What I suggest is change signature of your method, so it returns:
return new Pair<String, ArrayList<String>> (var1, var2);
Krishna's answer is also correct, but I see no real need in such architecture.
Maybe somethink like this. The signature of someMethod was changed.
public class SOActivity extends Activity
{
private String var1;
private ArrayList<String> var2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OuterClass outerClass = new OuterClass();
outerClass.someMethod(this);
android.util.Log.d("SOActivity", "var1=" + var1);
android.util.Log.d("SOActivity", "var2=" + var2.get(0) + var2.get(1));
}
public void setVar1(String var1) {
this.var1 = var1;
}
public void setVar2(ArrayList<String> var2) {
this.var2 = var2;
}
}
public class OuterClass {
public void someMethod(SOActivity soActivity) {
// Some big init for var1 and var2
soActivity.setVar1("somevalue1");
ArrayList<String> al = new ArrayList<String>();
al.add("My");
al.add("solution");
soActivity.setVar2(al);
}
}

How to declare a variable that can be accessed by all the classes in android?

I'm a new to android please help me with the following.
I'm having an integer value which stores the id of a checked radiobutton. I need to access this value throughout the various classes of my app for a validation purpose.
Please let me know how to declare and access this variable from all the classes.
Thank you.
U can use:
MainActivity.class
Public static int myId;
In other Activities.
int otherId=MainActivity.myId;
following singleton pattern is the only way to do this.in java/android if u create a instance for a class every time it create a new object.what you should do is
1.create a model class and make its as singleton
2.try to access the modelclass from every class
public class CommonModelClass
{
private static CommonModelClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private CommonModelClass()
{
// Optional Code
}
public static synchronized CommonModelClass getSingletonObject()
{
if (singletonObject == null)
{
singletonObject = new CommonModelClass();
}
return singletonObject;
}
/**
* used to clear CommonModelClass(SingletonClass) Memory
*/
public void clear()
{
singletonObject = null;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
//getters and setters starts from here.it is used to set and get a value
public String getcheckBox()
{
return checkBox;
}
public void setcheckBox(String checkBox)
{
this.checkBox = checkBox;
}
}
accessing the model class values from other class
commonModelClass = CommonModelClass.getSingletonObject();
commonModelClass.getcheckBox();
http://javapapers.com/design-patterns/singleton-pattern/
You can declare your integer variable as static and access in any class.Like this
class A{
static int a;
}
You can access in another class like this.
class B{
int b = A.a;
}

Android passing ArrayList via Bundle [duplicate]

I am trying to pass my own custom object into a bundle:
Bundle b = new Bundle();
STMessage message = (STMessage)a.getAdapter().getItem(position);
b.putObject("message",message);
I get the error:
The method putObject(String, Object) is undefined for the type Bundle
One way is to have your custom object implement the Parcelable interface and use Bundle.putParcelable/Bundle.getParcelable
Model Class
package com.sam.bundleobjectpass;
import java.io.Serializable;
/**
* Created by Samir on 31.8.2016.
*/
public class Model implements Serializable {
private String name;
private String surName;
private int age;
public Model(String name, String surName, int age) {
this.name = name;
this.surName = surName;
this.age = age;
}
public String getName() {
return name;
}
public String getSurName() {
return surName;
}
public int getAge() {
return age;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Model model = new Model("Sam", "Sami",32);
Intent i = new Intent(MainActivity.this, ReceiverActivity.class);
i.putExtra("Editing", model); // sending our object. In Kotlin is the same
startActivity(i);
}
}
ReceiverActivity
public class ReceiverActivity extends Activity {
TextView txt_name;
TextView txt_surname;
TextView txt_age;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
txt_name = (TextView)findViewById(R.id.txt_name);
txt_surname = (TextView)findViewById(R.id.txt_surname);
txt_age = (TextView)findViewById(R.id.txt_age);
// receiving our object
Model model = (Model) getIntent().getSerializableExtra("Editing");
txt_name.setText(model.getName());
txt_surname.setText(model.getSurName());
txt_age.setText(""+model.getAge());
}
}
// Kotlin
val model: ProgramModel? = intent.getSerializableExtra("Editing") as ProgramModel?
model?.let { // means if not null or empty
txt_act_daily_topic.text = it.title
}
Since using Parsable is designed for high performance IPC transport as mentioned in some of the comments, I tried using a different approach.
My approach uses GSON library by google.
Example
public class Person{
private String name;
private int age;
// Getter and Setters omitted
}
You can have a method in utility class that returns Gson instance, this is for the sake of clean code and organisation. I will use GsonBuilder incase someone what to register custom adapter.
public class Utils {
private static Gson gson;
public static Gson getGsonParser() {
if(null == gson) {
GsonBuilder builder = new GsonBuilder();
gson = builder.create();
}
return gson;
}
}
Moment of truth!
PUT
Bundle args = new Bundle();
String personJsonString = Utils.getGsonParser().toJson(person);
args.putString(PERSON_KEY, personJsonString);
GET
Bundle args = getArguments();
String personJsonString = args.getString(PERSON_KEY);
Person person= Utils.getGsonParser().fromJson(personJsonString, Person.class);
Currently I don't know the performance limitation of this approach. But it works just fine
Make your custom object Parcelable or Serializable then use putParcelable or putSerializable.
Depending on the complexity of your object one or other may be easier.
As Ryan stated. Also if you only want to pass one object on a soft kill consider using onRetainConfigurationInstance and getLastNonConfigurationInstance to pass the serializable object. The entire object tree must be serializable. If you are passing the object via an intent, consider refactoring the object code to a Parceable code later, once the architecture has stabilized. Finally, consider using the fully qualified name of the class when storing the object into the Bundle as in:
inPWState= (PasswordState) getIntent().getSerializableExtra("jalcomputing.confusetext.PasswordState");
Hope that helps.
JAL
It's work
if you make your object class as Serializable
class your_data_class implements Serializable

sending string value from classes extending BaseAdapter to Overlay

i am writing a code where i get a string value in a class that extends BaseAdapter. I want this value to be used in another class that extends an Overlay. If my class extends an Activity i can use intent,putstring() and getString, but is to be used for these above specified classes..Can anyone tell me how can i do this. Thanks in advance.
You can either make your variable global or make a singleton FileHelper class that contains values you want to pass between classes.
MyClass:
public String myString = "Hello";
and if you want to use it in
OtherClass:
String myString = MyClass.myString;
If your the FileHelper use this:
public class FileHelper {
private static FileHelper instance;
private String myString;
private FileHelper() {
}
public static FileHelper getInstance() {
if (instance == null) {
instance = new FileHelper();
}
return instance;
}
public void setMyString(String s){
myString = s;
}
public String getMyString(){
return myString();
}
}
You can use the FileHelper with this:
private static FileHelper fileHelper = FileHelper.getInstance();
fileHelper.setString("hello");
String myString = fileHelper.getMyString();

Categories

Resources