Why am I getting an InvocationTargetException? Android 2D game - java

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.

Related

Android BackgroundTask Throwing Run-time Error

Im attempting to connect to a database via a backgroundtask via a tab but it does not like it. Can you guys see what the issue is, as I used same code in another project and worked fine..
public class Tab2Activity extends Activity
{
SharedPreferences preferences;
String driver;
String task;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tab2);
preferences = getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
TextView name = (TextView) findViewById (R.id.textView1);
// dummy data to send
task="login";
driver="2";
// create and call background activity
BackgroundTask backgroundTask = new BackgroundTask(Tab2Activity.this);
backgroundTask.execute(task,driver);
//get data back from sharedpreference
String mName = preferences.getString("myData","ERROR getting name");
//display data
name.setText(mName);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tab2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the backGroundTask code
public class BackgroundTask extends AsyncTask<String,Void,String>
{
SharedPreferences preferences;
SharedPreferences.Editor editor;
SharedPreferences.Editor pig;
Context context;
BackgroundTask(Context ctx)
{
this.context = ctx;
}
#Override
protected String doInBackground(String... params)
{
preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.putString("flag","0");
editor.commit();
String urlLogin = "http://Domain.com/GetJobs.php";
String task = params[0];
String driver_id_app = params[1];
try {
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the driver number to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myData = URLEncoder.encode("driver_id","UTF-8")+"="+URLEncoder.encode(driver_id_app,"UTF-8");
//+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8");
bufferedWriter.write(myData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null){
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
///System.out.println(dataResponse);
editor.putString("flag","login");
editor.commit();
pig = preferences.edit();
pig.putString("myData",dataResponse);
pig.commit();
return dataResponse;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
public void display(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
These are the error logs
01-21 23:28:26.074: E/AndroidRuntime(27426): FATAL EXCEPTION: AsyncTask #3
01-21 23:28:26.074: E/AndroidRuntime(27426): Process: com.example.tabdemo, PID: 27426
01-21 23:28:26.074: E/AndroidRuntime(27426): java.lang.RuntimeException: An error occurred while executing doInBackground()
01-21 23:28:26.074: E/AndroidRuntime(27426): at android.os.AsyncTask$3.done(AsyncTask.java:309)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
01-21 23:28:26.074: E/AndroidRuntime(27426): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.lang.Thread.run(Thread.java:818)
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.lookupHostByName(InetAddress.java:464)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.getAllByName(InetAddress.java:215)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:220)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:176)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:108)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:482)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:465)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:447)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:353)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:118)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:249)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.example.tabdemo.BackgroundTask.doInBackground(BackgroundTask.java:63)
01-21 23:28:26.074: E/AndroidRuntime(27426): at com.example.tabdemo.BackgroundTask.doInBackground(BackgroundTask.java:1)
01-21 23:28:26.074: E/AndroidRuntime(27426): at android.os.AsyncTask$2.call(AsyncTask.java:295)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
01-21 23:28:26.074: E/AndroidRuntime(27426): ... 4 more
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
01-21 23:28:26.074: E/AndroidRuntime(27426): at libcore.io.Posix.android_getaddrinfo(Native Method)
01-21 23:28:26.074: E/AndroidRuntime(27426): at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
01-21 23:28:26.074: E/AndroidRuntime(27426): at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
01-21 23:28:26.074: E/AndroidRuntime(27426): ... 21 more
01-21 23:28:26.074: E/AndroidRuntime(27426): Caused by: android.system.ErrnoException: android_getaddrinfo failed: EACCES (Permission denied)
01-21 23:28:26.074: E/AndroidRuntime(27426): ... 24 more
Really hope you guys can suggest something...
I can clearly see that you are missing the internet connection permission.
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
You need to add this in your manifest to enable internet connection:
<uses-permission android:name="android.permission.INTERNET" />

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

Debugging AsyncTask - strange behaviour, debug jumping into the code

I'm debugging an Asynctask that simply downloads a file: here the code:
public class AsyncDownloadFilesTask extends AsyncTask<String, Integer, Boolean> {
public AsyncResponse<Boolean> delegate=null;
protected Boolean doInBackground(String... params) {
android.os.Debug.waitForDebugger();
try {
URL url = new URL(params[0]);
int count;
String fileName = new String(params[1]);
URLConnection connessione = url.openConnection();
connessione.connect();
int lenghtOfFile = connessione.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileName);
long total = 0;
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return Boolean.valueOf(true);
} catch (Exception e) {
return null;
}
}
protected void onPostExecute(Boolean result) {
delegate.processFinish(result);
}
}
I obtain a strange behaviour: when execution arrive to return
Boolean.valueOf(true);
it skips to
return null;
into the catch block, but Exception e is null, and then debugger goto line 1 of AsyncTask, that is simply
package com.example.compa.asynctasks;
Then execution goes on (executing onPostExecute method) and, of course, returned result is null
What happens? Why debug jump in this way?
Task download correctly the file.
Here code of the Activity that instantiates and calls Async Task
package com.example.compa.activities;
import android.app.Activity;
import ...
public class CoverActivity extends Activity implements AsyncResponse<Boolean>{
ImageView coverImg;
Drawable d;
CompassesFileManager cfm;
int coverId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cover);
coverId = getIntent().getExtras().getInt("coverId");
cfm = new CompassesFileManager(this);
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
d = cfm.getCover(coverId);
if (d!=null){
coverImg.setImageDrawable(d);
} else {
AsyncDownloadFilesTask task = new AsyncDownloadFilesTask();
task.delegate = this;
task.execute(cfm.getCoverURL(coverId), cfm.getCoverFileName(coverId));
}
}
#Override
public void processFinish(Boolean output) {
if (output){
Drawable d = cfm.getCover(coverId);
coverImg.setImageDrawable(d);
} else {
finish();
}
}
}
Stacktrace of error:
02-21 19:37:29.520: E/AndroidRuntime(407): FATAL EXCEPTION: main
02-21 19:37:29.520: E/AndroidRuntime(407): java.lang.NullPointerException
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:1)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.finish(AsyncTask.java:631)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask.access$600(AsyncTask.java:177)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Handler.dispatchMessage(Handler.java:99)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.os.Looper.loop(Looper.java:176)
02-21 19:37:29.520: E/AndroidRuntime(407): at android.app.ActivityThread.main(ActivityThread.java:5419)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 19:37:29.520: E/AndroidRuntime(407): at java.lang.reflect.Method.invoke(Method.java:525)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-21 19:37:29.520: E/AndroidRuntime(407): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-21 19:37:29.520: E/AndroidRuntime(407): at dalvik.system.NativeStart.main(Native Method)
line:
02-21 19:37:29.520: E/AndroidRuntime(407): at com.example.compa.asynctasks.AsyncDownloadFilesTask.onPostExecute(AsyncDownloadFilesTask.java:65)
is the last one of AsyncDownloadFilesTask class, and is a closing bracket, }
Thank you
I don't have enough points to comment, but it looks like delegate is null in your onPostExecute
delegate.processFinish(result); // delegate is null
if that's not the case, you're code stub above doesn't define it though.
I solved on my own.
1st, I move call to the Async Task in the onStart() method, instead of onCreate()
2nd, I made a mistake, in change line
ImageView coverImg = (ImageView)findViewById(R.id.cover_image);
in
coverImg = (ImageView)findViewById(R.id.cover_image);
to avoid a stupid null pointer (I already declared coverImg)!
Anyway, I still don't understand debug's behaviour, but I solved my problem.
Thank you everybody

How come this Fragment crashes my program on rotate?

I have the following Fragment. It works completely fine, until I rotate my device. It then crashes with errors about the RadarSelectionFragment failing to Instantiate. The code for the FragmentPagerAdapter and the Fragment in question are below:
#SuppressLint("DefaultLocale")
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter() {
// Do some stuff
}
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
Fragment fragment = new RadarSelectionFragment();
Bundle args = new Bundle();
args.putInt(RadarSelectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
} else if (position == 1) {
Fragment fragment = new WeatherMapDisplayFragment();
Bundle args = new Bundle();
args.putInt(WeatherMapDisplayFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
} else {
Fragment tf = new RadarSelectionFragment();
return tf;
}
}
#Override
public int getCount() {
return 2;
}
#SuppressLint("DefaultLocale")
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
}
return null;
}
}
public static class RadarSelectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public RadarSelectionFragment() {}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
return inflater.inflate(R.layout.radars, container, false);
} else {
return container;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
...
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
}
}
public class WeatherMapDisplayFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public WeatherMapDisplayFragment() {
}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
return inflater.inflate(R.layout.display, container, false);
} else {
return container;
}
}
}
I have tried Googling the problem, but all I keep turning up are various solutions pertaining to ensuring that the Fragment Class is static (Which I've done).
I am relatively new to Android programming, so if you answer, could you please either post an example and/or link to other examples if you have the time.
Thanks in advance!
EDIT 1: Stacktrace
01-21 13:46:31.907: E/AndroidRuntime(1101): FATAL EXCEPTION: main
01-21 13:46:31.907: E/AndroidRuntime(1101): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.radarau/com.example.radarau.MainActivity}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3692)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.access$700(ActivityThread.java:141)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.os.Looper.loop(Looper.java:137)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.reflect.Method.invokeNative(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.reflect.Method.invoke(Method.java:511)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-21 13:46:31.907: E/AndroidRuntime(1101): at dalvik.system.NativeStart.main(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.Fragment.instantiate(Fragment.java:405)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentState.instantiate(Fragment.java:97)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1767)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:208)
01-21 13:46:31.907: E/AndroidRuntime(1101): at com.example.radarau.MainActivity.onCreate(MainActivity.java:35)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.Activity.performCreate(Activity.java:5104)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-21 13:46:31.907: E/AndroidRuntime(1101): ... 12 more
01-21 13:46:31.907: E/AndroidRuntime(1101): Caused by: java.lang.InstantiationException: can't instantiate class com.example.radarau.MainActivity$WeatherMapDisplayFragment; no empty constructor
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.Class.newInstanceImpl(Native Method)
01-21 13:46:31.907: E/AndroidRuntime(1101): at java.lang.Class.newInstance(Class.java:1319)
01-21 13:46:31.907: E/AndroidRuntime(1101): at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
01-21 13:46:31.907: E/AndroidRuntime(1101): ... 19 more
Your logcat says
Caused by: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.radarau.MainActivity$WeatherMapDisplayFragment: make sure class name exists, is public, and has an empty constructor that is public
You should provide a public Default constructor for that
public WeatherMapDisplayFragment() {
// Do some stuff
}
If that class is nested, make that class to static class and provide a public default constructor or move that fragment into a new java file.

Android JavaCV dilemma, NoClassDefFoundError thrown inside of method 'draw' when IplImage is created

I am using the JavaCV library with pre-built OpenCV libraries for Android. I think I have setup Eclipse the right way, because I have included the jars both javacv.jar and javacpp.jar. In addition, the java-cv-android-arm.jar, in my project. Everything compiles fine, no errors, warning, anything that should be suspicious of something that will go wrong at runtime. But I get NoClassDefFOundError exception that is thrown in this method body below:
#Override
public void draw(Canvas canvas)
{
try
{
canvas.drawColor(Color.BLUE);
if (current != null)
{
int width = current.getWidth();
int height = current.getHeight();
IplImage i = IplImage.create(width, height, IPL_DEPTH_8U, 1); // I assume here is where the exception gets thrown
ByteBuffer buffer = i.getByteBuffer();
current.copyPixelsToBuffer(buffer);
// We need a grayscale image in order to do the recognition, so
// we
// create a new image of the same size as the original one.
IplImage grayImage = IplImage.create(i.width(), i.height(),
IPL_DEPTH_8U, 1);
// We convert the original image to grayscale.
cvCvtColor(i, grayImage, CV_BGR2GRAY);
CvMemStorage storage = CvMemStorage.create();
// We instantiate a classifier cascade to be used for detection,
// using the cascade definition.
CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(
cvLoad("haarcascade_frontalface_alt.xml"));
// We detect the faces.
CvSeq faces = cvHaarDetectObjects(grayImage, cascade, storage,
1.1, 1, 0);
// We iterate over the discovered faces and draw yellow
// rectangles around them.
for (int index = 0; index < faces.total(); index++)
{
CvRect r = new CvRect(cvGetSeqElem(faces, index));
cvRectangle(i, cvPoint(r.x(), r.y()),
cvPoint(r.x() + r.width(), r.y() + r.height()),
opencv_core.CvScalar.YELLOW, 1, CV_AA, 0);
}
Bitmap b = BitmapFactory.decodeByteArray(i.getByteBuffer()
.array(), 0, i.getByteBuffer().array().length);
canvas.drawBitmap(b, x, y, paint);
canvas.drawText(new Date().toLocaleString(), canvas.getWidth() - 100,
canvas.getHeight() - 50, paint);
paint.setColor(Color.GREEN);
}
} catch (Exception e)
{
canvas.drawColor(Color.RED);
canvas.drawText(
"Handled exception occurred in panel:\n" + e.getMessage(),
250, 250, paint);
paint.setColor(Color.GREEN);
}
super.draw(canvas);
}
And of course, right after the exception is thrown, my Android crashes, and I force close the application. Did I include the jars, and required libraries correctly? Is there anything that I should be aware of? Any help would be greatly appreciated.
Here is the LogCat for those who love Cats (insert emoticon here):
05-03 19:07:53.217: E/AndroidRuntime(741): FATAL EXCEPTION: main
05-03 19:07:53.217: E/AndroidRuntime(741): java.lang.NoClassDefFoundError: com.googlecode.javacv.cpp.opencv_core$IplImage
05-03 19:07:53.217: E/AndroidRuntime(741): at home.security.DrawingPanel.draw(DrawingPanel.java:81)
05-03 19:07:53.217: E/AndroidRuntime(741): at home.security.Main$2.run(Main.java:105)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.os.Handler.handleCallback(Handler.java:587)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.os.Handler.dispatchMessage(Handler.java:92)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.os.Looper.loop(Looper.java:123)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-03 19:07:53.217: E/AndroidRuntime(741): at java.lang.reflect.Method.invokeNative(Native Method)
05-03 19:07:53.217: E/AndroidRuntime(741): at java.lang.reflect.Method.invoke(Method.java:507)
05-03 19:07:53.217: E/AndroidRuntime(741): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-03 19:07:53.217: E/AndroidRuntime(741): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-03 19:07:53.217: E/AndroidRuntime(741): at dalvik.system.NativeStart.main(Native Method)
Folder Structure Of 'libs Folder
The jars need to be in the project-root/libs folder or to mark them as exported in the build path of the project...
now it should work...

Categories