i am trying to build a newbie app which drop an array of pizza topic from the top of the screen and the user is supposed to avoid them, but for some reason I'm getting NullPointerException in the logcat and the app crashes..
it says it happens in the firstSet() when i'm trying to put value in the point.y which make no sense because i'm initializing them in the constractor.
package com.example.secondapp;
import java.util.Random;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.View;
public class EnemyTopics extends View {
private Drawable[] topic;
private Point[] cords;
private int width,height,screenHgt,screenWid,ClosestTopic,score;
private int tomatos,olives,mushroom,onion;
private UserCharacter character;
private Context context;
#SuppressLint("NewApi")
public EnemyTopics(Context context,int wid,int hgt,int screenHgt,int screenWid,UserCharacter uc) {
super(context);
this.cords = new Point[20];
for(Point point : cords) {
point = new Point();
point.x = 0;
point.y = 0;
}
this.width = wid;
this.height = hgt;
this.topic = new Drawable[20];
this.tomatos = R.drawable.tomatos;
this.olives = R.drawable.olives;
this.mushroom = R.drawable.mushroom;
this.onion = R.drawable.onion;
this.ClosestTopic = 0;
this.screenHgt = screenHgt;
this.screenWid = screenWid;
this.character = uc;
this.score = 0;
this.context = context;
this.firstSet();
this.setBounds();
}
public int maxLeft(int position) {
return this.cords[position].x - (this.width/2);
}
public int maxRight(int position) {
return this.cords[position].x + (this.width/2);
}
public int maxTop(int position) {
return this.cords[position].y - (this.height/2);
}
public int maxBottom(int position) {
return this.cords[position].y + (this.height/2);
}
public void setBounds() {
int pos = 0;
for (Drawable topics : this.topic) {
topics.setBounds(maxLeft(pos), maxTop(pos), maxRight(pos), maxBottom(pos));
pos++;
}
}
public void moveTopics() {
int pos = 0;
for (Point p : this.cords) {
if(maxBottom(pos) <= screenHgt) {
p.y++;
}
else {
p.y = -200;
}
pos++;
}
if(maxTop(ClosestTopic) > character.maxBottom()) {
ClosestTopic++;
score++;
}
if(ClosestTopic <= 19)
ClosestTopic = 0;
}
public void checkHit() {
if(maxBottom(ClosestTopic) >= character.maxTop() && maxTop(ClosestTopic) <= character.maxBottom() && maxLeft(ClosestTopic) <= character.maxRight() && maxRight(ClosestTopic) >= character.maxLeft()) {
score = 0;
this.firstSet();
character.restart();
}
}
#SuppressLint("NewApi")
public void firstSet() {
Random r = new Random();
int random = r.nextInt(4);
int pos = 0;
for (Point p : cords) {
p.y = (0 - pos*15);
p.x = screenWid/2;
switch (random) {
case 0:
topic[pos]= context.getResources().getDrawable(tomatos,null);
break;
case 1:
topic[pos]= context.getResources().getDrawable(olives,null);
break;
case 2:
topic[pos]= context.getResources().getDrawable(mushroom,null);
break;
case 3:
topic[pos]= context.getResources().getDrawable(onion,null);
break;
default:
topic[pos]= context.getResources().getDrawable(tomatos,null);
}
pos++;
random = r.nextInt(4);
}
}
public void draw (Canvas canvas) {
for (Drawable topics : this.topic) {
topics.draw(canvas);
}
}
}
i disabled the thread that moves them, which means the problem is either on the constructor,firstSet or setBound but i cant find it, so i'll appriciate help:)
thanks in advance.
logcat:
09-20 14:13:53.725: E/AndroidRuntime(1154): FATAL EXCEPTION: main
09-20 14:13:53.725: E/AndroidRuntime(1154): Process: com.example.secondapp, PID: 1154
09-20 14:13:53.725: E/AndroidRuntime(1154): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.secondapp/com.example.secondapp.MainActivity}: java.lang.NullPointerException: Attempt to write to field 'int android.graphics.Point.y' on a null object reference
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.ActivityThread.-wrap11(ActivityThread.java)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.os.Handler.dispatchMessage(Handler.java:102)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.os.Looper.loop(Looper.java:148)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.ActivityThread.main(ActivityThread.java:5417)
09-20 14:13:53.725: E/AndroidRuntime(1154): at java.lang.reflect.Method.invoke(Native Method)
09-20 14:13:53.725: E/AndroidRuntime(1154): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
09-20 14:13:53.725: E/AndroidRuntime(1154): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-20 14:13:53.725: E/AndroidRuntime(1154): Caused by: java.lang.NullPointerException: Attempt to write to field 'int android.graphics.Point.y' on a null object reference
09-20 14:13:53.725: E/AndroidRuntime(1154): at com.example.secondapp.EnemyTopics.firstSet(EnemyTopics.java:96)
09-20 14:13:53.725: E/AndroidRuntime(1154): at com.example.secondapp.EnemyTopics.<init>(EnemyTopics.java:42)
09-20 14:13:53.725: E/AndroidRuntime(1154): at com.example.secondapp.MainActivity.onCreate(MainActivity.java:19)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.Activity.performCreate(Activity.java:6237)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
09-20 14:13:53.725: E/AndroidRuntime(1154): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
09-20 14:13:53.725: E/AndroidRuntime(1154): ... 9 more
You cannot assign objects to an array using this kind of loop. point is a copy of the reference, and it is not copied back into the array.
this.cords = new Point[20];
for(Point point : cords) {
point = new Point();
point.x = 0;
point.y = 0;
}
Use the "old-fashioned" way:
this.cords = new Point[20];
for(int i = 0; i < cords.length; ++i ) {
cords[i] = new Point();
cords[i].x = 0;
cords[i].y = 0;
}
Related
So basically I have a problem. When the user presses the calculate button (I'm making a calculator) without entering a value the app crashes. I want it to display a message instead but I don't know how. (updated)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
//h is cm edittext
final EditText h = (EditText)findViewById(R.id.editText2);
final EditText w = (EditText)findViewById(R.id.editText3);
final EditText r = (EditText)findViewById(R.id.textView4);
});
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
float height=0;
float weight=0;
float result=0;
result = (float) (( weight / height ) + 0.005) ;
if ((h.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your height", Toast.LENGTH_SHORT).show();
float height = Float.parseFloat(h.getText().toString());
}
if ((w.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your weight", Toast.LENGTH_SHORT).show();
float weight = Float.parseFloat(w.getText().toString());
}
r.setText(String.valueOf(result));
}
the code below is where i have the problem
if ((h.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your height", Toast.LENGTH_SHORT).show();
float height = Float.parseFloat(h.getText().toString());
}
if ((w.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter your weight", Toast.LENGTH_SHORT).show();
float weight = Float.parseFloat(w.getText().toString());
}
This is the best I can come up with but it doesn't work.
Here is the LogCat (Updated)
09-20 18:50:38.509: E/AndroidRuntime(29769): FATAL EXCEPTION: main
09-20 18:50:38.509: E/AndroidRuntime(29769): Process: com.NovaPlex.personalfitnessfree, PID: 29769
09-20 18:50:38.509: E/AndroidRuntime(29769): java.lang.NumberFormatException: Invalid float: ""
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.StringToReal.invalidReal(StringToReal.java:63)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.StringToReal.parseFloat(StringToReal.java:308)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.Float.parseFloat(Float.java:306)
09-20 18:50:38.509: E/AndroidRuntime(29769): at com.NovaPlex.personalfitnessfree.WH$2.onClick(WH.java:80)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.view.View.performClick(View.java:4780)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.view.View$PerformClick.run(View.java:19866)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.os.Handler.handleCallback(Handler.java:739)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.os.Handler.dispatchMessage(Handler.java:95)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.os.Looper.loop(Looper.java:135)
09-20 18:50:38.509: E/AndroidRuntime(29769): at android.app.ActivityThread.main(ActivityThread.java:5254)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.reflect.Method.invoke(Native Method)
09-20 18:50:38.509: E/AndroidRuntime(29769): at java.lang.reflect.Method.invoke(Method.java:372)
09-20 18:50:38.509: E/AndroidRuntime(29769): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
09-20 18:50:38.509: E/AndroidRuntime(29769): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Don't use == null. Assuming you've done findviewbyid, it cannot be null. It doesn't check for contents.
This is a simple method how to find if EditText is empty. Parameter is the EditText you want to check and it returns true for empty / false for non-empty.
private boolean isEmpty(EditText etText) {
return etText.getText().toString().trim().length() <= 0;
}
EDIT :
by using android:id="#+id/someId in xml files, we tell Android to create new resource with chosen id (in this case someId) in our R.java class. When doing findviewbyid we assign that value to our View.
In short if OP did something like EditText EditText1 = (EditText) findViewById(R.id.myFistEditText); before and he later tries to compare it in his if like (EditText1 == null), it's not actually getting value of text in his EditText, it's just telling him that - yes, this view was found before and it's assigned.
You can just try this, to check if value is not entered in the EditText.
if ((EditText1.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if ((EditText2.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
Alternatively, you can use .matches("") instead of .equals("")
UPDATE
You have to do it like this
if (!(h.getText().toString()).equals(""))
{
height= Float.parseFloat(h.getText().toString());
}
and
if (!(w.getText().toString()).equals(""))
{
weight= Float.parseFloat(w.getText().toString());
}
UPDATE
if ((EditText1.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value1", Toast.LENGTH_LONG).show();
}
if ((EditText2.getText().toString()).equals(""))
{
Toast.makeText(getApplicationContext(),"Please enter Value2", Toast.LENGTH_LONG).show();
}
if (!(h.getText().toString()).equals(""))
{
height= Float.parseFloat(h.getText().toString());
}
if (!(w.getText().toString()).equals(""))
{
weight= Float.parseFloat(w.getText().toString());
}
Replace the above code instead of yours
It is already said that you'd better write a method isEmpty.
My suggestion is rather than writing isEmpty write a method called isValid which checks if the value is a desired value i.e. integer, double etc.
This way your program wont crash when a string is entered.
use
if(textView.getText().toString().isEmpty()){
Toast.makeText(this , "Enter A Number" , Toast.LENGTH_SHORT).show();
}
I am new to Android and Java programming and for some reason (I cant point out) my app wont even open.It says "Unfortunately 'app name' has crashed". It has no compile-time errors in it?
Here is the Logcat:
08-19 04:54:07.024 24170-24170/com.elie.billsplitter E/AndroidRuntime﹕FATAL EXCEPTION: main
Process: com.elie.billsplitter, PID: 24170
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.elie.billsplitter/com.elie.billsplitter.MainActivity}: java.lang.NumberFormatException: Invalid int: ""
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.elie.billsplitter.MainActivity.<init>(MainActivity.java:11)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
08-19 04:54:09.781 24170-24177/com.elie.billsplitter W/art﹕ Suspending all threads took: 793.743ms
08-19 04:54:36.935 24170-24170/com.elie.billsplitter I/Process﹕ Sending signal. PID: 24170 SIG: 9
Here is the Java file:
public class MainActivity extends Activity {
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button
Button btn = (Button) findViewById(R.id.button);
//EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int z = x / y;
tv.setText(z);
}
});
}
}
Most probably you are parsing an empty string into the integer.
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
before getting the text from the Edittext check that whether it is empty or not. You are parsing an empty string probably.
you can make a check like this:
if(!(nop.toString().trim().equalsIgnoreCase("") && cob.toString().trim().equalsIgnoreCase(""))){
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
}
and also your are making the initilization the integers in an incorrect way:
May be these are the lines where you are getting exceptions. You cannot parse blank strings to integer.
instead of this:
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
write this:
public int x = 0;
public int y = 0;
or
public int x = Integer.parseInt("0");
public int y = Integer.parseInt("0");
Before converting to a number you can check if it is a numeric string. For some ideas read this thread on stackoverflow: How to check if a String is numeric in Java
Somewhere in your code you are converting a invalid string or a empty string into a number, which is causing the NumberFormatException.
String x = "abc";
int num = Integer.parseInt(x);
How do I solve it?
try
{
String x = "abc";
int num = Integer.parseInt(x);
}
catch(NumberFormatException ne)
{
System.out.println("Invalid Number!");
}
In your code, replace:
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
with
public int x;
public int y;
The default values of x and y will be 0. You don't have to add that.
Reason of Error: Integer.parseInt() converts the string inside it to an integer. You have tried to convert "" to an integer, which is not even a number... So NumberFormatException occurred.
Im trying to implement a different font than the default one using TextFieldStyle as I´ve been told. It´s inside a textbox that I want to change the font. But have yet not manage to do it.
This is the class itself:
public class StoneScreen implements Screen {
OrthographicCamera camera;
final TombStone game;
//Textures and art.
public Texture background, sdStone, arrowBack;
public Sprite backgrounds;
//TextField´s stuff
private Stage stage;
private Skin skin;
ImageButton btnArrow;
public StoneScreen(TombStone gam) {
this.game = gam;
camera = new OrthographicCamera();
camera.setToOrtho(false, 136, 204);
game.assets.load();
loadStandard();
}
public void loadStandard(){
background = game.assets.background;
sdStone = game.assets.sdStone;
//backgrounds = Assets.backgrounds;
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0.2f,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//Recieves the screen width and height
float gameHeight = Gdx.graphics.getHeight();
float gameWidth = Gdx.graphics.getWidth();
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
Gdx.app.log("X", "FPS:" + Gdx.graphics.getFramesPerSecond());
game.batch.draw(background,0,0, 136, 204);
game.batch.draw(sdStone, 40, 20, 70, 110);
//SpriteBatch batcher = (SpriteBatch)stage.getBatch();
game.batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void show() {
BitmapFont textFont;
FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("NothingYouCouldDoBold.ttf"));
FreeTypeFontParameter parameter = new FreeTypeFontParameter();
parameter.size = 12;
textFont = generator.generateFont(parameter);
//String text = Gdx.app.getPreferences("prefs").getString("text", "Default text if missing");
//String txtArea = Gdx.app.getPreferences("prefs").getString("text", "Default text if missing");
Preferences prefs = Gdx.app.getPreferences("preferences");
Skin skin = new Skin();
Skin textSkin = new Skin();
skin.add("font", textFont);
stage = new Stage();
Gdx.input.setInputProcessor(stage);
skin = new Skin(Gdx.files.internal("uiskin.json"));
TextFieldStyle textstyle = new TextFieldStyle();
textstyle.font = textSkin.getFont("textFont");
final TextArea textArea = new TextArea(prefs.getString("textArea", "Enter text:"), skin);
textArea.setX(500);
textArea.setY(500);
textArea.setWidth(270);
textArea.setHeight(270);
textArea.setMaxLength(50);
final TextField textField = new TextField(prefs.getString("textField", "Enter name:"), textstyle);
textField.setX(500);
textField.setY(750);
textField.setMaxLength(20);
//textField.setWidth(450);
//textField.setHeight(200);
textField.setSize(400, 200);
//String text = Gdx.app.getPreferences("prefs").getString("text", "Default text if missimg");
//TextField textField = new TextField(text, skin);
//Backbutton
ImageButtonStyle styleTwo = new ImageButtonStyle();
TextureRegionDrawable arrowImage = new TextureRegionDrawable(new TextureRegion(new Texture("arrowLeft.png")));
styleTwo.up = skin.newDrawable(skin.newDrawable(arrowImage));
styleTwo.down = skin.newDrawable(skin.newDrawable(arrowImage));
btnArrow = new ImageButton(styleTwo);
btnArrow.setSize(150, 150);
btnArrow.setPosition(450, 10);
stage.addActor(textArea);
stage.addActor(textField);
stage.addActor(btnArrow);
//Backbutton takes us back to mainmenu
btnArrow.addListener(new ChangeListener() {
#Override
public void changed(ChangeEvent event, Actor actor) {
game.setScreen(new MainScreen(game));
//Saves the entered text.
Preferences prefs = Gdx.app.getPreferences("preferences");
prefs.putString("textField", textField.getText());
prefs.putString("textArea", textArea.getText());
prefs.flush();
}
});
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
And the important part of this code is inside the Show() class. Where I´ve had no success with it. I get error saying :
09-20 17:26:22.606: D/dalvikvm(17329): Trying to load lib /data/app-lib/com.progrmor.tombstone.android-25/libgdx-freetype.so 0x42a968d0
09-20 17:26:22.606: D/dalvikvm(17329): Added shared lib /data/app-lib/com.progrmor.tombstone.android-25/libgdx-freetype.so 0x42a968d0
09-20 17:26:22.606: D/dalvikvm(17329): No JNI_OnLoad found in /data/app-lib/com.progrmor.tombstone.android-25/libgdx-freetype.so 0x42a968d0, skipping init
09-20 17:26:22.887: W/dalvikvm(17329): threadid=11: thread exiting with uncaught exception (group=0x4189dda0)
09-20 17:26:22.887: E/AndroidRuntime(17329): FATAL EXCEPTION: GLThread 30481
09-20 17:26:22.887: E/AndroidRuntime(17329): Process: com.progrmor.tombstone.android, PID: 17329
09-20 17:26:22.887: E/AndroidRuntime(17329): com.badlogic.gdx.utils.GdxRuntimeException: No com.badlogic.gdx.graphics.g2d.BitmapFont registered with name: textFont
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.ui.Skin.get(Skin.java:145)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.ui.Skin.getFont(Skin.java:175)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.progrmor.tombstone.screens.StoneScreen.show(StoneScreen.java:144)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.Game.setScreen(Game.java:61)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.progrmor.tombstone.screens.MainScreen$1.changed(MainScreen.java:142)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.handle(ChangeListener.java:28)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.Actor.notify(Actor.java:174)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.Actor.fire(Actor.java:139)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.ui.Button.setChecked(Button.java:112)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.ui.Button$1.clicked(Button.java:86)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.utils.ClickListener.touchUp(ClickListener.java:89)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:57)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.scenes.scene2d.Stage.touchUp(Stage.java:342)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.backends.android.AndroidInput.processEvents(AndroidInput.java:382)
09-20 17:26:22.887: E/AndroidRuntime(17329): at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:413)
09-20 17:26:22.887: E/AndroidRuntime(17329): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1531)
09-20 17:26:22.887: E/AndroidRuntime(17329): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1248)
09-20 17:26:27.111: E/AndroidGraphics(17329): waiting for pause synchronization took too long; assuming deadlock and killing
so.. what can I might be doing wrong here?
Here:
textstyle.font = textSkin.getFont("textFont");
you try to get the font with name textFont from the skin textSkin.
But previously you added the font with a different name font to a different skin:
Skin textSkin = new Skin();
skin.add("font", textFont);
==> It won't find your BitmapFont
A possible solution is to just get rid of that textSkin since you anyway don't add anything to it and do the following instead:
//Skin textSkin = new Skin(); // remove this
skin.add("textFont", textFont);
//...
textstyle.font = skin.getFont("textFont");
I'm trying to retrieve data from a json with multiple values and cast it into a listview but im gettting the error java.util.hashmap cannot be cast to java.util.list.
I'm using volley.
The FeedListActivity Class:
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
feedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
ClientesContatosModel newsData = (ClientesContatosModel) o;
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("nome", newsData);
startActivity(intent);
}
});
}
JSONArray dados = json.getJSONArray("dados");
// parsing json object
for (int i = 0; i < dados.length(); i++) {
JSONObject item = dados.getJSONObject(i);
feedList = new ArrayList<ClientesModel>();
ClientesModel mClientesModel = new ClientesModel();
ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();
/* cadastra os dados necessários no objeto no modelo */
mClientesModel.setId(item.optInt("id"));
mClientesModel.setNome(item.optString("nome"));
mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
mClientesModel.setCpf(item.optString("cpf"));
mClientesModel.setCnpj(item.optString("cnpj"));
JSONArray contatos = item.getJSONArray("contatos");
for (int j = 0; j < contatos.length(); j++) {
JSONObject data = contatos.getJSONObject(j);
mClientesContatoModel.setNome(data.optString("nome"));
mClientesContatoModel.setCargo(data.optString("cargo"));
FeedDetailsActivity class:
public class FeedDetailsActivity extends Activity {
private ClientesContatosModel feed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed_details);
feed = (ClientesContatosModel) this.getIntent().getSerializableExtra("nome");
if (null != feed) {
TextView title = (TextView) findViewById(R.id.title);
title.setText(feed.getNome());
}
}
Here is the Log:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.javatechig.feedreader/com.javatechig.feedreader.FeedDetailsActivity}: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.javatechig.feedreader.model.ClientesContatosModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.util.HashMap cannot be cast to com.javatechig.feedreader.model.ClientesContatosModel
at com.javatechig.feedreader.FeedDetailsActivity.onCreate(FeedDetailsActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
Because HashMap#values() return a java.util.Collection and you cant cast Collection into ArrayList, thus you get ClassCastException.
where as in case of ArrayList(HashMap.values()) ArrayList constructor takes Collection as an argument. Thus you wont get ClassCastException when you pass HashMap.values() as an argument to ArrayList.
HashMap#values(): check the return type in the source, as ask yourself, can a java.util.Collection be casted into java.util.ArrayList ?? No
public Collection<V> values() {
921 Collection<V> vs = values;
922 return (vs != null ? vs : (values = new Values()));
923 }
ArrayList(Collection): check the argument type in the source. can a method whose argument is a super type accepts sub type ? Yes
public ArrayList(Collection<? extends E> c) {
151 elementData = c.toArray();
152 size = elementData.length;
153 // c.toArray might (incorrectly) not return Object[] (see 6260652)
154 if (elementData.getClass() != Object[].class)
155 elementData = Arrays.copyOf(elementData, size, Object[].class);
156 }
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
In my app, the user has 3 different types of quizzes they can choose. When they choose one of quiz types called "levels", I get a NullPointerException. The order of the algorithm for "levels" is the same as when the game type is "original". You can see this in the code below. It is hard to explain why the algorithms are the same so I will spare you those details but just accept the algorithms are the same for now. :)
Why am I getting this NPE exception with the quiz/game type is "levels" but not when the quiz/game type is "original" even though the code/algorithm for them are the same?
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter, timeremaining;
ArrayList<Question> queries;
public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
Timer cdTimer;
ProgressBar bar;
Context c;
Singleton singleton = Singleton.getInstance();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.questionview);
c = this;
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
questionNumber = (TextView)findViewById(R.id.questionnumber);
timeremaining = (TextView)findViewById(R.id.timeremaining);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointsPerQuestion.clear();
if(singleton.getGameType() == "levels") {
if(singleton.getLevel() <= 10) {
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
loadLevelsQuizTen();
}
//...
} else if (singleton.getGameType() == "original") {
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
loadOriginalQuiz();
} else if (singleton.getGameType() == "freeplay") {
loadFreeplayQuiz();
}
}
public void loadFreeplayQuiz() {
//...
}
public void loadLevelsQuizTen() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
//answer = queries.get(i).getCorrectAnswer(); //NULLPOINTEREXCEPTION HERE
answer = 2;
question.setText(queries.get(i).getQuery()); // I COMMENTED OUT ABOVE LINE OF CODE AND NOW NPE IS NOW HERE
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
//...
}
});
answer2.setOnClickListener(new OnClickListener() {
//...
});
answer3.setOnClickListener(new OnClickListener() {
//...
});
answer4.setOnClickListener(new OnClickListener() {
//...
});
}
}
public void loadOriginalQuiz() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
//...
});
answer2.setOnClickListener(new OnClickListener() {
//...
});
answer3.setOnClickListener(new OnClickListener() {
//...
});
answer4.setOnClickListener(new OnClickListener() {
//...
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public static ArrayList<Long> getPointsPerQuestion() {
//...
}
public void correct() {
pointsPerQuestion.add(points);
score = score + points;
i++;
if(singleton.getGameType() == "original") {
loadOriginalQuiz();
} else if(singleton.getGameType() == "levels") {
loadLevelsQuizTen();
}
}
public void incorrect() {
long zero = 0;
pointsPerQuestion.add(zero);
i++;
loadOriginalQuiz();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
points = 0;
if(i >= 9) {
cdTimer.cancel();
pointsPerQuestion.add(points);
endQuiz();
} else {
wrongAnswers++;
incorrect();
}
}
#Override
public void onTick(long millisUntilFinished) {
bar.setProgress((int) millisUntilFinished);
points = (millisUntilFinished / 200) + 1;
timeremaining.setText("Score remaining: " + points);
if(i < 10) {
questionNumber.setText(c.getResources().getString(R.string.question) + " " + (i + 1) + " " + c.getResources().getString(R.string.of10));
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putExtra("pointsPerQuestion", pointsPerQuestion);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
public void onStop() {
super.onStop();
}
public void onResume() {
super.onResume();
}
}
LogCat
06-14 20:44:45.413: E/AndroidRuntime(1335): java.lang.RuntimeException: Unable to start activity ComponentInfo{matt.lyons.bibletrivia.lite/matt.lyons.bibletrivia.lite.QuestionView}: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.os.Handler.dispatchMessage(Handler.java:99)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.os.Looper.loop(Looper.java:137)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-14 20:44:45.413: E/AndroidRuntime(1335): at java.lang.reflect.Method.invokeNative(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335): at java.lang.reflect.Method.invoke(Method.java:511)
06-14 20:44:45.413: E/AndroidRuntime(1335): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-14 20:44:45.413: E/AndroidRuntime(1335): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-14 20:44:45.413: E/AndroidRuntime(1335): at dalvik.system.NativeStart.main(Native Method)
06-14 20:44:45.413: E/AndroidRuntime(1335): Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.onCreate(QuestionView.java:80)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.Activity.performCreate(Activity.java:5104)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-14 20:44:45.413: E/AndroidRuntime(1335): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
Why "accept"? That might be the fatal flaw in your argument.
Here's the problem:
Caused by: java.lang.NullPointerException
06-14 20:44:45.413: E/AndroidRuntime(1335): at matt.lyons.bibletrivia.lite.QuestionView.loadLevelsQuizTen(QuestionView.java:195)
Go to line 195 in the QuestionView.java file, look at the object references on that line, and see which one you failed to initialize.
The sooner you stop telling yourself that everything is fine and start looking at what's really happening, the sooner you'll fix the problem and move on.
You should not be duplicating any code. You should encapsulate it in a single method call and calling it in both places. This is a recipe for error.
You have lots of other issues. You use a private data member i to do different things in different methods. It's not synchronized in any way that I can see. I see no reason why that value couldn't be a method parameter and passed in. That would be more more thread safe.
When you're doing things like that, comparing Strings with ==, and duplicating code it puts everything you've done in doubt for me. No wonder you're having trouble. Voting to close.
Set a breakpoint where you are getting the NPE and check the values of your variables. I would guess either queries is null (not setting or getting from intent bundle correctly), or queries.get(i) is null.
you get the error because you are calling 2 different methods. In levels you call loadLevelsQuizTen();, in original you call loadOriginalQuiz();
Despite the fact you say they are the same, they aren't. I'd use a debugger to step through the method and figure out what is null and why.