I have a problem launching my application in my emulator. When I run it, I get the message "Sorry MyApp has stopped unexpectedly"
This is what I get in my LogCat:
12-22 06:59:42.196: D/AndroidRuntime(1083): Shutting down VM
12-22 06:59:42.196: W/dalvikvm(1083): threadid=1: thread exiting with uncaught exception (group=0xb60294f0)
12-22 06:59:42.285: E/AndroidRuntime(1083): FATAL EXCEPTION: main
12-22 06:59:42.285: E/AndroidRuntime(1083): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.helloworld5/com.example.helloworld5.MainActivity}: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.os.Handler.dispatchMessage(Handler.java:99)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.os.Looper.loop(Looper.java:130)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.reflect.Method.invokeNative(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.reflect.Method.invoke(Method.java:507)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-22 06:59:42.285: E/AndroidRuntime(1083): at dalvik.system.NativeStart.main(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): Caused by: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Activity.findViewById(Activity.java:1647)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.example.helloworld5.MainActivity.<init>(MainActivity.java:14)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstanceImpl(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstance(Class.java:1409)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
12-22 06:59:42.285: E/AndroidRuntime(1083): ... 11 more
So I looked in my Manifest file and changed
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
to:
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.helloworld5.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
However when I run it after the change I get No launch activity found!.
This is my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld5"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Floor"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.helloworld5.FLOOR" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
This is my MainActivity code:
MainActivity.java
package com.example.helloworld5;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
//String name;
DrawView drawView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText dest = (EditText)findViewById(R.id.y_editText2);
//final String roomName = dest.getText().toString();
final Button openFloor = (Button)findViewById(R.id.y_button1);
openFloor.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
drawView.setRoomName(dest.getText().toString());
startActivity(new Intent("com.example.helloworld5.FLOOR"));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
}
DrawView.java:
public class DrawView extends View {
Paint paint = new Paint();
float ux, dx, rx,lx;
String roomName2 ;
public DrawView(Context context) {
super(context);
paint.setColor(Color.RED);
//roomName2 = drawView.getTag();
}
public void setRoomName(String name) {
this.roomName2 = name;
}
public String getRoomName(){
return roomName2;
}
public void setCoordinates(){
};
#Override
public void onDraw(Canvas canvas) {
String roomName = getRoomName();
if(roomName == "C154"){
ux =90;
dx = 250;
rx = 90;
lx = 400;
}else {
ux =76;
dx = 98;
rx = 140;
lx = 300;
}
canvas.drawLine(90, 250 , 90, 400, paint);
canvas.drawLine(20, 0, 0, 20, paint);
canvas.drawCircle(150, 400, 30, paint);
}
}
How can I fix this crash?
According to this
12-22 06:59:42.285: E/AndroidRuntime(1083): Caused by: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Activity.findViewById(Activity.java:1647)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.example.helloworld5.MainActivity.<init>(MainActivity.java:14)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstanceImpl(Native Method)
12-22 06:59:42.285: E/AndroidRuntime(1083): at java.lang.Class.newInstance(Class.java:1409)
You are calling findViewById in the constructor of your activity. However, by then, the layout hasnt been inflated. Move the method call to onCreate:
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
dest = (EditText)findViewById(R.id.y_editText2);
//et cetera
}
EDIT:
Also, you're setting String roomName = dest.getText().toString(); on a null reference now. set the onClickListener like this:
openFloor.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
drawView.setRoomName(dest.getText().toString);
startActivity(new Intent("com.example.helloworld5.FLOOR"));
}
});
EDIT2: Your second NPE is because DrawView is not initialized, initialize it as well:
public void onCreate(Bundle b) {
super.onCreate(b);
//...your other stuff
this.drawView = (DrawView) findViewById(R.id.myDrawView);
}
You should move
EditText dest = (EditText)findViewById(R.id.y_editText2);
inside onCreate(...) after setContentView(...)
Issue is:
12-22 06:59:42.285: E/AndroidRuntime(1083): Caused by: java.lang.NullPointerException
12-22 06:59:42.285: E/AndroidRuntime(1083): at android.app.Activity.findViewById(Activity.java:1647)
12-22 06:59:42.285: E/AndroidRuntime(1083): at com.example.helloworld5.MainActivity.<init>(MainActivity.java:14)
Put
EditText dest = (EditText)findViewById(R.id.y_editText2);
after your setContentView
This will just resolve current crash.
PLUS
put your
String roomName = dest.getText().toString();
in button click call.
If you will keep it in global variale section, it will give you NullPointerException for dest. And if you put this line in onCreate just after findViewById, it will just give you roomName = "" as at that time view has just been initialized. User entered value won't be there.
Your activity should be like this.
public class MainActivity extends ActionBarActivity {
DrawView drawView;
String roomName;
EditText dest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dest = (EditText)findViewById(R.id.y_editText2);
final Button openFloor = (Button)findViewById(R.id.y_button1);
openFloor.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
roomName = dest.getText().toString();
drawView.setRoomName(roomName);
startActivity(new Intent("com.example.helloworld5.FLOOR"));
}
});
}
}
Related
I create custom action bar I really don't know where is my mistake.I have some problems while creating Custom action bar.
And showing the null pointer exception at the line = mActionBar.setDisplayShowHomeEnabled(false);
Here is my error log
07-29 16:19:20.180 32714-32714/com.example.tazeen.classnkk E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tazeen.classnkk/com.example.tazeen.classnkk.AllPosts_Page}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.tazeen.classnkk.AllPosts_Page.CustomActionBar(AllPosts_Page.java:37)
at com.example.tazeen.classnkk.AllPosts_Page.onCreate(AllPosts_Page.java:28)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
I have try last 5 to 7 hours , but can not find any proper solution.Please help me.Thanks.
Here is my Activity code
public class AllPosts_Page extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_post);
CustomActionBar();
}
public void CustomActionBar()
{
android.app.ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.custom_action_bar, null);
TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.txtTitle);
mTitleTextView.setText("All Post");
ImageView imageButton = (ImageView) mCustomView
.findViewById(R.id.imgLeftMenu);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
}
});
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
}
menifest file
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar">
<activity
android:name=".Splash_Screen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Login_Screen" />
<activity
android:name=".AllPosts_Page">
</activity>
<activity
android:name=".Filter_Page"
android:label="#string/title_activity_filter__page"
android:theme="#style/ListFont">
</activity>
</application>
</manifest>
style.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="android:height">5dp</item>
</style>
</resources>
you are using Theme.AppCompat.Light.DarkActionBar so you should get your ActionBar by getSupportActionBar() method, not getActionBar()
if your extended Activity is from Android system then style is incorrect (AppCompat) and Activity gets some default styling without ActionBar, so getActionBar() return null
else if you want to use this AppCompat style it is applicable for AppCompatActivity (and then you use should getSupportActionBar())
I'm trying unzip some files in background, so I use IntentService like in google's tutorial. My service class declared in AndroidManifest like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.osmdroid">
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="21" />
<application
android:configChanges="orientation|screenSize|keyboardHidden"
android:hardwareAccelerated="true"
android:icon="#drawable/ecn_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MapActivity"
android:icon="#drawable/ecn_icon"
android:label="test" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings">
</activity>
<service
android:name=".UnZipService"
android:exported="false"/>
</application>
In activity, I have
IntentFilter intentFilter = new IntentFilter(DownloadManager
.ACTION_DOWNLOAD_COMPLETE);
receiverDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long reference = intent.getLongExtra(DownloadManager
.EXTRA_DOWNLOAD_ID, -1);
if (myDownloadReference == reference) {
...
switch (status) {
case DownloadManager.STATUS_SUCCESSFUL:
Intent mServiceIntent = new Intent(context, UnZipService.class);
mServiceIntent.setData(Uri.parse(savedFilePath));
startActivity(mServiceIntent);
break;
...
}
cursor.close();
}
}
};
registerReceiver(receiverDownloadComplete, intentFilter);
And service here:
public class UnZipService extends IntentService {
public UnZipService() {
super("UnZipService");
}
#Override
protected void onHandleIntent(Intent workIntent) {
String dataString = workIntent.getDataString();
Log.v("IntentURI", dataString);
Toast.makeText(this, "Installing....", Toast.LENGTH_SHORT).show();
}
It should show toast just for test, but I always get an error:
01-29 19:08:25.740 15521-15521/org.osmdroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.DOWNLOAD_COMPLETE flg=0x10 pkg=org.osmdroid (has extras) } in org.osmdroid.SettingsActivity$1#21292650
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:768)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5147)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {org.osmdroid/org.osmdroid.UnZipService}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1618)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1417)
at android.app.Activity.startActivityForResult(Activity.java:3404)
at android.app.Activity.startActivityForResult(Activity.java:3365)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:817)
at android.app.Activity.startActivity(Activity.java:3600)
at android.app.Activity.startActivity(Activity.java:3568)
at org.osmdroid.SettingsActivity$1.onReceive(SettingsActivity.java:148)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:758)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5147)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Both (class and activity) in same folder (org.osmdroid). Seems like paths is ok, but the problem appears and I have no more ideas...
You are starting a service as an activity
Change
Intent mServiceIntent = new Intent(context, UnZipService.class);
mServiceIntent.setData(Uri.parse(savedFilePath));
startActivity(mServiceIntent);
to
Intent mServiceIntent = new Intent(context, UnZipService.class);
mServiceIntent.setData(Uri.parse(savedFilePath));
startService(mServiceIntent); // Only this line is changed
Please declared this activity in your AndroidManifest.xml
I have created new activity that my MainActivity Should lunch, some why the application is crashing on the start of the new activity (called GamePlayActivity).
Here is the java code:
Intent startGameDrill = new Intent(MainActivity.this, GamePlayActivity.class);
startActivity(startGameDrill);
Here is the startGameDrill:
package com.simplemathgame;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class GamePlayActivity extends MainActivity {
int addDrills;
int subDrils;
int mulDrills;
int divDrills;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_play);
try {
numberOfAddDrills = (TextView) findViewById(R.id.add_drills_number);
numberOfSubDrills = (TextView) findViewById(R.id.sub_drills_number);
numberOfMulDrills = (TextView) findViewById(R.id.mul_drills_number);
numberOfDivDrills = (TextView) findViewById(R.id.div_drills_number);
minBoundText = (TextView) findViewById(R.id.min_text);
maxBoundText = (TextView) findViewById(R.id.max_text);
} catch (Exception e1) {
// TODO Auto-generated catch block
Log.w("game","error");
}
try {
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());
subDrils = Integer.parseInt((String) numberOfSubDrills.getText());
mulDrills = Integer.parseInt((String) numberOfMulDrills.getText());
divDrills = Integer.parseInt((String) numberOfDivDrills.getText());
} catch (NumberFormatException e) {
Log.w("GameDrills","string to int");
}
Log.w("add", "" + addDrills);
Log.w("add", "" + subDrils);
Log.w("add", "" + mulDrills);
Log.w("add", "" + divDrills);
}
}
Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.simplemathgame"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<activity
android:name="com.simplemathgame.Splash"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.simplemathgame.MainActivity"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="com.simplemathgame.MainActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.simplemathgame.GamePlayActivity"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen" >
</activity>
</application>
</manifest>
here is the logCat:
12-21 22:05:53.949: D/dalvikvm(610): GC_EXTERNAL_ALLOC freed 42K, 53% free 2546K/5379K, external 1917K/2137K, paused 41ms
12-21 22:06:32.809: D/AndroidRuntime(610): Shutting down VM
12-21 22:06:32.809: W/dalvikvm(610): threadid=1: thread exiting with uncaught exception (group=0x40015560)
12-21 22:06:32.818: E/AndroidRuntime(610): FATAL EXCEPTION: main
12-21 22:06:32.818: E/AndroidRuntime(610): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.simplemathgame/com.simplemathgame.GamePlayActivity}: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.os.Handler.dispatchMessage(Handler.java:99)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.os.Looper.loop(Looper.java:123)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.main(ActivityThread.java:3683)
12-21 22:06:32.818: E/AndroidRuntime(610): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 22:06:32.818: E/AndroidRuntime(610): at java.lang.reflect.Method.invoke(Method.java:507)
12-21 22:06:32.818: E/AndroidRuntime(610): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-21 22:06:32.818: E/AndroidRuntime(610): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-21 22:06:32.818: E/AndroidRuntime(610): at dalvik.system.NativeStart.main(Native Method)
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-21 22:06:32.818: E/AndroidRuntime(610): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-21 22:06:32.818: E/AndroidRuntime(610): ... 11 more
Here is the layout of the GamePlayActivity:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:background="#000044">
<TableRow
android:layout_marginTop="10dp"
android:gravity="center_vertical" >
<TextView
android:textColor="#FFFFFFFF"
android:textSize="16sp"
android:textStyle="bold"
android:text="Addition Drills:"/>
</TableRow>
</TableLayout>
Why does it crashes?
Have a look here:
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)
Line 31 of GamePlayActivity.java is this line:
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());
Since the only thing on this line that you reference a member or method of is numberOfAddDrills, then it must be null.
Consider that you are checking for exceptions when using findViewById; however, if the view is not found it will just return null, not throw an exception.
Have a look at the activity_game_play.xml you posted; there is no TextView with android:id="#+id/add_drills_number". You need to create it, and the same deal for the other five TextViews.
Oh, and a hint: Don't just catch generic exceptions with } catch (Exception e1) {, especially if you have no intent of reading the logs. I can't tell you how many times people have missed errors from doing this.
If you want to pass values from another layout, you have two options: keep a reference to the View objects (this is a bit silly, don't do this); or pass the data you need from them to your new Activity:
startGameDrill.putExtra("myIntExtra", 5); // For example
Then, in GamePlayActivity.onCreate(), you can fetch it using getIntent()'s extras:
Bundle extras = getIntent().getExtras();
int myIntExtra = extras.getInt("myIntExtra");
Then use that value instead of relying on the view in the previous layout. There is a fuller example in this answer.
Follow the stacktrace until you find some references to your classes:
It shows:
12-21 22:06:32.818: E/AndroidRuntime(610): Caused by: java.lang.NullPointerException
12-21 22:06:32.818: E/AndroidRuntime(610): at com.simplemathgame.GamePlayActivity.onCreate(GamePlayActivity.java:31)
So you are creating a NullPointerException at line 31 in GamePlayActivity.java
Line 31:
addDrills = Integer.parseInt((String) numberOfAddDrills.getText());
so maybe numberOfAddDrills is null?
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm a novice android app developer. I wrote an application which fetches Bible Readings from online. I wrote the separate Java class for fetching the reading and I tested it and it's working fine. But when I tried to use that in my Android App, my app crashed and stops working. I've understood from the logs that it's throwing a null pointer exception, but I don't how to fix that. I've also checked the internet and I can't find an exact solution for this. I'm attaching the logs and file related to my application below. Could anyone go through my code and throw some light on fixing the error. I appreciate your time on my behalf and many thanks in advance.
10-25 09:49:23.243: E/AndroidRuntime(620): FATAL EXCEPTION: main
10-25 09:49:23.243: E/AndroidRuntime(620): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mgocsm/com.mgocsm.EveningKymthaPrayers}: java.lang.NullPointerException: println needs a message
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.os.Handler.dispatchMessage(Handler.java:99)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.os.Looper.loop(Looper.java:137)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-25 09:49:23.243: E/AndroidRuntime(620): at java.lang.reflect.Method.invokeNative(Native Method)
10-25 09:49:23.243: E/AndroidRuntime(620): at java.lang.reflect.Method.invoke(Method.java:511)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-25 09:49:23.243: E/AndroidRuntime(620): at dalvik.system.NativeStart.main(Native Method)
10-25 09:49:23.243: E/AndroidRuntime(620): Caused by: java.lang.NullPointerException: println needs a message
10-25 09:49:23.243: E/AndroidRuntime(620): at android.util.Log.println_native(Native Method)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.util.Log.d(Log.java:138)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.mgocsm.BibleReader.getVerses(BibleReader.java:44)
10-25 09:49:23.243: E/AndroidRuntime(620): at com.mgocsm.EveningKymthaPrayers.onCreate(EveningKymthaPrayers.java:25)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.Activity.performCreate(Activity.java:5008)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-25 09:49:23.243: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-25 09:49:23.243: E/AndroidRuntime(620): ... 11 more
EveningKymthaPrayers.java (Activitiy from where I call the Java class to fetch readings)
=========================
.
public class EveningKymthaPrayers extends Activity {
AssetManager am;
FileReader f;
TextView kymtha_prayer;
BibleReader bible;
//ReadingList rl = new ReadingList();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.evening_kymtha);
am = getAssets();
f = new FileReader(am,"kymtha.txt");
kymtha_prayer = (TextView) findViewById(R.id.show_kymtha);
kymtha_prayer.setMovementMethod(new ScrollingMovementMethod());
bible = new BibleReader("John 3:16-17");
kymtha_prayer.setText(bible.getVerses());
//kymtha_prayer.setText(f.readFile());
//kymtha_prayer.setText(setText);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
BibleReader.java (Java class for fetching Bible verses)
public class BibleReader {
public static final String URL="http://labs.bible.org/api/?passage=";
String verse;
String logName = "BibleReader";
String line;
StringBuilder recText;
private static final int BUFFER_SIZE = 1024 * 10;
private final byte[] dataBuffer = new byte[BUFFER_SIZE];
public BibleReader(String verse) {
// TODO Auto-generated constructor stub
this.verse = verse;
this.verse = this.verse.toString().replaceAll(" ", "%20");
}
public String getVerses()
{
String body = null;
try{
URL url = new URL(URL+this.verse);
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(dataBuffer)) != -1) {
baos.write(dataBuffer, 0, len);
}
body = new String(baos.toByteArray(), encoding);
Log.d(logName, "Fetched Verse"+body);
}
catch(Exception e){
Log.d(logName, e.getMessage());
}
return body.toString();
}
}
AndroidMainfest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mgocsm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DailyPrayers" android:label="#string/app_name"></activity>
<activity android:name=".EveningPrayers" android:label="#string/app_name"></activity>
<activity android:name=".EveningKymthaPrayers" android:label="#string/app_name"></activity>
</application>
</manifest>
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
switch(v.getId()){
case R.id.daily_prayers:
startActivity(new Intent(getApplicationContext(),DailyPrayers.class));
break;
}
}
}
DailyPrayers.java
public class DailyPrayers extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_prayers);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
switch(v.getId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
break;
case R.id.evening_prayers:
startActivity(new Intent(getApplicationContext(),EveningPrayers.class));
break;
}
}
}
EveningPrayers.java
public class EveningPrayers extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.evening_prayers);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
switch(v.getId()){
case R.id.kymtha_evening:
startActivity(new Intent(getApplicationContext(),EveningKymthaPrayers.class));
break;
case R.id.sleeba_evening:
break;
}
}
}
The body that you are trying to print is getting null as a value.Check first you receive any value in body or not.
What i have noticed in your code:
bible.getVerses() is returning null
It seems INTERNET permission is not included in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Don't make a web call on Main thread. Instead you can use AsyncTask or AsyncTaskLoader
Instead of using:
this.verse = this.verse.toString().replaceAll(" ", "%20");
You must use:
String webURL = URLEncoder.encode("your web url", "utf-8");
What are you logging at this place: com.mgocsm.BibleReader.getVerses(BibleReader.java:44)
?
You are probably passing a Null.
Add this permission in your Manifest
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
body = new String(baos.toByteArray(), encoding);
Log.d(logName, "Fetched Verse"+body);
your Body is getting null value that is why ur log is giving nullpointer exception
I've been reading up examples on how to do this, trying to piece together a functioning example from posts on this site and others. I'm sure I'm missing something small, but as a novice to Java, I could use some assistance.
I'm merely trying to create a small example, derived from the automated hello world generated when creating a new project in Eclipse. All I want to do is be able to store a few global variables in a subclass, then reference those values in my main activity. Unfortunately, every time I try to run the app, it crashes "Unfortunately, GeneralTest1 has stopped", and the log cat error is not very helpful.
Quick overview:
GlobalVars class extends Application
In the manifest, android:name has been added to reference the additional GlobalVars class
Within my main activity, I'm initializing the global vars class with getApplicationContext()
Here is everything I've got; any help would be much appreciated!
MainActivity.java
package com.example.generaltest1;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
GlobalVars myVars = ((GlobalVars)getApplicationContext());
TextView myText = (TextView) findViewById(R.id.myText);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myText.setText(myVars.getMyString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
GlobalVars.java
package com.example.generaltest1;
import android.app.Application;
public class GlobalVars extends Application {
String myString = "Some Text";
public String getMyString() {
return myString;
}
public String setMyString(String string) {
this.myString = string;
return myString;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
strings.xml
<resources>
<string name="app_name">GeneralTest1</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>
GeneralTest1 Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.generaltest1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:name="GlobalVars">
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Log Cat
08-14 09:53:05.546: E/Trace(620): error opening trace file: No such file or directory (2)
08-14 09:53:05.656: D/AndroidRuntime(620): Shutting down VM
08-14 09:53:05.656: W/dalvikvm(620): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
08-14 09:53:05.676: E/AndroidRuntime(620): FATAL EXCEPTION: main
08-14 09:53:05.676: E/AndroidRuntime(620): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.generaltest1/com.example.generaltest1.MainActivity}: java.lang.NullPointerException
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.access$600(ActivityThread.java:130)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.os.Handler.dispatchMessage(Handler.java:99)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.os.Looper.loop(Looper.java:137)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.main(ActivityThread.java:4745)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.reflect.Method.invokeNative(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.reflect.Method.invoke(Method.java:511)
08-14 09:53:05.676: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-14 09:53:05.676: E/AndroidRuntime(620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-14 09:53:05.676: E/AndroidRuntime(620): at dalvik.system.NativeStart.main(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620): Caused by: java.lang.NullPointerException
08-14 09:53:05.676: E/AndroidRuntime(620): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:101)
08-14 09:53:05.676: E/AndroidRuntime(620): at com.example.generaltest1.MainActivity.<init>(MainActivity.java:10)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.Class.newInstanceImpl(Native Method)
08-14 09:53:05.676: E/AndroidRuntime(620): at java.lang.Class.newInstance(Class.java:1319)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
08-14 09:53:05.676: E/AndroidRuntime(620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
08-14 09:53:05.676: E/AndroidRuntime(620): ... 11 more
You are calling getApplicationContext() in your class definition, which is too early in the activity lifetime and results in a nullpointer exception. Move the assignments to your onCreate() function and it should work as expected.
Please check this article about activities and their lifecycle :
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Your activity should look like this:
public class MainActivity extends Activity {
GlobalVars myVars;
TextView myText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myVars = ((GlobalVars)getApplication());
myText = (TextView) findViewById(R.id.myText);
myText.setText(myVars.getMyString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Add these lines in oncreate()..
GlobalVars myVars = ((GlobalVars)getApplicationContext());
TextView myText = (TextView) findViewById(R.id.myText);