Some of my code is not executing in android studios? [duplicate] - java

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 6 years ago.
In the program below used for an android app in android studios, When getPercent() from the second class(Main2Activity) is invoked, it always returns 999(the default value), and the,
ttper = .....;
statement from the main class in the onClick() is never executed. Is there any specific reason for this? Can you guys point it out please!
This is the main activity,
public class MainActivity extends AppCompatActivity {
float i1m,i2m,mm,atp,assp;
float ttper=999;
boolean b=false;
EditText i1,i2,model,assignment,attendence;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context cont = this;
final Intent intent = new Intent(cont, Main2Activity.class);
b1=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//try {
i1=(EditText)findViewById(R.id.int1);
i2=(EditText)findViewById(R.id.int2);
model=(EditText)findViewById(R.id.mod);
assignment=(EditText)findViewById(R.id.assign);
attendence=(EditText)findViewById(R.id.attend);
i1m = Float.parseFloat(String.valueOf(i1.getText()));
i2m = Float.parseFloat(i2.getText().toString());
mm = Float.parseFloat(model.getText().toString());
assp = Float.parseFloat(assignment.getText().toString());
atp = Float.parseFloat(attendence.getText().toString());
ttper = ((i1m / 10) + (i2m / 10) + ((mm / 100) * 15) + (assp) + ((atp >= 75.0f) ? ((atp - 75) / 5) : 0.0f));
//setValues();
startActivity(intent);
//}
//catch (Exception e) {
// Log.e("app crash",e.getMessage());
//}
}
});
}
/*void setValues()
{
/* i1m = Float.parseFloat(String.valueOf(i1.getText()));
i2m = Float.parseFloat(i2.getText().toString());
mm = Float.parseFloat(model.getText().toString());
assp = Float.parseFloat(assignment.getText().toString());
atp = Float.parseFloat(attendence.getText().toString());*/
}/*
float getPercent()
{
//float ttper=50.0f;
return ttper;
}
}
This is the second activity,
public class Main2Activity extends AppCompatActivity {
float tper=1.0f;
String str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView v1 = (TextView) findViewById(R.id.textView11);
MainActivity m1 = new MainActivity();
//m1.setValues();
//try {
str = String.valueOf(m1.getPercent()) + "%";
v1.setText(str);
//}
//catch (Exception e) {
// Log.e("app crash",e.getMessage());
//}
}
}

it can not work. If you create new MainActivity(), your ttper will be 999.
You should pass data between Activities in this way:
Put the new calculated ttper into Intent: intent.putExtra("ttper", ttper );
Then in MainActivity2 use getIntent().getFloatExtra("ttper", 999.0f);

You have an instance of MainActivity which has a variable ttper. You modify that value.
Then in another class Main2Activity you create a NEW instance of MainActivity and try to get that value, but ttper has the default value because this is a NEW instance and it hasn't been modified yet.
What you can do is defining ttper as static:
static float ttper=999;
You can even define your function getPercent() as static so you don't have to create a new instance of this class to get the value. You would just call MainActivity.getPercent().
For more information, read:
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Anyway, this is not the correct way of passing data from one activity to another. You should follow this guidelines: https://developer.android.com/training/basics/firstapp/starting-activity.html

You should use extras on intents to pass data between activies.

Related

How to display many variables in one textView

I'm working on my first project in Android Studio and I got stuck in "how to display different variables in one textView". to be more clear I'm working on an app that requires the user to enter the gender. each gender has its own calculation method. so I want to display the result calculation the user do in the main interface and In one TextView. I've tried many times to do it but the result is "0.0"
I added another textView and assigned each calculation method to one textview I was able to display the two results.
public class Main_Interface extends AppCompatActivity implements View.OnClickListener{
private TextView results;
//private TextView fResults;//this is the second textview that I created.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
//fResults = (TextView)findViewById(R.id.fResults);
// if(fResults.getText().toString().equals("0.0")){
// fResults.setVisibility(View.INVISIBLE );
// }
calculateMale();
calculateFemale();
}
public void calculateMale(){
SharedPreferences s = getSharedPreferences("data", Context.MODE_PRIVATE);
double weight = s.getFloat("weight",0.0f);
double height = s.getFloat("height",0.0f);
int age = s.getInt("theDate", 0);
double results2 = 66+(13.7*weight)+(5*height)-(6.8*age);
results.setText(""+results2);
public void calculateFemale(){
SharedPreferences s1 = getSharedPreferences("data", Context.MODE_PRIVATE);
double fWeight = s1.getFloat("fWeight",0.0f);
double fHeight = s1.getFloat("fHeight",0.0f);
int Fage = s1.getInt("theDate", 0);
double results3 = 655 + (9.6 * fWeight) + (1.8 * fHeight) - (4.7 *Fage)
;
fResults.setText(""+results3);
SharedPreferences.Editor editor = s1.edit();
editor.putFloat("results", (float) results3);
editor.commit();
}
}
displaying the calculation in one textview.
You Are calling these two methods before checking these two methods
calculateMale();
calculateFemale();
in onCreate() {
//do this
calculateMale();
calculateFemale();
//Then check the result to make results visible or invisible.
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
You just need to make it clear when the function is being called. What actually happening here is you are checking textView's value even before calculating your required values. So it is throwing 0.0.
Simply call calculateMale(); calculateFemale(); before checking textView's value.
You are printing results before calling the two function. Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
calculateMale();
calculateFemale();
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
Return the result from calculateMale() and calculateFemale() methods:
String calculateMale = calculateMale();
String calculateFemale = calculateFemale();
results = (TextView)findViewById(R.id.results);
String result = calculateMale.concat(calculateFemale);
if (result.length() >= 0) {
results.setText(result);
} else {
results.setVisibility(View.INVISIBLE);
}

Losing data when sending between two classes

My app doesn't display anything when passing data from one class to another. I located through with the debugger that my ArrayList doesn't get the right value from the class.
I'm sending data with the following function:
public class Adaugare extends AppCompatActivity {
private ListView myListView;
private NumeAdapter numeAdapter;
String inume;
int ivarsta;
Intent intent = new Intent();
private ArrayList persoanaArrayList = new ArrayList<>();
public ArrayList getPersoanaArrayList() {
return persoanaArrayList;
}
public int getPersoanaArrayListsize() {
return persoanaArrayList.size();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adaugare);
myListView = (ListView) findViewById(R.id.persoana_list);
Button btn_fin = (Button) findViewById(R.id.btn_fin);
btn_fin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText nume_edit_text = (EditText) findViewById(R.id.ins_nume);
EditText varsta_edit_text = (EditText) findViewById(R.id.ins_var);
ivarsta = Integer.parseInt(varsta_edit_text.getText().toString());
inume = nume_edit_text.getText().toString();
persoanaArrayList.add(new Persoana(inume, ivarsta));
}
});
}
}
And recieving it with:
public class Afisare extends AppCompatActivity {
ListView myListView;
NumeAdapter numeAdapter;
Adaugare ad = new Adaugare();
int cate;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afisare);
myListView = (ListView) findViewById(R.id.persoana_list);
ArrayList<Persoana> persoanaArrayList = new ArrayList<Persoana>(ad.getPersoanaArrayList());
numeAdapter = new NumeAdapter(this, persoanaArrayList);
myListView.setAdapter(numeAdapter);
}
The class Persoana is:
public class Persoana {
private String nume;
private int varsta;
Persoana(String inume, int ivar) {
this.nume = inume;
this.varsta = ivar;
}
public String getNume() {
return nume;
}
public int getVarsta() {
return varsta;
}
public void setNume(String nume) {
this.nume = nume;
}
public void setVarsta(int varsta) {
this.varsta = varsta;
}
}
Persoana is the main class, everything is saved in it. ad is an object of Adaugare, Adaugare being the class from which I've taken the code for getPersoanaArrayList. At debugging some values appeared at ad, namely Adaugare #4556, and persoanaArrayList remains null.
I need the persoanaArrayList so that i can initialize my Adapter and listView. Everything else in the code seems fine from step by step testing with debugger.
Your problem is with the following line in the Afisare class:
Adaugare ad = new Adaugare();
You can't simply new one activity from another activity and expect to access a shared list between them. To share instance data between java objects you need a reference to the other object. Creating a new instance will create a new empty list. That's why you are "losing" data. A quick fix would be to make the list static so it can be accessed from any instance.
But since you're dealing with Android, the right way to share data between activities is by using intent extras. The first activity starts the second activity via an intent. The first activity places the desired data in the intent as extras. The second activity uses getIntent() and the various methods on Intent to access the extras.
One last tip, in Android, you never use the new operator with Activities. Activities are created by the system to service an intent. If you find yourself using the new operator, that's a sign that you're doing something wrong.

How to receive data from one activity to another - android

I'm trying to send an integer from one activity to another in Android studio. In my source class I have sent the data using putExtra() and in the recipient class, I am trying to receive it using getIntent(). However, I get the error 'Could not resolve method 'getIntent()' in the recipient class. Here is my code:
I'm a total newbie to Android studio as well as Java so if I'm missing something really obvious, please be considerate.
Source Activity:
public class AugmentedImageActivity extends AppCompatActivity {
private ArFragment arFragment;
private ImageView fitToScanView;
// Augmented image and its associated center pose anchor, keyed by the augmented image in
// the database.
private final Map<AugmentedImage, AugmentedImageNode> augmentedImageMap = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);
fitToScanView = findViewById(R.id.image_view_fit_to_scan);
arFragment.getArSceneView().getScene().addOnUpdateListener(this::onUpdateFrame);
}
#Override
protected void onResume() {
super.onResume();
if (augmentedImageMap.isEmpty()) {
fitToScanView.setVisibility(View.VISIBLE);
}
}
/**
* Registered with the Sceneform Scene object, this method is called at the start of each frame.
*
* #param frameTime - time since last frame.
*/
private void onUpdateFrame(FrameTime frameTime) {
Frame frame = arFragment.getArSceneView().getArFrame();
// If there is no frame or ARCore is not tracking yet, just return.
if (frame == null || frame.getCamera().getTrackingState() != TrackingState.TRACKING) {
return;
}
Collection<AugmentedImage> updatedAugmentedImages =
frame.getUpdatedTrackables(AugmentedImage.class);
for (AugmentedImage augmentedImage : updatedAugmentedImages) {
switch (augmentedImage.getTrackingState()) {
case PAUSED:
// When an image is in PAUSED state, but the camera is not PAUSED, it has been detected,
// but not yet tracked.
int value=augmentedImage.getIndex();
Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
i.putExtra("key",value);
startActivity(i);
String text = "Detected Image " + augmentedImage.getIndex();
SnackbarHelper.getInstance().showMessage(this, text);
break;
case TRACKING:
// Have to switch to UI Thread to update View.
fitToScanView.setVisibility(View.GONE);
// Create a new anchor for newly found images.
if (!augmentedImageMap.containsKey(augmentedImage)) {
AugmentedImageNode node = new AugmentedImageNode(this);
node.setImage(augmentedImage);
augmentedImageMap.put(augmentedImage, node);
arFragment.getArSceneView().getScene().addChild(node);
}
break;
case STOPPED:
augmentedImageMap.remove(augmentedImage);
break;
}
}
}
}
Recipient activity:
public class AugmentedImageNode extends AnchorNode {
private static final String TAG = "AugmentedImageNode";
// The augmented image represented by this node.
private AugmentedImage image;
private static CompletableFuture<ModelRenderable> ulCorner;
public AugmentedImageNode(Context context) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int value = extras.getInt("key");
if (value == 0) {
// Upon construction, start loading the models for the corners of the frame.
if (ulCorner == null) {
ulCorner =
ModelRenderable.builder()
.setSource(context, Uri.parse("models/tinker.sfb"))
//.setSource(context, Uri.parse("models/borderfence-small2.sfb"))
.build();
}
}
}
#SuppressWarnings({"AndroidApiChecker", "FutureReturnValueIgnored"})
public void setImage(AugmentedImage image) {
this.image = image;
// If any of the models are not loaded, then recurse when all are loaded.
if (!ulCorner.isDone())// || !urCorner.isDone() || !llCorner.isDone() || !lrCorner.isDone())
{
CompletableFuture.allOf(ulCorner)//, urCorner, llCorner, lrCorner)
.thenAccept((Void aVoid) -> setImage(image))
.exceptionally(
throwable -> {
Log.e(TAG, "Exception loading", throwable);
return null;
});
}
// Set the anchor based on the center of the image.
setAnchor(image.createAnchor(image.getCenterPose()));
// Make the 4 corner nodes.
Vector3 localPosition = new Vector3();
Node cornerNode;
localPosition.set(-0.0f * image.getExtentX(), 0.1f, +0.5f * image.getExtentZ());
cornerNode = new Node();
cornerNode.setParent(this);
cornerNode.setLocalPosition(localPosition);
cornerNode.setLocalRotation(Quaternion.axisAngle(new Vector3(-1f, 0, 0), 90f));
cornerNode.setRenderable(ulCorner.getNow(null));
}
private void setLocalRotation() {
}
public AugmentedImage getImage() {
return image;
}
}
getIntent() method are only available in class which extends the activity[directly or indirectly]
Here is code how to use share preference in your scenario.I hope it will help you.
Instead of below code
Intent i = new Intent(AugmentedImageActivity.this, AugmentedImageNode.class);
i.putExtra("key",value);
startActivity(i);
Use this one
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putInt("Key", "int value");
editor.commit();
And retrieve preference value on your AugmentedImageNode screen using below code
SharedPreferences settings = getSharedPreferences("MyPref", MODE_PRIVATE);
int snowDensity = settings.getInt("Key", 0); //0 is the default value
remove the first three lines of your AugmentedImageNode(Context context) in recipient activity and replace it with following
int value = getIntent().getIntExtra("key",0);
where 0 is just default value.
getintent is working if you are extent Activity and AppCompatActivity
for example:
MainActivity.java
choice_a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
//putExtra(key name,default value);
intent.putExtra("int_key",22);
startActivity(intent);
}
});
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//get intent values
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int value = extras.getInt("int_key");
Log.e("Int_Value", "" + value);
// another way
int i = getIntent().getIntExtra("int_key", 0);
Log.e("Int_Value", "" + i);
}
}
In your code you have extend AnchorNode

Cannot pass an Integer in an Intent [duplicate]

This question already has an answer here:
How to receive an int through an Intent
(1 answer)
Closed 4 years ago.
I'm trying to pass an Integer (from an edittext) to another activity through an intent.
When the user clicks a button, the text in the edittext will transform into a string and then into an int, then the int will be sent through an intent to another activity, but i have to use the int after that.
Here the activity sending the intent:
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext = (EditText) findViewById ( R.id.texthome );
Button buttone = (Button) findViewById(R.id.buttone);
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Here the activity receiving it:
public class GuessOne extends ActionBarActivity {
int randone;
int contone;
int wall = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_guess_one);
wall = getIntent().getIntExtra("maxPressed", -1);
randone = (int) (Math.random()*10+1);
contone = 0;
}
Here i'm using it:
public void guessone (View view){
contone++;
textcontone.setText(getString(R.string.attempts) + "" + contone);
if (contone >= wall ){
resultaone.setText("You Failed" + " " + wall);
Toast.makeText(this, "You Failed", Toast.LENGTH_LONG).show();
}
When i use the app, the value of the int is always -1. Where i am wrong.
You can't use findViewById without setting the xml to the activity. That means you need to use findViewById method only after you have called setContentView.
Also you need to read the EditText text value once you click on the button otherwise it always will be null/empty.
Do this
public class HomeActivityPro extends ActionBarActivity {
private InterstitialAd interstitial;
EditText conttext;
Button buttone;
String maxom;
int maxam = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
View.OnClickListener maxim = new View.OnClickListener() {
#Override
public void onClick (View view) {
maxom = conttext.getText().toString();
maxam = Integer.parseInt(maxom);
Intent wall = new Intent(HomeActivityPro.this, GuessOne.class);
wall.putExtra("maxPressed", maxam);
startActivity(wall);
}
};
buttone.setOnClickListener(maxim);
Problem 1
Put this in the on click listener instead:
String maxom = conttext.getText().toString();
int maxam = Integer.parseInt(maxom);
You want the values to be read at the time you click the button not when you open the activity, correct?
Problem 2
The following needs to be after setContentView in onCreate:
conttext = (EditText) findViewById ( R.id.texthome );
buttone = (Button) findViewById(R.id.buttone);
Keep the declarations where they are. Just the declarations:
EditText conttext;
Button buttone;
Note
Follow the same pattern in all your activities. Declare views as field variables, assign them in onCreate after setContentLayout. Get the values at the time they're needed.
public int getIntExtra (String name, int defaultValue)
Added in API level 1 Retrieve extended data from the intent.
Parameters name The name of the desired item. defaultValue the value
to be returned if no value of the desired type is stored with the
given name. Returns the value of an item that previously added with
putExtra() or the default value if none was found. See Also
putExtra(String, int)
This means that no int was found when you called getIntExtra(valueName, defaultValue); so the default value was chosen.
You should check to see what your maxam value is before you call the new activity.
In the activity you receive it:
wall = getIntent().getIntExtra("maxPressed");
SOLVED: by getInt and String.valueOf
private static final String IMGID = "ImgID";
if (getIntent().getExtras().containsKey(IMGID)) {
//Picasso.with(this).load(getIntent().getExtras().getString(IMG)).into(mImg);
Picasso.with(this).load(getIntent().getExtras().getInt(String.valueOf(IMGID))).into(mImg);
}

Android: Passing int value from one activity to another

I'm struggling to figure out why I can't pass an int value from one activity to another. The app will ask you to press a button to generate a random number from 1-100 which will be displayed below the button. There is also another button which will open a new activity simply showing the random number that was rolled... but I just get 0.
I've looked into similar questions asked but to no avail.
Here's my code from MainActivity
public class MainActivity extends ActionBarActivity {
int n;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonRoll(View view) {
TextView textRoll = (TextView) findViewById(R.id.textview_roll);
Random rand = new Random();
n = rand.nextInt(100) + 1;
String roll = String.valueOf(n);
textRoll.setText("Random number is " + roll);
}
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
startActivity(getStats);
}
public int GetNumber (){ return n; }
}
Heres my 2nd class.
public class Stats extends Activity {
MainActivity statistics = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = statistics.GetNumber();
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
}
Is using getters the wrong way to get data from another class when using activities? Thanks for your time.
You should pass your data as an extra attached to your intent. To do this you need to first determine a global key to be used. You could do something like this in your MainActivity
public static final String SOME_KEY = "some_key";
then modify your OpenStats method to
public void OpenStats(View view) {
Intent getStats = new Intent(this, Stats.class);
getStats.putExtra(SOME_KEY, n);
startActivity(getStats);
}
and then in Stats.class onCreate method
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
int n = getIntent().getIntExtra(MainActivity.SOME_KEY, -1);
TextView tvStats = (TextView) findViewById(R.id.passedNumber_textview);
String number = String.valueOf(n);
tvStats.setText(number);
}
You obviously should make sure that you are calling ButtonRoll at least once or that you set n so that you aren't passing a null int.
Also, as note, convention states that methods should use lower camel case formatting. That is, the first word is completely lower case and the first letter of subsequent words is upper case. That would change your methods
OpenStats() -> openStats()
ButtonRoll() -> buttonRoll()
Classes/objects are upper camel case, just to help avoid confusion.

Categories