Give reference to string parameters in outer class method Android - 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);
}
}

Related

Crash appears on a member variable that is null despite Gson converter that never returns null: impossible case

In my Activity, I have a Training object member initialized during onCreate(). All the members of this object are set.
private Training mTraining; is a class member
public class Training extends BaseModel {
...
#SerializedName("state")
public TrainingState state;
....
public TrainingPreview() {
}
This object is got from server (JSON), and I had a converter on this state to ensure this enum can't be null (I use GSON engine):
public class TrainingStateConverter extends EnumConverter<TrainingState> {
public static final Type TYPE = new TypeToken<TrainingState>() {}.getType();
#Override
protected TrainingState deserialize(String value) {
return TrainingState.fromString(value);
}
#Override
protected TrainingState getUnknownValue() {
return TrainingState.UNKNOWN;
}
}
During the setup, I've created the exercise list with the listener to show a specific exercise:
private void refreshExercisesList() {
final Runnable showTrainingParts = new Runnable() {
public void run() {
int nbItems = mCardExercises.setExercises(mTraining.training, mTraining.state,
new FlatCardTrainingProfilePartExercisesView.OnClickExerciseListener() {
#Override
public void showPart(String trainingPartId, int index) {
onClickOnExercisesList(trainingPartId, index);
}
});
}
};
}
...
}
My onClickOnExercisesList() method:
private void onClickOnExercisesList(String trainingPartId, int index) {
...
switch (mTraining.state) {
...
This Activity code works perfectly since couple of months, but yesterday there was a NullPointerException on switch (mTraining.state) :
int com.xxx.model.training.TrainingState.ordinal()' on a null object reference
com.xxx.ui.training.TrainingActivity.onClickOnExercisesList
How is possible guys?
Thank you very much for your help!
This would occur if state did not appear in the JSON.
The TypeConverter is only used if there is a value in the JSON to convert. If the value isn't present, then there's nothing to convert, so the value is whatever the default is, which is null, because you didn't set it:
#SerializedName("state")
public TrainingState state;
To fix the issue, initialize the variable to a default value:
#SerializedName("state")
public TrainingState state = TrainingState.UNKNOWN;

How to pass data from activity to class

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;
}
}

Unit Testing for private member List<Integer> mTasks in android

I am trying to write unit test cases for below class. Specially, for 'isSumOfTaskWeightIsValid()' method from the below. it has private member involved it. Could you please help writing test cases for that. I find it difficult because of the 'for loop' in that method where it loops over the 'mTasks'. Thanks in advance.
Class TaskCard {
private List<Integer> mTasks = new ArrayList<>();
private boolean mIsGood;
public TaskCard(boolean isGood) { mIsGood = isGood}
public void setUpListofTasks(DataBaseHelper db){
mTasks.addAll(db.getTasks());
}
public boolean isSumOfTaskWeightIsValid(){
int sum = 0;
for(int taskWeight : mTasks)
{ sum += taskWeight;
}
return (sum>0 || mIsGood);
}
}
You can use #Before annotation to fill your mTasks list and then you can call your isSumOfTaskWeightIsValid method. You also need set your mIsGood parameter in your constructor. Here is a sample test class.
private TaskCard taskCard;
#Before
public void initObjects() {
taskCard = new TaskCard(...); //True or False
//Initialize DataBaseHelper here
DataBaseHelper db = new DataBaseHelper();
taskCard.setUpListofTasks(db);
}
#Test
public void testIsSumOfTaskWeightIsValid() {
// Now your list is filled with the value you prove in #Before
assertTrue(taskCard.isSumOfTaskWeightIsValid());
}

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

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;
}

Categories

Resources