Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can someone please assist me, no mater what i do i can't get around this problem of the app not working. I am using Android studio.
My Logcat
10-23 07:29:21.312 31399-31399/org.jaco.todo D/dalvikvm﹕ Late-enabling CheckJNI
10-23 07:29:21.512 31399-31402/org.jaco.todo D/dalvikvm﹕ GC_CONCURRENT freed 82K, 2% free 11049K/11271K, paused 11ms+0ms, total 16ms
10-23 07:29:21.532 31399-31399/org.jaco.todo D/AndroidRuntime﹕ Shutting down VM
10-23 07:29:21.536 31399-31399/org.jaco.todo W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa62d9288)
10-23 07:29:21.540 31399-31399/org.jaco.todo E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.jaco.todo/org.jaco.todo.TodoActivity}: java.lang.IllegalStateException: To use this functionality, add this to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: To use this functionality, add this to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
at com.parse.Parse.requirePermission(Parse.java:495)
at com.parse.ParseCommandCache.runEventuallyAsync(ParseCommandCache.java:250)
at com.parse.ParseAnalytics.trackAppOpened(ParseAnalytics.java:61)
at com.parse.ParseAnalytics.trackAppOpened(ParseAnalytics.java:32)
at org.jaco.todo.TodoActivity.onCreate(TodoActivity.java:41)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
... 11 more
10-23 07:29:58.452 31399-31399/? I/Process﹕ Sending signal. PID: 31399 SIG: 9
My TodoActivity.java
public class TodoActivity extends Activity implements OnItemClickListener {
private EditText mTaskInput;
private ListView mListView;
private TaskAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
Parse.initialize(this, "9YsgDgjMOqulfH9JYXVWZG5a6EBVf1SbMyz7gXH4", "CZ60kHo0V9cG190DAoIhB781BL3mRfdy6FSSPy6D");
ParseAnalytics.trackAppOpened(getIntent());
ParseObject.registerSubclass(Task.class);
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
mAdapter = new TaskAdapter(this, new ArrayList<Task>());
mTaskInput = (EditText) findViewById(R.id.task_input);
mListView = (ListView) findViewById(R.id.task_list);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
updateData();
}
public void updateData(){
ParseQuery<Task> query = ParseQuery.getQuery(Task.class);
query.whereEqualTo("user", ParseUser.getCurrentUser());
query.setCachePolicy(CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Task>() {
#Override
public void done(List<Task> tasks, ParseException error) {
if(tasks != null){
mAdapter.clear();
for (int i = 0; i < tasks.size(); i++) {
mAdapter.add(tasks.get(i));
}
}
}
});
}
public void createTask(View v) {
if (mTaskInput.getText().length() > 0){
Task t = new Task();
t.setACL(new ParseACL(ParseUser.getCurrentUser()));
t.setUser(ParseUser.getCurrentUser());
t.setDescription(mTaskInput.getText().toString());
t.setCompleted(false);
t.saveEventually();
mAdapter.insert(t, 0);
mTaskInput.setText("");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.todo, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_in:
ParseUser.logOut();
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
return true;
}
return false;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Task task = mAdapter.getItem(position);
TextView taskDescription = (TextView) view.findViewById(R.id.task_description);
task.setCompleted(!task.isCompleted());
if(task.isCompleted()){
taskDescription.setPaintFlags(taskDescription.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}else{
taskDescription.setPaintFlags(taskDescription.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
task.saveEventually();
}
}
my activity_todo.xml
<LinearLayout 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:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
tools:context=".TodoActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/task_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="text"
android:hint="input_hint">
<requestFocus />
</EditText>
<Button
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="createTask"
android:text="submit_button" />
</LinearLayout>
<ListView
android:id="#+id/task_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
My AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.jaco.todo" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".TodoActivity"
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>
Any ideas?
Add your TodoActivity class with package name in your Manifest File and also add next permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Related
I'm trying to build an app and have a little bit of a problem.
Android Monitor :
08-31 07:41:59.705 10118-10118/com.example.user.rotateit E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.rotateit/com.example.user.rotateit.HasilActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.user.rotateit.HasilActivity.onCreate(HasilActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
HasilActivity.Java :
public class HasilActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hasil);
int choice = 0;
final Random random = new Random();
choice = random.nextInt(2)+0;
EditText et_black = (EditText) findViewById(R.id.et_black);
EditText et_white = (EditText) findViewById(R.id.et_white);
TextView tv_result = (TextView) findViewById(R.id.tv_result);
String et_blackText = et_black.getText().toString();
String et_whiteText = et_white.getText().toString();
if (choice == 0) {
tv_result.setText(et_blackText);
}
if (choice == 1) {
tv_result.setText(et_whiteText);
}
}
}
XML (activity_hasil):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.rotateit.HasilActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/tv_result"/>
</LinearLayout>
MainActivity.Java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView btn_start = (ImageView) findViewById(R.id.btn_start);
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, HasilActivity.class);
startActivity(i);
}
});
}
}
XML (activity_main) :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#42079D"
tools:context="com.example.user.rotateit.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/et_black"
style="#style/EditText1"
android:background="#0B0503"
android:textColor="#FEFCFB"
/>
<EditText
android:id="#+id/et_white"
style="#style/EditText1"
android:background="#FEFCFB"
android:textColor="#0B0503"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_start"
android:id="#+id/btn_start"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
MANIFEST.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.rotateit">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".HasilActivity"></activity>
</application>
</manifest>
The app always stops working when I run the program.
This is the whole program. I'm pretty sure that the problem is in the editText.
Basically, i want the program itself be able to show what the user typed in, in random. So, there are two EditTexts, et_black and et_white. the user will typed in any text in both of the editText, than the program will show either et_black or et_white.
Just started learning android studio.
You have to create a String with the text inside the et_black TextEdit object. After that you can assign this String to the tv_result TextView
String et_blackText = et_black.getText().toString();
if (choice == 0 || choice == 1) {
tv_result.setText(et_blackText);
}
In addition, you have to create the following objects in your XML
EditText et_black = (EditText) findViewById(R.id.et_black);
EditText et_white = (EditText) findViewById(R.id.et_white);
TextView tv_result = (TextView) findViewById(R.id.tv_result);
R.id.et_black,R.id.et_white,R.id.tv_result are not created in your HasilXML file
You are trying to put the EditText et_black as the text of the TextView.
I won't say anything else, just..carefully check your code!!
PS post you manifest.xml
I am trying to add a facebook login to my app. Unfortunatly I am getting an error. I defined the app id in my strings.xml and add meta-data to my manifest. Although I added the facebook activity and the permission to use the Internet but the error is still there. I am of the opionen that there is a problem with the layout but I don't see one. Maybe you could help me.
EDIT: I changed the position of the initialization and the content view function but now I am getting a new error. I looked it up and found out that it is normally a problem with the app id but I have implemented the id using meta data in my manifest.
The error is the following:
10-07 10:06:36.249 4682-4748/de.homeproducts.ineedhelp E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: de.homeproducts.ineedhelp, PID: 4682
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:746)
at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:774)
at com.facebook.internal.Utility.queryAppSettings(Utility.java:802)
at com.facebook.login.widget.LoginButton$1.doInBackground(LoginButton.java:502)
at com.facebook.login.widget.LoginButton$1.doInBackground(LoginButton.java:499)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
This is my Activity class:
public ImageView view = null;
public LoginButton loginButton = null;
public CallbackManager callbackManager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) this.findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast toast = Toast.makeText(getApplicationContext(), "Login erfolgreich!", Toast.LENGTH_LONG);
}
#Override
public void onCancel() {
Toast toast = Toast.makeText(getApplicationContext(), "Login abgebrochen!", Toast.LENGTH_LONG);
}
#Override
public void onError(FacebookException e) {
Toast toast = Toast.makeText(getApplicationContext(), "Login fehlgeschlagen!", Toast.LENGTH_LONG);
}
});
And this is my XML file:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageView android:id="#+id/hello_world" android:src="#drawable/icon" android:layout_width="128dp"
android:layout_height="128dp" android:layout_centerHorizontal="true"/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
The manifest looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.homeproducts.ineedhelp" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/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="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="#android:style/Theme.Translucent.NoTitleBar"
android:label="#string/app_name" />
</application>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/app_id"/>
</manifest>
You have to write :
FacebookSdk.sdkInitialize(this.getApplicationContext());
Before:
setContentView(R.layout.activity_main);
See Facebook Sdk Has Not Been Initilized
I am up to the "Start Another Activity" section of the Android tutorial and it simply won't work when I install and test it.
It compiles fine but running it breaks after I click the send button.
I am using the command line tools on Ubuntu 12.04 and installing to a real device, my Galaxy S5.
I am aware of logcat but haven't been able to get it working, it either shows no output at all, or gives a massive spam of output I can't keep up with. I would happily provide logcat information if I could manage to isolate my app's output and cut through everything else.
I have seen a lot of similar questions on this which leads me to believe the tutorial isn't very well written.
Here is "MyActivity.java"
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.EditText;
import android.view.View;
public class MyActivity extends Activity
{
public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.MESSAGE";
/** Called when the activity is first created */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/** Called when the user clicks the send button */
public void sendMessage(View view)
{
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Here is DisplayMessageActivity
package com.example.myfirstapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.*;
import android.view.*;
import android.widget.*;
import com.example.myfirstapp.R;
public class DisplayMessageActivity extends ActionBarActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Get the message from intent
Intent intent = getIntent();
String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE);
//Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
//Set the text view as the activity layout
setContentView(textView);
}
}
Here is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0">
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity
android:name="MyActivity"
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="com.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MyActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MyActivity"
/>
</activity>
</application>
</manifest>
EDIT: Here is Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="#+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/edit_message"
/>
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage"
/>
</LinearLayout>
There was some code that I changed and took out as it said to add code in, but then would later show a "this is what your code should look like" and it was missing some of the original code. I also changed the manifest package names in the activities because at the beginning it uses com.example.myfirstapp but later uses com.mycompany.myfirstapp
Any help or advice on why this seemingly simple tutorial doesn't work is greatly appreciated.
EDIT:
Logcat output - (after pressing the send button)
I/Timeline( 3812): Timeline: Activity_launch_request id:com.example.myfirstapp time:74636924
D/AndroidRuntime( 3812): Shutting down VM
E/AndroidRuntime( 3812): FATAL EXCEPTION: main
E/AndroidRuntime( 3812): Process: com.example.myfirstapp, PID: 3812
E/AndroidRuntime( 3812): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2658)
E/AndroidRuntime( 3812): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
E/AndroidRuntime( 3812): at android.app.ActivityThread.access$900(ActivityThread.java:172)
E/AndroidRuntime( 3812): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1422)
E/AndroidRuntime( 3812): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime( 3812): at android.os.Looper.loop(Looper.java:145)
E/AndroidRuntime( 3812): at android.app.ActivityThread.main(ActivityThread.java:5834)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 3812): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
E/AndroidRuntime( 3812): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
E/AndroidRuntime( 3812): Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:151)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivityDelegateBase.onCreate(ActionBarActivityDelegateBase.java:138)
E/AndroidRuntime( 3812): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:123)
E/AndroidRuntime( 3812): at com.example.myfirstapp.DisplayMessageActivity.onCreate(DisplayMessageActivity.java:16)
E/AndroidRuntime( 3812): at android.app.Activity.performCreate(Activity.java:6221)
E/AndroidRuntime( 3812): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
E/AndroidRuntime( 3812): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2611)
E/AndroidRuntime( 3812): ... 10 more
I/Process ( 3812): Sending signal. PID: 3812 SIG: 9
I/ActivityManager( 871): Process com.example.myfirstapp (pid 3812)(adj 13) has died(104,205)
Here's the working code :
MainActivity.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
}
public void Go(View v)
{
Log.d("check", "Pressed");
String value = et.getText().toString();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", value);
startActivity(intent);
}
}
SecondActivity.class
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.TextView;
public class SecondActivity extends ActionBarActivity {
TextView textv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
String txt = getIntent().getStringExtra("key");
Log.d("check", "got : " +txt);
textv = (TextView) findViewById(R.id.textView1);
textv.setText(txt);
}
}
res/layout/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"
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.testproject.MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="67dp"
android:layout_marginTop="46dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Go"
android:text="Button" />
</RelativeLayout>
res/layout/new_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
AndroidManifest.xml
<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=".SecondActivity"></activity> // Registered the newly created activity
</application>
Output :
Logcat :
BY SEEING YOUR LOGCAT, I got there is a problem in your Theme.
You didn't declared AppTheme in AndroidManifest.xml file
android:theme="#style/AppTheme"
Try by This Sample Code I have made For You.
mainactivity.xml Code
<EditText
android:id="#+id/edtMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="message"
/>
<Button
android:id="#+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
/>
MainActivity.class
Button btnSend;
EditText edtMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtMessage=(EditText)findViewById(R.id.edtMessage);
btnSend=(Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String Message=edtMessage.getText().toString();
Intent intent=new Intent(getApplicationContext(),Second.class);
intent.putExtra("Message", Message);
startActivity(intent);
}
});
}
second.xml
<TextView
android:id="#+id/tviMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
/>
Second.class
TextView tviMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tviMessage=(TextView)findViewById(R.id.tviMessage);
Bundle extras = getIntent().getExtras();
String message = extras.getString("Message");
tviMessage.setText(message);
}
Manifesto.xml
<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=".Second"
android:label="#string/app_name" >
</activity>
By using logcat with this command:
adb logcat | grep `adb shell ps | grep com.example.myfirstapp | cut -c10-15`
I was able to find the error causing the app to crash. It came from missing the line:
android:theme="#style/Theme.AppCompat.Light"
In the Manifest.xml file. This is required by the Activity bar compatibility class. This part was completely overlooked in the tutorial, presumably because IDEs do this part automatically.
Thank you to everybody for their help and suggestions, it helped me keep looking and trying things until I finally found my solution.
i'm making an app that has a sign in or log in button, the log in button works perfectly but the sign up button gives me a fatal error, making the AVD to stop running the app, this is the code of the sign up activity
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_activity);
// Set up the signup form.
usernameView = (EditText) findViewById(R.id.username);
passwordView = (EditText) findViewById(R.id.password);
passwordAgainView = (EditText) findViewById(R.id.passwordAgain);
// Set up the submit button click handler
findViewById(R.id.action_button).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Validate the sign up data
boolean validationError = false;
StringBuilder validationErrorMessage =
new StringBuilder(getResources().getString(R.string.error_intro));
if (isEmpty(usernameView)) {
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_username));
}
if (isEmpty(passwordView)) {
if (validationError) {
validationErrorMessage.append(getResources().getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_password));
}
if (!isMatching(passwordView, passwordAgainView)) {
if (validationError) {
validationErrorMessage.append(getResources().getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getResources().getString(
R.string.error_mismatched_passwords));
}
validationErrorMessage.append(getResources().getString(R.string.error_end));
// If there is a validation error, display the error
if (validationError) {
Toast.makeText(SignUpActivity.this, validationErrorMessage.toString(), Toast.LENGTH_LONG)
.show();
return;
}
// Set up a progress dialog
final ProgressDialog dlg = new ProgressDialog(SignUpActivity.this);
dlg.setTitle("Please wait.");
dlg.setMessage("Signing up. Please wait.");
dlg.show();
// Set up a new Parse user
ParseUser user = new ParseUser();
user.setUsername(usernameView.getText().toString());
user.setPassword(passwordView.getText().toString());
// Call the Parse signup method
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
dlg.dismiss();
if (e != null) {
// Show the error message
Toast.makeText(SignUpActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
// Start an intent for the dispatch activity
Intent intent = new Intent(SignUpActivity.this, DispatchActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
});
}
});
}
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0) {
return false;
} else {
return true;
}
}
private boolean isMatching(EditText etText1, EditText etText2) {
if (etText1.getText().toString().equals(etText2.getText().toString())) {
return true;
} else {
return false;
}
}
and here is the manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".ParseStarter">
<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity android:name=".SignUpOrLogInActivity"
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=".DispatchActivity"/>
<activity android:name=".LoginActivity" />
<activity android:name=".SignUpActivity" />
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
</application>
here is the logCat
Process: com.sebasdeldihotmail.mediocre11, PID: 2020
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sebasdeldihotmail.mediocre11/com.sebasdeldihotmail.mediocre11.SignUpActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.sebasdeldihotmail.mediocre11.SignUpActivity.onCreate(SignUpActivity.java:35)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
here is the code of the class that has the button that calls the sign up activity
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signinorsignup_activity);
// Log in button click handler
((Button) findViewById(R.id.login)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Starts an intent of the log in activity
startActivity(new Intent(SignUpOrLogInActivity.this, LoginActivity.class));
}
});
// Sign up button click handler
((Button) findViewById(R.id.signup)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Starts an intent for the sign up activity
startActivity(new Intent(SignUpOrLogInActivity.this, SignUpActivity.class));
}
});
}
}
and here is the layout of the sign up
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#67AAE4">
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_username"
android:inputType="textEmailAddress"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<EditText
android:id="#+id/passwordAgain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/prompt_password_again"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
</LinearLayout>
and here is the layout where the sign up button appears
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#67AAE4">
<Button
android:id="#+id/signup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign Up"/>
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"/>
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
Thank you very much for reading :) .
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
It appears your signup_activity.xml layout does not have a view with id action_button, and findViewById() returns null.
The view you are adding the onClickListener to, r.id.action_button, is not found, hence the NullPointerException.
So make sure you have it in the current view, signup_activity.xml.
More:
To make your 'onCreate'-method less chunky, and to avoid this to happen again, consider using android:onClick on your button in the layoutfile, signup_activity.xml.
<Button
android:id="#+id/action_button"
android:onClick="onSignUpClick"
...
/>
Then in SignUpActivity.java add the method:
public void onSignUpClick(View view) {
// add code here instead of creating onClickListener in onCreate...
}
Ive only been programming a few days, so I am struggling to grasp what I am doing wrong here, hoping the community can point me in the right direction..
Here my MainActivity:
package com.whatsonwhere.app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends ActionBarActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener{
private SupportMapFragment mapFragment;
private GoogleMap map;
private LocationClient mLocationClient;
/*
* Define a request code to send to Google Play services
* This code is returned in Activity.onActivityResult
*/
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLocationClient = new LocationClient(this, this, this);
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView));
map = mapFragment.getMap();
map.setMyLocationEnabled(true);
}
/*
* Called when the Activity becomes visible.
*/
#Override
protected void onStart() {
super.onStart();
// Connect the client.
if(isGooglePlayServicesAvailable()){
mLocationClient.connect();
}
}
/*
* Called when the Activity is no longer visible.
*/
#Override
protected void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
/*
* Handle results returned to the FragmentActivity
* by Google Play services
*/
#Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
// Decide what to do based on the original request code
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
/*
* If the result code is Activity.RESULT_OK, try
* to connect again
*/
switch (resultCode) {
case Activity.RESULT_OK:
mLocationClient.connect();
break;
}
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog( resultCode,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
Location location = mLocationClient.getLastLocation();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
map.animateCamera(cameraUpdate);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
// Display the connection status
Toast.makeText(this, "Disconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Sorry. Location services not available to you", Toast.LENGTH_LONG).show();
}
}
#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);
}
}
and my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.whatsonwhere.app" >
<permission
android:name="com.whatsonwhere.app.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.whatsonwhere.app.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.whatsonwhere.app.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>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="mykey_here(removed)" />
</application>
</manifest>
Activity_main:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.whatsonwhere.app.MainActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/TopText"
android:id="#+id/textView2"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/nearme"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/search"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/loc"
android:id="#+id/textView"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
And finally the logcat:
03-25 11:28:19.417 6650-6650/com.whatsonwhere.app D/AndroidRuntime﹕ Shutting down VM
03-25 11:28:19.417 6650-6650/com.whatsonwhere.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x415e88b0)
03-25 11:28:19.417 6650-6650/com.whatsonwhere.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.whatsonwhere.app/com.whatsonwhere.app.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$600(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.whatsonwhere.app.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2316)
at android.app.ActivityThread.access$600(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
03-25 11:28:19.537 6650-6682/com.whatsonwhere.app W/ActivityThread﹕ ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
03-25 11:28:21.477 6650-6650/com.whatsonwhere.app I/Process﹕ Sending signal. PID: 6650 SIG: 9
When you specify:
setContentView(R.layout.activity_main);
And
mapFragment =((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapView));
map = mapFragment.getMap();
The compiler looks for R.id.mapView in R.layout.activity_main .The names are case sensitive.
The line:
map=mapFragment.getMap():
throws a NPE as the mapView isn't found in its respective layout. Check the names if id(s) and whether it is declared in the mentioned layout.
Also, alternatively..you can use:
map = ((SupportMapFragment) this.getSupportFragmentManager()
.findFragmentById(R.id.mapView)).getMap();
saves a variable declaration and l-o-c, if not necessary otherwise.
Add fragment like this:
<fragment
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/button"
class="com.google.android.gms.maps.SupportMapFragment" />
Sometimes, when the activity is created, the map is not initialised. This leads to NullPointerException.
You must move the code mapFragment etc from onCreate to onResume.
This will ensure that the activity is created and in foreground.
mapFragment is null after the findFragmentById() call. Please make sure you have id = mapView (case-sensitive) inside activity_main.xml. If you have it there, you can also try to move the work with MapFragment from onCreate to onStart or onResume
Change here from
mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView));
to
mapFragment = ((MapFragment) getSupportFragmentManager().findFragmentById(R.id.mapView));
Because in your xml file you are using
android:name="com.google.android.gms.maps.MapFragment"