Syntax error on token for a "private static final" - java

I'm so sick of android errors in eclipse.. this has been happening for too long but here it goes.
here's the code
import android.app.Activity;
import android.os.Bundle;
import android.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
//constants used when saving/restoring state
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
I just threw the imports in to see where the code starts
the first private static final (BILL_TOTAL) errors like this:
Multiple markers at this line
- Syntax error on token(s), misplaced
construct(s)
- Syntax error on tokens, delete these
tokens
- Syntax error on tokens, delete these
tokens
I delete the first private static final then the error jumps to the next static method declaration... ugh.. the code is 90% done and I know there are no errors.. (if anything a curly brace somewhere)..
Please help me understand these random eclipse errors.
thanks in advance
Also... in the midst of all this i lost access to my main layout
main cannot be resolved or is not a field
also one last thing
NONE of my variables "can be resolved as a variable"

Those private static final variables need to be inside of a class context:
import android.app.Activity;
import android.os.Bundle;
import android.R;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
class MyClass {
//constants used when saving/restoring state
private static final String BILL_TOTAL = "BILL_TOTAL";
private static final String CUSTOM_PERCENT = "CUSTOM_PERCENT";
...
}

Related

Android create Toast using class reflection?

I am creating a hook using AndHook to test some functions getting called. I need to show a Toast inside a method without being able to get the context object (I can't directly import MainActivity because I am injecting the script without having the corresponding package when compiling so I can't use MainActivity.this). Here's the code sample:
import andhook.lib.HookHelper;
import android.widget.Toast;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
public class AndHookConfig {
#HookHelper.Hook(clazz = BitmapFactory.class)
private static Bitmap decodeFile(BitmapFactory thiz, String path) {
Toast.makeText(Class.forName("com.example.activity.MainActivity").this, "Bitmap.decodeFile("+path+")", Toast.LENGTH_LONG).show();
return (Bitmap)(HookHelper.invokeObjectOrigin(thiz, path));
}
}
I think the only way to do this is using reflection but the code sample doesn't compile and results in an error. Do you have any solutions ?
Thanks in advance.

How can I get extra data by Intent using Android annotation?

I'm really new to Android. I'm trying to pass the data to the text view of another class. But for some reason, it does not appear in the second class / page (the textview didnt change). I was able to do it when I was not using android annotation, but I was told that using annotations is a lot easier so I'm trying to convert it to that but for some reason it isn't working? I might be missing something.
Main 1
package com.example.faculty.labactivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
#EActivity(R.layout.world)
public class MainActivity extends AppCompatActivity {
#ViewById(R.id.userName)
EditText user;
#Click(R.id.signIn)
public void signInButton(){
Main2Activity_.intent().name(user.getText().toString()).start();
}
Main 2
package com.example.faculty.labactivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
#EActivity(R.layout.welcome)
public class Main2Activity extends AppCompatActivity {
#Extra("name")
String n;
#ViewById(R.id.name)
TextView tv;
Intent in2 = getIntent();
#AfterViews
void home(){
tv.setText("Hello, " + n + " !");
}
}
In your receiving Activity (for example MyActivity) you must declare the name of the object you want to receive like that
#Extra("name")
String name;
To pass data, when you create your intent you must do something like this:
Main2Activity_.intent(this).name(user.getText().toString()).start();
If you need a more precise solution edit your question to show more of your code.
You can look at the official doc for a more complete example
It might have to do with the dependencies you should add for the annotations to your project_root/build.gradle and app/build.gradle files.
Make sure to check this thread: what is Android Annotations and why we use Android Annotations?

libgdx not initialized yet

I have been coding my libgdx application (for desktop only) for a while and after deciding to cleanup the code part by part iv'e gotten into a problem i cant seem to solve myself..
exception:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.UnsatisfiedLinkError: com.badlogic.gdx.physics.box2d.PolygonShape.newPolygonShape()J
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:131)
Caused by: java.lang.UnsatisfiedLinkError: com.badlogic.gdx.physics.box2d.PolygonShape.newPolygonShape()J
at com.badlogic.gdx.physics.box2d.PolygonShape.newPolygonShape(Native Method)
at com.badlogic.gdx.physics.box2d.PolygonShape.<init>(PolygonShape.java:29)
at com.mygdx.game.handler.BodyEditorLoader.<init>(BodyEditorLoader.java:41)
at com.mygdx.game.util.GameUtils.init(GameUtils.java:23)
at com.mygdx.game.DungeonLife.create(DungeonLife.java:168)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:147)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)
after googling for a while i figured my error is as mentioned in this thread
as in
Another problem might be that you instantiate a SpriteBatch (or something else which internally uses a SpriteBatch) too early (looked a bit like this in the stacktrace).
but as the answer mentions
Instead, create such things in the create/show methods of your game.
I cant seem to understand when libgdx is initialized and ready for use, and where to place my GameUtils.init() method to assure libgdx is initialized
My code is as follows: (i have taken out e-relevant methods)
Application Class
package com.mygdx.game;
import box2dLight.RayHandler;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;
import com.mygdx.game.entity.MobEntity;
import com.mygdx.game.entity.PhysicalEntity;
import com.mygdx.game.entity.Player;
import com.mygdx.game.entity.Weapon;
import com.mygdx.game.handler.*;
import com.mygdx.game.util.CollisionConstants;
import com.mygdx.game.util.GameUtils;
import com.mygdx.game.util.TileObjectUtil;
import com.mygdx.game.util.WorldConstants;
import com.mygdx.game.valtype.WeaponDefinition;
public class DungeonLife extends ApplicationAdapter implements WorldConstants {
OrthographicCamera camera;
float width , height;
Texture texture;
TextureRegion[] enttex;
//TEMP
MobEntity demo;
Player thePlayer;
PlayerInputProcessor playerInputProcessor;
ScreenUI ui;
int mapWidth , mapHeight;
//========================================
GameMap gameMap;
//========================================
#Override
public void create () {
texture = new Texture("maps/img/tileset_entity.png");
enttex = new TextureRegion[(int) ((texture.getWidth()*texture.getHeight()) / (BLOCK*BLOCK))];
enttex[0] = new TextureRegion(texture , 0 , 0 , (int)BLOCK , (int)BLOCK);
enttex[1] = new TextureRegion(texture , (int)BLOCK , 0 , (int)BLOCK , (int)BLOCK);
width = Gdx.graphics.getWidth()/5;
height = Gdx.graphics.getHeight()/5;
camera = new OrthographicCamera(width,height);
camera.position.set(width / 2, height / 2, 0);
camera.update();
GameUtils.init(); // <------this guy
//init();
} ...
GameUtils
package com.mygdx.game.util;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.World;
import com.mygdx.game.entity.PhysicalEntity;
import com.mygdx.game.handler.*;
import java.util.PriorityQueue;
public class GameUtils {
public static void init(){
weapon_bodyEditorLoader = new BodyEditorLoader(Gdx.files.internal("textures/weapons/dungeonlife_weapons.json"));
resourceManager = new ResourceManager();
resourceManager.addRes("friendlyhealth" , new Texture("textures/ui/friendlyhealth.png"));
resourceManager.addRes("enemyhealth" , new Texture("textures/ui/enemyhealth.png"));
tmxMapLoader = new TmxMapLoader();
gameContactListender = new GameContactListender();
}
//GLOBAL
public static BodyEditorLoader weapon_bodyEditorLoader;
public static GameContactListender gameContactListender;
public static ResourceManager resourceManager;
public static TmxMapLoader tmxMapLoader;
//CURRENTS ============================
public static GameMap CURRENT_GAMEMAP;
}
Desktop launcher (the usual)
package com.mygdx.game.desktop;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.mygdx.game.DungeonLife;
import com.mygdx.game.util.GameUtils;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useGL30 = false;
config.width=640;
config.height=360;
DungeonLife dungeonLife = new DungeonLife();
new LwjglApplication(dungeonLife, config);
}
}
Help is much appriciated! :D
As I've already wrote in the other linked answer, make sure that your project is correctly set up. Box2D is an extension and needs its own native libraries to be able to run.
It seems that it's a specific problem with the Box2D natives which are not loaded yet. They are not loaded automatically when LibGDX is initializing, but you have to trigger that yourself (see wiki).
The code you've posted looks correct, but before you can use anything Box2D related, you have to call Box2D.init(). Alternatively, creating a World object does the same, but isn't the nicest way to do it.

Java boolean array instantiating as null

I'm creating a boolean array pre-populated with false values. I understand that I don't have to declare false values as they are automatically assigned however I've been trying different methods to try and solve the problem.
package com.bignerdranch.android.geoquiz;
import android.app.ActionBar;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends ActionBarActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
private boolean mIsCheater;
private boolean[] mCheatedAnswers = new boolean[] {false, false, false, false, false};
I have a breakpoint on the last line, and when the program breaks here the mCheatedAnswers is instantiated as null. I don't understand why as I have given it a boolean array - does anyone know why this could be?
The previous variables all have the correct values assigned to them when I check them in the debug mode.
If you've put the breakpoint on the last line, then when it hits, the assignment hasn't executed yet.
If you put a breakpoint in the constructor body - or just step over the line - you'll find the value is assigned appropriately. (It would be simpler just to use new boolean[5], mind you... false is the default value... Mind you, it would probably be better to have a class which included the question and whether or not the user cheated. Then you'd only need one collection.)

Passing an Enum to a method as a parameter in Java?

I am trying to call a docx4j method "setAlgn" in the interface CTTextParagraphProperties, which, per the docx4j jar I am using and the compiler takes an Enum type as a parameter. I am passing the actual argument STTextAlignType.CTR which I believe should resolve to the value 'ctr' (citation: http://grepcode.com/file/repo1.maven.org/maven2/org.docx4j/docx4j/3.0.1/org/docx4j/dml/STTextAlignType.java?av=f, I am running this same code).
Here is my code:
import java.lang.Enum;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFChildAnchor;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSimpleShape;
import org.apache.poi.xssf.usermodel.XSSFShapeGroup;
import org.apache.poi.xssf.usermodel.XSSFTextBox;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.docx4j.dml.*;
public static XSSFTextBox createTextBox(XSSFSheet sh, String message, int row1, int col1, int row2, int col2, boolean is_bold, boolean is_italics, boolean is_underline, boolean centered, int fontSize){
//Various apache-poi stuff
XSSFWorkbook wb = sh.getWorkbook();
XSSFDrawing drawing = sh.createDrawingPatriarch();
XSSFClientAnchor clientanchor = new XSSFClientAnchor(0,0,0,0,(short)col1,row1,(short)col2,row2);
XSSFChildAnchor childanchor = new XSSFChildAnchor(0,0,0,0);
XSSFShapeGroup group = drawing.createGroup(clientanchor);
XSSFTextBox textbox = group.createTextbox(childanchor);
XSSFRichTextString richMessage = new XSSFRichTextString(message);
XSSFFont textFont = wb.createFont();
textFont.setFontHeightInPoints((short)fontSize);
textFont.setFontName("Verdana");
if(is_bold){
textFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
}
textFont.setItalic(is_italics);
if(is_underline){
textFont.setUnderline(XSSFFont.U_SINGLE);
}
if(centered){
//Here is the code in question.
textbox.getCTShape().getTxBody().getPArray(0).getPPr().setAlgn(STTextAlignType.CTR);
}
richMessage.applyFont(textFont);
textbox.setText(richMessage);
return textbox;
}
My compiler returns the following error message:
com\tem\POIStuff.java:1105: error: method setAlgn in interface CTTextParagraphProperties cannot be applied to given types;
textbox.getCTShape().getTxBody().getPArray(0).getPPr().setAlgn(STTextAlignType.CTR);
Ultimately, my question is how can I get the "setAlgn" method to accept 'STTextAlignType.CTR' as an Enum and not as object type 'STTextAlignType'? Thank you in advance very much for your help!
The problem is actually on the first line of your code snippet! Your issue is with
import java.lang.Enum;
CTTextParagraphProperties.setAlgn does take a class of type Enum, but it's not that kind of Enum. It has to be a org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType.Enum
I'd suggest you switch your imports to be:
import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType;
import org.openxmlformats.schemas.drawingml.x2006.main.STTextAlignType.Enum;
You can then set the alignment with things like STTextAlignType.L and it'll work fine

Categories