setText causing a crash - java

For the better part of every day for the past week, I have been working on this project of controlling a textfield with the input of a potentiometer, and my setText command keeps crashing the program. I'm tired of tinkering and debugging but getting very little accomplished, and I need some help badly.
If you need to see all of the projects files, I can upload them as well.
Search for "This line causes a crash"
package edu.uidaho.pong;
import java.io.IOException;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import android.app.Activity;
import android.view.SurfaceHolder;
public class GameThread extends Thread {
/** Handle to the surface manager object we interact with */
private SurfaceHolder _surfaceHolder;
private Paint _paint;
private GameState _state;
public PongActivity _pong;
public GameThread(SurfaceHolder surfaceHolder, Context context,
Handler handler) {
_surfaceHolder = surfaceHolder;
_paint = new Paint();
_state = new GameState();
_pong = new PongActivity();
}
// #Override
public void run() {
while (true) {
Canvas canvas = _surfaceHolder.lockCanvas();
_state.update(_pong);
_state.draw(canvas, _paint);
_surfaceHolder.unlockCanvasAndPost(canvas);
int ret = 0;
byte[] buffer = new byte[16384];
int i;
int tempdebug = 0;
//while (true) { // read data
while (tempdebug++ < 10){
// try {
// ret = _pong.mInputStream.read(buffer);
// } catch (IOException e) {
// break;
// }
ret = 5; // let's pretend there's a 5 every time since I can't test the usb
i = 0;
while (i < ret) {
int len = ret - i;
if (len >= 1) {
Message m = Message.obtain(_pong.mHandler);
int value = (int)buffer[i];
// 'f' is the flag, use for your own logic
// value is the value from the arduino
m.obj = new ValueMsg('f', value);
_pong.mHandler.sendMessage(m);
}
i += 1; // number of bytes sent from arduino
}
}
//_pong.mResponseField.setText("Reading: "); This line causes a crash
}
}
public GameState getGameState() {
return _state;
}
}
Logcat output -
03-03 22:45:49.639: W/dalvikvm(381): threadid=9: thread exiting with uncaught exception (group=0x40015560)
03-03 22:45:49.639: E/AndroidRuntime(381): FATAL EXCEPTION: Thread-10
03-03 22:45:49.639: E/AndroidRuntime(381): java.lang.NullPointerException
03-03 22:45:49.639: E/AndroidRuntime(381): at edu.uidaho.pong.GameThread.run(GameThread.java:70)
03-03 22:45:50.189: E/global(381): Deprecated Thread methods are not supported.
03-03 22:45:50.189: E/global(381): java.lang.UnsupportedOperationException
03-03 22:45:50.189: E/global(381): at java.lang.VMThread.stop(VMThread.java:85)
03-03 22:45:50.189: E/global(381): at java.lang.Thread.stop(Thread.java:1280)
03-03 22:45:50.189: E/global(381): at java.lang.Thread.stop(Thread.java:1247)
03-03 22:45:50.189: E/global(381): at edu.uidaho.pong.GameView.surfaceDestroyed(GameView.java:46)
03-03 22:45:50.189: E/global(381): at android.view.SurfaceView.reportSurfaceDestroyed(SurfaceView.java:587)
03-03 22:45:50.189: E/global(381): at android.view.SurfaceView.updateWindow(SurfaceView.java:481)
03-03 22:45:50.189: E/global(381): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:213)
03-03 22:45:50.189: E/global(381): at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
03-03 22:45:50.189: E/global(381): at android.view.ViewRoot.performTraversals(ViewRoot.java:782)
03-03 22:45:50.189: E/global(381): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859)
03-03 22:45:50.189: E/global(381): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 22:45:50.189: E/global(381): at android.os.Looper.loop(Looper.java:130)
03-03 22:45:50.189: E/global(381): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-03 22:45:50.189: E/global(381): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 22:45:50.189: E/global(381): at java.lang.reflect.Method.invoke(Method.java:507)
03-03 22:45:50.189: E/global(381): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-03 22:45:50.189: E/global(381): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-03 22:45:50.189: E/global(381): at dalvik.system.NativeStart.main(Native Method)

I can't say exactly since there is no logcat, but this is probably happening because you're trying to change your TextView from a separate thread, which is prohibited in Android. One of the solutions to this problem is to put a reference to your Activity inside the class that runs a separate thread and place any View changing code inside the Activity.runOnUiThread() method, which takes a Runnable as the argument. Hope this helps.
EDIT
_pong.runOnUiThread(new Runnable() {
#Override
public void run() {
_pong.mResponseField.setText("Reading: ");
}
});

Related

Converter application error on Android

Hello guys I am making an Android app that convert from binary to decimal and I have made a class called Binary and a class called Decimal and a function in the Binary class that convert from decimal to binary
public Binary DtoB(Decimal decimal)
{
String temp = null;
do
{
if(decimal.decimal%2!=0)
temp+='1';
else
temp+='0';
decimal.decimal/=2;
}while(decimal.decimal>0);
while(temp.length()%4!=0)
temp+='0';
for(int i=temp.length()-1;i>=0;i--)
{
this.bn+=temp.charAt(i);
}
return this;
}
and in the activity there's a button that converts, but when I test and press on the button the app breaks
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d1.decimal=Integer.parseInt(e1.getText().toString());
b.DtoB(d1);
t1.setText(b.bn);
}
});
can any one help me please ???
Here is the logcat:
10-26 09:16:15.831: E/AndroidRuntime(280): FATAL EXCEPTION: main
10-26 09:16:15.831: E/AndroidRuntime(280): java.lang.NullPointerException
10-26 09:16:15.831: E/AndroidRuntime(280): at com.example.converter.MainActivity$1.onClick(MainActivity.java:34)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123) 10-26 09:16:15.831: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
Try this...!
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
BinaryToDecimal bd = new BinaryToDecimal();
System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
}
}
check variable all are initialize perfectly . because some time objectc are created but it is null so can't work and throw java.lang.NullPointerException .....
b1 , d1 , b ,t1

Error in fetching data from database table

I am making an android app. and am trying to fetching data from column, name and score from
the database table but getting this error at run time,
Sorry this application has stopped unexpectedly.
This is my Code from Database Class,
public long addscore(String name, int score)
{
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_score, score);
// Inserting Row
return db.insert(DATABASE_TABLE, null, values);
}
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },,KEY_scoreid + "="
+ rowid,null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
And this is the code of class from where i m trying to
fetch the Data from Database table (Highscore.java),
public class Highscore extends Activity
{
TextView name1,name2,name3,name4,name5,score1,score2,score3,score4,score5;
DBAdapter db1;
Cursor c;
int id;
String n1,n2,n3,n4,n5;
String s1,s2,s3,s4,s5;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.highscore);
Button backbtn=(Button)findViewById(R.id.backbtn);
OnClickListener listener=new OnClickListener()
{
public void onClick(View v)
{
Intent i=new Intent(Highscore.this,MainActivity.class);
startActivity(i);
finish();
}
};
backbtn.setOnClickListener(listener);
id=1;
name1=(TextView)findViewById(R.id.name1);
score1=(TextView)findViewById(R.id.score1);
db1=new DBAdapter(this);
db1.open();
c=db1.getScore(1);
n1=c.getString(1);
name1.setText(n1);
s1=c.getString(2);
score1.setText(s1);
c=db1.getScore(2);
n2=c.getString(1);
name2.setText(n2);
s2=c.getString(2);
score2.setText(s2);
c=db1.getScore(3);
n3=c.getString(1);
name3.setText(n3);
s3=c.getString(2);
score3.setText(s3);
id++;
c=db1.getScore(4);
n4=c.getString(1);
name4.setText(n4);
s4=c.getString(2);
score4.setText(s4);
id++;
c=db1.getScore(5);
n5=c.getString(1);
name5.setText(n5);
s5=c.getString(2);
score5.setText(s5);
c.deactivate();
c.close();
db1.close();
}
}
This time i am only fetching 5 names and scores.
Here's my Logcat Error,
09-19 12:01:36.046: D/AndroidRuntime(455): Shutting down VM
09-19 12:01:36.046: W/dalvikvm(455): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-19 12:01:36.066: E/AndroidRuntime(455): FATAL EXCEPTION: main
09-19 12:01:36.066: E/AndroidRuntime(455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.Highscore}: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Handler.dispatchMessage(Handler.java:99)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.os.Looper.loop(Looper.java:123)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invokeNative(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): at java.lang.reflect.Method.invoke(Method.java:521)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-19 12:01:36.066: E/AndroidRuntime(455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-19 12:01:36.066: E/AndroidRuntime(455): at dalvik.system.NativeStart.main(Native Method)
09-19 12:01:36.066: E/AndroidRuntime(455): Caused by: java.lang.NullPointerException
09-19 12:01:36.066: E/AndroidRuntime(455): at com.example.quizapp.Highscore.onCreate(Highscore.java:59)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-19 12:01:36.066: E/AndroidRuntime(455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-19 12:01:36.066: E/AndroidRuntime(455): ... 11 more
If you people are not getting any thing from my question so please ask..
Please help me to Solve out the Error.
Thanks in Advance
From what I see you problem is not in the database connection, you have some untreated exceptions. You have a NULL pointer exception also in onCreate(Highscore.java:59)
You can do a thing: comment parts of the code until you get a working app(that does nothing) and then uncomment until you find the exact code that crashes the app, it is easy to do and usually you will find the line that is problematic
Good luck
Use this code insted of your.....
public Cursor getScore(long rowId) throws SQLException
{
Cursor mCursor = db.query(true,DATABASE_TABLE, new String[] {
KEY_scoreid,KEY_name,KEY_score },KEY_scoreid + " ='"
+ rowid + "'",null,null,null,null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}

Google Places API on Android: No route to host

I am using google places api in my application to show nearby food locations.
I'm using the following code:
public class Background extends AsyncTask<String, Integer, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected String doInBackground(String... params) {
pfr = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
lctn = "location=" + latitude + "," + longitude;
key = "&key=my key";
type = "&types=" + pfr.getString("type", "food");
radius = "&radius=" + pfr.getString("radius", "500");
sensor = "&sensor=false";
StringBuilder requesturl = new StringBuilder(googlegives);
requesturl.append(lctn);
requesturl.append(radius);
requesturl.append(type);
requesturl.append(key);
requesturl.append(sensor);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet req = new HttpGet(requesturl.toString());
Log.d("create", "0");
try {
HttpResponse res = client.execute(req);
HttpEntity jsonentity = res.getEntity();
String data = EntityUtils.toString(jsonentity);
JSONObject jsonobj = new JSONObject(data);
JSONArray resarray = jsonobj.getJSONArray("results");
if (resarray.length() == 0) {
Toast.makeText(getApplicationContext(), "nothing found",
Toast.LENGTH_LONG).show();
} else {
int len = resarray.length();
for (int j = 0; j < len; j++) {
lon = resarray.getJSONObject(j).getJSONObject("geometry")
.getJSONObject("location").getDouble("lng");
lat = resarray.getJSONObject(j).getJSONObject("geometry")
.getJSONObject("location").getDouble("lat");
LatLng latLng = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title(
resarray.getJSONObject(j).getJSONObject("name")
.toString())
.snippet(
resarray.getJSONObject(j)
.getJSONObject("formatted_address")
.toString()));
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
getting latitude and longitude as global variable for getting the user's current location, on running this application on my phone following appear in log cat
03-03 16:52:37.859: W/System.err(4780): java.net.SocketException: No route to host
03-03 16:52:37.906: W/System.err(4780): at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
03-03 16:52:37.906: W/System.err(4780): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
03-03 16:52:37.906: W/System.err(4780): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
03-03 16:52:37.914: W/System.err(4780): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
03-03 16:52:37.914: W/System.err(4780): at java.net.Socket.connect(Socket.java:1002)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-03 16:52:37.921: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-03 16:52:37.921: W/System.err(4780): at com.abhishekbietcs.locomap.Mapme$Background.doInBackground(Mapme.java:258)
03-03 16:52:37.921: W/System.err(4780): at com.abhishekbietcs.locomap.Mapme$Background.doInBackground(Mapme.java:1)
03-03 16:52:37.921: W/System.err(4780): at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-03 16:52:37.921: W/System.err(4780): at java.lang.Thread.run(Thread.java:1019)
Why is this exception being thrown? How can I get rid of it?
java.net.SocketException: No route to host.
This exception occur when there is no route to connect to host.
I found your problem here.
key = "&key=my key";
Replace this with
String APIKEY="AIzaSyDcLMS0IKQL3N76rO-aD2thfO46r96OCQI";
key = "&key=" + APIKEY;
and you have made wrong link.
Your link:
https://maps.googleapis.com/maps/api/place/nearbysearch/output?jsonlocation=25.4509294,78.630043&radius=15000&types=food&key=key&sensor=false
Link must be like:
String url = https://maps.googleapis.com/maps/api/place/search/json?location=25.4509294,78.630043&radius=15000&types=food&key=AIzaSyDcLMS0IKQL3N76rO-aD2thfO46r96OCQI&sensor=false
To get JSON you can use my code.
String data = getUrlContents(url); //Calling method
Definition of Method.
private String getUrlContents(String Url)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(Url);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}

Why does this FileOutputStream give a NullPointerException?

so I am running an app that creates a NullPointerException when I try to write a file.
My first activity (see below) calls the NewSet activity when the user presses the new set button. When I try to write the input in the NewSet activity, it throws a NullPointerException. Printing out fileOut displays me with it having a value of null, which it shouldn't. fileOut is declared globally, but initialized in onCreate. The Two classes are below. (... represents omitted code due to being irrelevant.)
public class MainActivity extends Activity {
static ArrayList sets;
FileOutputStream fileOut;
BufferedReader read;
String line;
ArrayAdapter<String> adapter;
ListView listView;
Intent newSetIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
newSetIntent=new Intent(this,NewSet.class);
listView=(ListView)findViewById(R.id.setList);
sets=new ArrayList();
try {
read=new BufferedReader(new BufferedReader(new InputStreamReader(openFileInput("SETS.txt"))));
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
System.out.println("File not found");
try {
fileOut.write("".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOE");
// TODO Auto-generated catch block
e.printStackTrace();
}
getSets();
toList();
super.onCreate(savedInstanceState);
}
...
public void newSet(String newSetName){
System.out.println(newSetName);
sets.add(newSetName);
try {
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
fileOut.write(newSetName.getBytes());
fileOut.write("\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException NPE){
System.out.println(fileOut);
NPE.printStackTrace();
}
}
}
public class NewSet extends Activity {
EditText input;
String setName;
MainActivity main;
...
public void submit(View view){
setName=input.getText().toString();
System.out.println("CREATING SET:"+setName);
main.newSet(setName);
finish();
}
}
The full stack trace
03-03 23:08:42.183: W/System.err(8435): java.lang.NullPointerException
03-03 23:08:42.183: W/System.err(8435): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:173)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.MainActivity.newSet(MainActivity.java:112)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.NewSet.submit(NewSet.java:35)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$1.onClick(View.java:3594)
03-03 23:08:42.193: W/System.err(8435): at android.view.View.performClick(View.java:4204)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$PerformClick.run(View.java:17355)
03-03 23:08:42.193: W/System.err(8435): at android.os.Handler.handleCallback(Handler.java:725)
03-03 23:08:42.203: W/System.err(8435): at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 23:08:42.203: W/System.err(8435): at android.os.Looper.loop(Looper.java:137)
03-03 23:08:42.203: W/System.err(8435): at android.app.ActivityThread.main(ActivityThread.java:5226)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-03 23:08:42.203: W/System.err(8435): at dalvik.system.NativeStart.main(Native Method)
Exception is getting thrown in android.content.ContextWrapper class. Method is:
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException
{
return mBase.openFileOutput(name, mode); // Line number 173
}
Here, the only possibility I see which could result in NullPointerException is data member mBase of type Context is NULL.
Can you check if Context data member is non-null.

Why am I getting an InvocationTargetException? Android 2D game

I am making a 2D game in Android with Cocos2D, written in Java. Here is my code for the main stuff:
public void gameLoop(float dt) {
//Player Gravity
if(canExecuteMovement(0, 6)) {
guy.moveY(6);
}
//Player Movement
if(direction == 1) {
if(canExecuteMovement(-3, 0))
guy.moveX(-3);
} else if(direction == 2) {
if(canExecuteMovement(3, 0))
guy.moveX(3);
}
}
private boolean canExecuteMovement(int xChange, int yChange) {
int projectedX = guy.getBounds().left + xChange;
int projectedY = guy.getBounds().top + yChange;
Log.i("DD", "guy:" + guy.getBounds().toString());
Rect projectedBounds = new Rect(projectedX, projectedY, projectedX + guy.getWidth(), projectedY + guy.getHeight());
Log.i("DD", "guy:" + projectedBounds.toString());
for (int i = 0; i < platformCount; i++) {
if (Rect.intersects(projectedBounds, platform[i].getBounds())) {
return false;
}
}
return true;
}
As you see, this function looks just fine, and the rectangles in canExecuteMovement are perfectly fine too, however in this line:
LINE 107: if (Rect.intersects(projectedBounds, platform[i].getBounds())) {
I am getting a InvocationTargetException. Here is the logcat:
01-21 23:10:12.601: W/System.err(13118): java.lang.reflect.InvocationTargetException
01-21 23:10:12.601: W/System.err(13118): at java.lang.reflect.Method.invokeNative(Native Method)
01-21 23:10:12.605: W/System.err(13118): at java.lang.reflect.Method.invoke(Method.java:511)
01-21 23:10:12.605: W/System.err(13118): at org.cocos2d.actions.CCTimer.update(CCTimer.java:82)
01-21 23:10:12.605: W/System.err(13118): at org.cocos2d.actions.CCScheduler.tick(CCScheduler.java:253)
01-21 23:10:12.605: W/System.err(13118): at org.cocos2d.nodes.CCDirector.drawCCScene(CCDirector.java:679)
01-21 23:10:12.605: W/System.err(13118): at org.cocos2d.nodes.CCDirector.onDrawFrame(CCDirector.java:649)
01-21 23:10:12.605: W/System.err(13118): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1462)
01-21 23:10:12.605: W/System.err(13118): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1216)
01-21 23:10:12.605: W/System.err(13118): Caused by: java.lang.NullPointerException
01-21 23:10:12.608: W/System.err(13118): at com.qasim.platformer.GameLayer.canExecuteMovement(GameLayer.java:107)
01-21 23:10:12.608: W/System.err(13118): at com.qasim.platformer.GameLayer.gameLoop(GameLayer.java:86)
01-21 23:10:12.608: W/System.err(13118): ... 8 more
01-21 23:10:12.620: D/dalvikvm(13118): GC_CONCURRENT freed 460K, 6% free 9279K/9863K, paused 2ms+3ms
01-21 23:10:12.624: I/DD(13118): guy:Rect(252, 63 - 300, 111)
What could be the problem? the getBounds() class in guy is this:
public Rect getBounds() {
return new Rect(x, y, x+width, y+height);
}
InvocationTargetException is just a wrapper for an exception that's thrown within a dynamic invocation. The true problem is the NullPointerException that it's wrapping:
Caused by: java.lang.NullPointerException
at com.qasim.platformer.GameLayer.canExecuteMovement(GameLayer.java:107)
at com.qasim.platformer.GameLayer.gameLoop(GameLayer.java:86)
As you've pointed out, this is the offending line:
if (Rect.intersects(projectedBounds, platform[i].getBounds())) {
The only place a null pointer could be happening on this line is at platform[i].getBounds(). Either platform itself is null, or the element at platform[i] is.

Categories