TextFieldStyle in Libgdx - java

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");

Related

Android app Null pointer exception

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

How to stop program crashing when user does not enter a value?

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

Force close when setting onclick

I created a button and assigned it 1 by doing
remove.setId(0 + count);
Then I tried to put that button in my onCreate bundle to use it
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
When I create the button remove in my oncreate it runs but as soon as I add my onclick listener I dont get any errors but when I run it it force closes
Log
12-12 13:42:06.172: D/AndroidRuntime(19502): Shutting down VM
12-12 13:42:06.172: W/dalvikvm(19502): threadid=1: thread exiting with uncaught exception (group=0x416bbd40)
12-12 13:42:06.178: E/AndroidRuntime(19502): FATAL EXCEPTION: main
12-12 13:42:06.178: E/AndroidRuntime(19502): Process: com.th3ramr0d.armytrooptotask, PID: 19502
12-12 13:42:06.178: E/AndroidRuntime(19502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.th3ramr0d.armytrooptotask/com.th3ramr0d.armytrooptotask.MainActivity}: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.access$800(ActivityThread.java:139)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Looper.loop(Looper.java:136)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.main(ActivityThread.java:5102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invokeNative(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invoke(Method.java:515)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-12 13:42:06.178: E/AndroidRuntime(19502): at dalvik.system.NativeStart.main(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): Caused by: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.th3ramr0d.armytrooptotask.MainActivity.onCreate(MainActivity.java:45)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Activity.performCreate(Activity.java:5248)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
12-12 13:42:06.178: E/AndroidRuntime(19502): ... 11 more
Here is my full file
package com.th3ramr0d.armytrooptotask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addTroopBtn = (Button) findViewById(R.id.addTroop);
addTroopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count <= 5)
{
inputName(v);
}
else
{
}
}
});
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
public void inputName(final View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//alert.setTitle("Enter Name and Rank");
alert.setMessage("Please Enter A Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable name = input.getText();
addTroop(name);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
public void addTroop(Editable name){
LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);
if (count <= 5)
{
//CREATE NEW LINEAR LAYOUT
LinearLayout addTroopLayout = new LinearLayout(this);
//CREATE LAYOUT PARAMS FOR LAYOUT
LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLayout.bottomMargin = 10;
//STYLE NEW LINEAR LAYOUT
addTroopLayout.setTag("addTroopLayout" + count);
addTroopLayout.setLayoutParams(newLayout);
addTroopLayout.setOrientation(LinearLayout.HORIZONTAL);
//CREATE NEW BUTTONS
Button newTroop = new Button(this);
Button remove = new Button(this);
Button change = new Button(this);
//CREATE LAYOUT PARAMS FOR BUTTONS
LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
//STYLE NEW BUTTONS
newTroop.setText(name);
newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
newTroop.setLayoutParams(newTroopParam);
remove.setId(0 + count);
remove.setText("-");
remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
remove.setLayoutParams(rmvBtnParam);
change.setText("...");
change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
change.setLayoutParams(chngNameParam);
//ADD VIEWS TO NEW LAYOUT
addTroopLayout.addView(newTroop);
addTroopLayout.addView(remove);
addTroopLayout.addView(change);
//ADD NEW LAYOUT TO mainPage LAYOUT
mainPage.addView(addTroopLayout);
//Increment Counter
count++;
}
}
}
This is your problem:
Button remove = (Button)findViewById(1);
This should be something like this:
Button remove = (Button)findViewById(R.id.buttonRemove); // that should be a long int
The crash is likely happening from this line:
Button remove = (Button)findViewById(1);
You'll need to provide a valid ID for a Button within your inflated layout. A value of 1 is not meaningful.

Getting a javaNullPointer Exception dealing with a call to the camera and previewing it

I'm following the Camera guide on Android developers. However when I try to run the activity I get a Java lang NullPointer Exception which I don't understand where it's coming from.
This is the Camera activity I wrote down.
public class Call extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
// Create an instance of Camera
mCamera = getCameraInstance();
System.out.println(Camera.open());
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.start_call, menu);
return true;
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
System.out.println("Has a camera it has "+Camera.getNumberOfCameras());
getCameraInstance();
return true;
} else {
// no camera on this device
System.out.println("Does not have a camera");
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
System.out.println("Got the camera");
}
catch (Exception e){
// Camera is not available (in use or does not exist)
System.out.println("Not available");
}
return c; // returns null if camera is unavailable
}
}
and this is the camerapreview class
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("error", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("error", "Error starting camera preview: " + e.getMessage());
}
}
}
This is the error I got.
07-24 17:55:11.856: E/AndroidRuntime(796): FATAL EXCEPTION: main
07-24 17:55:11.856: E/AndroidRuntime(796): java.lang.NullPointerException
07-24 17:55:11.856: E/AndroidRuntime(796): at com.reflap.reflap.CameraPreview.surfaceCreated(CameraPreview.java:31)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.SurfaceView.updateWindow(SurfaceView.java:543)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.SurfaceView.access$000(SurfaceView.java:81)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:169)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:671)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1820)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer.doFrame(Choreographer.java:525)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.os.Handler.handleCallback(Handler.java:615)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.os.Handler.dispatchMessage(Handler.java:92)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.os.Looper.loop(Looper.java:137)
07-24 17:55:11.856: E/AndroidRuntime(796): at android.app.ActivityThread.main(ActivityThread.java:4745)
07-24 17:55:11.856: E/AndroidRuntime(796): at java.lang.reflect.Method.invokeNative(Native Method)
07-24 17:55:11.856: E/AndroidRuntime(796): at java.lang.reflect.Method.invoke(Method.java:511)
07-24 17:55:11.856: E/AndroidRuntime(796): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
07-24 17:55:11.856: E/AndroidRuntime(796): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-24 17:55:11.856: E/AndroidRuntime(796): at dalvik.system.NativeStart.main(Native Method)
07-24 17:55:15.045: I/Process(796): Sending signal. PID: 796 SIG: 9
07-24 17:55:15.956: E/Trace(817): error opening trace file: No such file or directory (2)
I don't know where the null is coming from. I did print out this System.out.println(Camera.open()); and it printed out null which was weird but the error stack points to this, mCamera.setPreviewDisplay(holder);
I'm running it on the android emulator but I turned on the camera and tested it in the camera app which worked.
You have no code to test you have a camera. Make sure you have a camera before doing anything else with it.
In this code I am looking for the only camera or the camera facing the back ...
public int getCameraId() {
Log.d(TAG, "getCameraId()");
int cameraId = -1;
// Search for the back facing camera (or any camera)
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK || numberOfCameras == 1) {
Log.d(TAG, "CameraInfo.CAMERA_FACING_BACK = "
+ (info.facing == CameraInfo.CAMERA_FACING_BACK));
cameraId = i;
break;
}
}
return cameraId;
}
public static Camera getCameraInstance(int cameraId) {
Log.d(TAG, "getCameraInstance("+cameraId+")");
Camera c = null;
try {
c = Camera.open(cameraId); // attempt to get a Camera instance
Camera.Parameters cp = c.getParameters();
Log.d(TAG, "getCameraInstance("+cameraId+"): Camera.Parameters = "
+ cp.flatten());
} catch (Exception e) {
Log.d(TAG, "Camera.open("+cameraId+") exception="+e);
}
Log.d(TAG, "getCameraInstance("+cameraId+") = "+c);
return c; // returns null if camera is unavailable
}
The calling checks that cameraId returned from getCameraId is > -1 before calling getCameraInstance.
override the ondestroy() method and release your camera instance mcamera.release()
reference link http://developer.android.com/training/camera/cameradirect.html

Tesseract RECOGNITION fix?

I have been able to export my code into an application and use the Tess-Two file from this tutorial
to integrate the tesseract into it. But now I'm facing problems; when the picture is sent to the tesseract it just returns the same random characters each time: 'f' wig, W fin. A. " 5' ' ,{ >>zv' ' ~" > ';>'. What seems to be the problem?
ImageView iv;
TextView tv;
protected Bitmap _image;
protected Bitmap bmp;
public static String The_path = "/mnt/sdcard/DCIM/100MEDIA/TESS.jpg";
public static String lang = "eng";
public static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
private int pageSegmentationMode = TessBaseAPI.PageSegMode.PSM_AUTO;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/eng.traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH + "tessdata/eng.traineddata");
//Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((len = gin.read(buf)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.imageView1);
tv = (TextView) findViewById(R.id.textView1);
Button but = (Button) findViewById(R.id.button1);
Button but2 = (Button) findViewById(R.id.button2);
but.setOnClickListener(new OnClickListener() {
public void onClick(View v){
//File file = new File( _path );
//Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult(intent, 0);
}
});
but2.setOnClickListener(new OnClickListener() {
public void onClick(View v){
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.setPageSegMode(pageSegmentationMode);
baseApi.init(DATA_PATH, lang);
// DATA_PATH = Path to the storage
// lang for which the language data exists, usually "eng"
try {
baseApi.setImage(ReadFile.readBitmap(bmp));
String recognizedText = baseApi.getUTF8Text();
txt(recognizedText);
} catch(RuntimeException e) {
}
baseApi.end();
}
private void txt(String txt) {
// TODO Auto-generated method stub
tv.setText(txt);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(The_path, options);
try {
ExifInterface exif = new ExifInterface(The_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
bitmap = toGrayscale(bitmap);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
}
_image = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(_image);
bmp = bitmap;
} public static Bitmap toGrayscale(Bitmap bmpOriginal){
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
here is the new log cat after adding the grayscale function:
(receiving a new set of reoccurring random characters)
01-26 10:21:36.973: D/libEGL(1389): loaded /system/lib/egl/libEGL_adreno200.so
01-26 10:21:36.973: D/libEGL(1389): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
01-26 10:21:36.973: D/libEGL(1389): loaded /system/lib/egl/libGLESv2_adreno200.so
01-26 10:21:36.983: I/Adreno200-EGL(1389): <eglInitialize:269>: EGL 1.4 QUALCOMM build: Nondeterministic AU_full_mako_PARTNER-ANDROID/JB-MR1- DEV_CL2946718_release_AU (CL2946718)
01-26 10:21:36.983: I/Adreno200-EGL(1389): Build Date: 11/04/12 Sun
01-26 10:21:36.983: I/Adreno200-EGL(1389): Local Branch:
01-26 10:21:36.983: I/Adreno200-EGL(1389): Remote Branch: m/partner-android/jb-mr1-dev
01-26 10:21:36.983: I/Adreno200-EGL(1389): Local Patches: NONE
01-26 10:21:36.983: I/Adreno200-EGL(1389): Reconstruct Branch: NOTHING
01-26 10:21:37.043: D/OpenGLRenderer(1389): Enabling debug mode 0
01-26 10:21:45.502: E/BitmapFactory(1389): Unable to decode stream: java.io.FileNotFoundException: /mnt/sdcard/DCIM/100MEDIA/TESS.jpg: open failed: ENOENT (No such file or directory)
01-26 10:21:45.502: E/JHEAD(1389): can't open '/mnt/sdcard/DCIM/100MEDIA/TESS.jpg'
01-26 10:21:45.512: D/AndroidRuntime(1389): Shutting down VM
01-26 10:21:45.512: W/dalvikvm(1389): threadid=1: thread exiting with uncaught exception (group=0x417b0930)
01-26 10:21:45.522: E/AndroidRuntime(1389): FATAL EXCEPTION: main
01-26 10:21:45.522: E/AndroidRuntime(1389): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.cam.calc/cam.calc.Main}: java.lang.NullPointerException
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.deliverResults(ActivityThread.java:3319)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3362)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.os.Handler.dispatchMessage(Handler.java:99)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.os.Looper.loop(Looper.java:137)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-26 10:21:45.522: E/AndroidRuntime(1389): at java.lang.reflect.Method.invokeNative(Native Method)
01-26 10:21:45.522: E/AndroidRuntime(1389): at java.lang.reflect.Method.invoke(Method.java:511)
01-26 10:21:45.522: E/AndroidRuntime(1389): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-26 10:21:45.522: E/AndroidRuntime(1389): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-26 10:21:45.522: E/AndroidRuntime(1389): at dalvik.system.NativeStart.main(Native Method)
01-26 10:21:45.522: E/AndroidRuntime(1389): Caused by: java.lang.NullPointerException
01-26 10:21:45.522: E/AndroidRuntime(1389): at cam.calc.Main.onActivityResult(Main.java:388)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.Activity.dispatchActivityResult(Activity.java:5293)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
01-26 10:21:45.522: E/AndroidRuntime(1389): ... 11 more
You need to process the images before OCR, at least convert the image to black&white (gray scale) can enhance the result :
bitmap = toGrayscale(bitmap);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
you can user OpenCV or any Image Processing Library, for for simple task like grayscale its enopugh to use
import android.graphics.*;
public static Bitmap toGrayscale(Bitmap bmpOriginal)
{
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
Also if the image is too large you may need to crop the image and get the area that contain the characters & numbers you want to recognize, its also make OCR engine job more easier/more accuracy and sometimes its prevents you from OutOfMemoryException.

Categories