Using a variable which has been changed in an if statement - android

I built two activities and the MainActivity is passing some variables to the activity "Calculation". This works as intended and the variables are submitted and received correctly. I now want to create the integer "size_int" depending on the values of the intent "size". The problem occurs in this line:
debug1.setText(size_int);
Eclipse tells me that I should create a local variable with the name "size_int". I do not understand why "size_int" can not be used in this line because it has been defined in the if statement before. Do you have any ideas on that? I assume it has something to do that the variable "size_int" is being defined in the if statement but I am not sure.
Here is the full code:
package com.example.eggtimer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class Calculation extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculation);
// get Intents (Size, Temperature and yolk from Main Activity)
String size = getIntent().getExtras().getString("size");
String temperature = getIntent().getExtras().getString("temperature");
String yolk = getIntent().getExtras().getString("yolk");
if (size.equals("Small")) {
int size_int = 30;
}
// Debug Variables
TextView debug1 = (TextView) findViewById(R.id.textViewDebug1);
debug1.setText(size_int);
}
}

Change like below. This is because if you declare inside the braces, the scope is restricted, so you need to increase scope by declaring outside
int size_int = 0;
if (size.equals("Small")) {
size_int = 30;
}

You need to read about concept called "variable scope". In general, variable declared in code block is local to that code block and is NOT visible outside. Therefore you should declare your size_int outside your if():
int size_int = 0;
if (size.equals("Small")) {
size_int = 30;
}
In general, variables declared outside code blocks are visible in the blocks, while variables declared inside code block are local to that code block.

Related

Creating Object from other class

I have a settings screen where you can choose between, add and remove configurations for the app.
When adding a configuration, I create a new Instance of a inputBox Class (extending the settings activity class - where I stored the procedure for the standard android text input box) to query the name for the new configuration.
In the Onclick of this inputbox a procedure from the superClass (the settings-activity) is called to create a new configuration object.
This Procedure queries some things from the activity (e.g. selected spinner element) including the progress of a seekBar.
This is where I get a NPE:
java.lang.NullPointerException: Attempt to invoke virtual method'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
The same object creation procedure is also called on initialization of the app and works just fine.
I understand from the Error that the issue is that when calling the procedure from a child class the reference of the variables to the corrseponding elements of the screen is not set anymore - and therefore cannot be queried.
So the question:
How can I query values of activity elements, when the procedure is called from another class?
I know that the topic is quite broad, but I can't figure it out for a couple of days now
Thanks for your help in advance.
Here is a scheme of the problem:
public class Settings extends AppCompatActivity{
Context settingsContext = this;
private Spinner someSpinner;
//other elements
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
someSpinner = (Spinner) findViewById(R.id.someView);
//other elements
addNewConfig.setOnClickListener((v) --> {
inputBox inputBox = new inputBox("OK", "Cancel", settingsContext, "sourcePath",1,1);
newConfigName = inputBox.show();
});
public sSetting makeNewConfig(String name, String sourcePath, int dataFrom, int dataTo){
sSetting newConfig;
newConfig = new sSetting("NAME", someSpinner.getProgress()>0, ...);
return newConfig;
}
}
And the inputBox:
public final class inputBox extends Settings {
//someVars
inputBox(String buttonOk, String buttonCancel, Context setContext, String sourcePath, int dataFrom, int dataTo){
//variable setters
}
private String show() {
//show msgbox
//onclick ok
super.makeNewConfig(....);
}
For solving the problem I restructured my Project a little:
I removed the inputBox-Part, which, after some research considered for a too complicated solution for what I needed anyway.
However: I now added a editText to my Settings View.
Although I had to change my Settings view for this, it now looks better and it was ridiculously easy to edit the configuration name for the user.
I think in most cases that will do the trick. Adding Popup-Boxes just needs more error handling and makes the design more complicated
I hope this helps ;)
If you need the code for it it is available here:
GitHub - AIM

Android Passing Variable doesn't seem to click

I have created a random number and would like to pass it along to use in the same file just different class. Please help:
public void Start() {
int number = random.nextInt(3); // Gives a number such that 0 <= number < 2
then a few lines down I try to use number but it's telling me it's not a variable to use:
public void renderBackground(Canvas canvas) {
//TODO: you may wish to change background colors from here
if(number=="0") {
any kind of help is great appreciated!
The problem you are facing is because of the scope of variable number. I'm not sure you are using inner class or a separate class.
If it's a inner class, then declare the number at top of the first class like,
class Firstclass
{
public int number; // scope is public it can be accessed anywhere in class
method();
...
...
class Secondclass
{
method()
{
System.out.println("Your number is : " + number); // here you are accessing variable `number`
}
}
}
Also, try to change
if(number=="0") {
to
if(number==0) {
I think the problem is you are initializing 'number' inside a class, not the main class.
initialize number inside the main class then modify it in your method. ex:

Static Keyword , Reinstallation Required

In my application I have an Activity" Model" in which i get a value 'n' from an edit text , I have declared this value n as static int . So , that i can access it inside any class of the Application.
The problem is that when I restart my application without reinstalling it , the value of 'n' remains the same as it was in the first case . And this affects my output.
I cannot use intent to send values because , the value is accessed randomly in the application even in classes that are not activities.
Can u please tell , where I m wrong.??
package com.integrated.mpr;
import java.io.File;
import android.app.Activity;
import android.app.Dialog;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Model extends Activity implements OnClickListener{
EditText etPos;
Button bmodel;
static int n;//static variable to be used in other classes
File folder ;
File subfolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.inputpage);
etPos = (EditText) findViewById(R.id.etpos);
bmodel = (Button) findViewById(R.id.bModel);
bmodel.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bModel:
String check = etPos.getText().toString();
String check1 = etNs.getText().toString();
n = Integer.parseInt(check);
Intent openAlternative = new Intent("com.integrated.mpr.ALTERNATIVE");
startActivity(openAlternative);
break;
}
}
}
If i first install my app , and enter value in the edittext as 2 , the value of n =2 ; If second time i run my app without installing it , even if i enter 3 in the edittext , value of n remains 2
Where is the twist??
Kumar,
The behavior you are seeing is the result of using a static member. static members do not require an instance and are therefore set upon first access (regardless of whether an instance was created or not) and stays in memory until Android decides it is no longer valid. In essence, it is doing exactly what it was supposed to. The proper use of static variables is a topic of extensive discussion among veteran and novice programmers alike, but essentially always leads to "be choosy about where and how you use static members".
That said, your need to access this from another component is a common problem, however, and there are a number of ways to solve it. If you need to have each instance have a different value, then it should not be static. Instead you will have to find a way to pass the instance of the Activity.
If each instance need not be different, but the value need to change according to some other parameter, simply find the appropriate place to change the value. If you can access it from anywhere in your application, you may also change it from anywhere in your application.
Solution 1: Passing by Intent
This solution is useful when the information is subject to change and must be sent to another component and the classes that it uses exlusively. You may pass virtually any value via an Intent extra.
openAlternative.putExtra("MyValue", Integer.parseInt(check));
In your responding component, you may retrieve the value by:
Intent myIntent = getIntent();
int n = myIntent.getIntExtra("MyValue", 0); //0 is the default if no value is sent.
From here, you may easily pass the retrieved value to any class being utilized by that component. An example:
MyClass.setN(n);
Solution 2: Storing outside of the LifeCycle
A safer alternative is to move the value to an extended Application. This is not subject to UI or LifeCycle processing.
public class MyApplication extends Application
{
static int n;
}
Adjust your AndroidManifest.xml...
<application android:name=".MyApplication" ... >
<!-- All of your components -->
</application>
Now, you can set the variable this way:
MyApplication.n = Integer.parseInt();
And you can get it by
int myN = MyApplication.n;
This solution has gotten me through many a troubled day. However, it should really be used for non-instance related data.
Solution 3: The REALLY UNSAFE method
This solution only works if you can guarantee a single instance of the component. This requires that singleTask is set. Be very careful with this
Change n to non-static
int n;
Change Activity to Singleton
static private Model myInstance;
In OnCreate, set myInstance
myInstance = this;
Create a getter:
static public Model getStaticInstance()
{
return myInstance;
}
This is unreliable (at best) and can cause huge memory leaks if not managed correctly.
Hope this helps,
FuzzicalLogic

Android: How to determine on which threads are my methods are running?

I would like to make sure that my methods are running on the threads that I supposed to be ran. For that, would like to add thread's name or id in my logs. In order to check if my methods are running in UIthread, thread1,thread2....threadx.
Problem:
guide me on what I need to set to have the thread's name or id. I am not sure of this, if you have better approach, please share to us on how to differentiate the UI threads to other additional running threads.
guide me on how to log the above mentioned name or id. I have already the logging system. Just want to know the method need to call to obtain the name or id. Maybe, thread.name() or thread.id().
Any guidance is appreciated.
Use ThreadLocal. Actually example in docs exactly what you need:
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueThreadIdGenerator {
private static final AtomicInteger uniqueId = new AtomicInteger(0);
private static final ThreadLocal < Integer > uniqueNum =
new ThreadLocal < Integer > () {
#Override protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};
public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator
If you want, you can pass desired name to Thread and set it to static ThreadLocal variable in the first line in run() method.

Android/Java - How to access a variable declared in another file?

I would like to know if it is possible to access a variable declared in another file. For example:
httpPostFileUpload(client,
"/data/data/fshizzle.com/files/image.jpg",
"http://10.0.2.2/upload.php", "uploaded",
s.getSelectedItem().toString());
Here, I'd like to replace http://10.0.2.2/upload.php with a URL stored in a variable, but with the variable declared in another file. How do I do this in Java?
You can declare in another java file a public static variable which can then be accessed every where else.
For example,
Class1.java
package com.my.app;
public class Class1 {
public static String URL = "http://10.0.2.2/upload.php";
}
Class2.java
package com.my.app;
public class Class2 {
public void Function(){
httpPostFileUpload(client, "/data/data/fshizzle.com/files/image.jpg",
Class1.URL, "uploaded", s.getSelectedItem().toString());
}
}
Class2 can see Class1 because both are in the same package (if they weren't, a simple import Class1; would fix this)
The static keyword means you can use the variable even without having access to an object of the specified class.
Finally, the public keyword allows you to access the variable from outside the class.

Categories

Resources