Getting NaN error in Android for Global Float - android

I am new to android. I am developing an CGPA App for my college. though many apps are available, I just wanted to do one on my own.
Let me come to the Question..
I want to get all the GPA values to my Main_Activity.java so that i can calculate my CGPA. I used the concept of Global Variables using Application in android. But i get my output as NaN. Though I referred many articles, I cant clear that error. As I need to submit the app to my college I am in need of help..
First i would like to show you my global class..
package com.example.cgpa;
import android.app.Application;
public class global extends Application{
private Float f[]={0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f};
private Float f1[]={0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f};
public Float getfloat(int a){
return f[a];
}
public void setfloat(Float a,int b){
this.f[b]=a;
}
public Float getfloat1(int a){
return f1[a];
}
public void setfloat1(Float a,int b){
this.f1[b]=a;
}
}
This is the place I have used the Global variables in mainactivity.java
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final global x=((global)getApplicationContext());
Float t=0.0f,c=0.0f;
for(int i=0;i<8;i++){
t+=x.getfloat(i);
c+=x.getfloat1(i);
}
final Float g=t/c;
txt.setText("Your CGPA is "+g.toString());
}
});
Also this is the place I have set the values in gpa1.java and like the same way I have used this in other classes.
b.setOnClickListener(new View.OnClickListener() {
Float[] n={4.0f,4.0f,3.0f,3.0f,3.0f,4.0f,2.0f,2.0f,1.0f};
Float t=0.0f;
Float c=0.0f;
#Override
public void onClick(View arg0) {
for(int i=0;i<9;i++){
c+=n[i];
}
for(int i=0;i<9;i++)
{
if(s[i]=="S")
n[i]*=10;
else if(s[i]=="A")
n[i]*=9;
else if(s[i]=="B")
n[i]*=8;
else if(s[i]=="C")
n[i]*=7;
else if(s[i]=="D")
n[i]*=6;
else if(s[i]=="E")
n[i]*=5;
else
n[i]*=0;
}
for(int i=0;i<9;i++){
t+=n[i];
}
Float g=t/c;
final global x=((global)getApplicationContext());
x.setfloat(t, 0);
x.setfloat1(c, 0);
TextView txt=(TextView)findViewById(R.id.textView9);
txt.setText("Your GPA is "+g.toString());}
});
You may also tell me how to get values from other classes as I already used intent and image buttons to move from main activity to other activities.

Thank you friends for your kind advice... I have found what's wrong. it is very silly.. (0/any number)=NaN.. I have just cleared the error using isNaN() method..
Thank you..

Related

I need an efficient way of duplicating an existing activity in Android Studio

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
public int currentQuestion;
public String[] questions;
public String[] answers;
int score = 0;
Button answerButton;
Button questionButton;
Button homeButton;///NEW ****
public TextView questionView;
public TextView answerView;
public EditText answerText;
public TextView scoreText;
public void main() {
questions = new String[]{"Type Yes", "Type No", "Type And", "Type The"}; /*Array of Hard Coded Questions*/
answers = new String[]{"Yes", "No", "And", "The",}; /*Array of Hard Coded Answers to indexed to match the questions*/
currentQuestion = -1; /*This will index the questions to be used*/
answerButton = (Button) findViewById(R.id.AnswerButton);
questionButton = (Button) findViewById(R.id.QuestionButton);
homeButton = (Button) findViewById(R.id.HomeButton);
questionView = (TextView) findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
scoreText = (TextView) findViewById(R.id.ScoreText);
///Check the user inserted answer string against the correct or incorrect answers.... NEEDS VALIDATION....
answerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer();
}
});
///Skips to the next questions
questionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getNextQuestion();
}
});
/// Returns you to the Home screen
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, _MainMenu.class));
}
});
}
public void getNextQuestion() {
//1st question so reset everything
if(currentQuestion == -1)
{
setupQuiz();
}
currentQuestion++;
//Check to see if the end of the questions has been reached
if(currentQuestion == questions.length)
{
endQuiz();
}
else
{
questionView.setText(questions[currentQuestion]);
answerText.setText("");
}
}
public void setupQuiz()
{
score = 0;
answerButton.setVisibility(View.VISIBLE);
questionView.setVisibility(View.VISIBLE);
answerText.setVisibility(View.VISIBLE);
answerView.setText("");
questionButton.setText("Skip Question");
}
public void endQuiz()
{
currentQuestion = -1;
answerButton.setVisibility(View.INVISIBLE);
questionView.setVisibility(View.INVISIBLE);
answerText.setVisibility(View.INVISIBLE);
questionButton.setText("Try Again");
scoreText.setText("Final Score: " + score);
}
public void checkAnswer() ///validaion goes here and not in getnextquestion
{
String answer = answerText.getText().toString();
boolean result = answer.equalsIgnoreCase(answers[currentQuestion]);
//answer is correct
if(result == true) {
score += 10; /* ++ will increment the score by 1, +=10 will increment the score by the value added (10)*/
answerView.setText("Correct!");
}/*answerView, text view set to print the string in the event of the correct answer*/
else //answer was wrong
answerView.setText("Incorrect, The answer was " + answers[currentQuestion]); /*answers[currentQuestion] answers reads the answer to the current question in use */
scoreText.setText("Current Score = "+score);
getNextQuestion();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main();
getNextQuestion();
}
}
I am building a simple Quiz game in Android that currently has a main Menu Activity that links you directly to a quiz activity that will ask you an "x amount of questions". Ultimately I want three difficulty levels for the Quiz. There will be 3 buttons on the home screen that will direct the user to an Easy, Medium or Hard version of the Quiz.
As each activity will be exactly the same other than the actual questions being asked. I was wondering if there is a more efficient way of duplicating the class a couple of times without having to rebuild the user interface and then copy the code into the separate classes.
I attached an example of my code that works perfectly fine so far. The game is very simple and is a learning exercise for me for than anything.
The best way for something like this is to use a single activity.
Every activity makes the application a lot heavier and this is why you usually try to create the smallest number of different activities as possible.
If your pages are pretty much the same you should consider adding a simple value and doing different stuffs based on the value.
On button click, simply add an int value to the intent opening the questions activity (1 = easy, 2 = medium, 3 = hard, or any value you like) with
intent.putExtra("lvl", lvl);
Now, on activity start, call this number retrieving the value from the intent with
int myLvl = getIntent().getIntExtra("lvl", 0);
now simply call a switch:
switch(myLvl){
case 1: doLvl1Stuffs();
break;
case 2: doLvl2Stuffs();
break;
case 3: doLvl3Stuffs();
break;
default: throw new Exception("no lvl found");
break;
Hope this helps, but generally avoid creating more activities than the needed ones
I think the real answer here is the good old "prefer composition over inheritance" mem.
Example: upon "collection" your UI elements; you could create a helper class like
public class QuizButtonManager {
private final Button answerButton;
private final Button questionButton;
private final Button homeButton;
public QuizButtonManager(Button answerButton ... ) {
this.answerButton = answerButton;
...
And then you simply move your setupQuiz() and endQuiz methods into that class.
Then you look into other responsibilities that you have currently forced into your activities. You "cut" them out and put them into distinct classes; thus enabling much simpler "re-use".
The best way is to Create BaseActivity that contains all the Mutual Components and the other activities extend from it and implement their logic
but as you say it's all the same. the difference is the Questions so you don't need to create multiple activities you can use the same activity and set a flag to know what is the current difficulty and set the questions based on it

Android Eclipse changing text on a snake game

How do i go to the next text when my snake eat a food? (When the snake eat the food, the text will change from testing to success.) I'm using the snake game provided by eclipse. This is the code i have done so far. I am doing this for my project so i appreciate all the help i can get.
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Snake extends Activity {
/**
* Constants for desired direction of moving the snake
*/
public static int MOVE_LEFT = 0;
public static int MOVE_UP = 1;
public static int MOVE_DOWN = 2;
public static int MOVE_RIGHT = 3;
private static String ICICLE_KEY = "snake-view";
private SnakeView mSnakeView;
/**
* Called when Activity is first created. Turns off the title bar, sets up the content views,
* and fires up the SnakeView.
*
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.snake_layout);
init();
mSnakeView = (SnakeView) findViewById(R.id.snake);
mSnakeView.setDependentViews((TextView) findViewById(R.id.text),
findViewById(R.id.arrowContainer), findViewById(R.id.background));
if (savedInstanceState == null) {
// We were just launched -- set up a new game
mSnakeView.setMode(SnakeView.READY);
} else {
// We are being restored
Bundle map = savedInstanceState.getBundle(ICICLE_KEY);
if (map != null) {
mSnakeView.restoreState(map);
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Store the game state
outState.putBundle(ICICLE_KEY, mSnakeView.saveState());
}
private int currentQuestion;
private String [] questions;
private TextView questionView;
public void init() {
questions = new String[]{"testing","success"};
currentQuestion = -1;
questionView = (TextView) findViewById(R.id.QuestionTextView);
showQuestion();
}
public void showQuestion() {
currentQuestion++;
if(currentQuestion == questions.length)
currentQuestion =0;
questionView.setText(questions[currentQuestion]);
}
}
After checking out the source code (which I did here: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.2_r1/com/example/android/snake/SnakeView.java), I dont think it's possible to add this functionality without altering the source code...
However, if u want to edit the source to make it work, I would suggest the following:
create an interface to use as a listener
public interface AppleEatenListener{
public void appleEaten(int size);
}
Then add a variable of this interface to the SnakeView class
private AppleEatenListener mAppleEatenListener;
Create a setter in the SnakeView class to set the mAppleEatenListener
public void setAppleEatenListener(AppleEatenListener listener){
this.mAppleEatenListener = listener;
}
After that, make your way down to the updateSnake() method in the SnakeView class and find the following piece of code (consider using ctrl+f (search function)):
This snippet comes from the current source code:
// except if we want the snake to grow
if (!growSnake) {
mSnakeTrail.remove(mSnakeTrail.size() - 1);
}
And here we want to add, that if the snake should grow, we call the AppleEatenListener's function appleEaten(), like so:
// except if we want the snake to grow
if (!growSnake) {
mSnakeTrail.remove(mSnakeTrail.size() - 1);
}
else{
if(mAppleEatenListener != null){
mAppleEatenListener.appleEaten(mSnakeTrail.size());
}
}
Now, we should return to your own Snake class and add the following in onCreate():
mSnakeView.setOnAppleEatenListener(new AppleEatenListener() {
#Override
public void appleEaten(int size) {
showQuestion();
//size is the current size of the snake after the apple was eaten
}
});
Note that I've added that the listener requests a "size" parameter, I'm supposing it could be useful to know the size of the snake after it has eaten an apple, since I didn't see a function for requesting the size of the snake in the API either...
I have not tested this code, but I hope this helps u at least a little

Non-static variable error in android

So I have a main class and another class that has a variable I need to pull out into the main class. I have tried some of the ways posted on the answered questions like this, but I'm still failing to get it right.
public class Example extends MapActivity
{
public void OnCreate(Bundle savedInstanceState){
final Button bttn = (Button)findViewById(R.id.button1);
bttn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast tulos = Toast.makeText(getBaseContext(),
"Area is: "
+MyItemizedOverlay.alue +""
/*I get the non static variable error here
which I get as it is not yet defined, it will be after the user
inputs values into the program*/
,Toast.LENGTH_LONG);
tulos.show();
}
});
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
int alue;
//irreleveant stuff (I assume)
public void Calc(Geopoint gp, Mapview map){
//there's some stuff before the variable I want to get like other variables
//not relevant for my problem I hope
alue = (int)Math.round(*formula: derived from user input data*)
}
}
So how can I get a value out of my other class, as it doesn't seem to be able to get it now? Or is this maybe an indication of a bigger problem?
There are two way
1 - make alue static but that will show the error that satic variable can't be accesses in non static function Calc so either make function Calcalso static as well or go to point 2
2-try this new MyItemizedOverlay().alue with making alue public as below
public class Example extends MapActivity
{
public void OnCreate(Bundle savedInstanceState){
final Button bttn = (Button)findViewById(R.id.button1);
bttn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast tulos = Toast.makeText(getBaseContext(),
"Area is: "
+new MyItemizedOverlay().alue +"" /<--------------------
/*I get the non static variable error here
which I get as it is not yet defined, it will be after the user has input
values into the program*/
,Toast.LENGTH_LONG);
tulos.show();
}
});
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
public int alue; /<--------------------
//irreleveant stuff (I assume)
public void Calc(Geopoint gp, Mapview map){
//there's some stuff before the variable I want to get like other variables
//not relevant for my problem I hope
alue = (int)Math.round(*formula: derived from user input data*)
}
There is no access modifier for int alue means it is default.
Make it public int alue to be accessible from other classes.
Have a Look At Controlling Access to Members of a Class

How to activate Text-To-Speech when clicked on TextView?

the question is as above.
scenario : i programmatically created table rows with text view in it. i wanted to allow text-to-speech when i clicked on the textview. there is some reason for not using listview. i tried to use button for easier usage, however the button that i created is always out of the dimension that gave. so, i wanted to use textview to activate the TTS.
how do i do that ?
i tried using
tv.setOnClickListener(new OnClickListener()
{
public void OnClick(View v)
{
String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null);
}
});
i uses for-loop for it, so that it will create a table row for every data collected. the problem is, it requested the "i" to be final. and when i made it final, i cant use i++.
please help. thanks alot =)
Try to declare your int i; in your class. I believe this will help you to avoid of using final modifier.
public class MyActivity extends Activity {
int i;
public void onCreate(Bundle savedInstanceState) {
...
tv.setOnClickListener(new OnClickListener()
{
public void OnClick(View v){
String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null);
}
});
...
}
}
or put this code String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null); to another method. for example:
tv.setOnClickListener(new OnClickListener()
{
public void OnClick(View v){
speak();
}
});
__
public void speak(){
String speech = list.get(i).toString();
tts.speak(speech,TextToSpeech.QUEUE_FLUSH,null);
}

onCreate method variables unaccessible?

I'm still struggling to find a clean easy way to load some values in my onCreate method and pass them to another class in order that a game may load and save option settings.
I can successfully retrieve and change values from my other class but the problem is, no matter what I try, variable set in the onCreate method will not carry to the rest of the code.
I take the point that by only showing snipits of the code I may have obscured the problem but my original is far to massive and sprawling to post HOWEVER it was based on a great tutorial by Martin
http://www.droidnova.com/android-3d-game-tutorial-part-i,312.html
So I've returned to first principles and just added the problematic portion to that tutorial code and my problem has been replicated. So here is the complete code:
Vortex.java **
package com.clockworkrobot.vortex;
import android.app.Activity;
import android.os.Bundle;
public class Vortex extends Activity {
private static final String LOG_TAG = Vortex.class.getSimpleName();
private VortexView _vortexView;
private float _red ; // these are the values that actually reach VortexRender class
private float _green = 1f ; // touch the screen, it will turn green.
private float _blue ; // but why don't the variable in my onCreate override these?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_red = 1f; // The test values I want to reach my Vortex Renderer class.
_green = 0f; // to help debug. they should make the screen magenta
_blue = 1f; // Eventually these value will be loaded during onCreate
setRed(_red); // I don't think these are needed
setGreen(_green); // But since the variable within this method
setBlue(_blue); // don't appear to be reaching their target..worth a try
_vortexView = new VortexView(this);
setContentView(_vortexView);
}
public float getRed() {
return _red;
}
public void setRed(float value) {
_red = value;
}
public float getGreen() {
return _green;
}
public void setGreen(float value) {
_green = value;
}
public float getBlue() {
return _blue;
}
public void setBlue(float value) {
_blue = value;
}
}
VortexRender.java**
package com.clockworkrobot.vortex;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
public class VortexRenderer extends Activity implements GLSurfaceView.Renderer {
private static final String LOG_TAG = VortexRenderer.class.getSimpleName();
// Vortex sw = new Vortex();
private Vortex sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sw = new Vortex();
}
private float _red = 0f;
private float _green = 0f;
private float _blue = 0f;
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Do nothing special.
}
#Override
public void onSurfaceChanged(GL10 gl, int w, int h) {
gl.glViewport(0, 0, w, h);
}
#Override
public void onDrawFrame(GL10 gl) {
// define the color we want to be displayed as the "clipping wall"
gl.glClearColor(_red, _green, _blue, 1.0f);
// clear the color buffer to show the ClearColor we called above...
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
public void setColor(float r, float g, float b) {
_red = sw.getRed(); // Want these to grab the values from my onCreate method
_green = sw.getGreen(); // But instead it's getting the nul values
_blue = sw.getBlue(); // eg values as set above me onCreate.
// _red = r;
// _green = g;
// _blue = b;
}
}
VortexView.java**
package com.clockworkrobot.vortex;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
public class VortexView extends GLSurfaceView {
private static final String LOG_TAG = VortexView.class.getSimpleName();
private VortexRenderer _renderer;
public VortexView(Context context) {
super(context);
_renderer = new VortexRenderer();
setRenderer(_renderer);
}
public boolean onTouchEvent(final MotionEvent event) {
queueEvent(new Runnable() {
public void run() {
_renderer.setColor(event.getX() / getWidth(), event.getY() / getHeight(), 1.0f);
}
});
return true;
}
}
AndroidManifest.xml**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.clockworkrobot.vortex"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Vortex"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
In essence.. What I require is a way to save and recover the current screen colour when the game opens and closes.
Thanks to everyone who has helped so far.
I'm still struggling to find a clean easy way to load some values in my onCreate method and pass them to another class in order that a game may load and save option settings.
Use SharedPreferences -- that is why they are there.
Anyone got any helpful ideas?
Either:
Your other class is not talking to the Activity object you think it is, or
You are not calling the code in the other class that invokes your setter, or
Your activity is being recreated (e.g., configuration change) as part of your testing, or
As #Arnout Engelen notes, you are calling the setter from multiple places and are overwriting what you want, or
Something else, since the code you have above most likely is not really the code from your app, and fake examples like this just cause problems when you go to ask people for help, because you introduce differences between what you're really running and what you're claiming you're running
UPDATE
You are creating a Vortex via new Vortex(). Vortex is an Activity. Never create activities via the constructor. You do not access activities from other activities. Your red/green/blue values need to be in some data model accessible from all your components.
Given your code and comments, I strongly encourage you to first learn Java outside of Android, then learn Android.
I had a similar problem. The solution is easy.
If the setter method is setting an int, initially it must be written as "public int...{} " instead of "public void...{} ".
Then it must return an int variable at the end with the following code line: "return a;" (where a is any int or int variable that has previously been initiated).
Then, whenever you want an int b to get a's number, simply write:
int b = new exampleClassWhereYourMethodIs().setterMethodName();
Hope I helped!

Categories

Resources