Fatal Exception on starting activity Android - java

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?

Related

"Unable to instantiate activity" when running app

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

Android: Switching between two activities Error - Unfortunately "App Name" has stopped

I'm a self learner for android app developer, then this problem came up and I'm not sure if people have this problem before but it says my app has stopped in the emulator.
So these are the codes I have :
MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button imageButton13 = (Button) findViewById(R.id.imageButton13);
imageButton13.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent Intent = new Intent(v.getContext(), EXOActivity.class);
v.getContext().startActivity(Intent);
}
});
}
}
EXOActivity.java:
package com.mhyuktown.exowallpaper;
import android.app.Activity; import android.os.Bundle;
public class EXOActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exo);
}
}
Lastly here is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mhyuktown.exowallpaper"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
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=".EXOActivity" >
</activity>
</application>
</manifest>
logcat:
09-09 00:40:02.006: D/dalvikvm(1564): GC_FOR_ALLOC freed 49K, 4% free 3304K/3436K, paused 79ms, total 86ms
09-09 00:40:02.256: D/dalvikvm(1564): GC_FOR_ALLOC freed 7K, 3% free 3770K/3876K, paused 35ms, total 37ms
09-09 00:40:02.326: D/AndroidRuntime(1564): Shutting down VM
09-09 00:40:02.326: W/dalvikvm(1564): threadid=1: thread exiting with uncaught exception (group=0xb1aa7ba8)
09-09 00:40:02.376: E/AndroidRuntime(1564): FATAL EXCEPTION: main
09-09 00:40:02.376: E/AndroidRuntime(1564): Process: com.mhyuktown.exowallpaper, PID: 1564
09-09 00:40:02.376: E/AndroidRuntime(1564): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mhyuktown.exowallpaper/com.mhyuktown.exowallpaper.MainActivity}: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.os.Handler.dispatchMessage(Handler.java:102)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.os.Looper.loop(Looper.java:136)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-09 00:40:02.376: E/AndroidRuntime(1564): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 00:40:02.376: E/AndroidRuntime(1564): at java.lang.reflect.Method.invoke(Method.java:515)
09-09 00:40:02.376: E/AndroidRuntime(1564): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-09 00:40:02.376: E/AndroidRuntime(1564): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-09 00:40:02.376: E/AndroidRuntime(1564): at dalvik.system.NativeStart.main(Native Method)
09-09 00:40:02.376: E/AndroidRuntime(1564): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
09-09 00:40:02.376: E/AndroidRuntime(1564): at com.mhyuktown.exowallpaper.MainActivity.onCreate(MainActivity.java:18)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.Activity.performCreate(Activity.java:5231)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-09 00:40:02.376: E/AndroidRuntime(1564): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-09 00:40:02.376: E/AndroidRuntime(1564): ... 11 more
Change it to this:
Intent intent = new Intent(MainActivity.this, EXOActivity.class);
startActivity(intent);
And
Button imageButton13 = (Button) findViewById(R.id.imageButton13);
to
ImageButton imageButton13 = (ImageButton) findViewById(R.id.imageButton13);
I coded it & it works fine. Import every thing needed.See the below code. Try pressing Ctrl+Shift+O, Eclipse will automatically add the import statement if missing.
Use ImageButton instead Button.
ImageButton button = (ImageButton)findViewById(R.id.imageButton13);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, EXOActivity.class);
startActivity(intent);
}
});
change
Intent Intent = new Intent(v.getContext(), EXOActivity.class);
v.getContext().startActivity(Intent);
To
Intent intent = new Intent(MainActivity.this, EXOActivity.class);
startActivity(intent);
Every activity you create must be included in the AndroidManifest.xml.
Find this:
</activity>
and after that just add this:
<activity android:name=".YourActivity"></activity>

Unfortunately the Wifi Scanner has stopped [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was trying to make a wifi scanner which can show the list of all the wifi access points. My code is as following :
MainActivity.java :
package com.example.wifiscanner;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
WifiManager wifi;
WifiScanReceiver wifireciever;
Button scan;
List<ScanResult> wifilist;
ListView list;
String wifis[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
list=(ListView)findViewById(R.id.listView1);
scan=(Button)findViewById(R.id.button1);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled()==false){
wifi.setWifiEnabled(true);
}
wifireciever = new WifiScanReceiver();
registerReceiver(wifireciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifi.startScan();
}
});
}
protected void onPause() {
unregisterReceiver(wifireciever);
super.onPause();
}
protected void onResume() {
registerReceiver(wifireciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
class WifiScanReceiver extends BroadcastReceiver {
#SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifilist = wifi.getScanResults();
wifis = new String[wifilist.size()];
for(int i = 0; i < wifilist.size(); i++){
wifis[i] = ((wifilist.get(i)).toString());
}
list.setAdapter(new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1,wifis));
}
}
#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;
}
}
fragment_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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.wifiscanner.MainActivity$PlaceholderFragment" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true" >
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/listView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="34dp"
android:layout_marginTop="37dp"
android:minWidth="#dimen/abc_action_bar_stacked_tab_max_width"
android:text="Scan" />
</RelativeLayout>
Log cat :
05-26 09:41:49.840: D/AndroidRuntime(11186): Shutting down VM
05-26 09:41:49.840: W/dalvikvm(11186): threadid=1: thread exiting with uncaught exception (group=0x414f82a0)
05-26 09:41:49.861: E/AndroidRuntime(11186): FATAL EXCEPTION: main
05-26 09:41:49.861: E/AndroidRuntime(11186): java.lang.SecurityException: WifiService: Neither user 10105 nor current process has android.permission.ACCESS_WIFI_STATE.
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.os.Parcel.readException(Parcel.java:1425)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.os.Parcel.readException(Parcel.java:1379)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.net.wifi.IWifiManager$Stub$Proxy.getWifiEnabledState(IWifiManager.java:900)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.net.wifi.WifiManager.getWifiState(WifiManager.java:1078)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.net.wifi.WifiManager.isWifiEnabled(WifiManager.java:1090)
05-26 09:41:49.861: E/AndroidRuntime(11186): at com.example.wifiscanner.MainActivity$1.onClick(MainActivity.java:44)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.view.View.performClick(View.java:4262)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.view.View$PerformClick.run(View.java:17421)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.os.Handler.handleCallback(Handler.java:615)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.os.Looper.loop(Looper.java:137)
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.app.ActivityThread.main(ActivityThread.java:4947)
05-26 09:41:49.861: E/AndroidRuntime(11186): at java.lang.reflect.Method.invokeNative(Native Method)
05-26 09:41:49.861: E/AndroidRuntime(11186): at java.lang.reflect.Method.invoke(Method.java:511)
05-26 09:41:49.861: E/AndroidRuntime(11186): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
05-26 09:41:49.861: E/AndroidRuntime(11186): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
05-26 09:41:49.861: E/AndroidRuntime(11186): at dalvik.system.NativeStart.main(Native Method)
05-26 09:41:49.941: D/dalvikvm(11186): GC_CONCURRENT freed 203K, 15% free 6966K/8135K, paused 12ms+9ms, total 73ms
05-26 09:42:00.201: I/Process(11186): Sending signal. PID: 11186 SIG: 9
My Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wifiscanner"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.wifiscanner.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>
</application>
</manifest>
As soon as I hit the scan button its stop working. If anybody can help me out I would be thankful.
You logcat clearly said
java.lang.SecurityException: WifiService: Neither user 10105 nor current process has android.permission.ACCESS_WIFI_STATE.
05-26 09:41:49.861: E/AndroidRuntime(11186): at android.os.Parcel.readException(Parcel.java:1425)
Add android.permission.ACCESS_WIFI_STATE in your manifest.xml
You need to add the following permissions to the manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
These need to be added outside the application tag. (Either before or after)
Your manifest file is located in the main folder of the project under the name: AndroidManifest.xml.

Unable to instantiate activity componentInfo, Activity declared in Manifest

I was adding the Google Cloud Messaging service to my App and altered my manifest file. I get the following StackTrace.
02-27 18:58:11.282: E/AndroidRuntime(988): FATAL EXCEPTION: main
02-27 18:58:11.282: E/AndroidRuntime(988): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.phptest/com.example.phptest.MainActivity}: java.lang.ClassNotFoundException: com.example.phptest.MainActivity
02-27 18:58:11.282: E/AndroidRuntime(988): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.os.Handler.dispatchMessage(Handler.java:99)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.os.Looper.loop(Looper.java:137)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-27 18:58:11.282: E/AndroidRuntime(988): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 18:58:11.282: E/AndroidRuntime(988): at java.lang.reflect.Method.invoke(Method.java:511)
02-27 18:58:11.282: E/AndroidRuntime(988): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-27 18:58:11.282: E/AndroidRuntime(988): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-27 18:58:11.282: E/AndroidRuntime(988): at dalvik.system.NativeStart.main(Native Method)
02-27 18:58:11.282: E/AndroidRuntime(988): Caused by: java.lang.ClassNotFoundException: com.example.phptest.MainActivity
02-27 18:58:11.282: E/AndroidRuntime(988): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
02-27 18:58:11.282: E/AndroidRuntime(988): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
02-27 18:58:11.282: E/AndroidRuntime(988): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
02-27 18:58:11.282: E/AndroidRuntime(988): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
02-27 18:58:11.282: E/AndroidRuntime(988): ... 11 more
Here is my Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.phptest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="16" />
<uses-configuration />
<permission
android:name="com.example.phptest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.phptest.permission.C2D_MESSAGE" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.phptest.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>
<service android:name=".GCMIntentService" />
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.example.phptest" />
</intent-filter>
</receiver>
</application>
</manifest>
MainActivity:
package com.example.phptest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import com.example.phptest.DeviceLogin.LoginReply;
import com.google.android.gcm.GCMRegistrar;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity implements LoginReply {
String TAG = "Main Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DeviceLogin d = new DeviceLogin(this);
d.execute("xxxx","12345");
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, GCMIntentService.senderId);
} else {
Log.v(TAG, "Already registered");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public static String makeCall(String scriptName) {
String address = "http://10.0.2.2/" + scriptName + ".php";
HttpPost httpPost = new HttpPost(address);
HttpClient httpClient = new DefaultHttpClient();
StringBuilder total = new StringBuilder();
try {
//httpPost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line = "";
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
// Return full string
System.out.println("TOTAL: " + total.toString());
return total.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "empty";
}
public void onDevicesDownloaded(String login) {
// TODO Auto-generated method stub
}
}
Any ideas?
I have seen Android apps get finicky when the full path is specified in the name attribute unless the package the class is in differs from the one you specify at the top of the manifest file. Try changing it to just ".MainActivity" and see if that makes it happy.
Solution was to clean project, D'oh! xD

Android Java: Global variables through subclass; can't launch app?

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

Categories