This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I make my application in Android Studio. I run this application but the Android app stopped. I make a app with an animation.
Here is my source code:
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.geven.animation" >
<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=".Animation"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.geven.animation.DRAWINGTHEBALL" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity:
package com.geven.animation;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button button = (Button) findViewById(R.id.button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, Animation.class));
}
});
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ActivityMain.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: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">
<Button
android:layout_width="400dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textSize="20dp"
android:id="#+id/button"
android:text="Goto animation"/>
</RelativeLayout>
Animation.java:
package com.geven.animation;
import android.app.Activity;
import android.os.Bundle;
public class Animation extends Activity {
DrawingTheBall v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v = new DrawingTheBall(this);
setContentView(v);
}
}
DrawingTheBall.java:
package com.geven.animation;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
public class DrawingTheBall extends View {
Bitmap bbal;
int x,y;
public DrawingTheBall(Context context) {
super(context);
bbal = BitmapFactory.decodeResource(getResources(), R.drawable.blueball);
x=0;
y=0;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Rect ourRect = new Rect();
ourRect.set(0,0,canvas.getWidth(), canvas.getHeight()/2);
Paint blue = new Paint();
blue.setColor(Color.BLUE);
blue.setStyle(Paint.Style.FILL);
canvas.drawRect(ourRect,blue);
if (x< canvas.getWidth()) {
x += 10;
}else {x=0;}
if (y<canvas.getHeight()) {
y += 10;
}else {y=0;}
Paint p = new Paint();
canvas.drawBitmap(bbal, x, y, p);
invalidate();
}
}
Logcat:
02-26 21:55:59.874 17975-17975/com.geven.animation D/AndroidRuntime﹕ Shutting down VM
02-26 21:55:59.874 17975-17975/com.geven.animation W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4174b700)
02-26 21:55:59.879 17975-17975/com.geven.animation E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.geven.animation/com.geven.animation.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2232)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.access$700(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:5493)
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:1225)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1914)
at com.geven.animation.MainActivity.<init>(MainActivity.java:14)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2223)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
at android.app.ActivityThread.access$700(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:177)
at android.app.ActivityThread.main(ActivityThread.java:5493)
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:1225)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1041)
at dalvik.system.NativeStart.main(Native Method)
02-26 22:01:00.199 17975-17975/com.geven.animation I/Process﹕ Sending signal. PID: 17975 SIG: 9
Button button = (Button) findViewById(R.id.button);
You need to put that line in your onCreate method.
Basically, at the field level, you can have Button button; and then in onCreate you would initialize the variable thusly: button = (Button) findViewById(R.id.button);. You can't call findViewById() before the view has been inflated.
As a side note, a stacktrace may look intimidating at first, but the easiest way to deal with it, is to search for your package name, in this case "com.geven.animation". The first entry in the stack trace that includes that package name is usually the offending line. at com.geven.animation.MainActivity.<init>(MainActivity.java:14) so line 14 of your MainActivity class.
Related
I am trying to run an app using Android Studio 3.4.1, but the application crashes when I try to debug or run it.
I've encountered the Unable to start activity ComponentInfo error once already, but on a project that used Kotlin (this project is using Java), and with a different exception. I've tried editing the manifest, modifying activities and changing all of the images in the mipmap folders to the drawable folders, but none of that worked.
Here is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.testapp">
<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"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2" />
<activity
android:name=".NotificationsActivity"
android:label="#string/title_notifications" />
<activity
android:name=".DashboardActivity"
android:label="#string/title_dashboard" />
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.testapp.DashboardActivity" />
<activity
android:name=".BaseActivity"
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>
My BaseActivity.java:
package com.example.testapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class BaseActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
protected BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId()); //References this line in the logs
navigationView = findViewById(R.id.nav_view);
navigationView.setOnNavigationItemSelectedListener(this);
}
#Override
protected void onStart() {
super.onStart();
updateNavigationBarState();
}
// Remove inter-activity transition to avoid screen tossing on tapping bottom navigation items
#Override
public void onPause() {
super.onPause();
overridePendingTransition(0, 0);
}
#Override
public boolean onNavigationItemSelected(#NonNull final MenuItem item) {
navigationView.postDelayed(new Runnable() {
#Override
public void run() {
int itemId = item.getItemId();
if (itemId == R.id.navigation_home) {
BaseActivity.this.startActivity(new Intent(BaseActivity.this, BaseActivity.class));
} else if (itemId == R.id.navigation_dashboard) {
BaseActivity.this.startActivity(new Intent(BaseActivity.this, DashboardActivity.class));
} else if (itemId == R.id.navigation_notifications) {
BaseActivity.this.startActivity(new Intent(BaseActivity.this, NotificationsActivity.class));
}
BaseActivity.this.finish();
}
}, 300);
return true;
}
private void updateNavigationBarState(){
int actionId = getNavigationMenuItemId();
selectBottomNavigationBarItem(actionId);
}
void selectBottomNavigationBarItem(int itemId) {
Menu menu = navigationView.getMenu();
for (int i = 0, size = menu.size(); i < size; i++) {
MenuItem item = menu.getItem(i);
boolean shouldBeChecked = item.getItemId() == itemId;
if (shouldBeChecked) {
item.setChecked(true);
break;
}
}
}
int getContentViewId() {
return 0;
}
int getNavigationMenuItemId() {
return 0;
}
}
And my debugging log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testapp, PID: 10261
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testapp/com.example.testapp.BaseActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2827)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1603)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:169)
at android.app.ActivityThread.main(ActivityThread.java:6578)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:204)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2133)
at android.content.res.Resources.getLayout(Resources.java:1142)
at android.view.LayoutInflater.inflate(LayoutInflater.java:421)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.testapp.BaseActivity.onCreate(BaseActivity.java:18)
at android.app.Activity.performCreate(Activity.java:7016)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2780)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2902)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1603)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:169)
at android.app.ActivityThread.main(ActivityThread.java:6578)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
The app was supposed to work, but after modifying the .javas, it started giving this error no matter what I did. I've seen some questions that had similar results, but none of them actually helped me.
Try changing
setContentView(getContentViewId());
to
setContentView(R.layout.activity_base);
The error :
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
means that the resource can't be found and since it is pointing to setContentView, it means that getContentViewId() could not be found.
I'm trying to enable the back button in this really simple activity (that is instantiated by another activity), but I always get the null pointer exception and therefore my app crashes when I launch the activity (without the back button in the action bar the activity works great).
I tried many different solution posted in the internet, but none worked...
I'm following this guide : Android Developer providing up navigation
Here the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.projectcalculator">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
android:screenOrientation="portrait">
<!--attività principale-->
<activity
android:name=".MainActivity"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--attività infixToPostfix-->
<activity
android:name=".InfixToPostfixActivity"
android:launchMode="singleTask"
android:label="#string/infix_to_postfix"/>
<!--attività figlia di infixToPostfix-->
<activity
android:name=".ShowPostfixProcedureActivity"
android:launchMode="standard"
android:label="#string/postfix_procedure"
android:parentActivityName=".InfixToPostfixActivity" />
</application>
</manifest>
Here the java file of the activity (ShowPostfixProcedureActivity):
package com.example.android.projectcalculator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.Stack;
import static java.lang.Character.isDigit;
public class ShowPostfixProcedureActivity extends AppCompatActivity {
private static String equation;
private static int openBracket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_infix_to_postfix_jurney);
Toolbar myToolbar = (Toolbar) findViewById(R.id.infix_to_postfix_toolbar_procedure);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView txview = (TextView)findViewById(R.id.postfix_jurney_text_wall);
Stack<String> s = new Stack<String>();
s = DataProcessor.ReturnProcess();
txview.setText(s.pop());
while (!s.empty())
{
if (s.peek().charAt(0) == '<')
{
txview.append(Html.fromHtml(s.pop()));
}
else
{
txview.append(s.pop());
}
}
//Log.d("SPPA/onCreate","text = "+DataProcessor.ReturnProcess());
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar_postfix_procedure, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
The XML file related to the layout (show_infix_to_postfix_jurney):
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--ActionBar in alto-->
<android.support.v7.widget.Toolbar
android:id="#+id/infix_to_postfix_toolbar_procedure"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#42f480"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
<TextView
android:id="#+id/postfix_jurney_text_wall"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10sp"
android:textSize="20sp"
android:gravity="center"
android:background="#f2f2f2"/>
</ScrollView>
</LinearLayout>
And finally the XML file related to the Navigation bar (action_bar_postfix_procedure):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
Here the error message:
10-29 17:14:43.841 18822-18822/com.example.android.projectcalculator E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.projectcalculator, PID: 18822
Theme: themes:{}
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.MenuItem.setEnabled(boolean)' on a null object reference
at com.example.android.projectcalculator.ShowPostfixProcedureActivity.onCreateOptionsMenu(ShowPostfixProcedureActivity.java:51)
at android.app.Activity.onCreatePanelMenu(Activity.java:2852)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:340)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:258)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:61)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I don't know what the line NavUtils.navigateUpFromSameTask(this); is supposed to do. If you want to close the activity on the press of the back button replace it with the method call onBackPressed()
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
onBackPressed()
return true;
}
return super.onOptionsItemSelected(item);
}
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
i have attached the registeractivity.xml file, registeractivity.java file, mainactivity.java file, manifest file and logcat.
Whenever i run this application after entering username, email and password when i click on sign-up button the stops working.
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="com.example.user.loginapp.RegisterActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Username"
android:ems="10"
android:id="#+id/usernameRegistereditText"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:hint="E-mail"
android:id="#+id/emailRegistereditText"
android:layout_below="#+id/usernameRegistereditText"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:hint="Password"
android:id="#+id/passwordRegistereditText"
android:layout_below="#+id/emailRegistereditText"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign Up"
android:id="#+id/signupbutton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
RegisterActivity.Java File:
package com.example.user.loginapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class RegisterActivity extends AppCompatActivity {
protected EditText mUsername;
protected EditText mEmail;
protected EditText mPassword;
protected Button mSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//initialise
mUsername=(EditText)findViewById(R.id.usernameRegistereditText);
mEmail=(EditText)findViewById(R.id.emailRegistereditText);
mPassword=(EditText)findViewById(R.id.passwordRegistereditText);
mSignup=(Button)findViewById(R.id.signupbutton);
//Listen to button
mSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get username password and email and convert to string
String username=mUsername.getText().toString().trim();
String email=mEmail.getText().toString().trim();
String password=mPassword.getText().toString().trim();
// store user to parse
ParseUser user=new ParseUser();
user.setUsername(username);
user.setEmail(email);
user.setPassword(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if(e==null){
Toast.makeText(RegisterActivity.this,"Sign-up successful",Toast.LENGTH_LONG).show();
}else{
//error message
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_register, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
mainActivity.java file:
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseObject.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("foo", "bar");
testObject.saveInBackground();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.loginapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.parse.APPLICATION_ID"
android:value="E9N4CpvflF5WfGVaQ5kBXYHgNA1Z2BE0cXhgc82j" />
<meta-data
android:name="com.parse.CLIENT_KEY"
android:value="IybWtApcNpi8Ky5odgHSAp34oyaxkFw0Jz9voH5U" />
<activity
android:name=".RegisterActivity"
android:label="#string/title_activity_register" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
LOGCAT:
01-26 16:40:41.028 3836-3836/com.example.user.loginapp E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache
01-26 16:40:41.048 3836-3836/com.example.user.loginapp E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
01-26 16:41:00.912 3836-3836/com.example.user.loginapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalArgumentException: You must create this type of ParseObject using ParseObject.create() or the proper subclass.
at com.parse.ParseObject.<init>(ParseObject.java:365)
at com.parse.ParseObject.<init>(ParseObject.java:334)
at com.parse.ParseUser.<init>(ParseUser.java:162)
at com.example.user.loginapp.RegisterActivity$1.onClick(RegisterActivity.java:43)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Replace below line in your code,
ParseObject testObject = new ParseObject("TestObject");
with,
ParseObject testObject = ParseObject.create("TestObject");
and it will be solved.
Reference
The error is saying that the ParseObject must be created with its create() method. You have just newed one up without using its factory method. You want something like this:
ParseObject testObject = ParseObject.create("TestObject");
Comment out the following lines an try running again:
// Parse.enableLocalDatastore(this);
// Parse.initialize(this);
// ParseObject testObject = new ParseObject("TestObject");
// testObject.put("foo", "bar");
// testObject.saveInBackground();
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.
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"