Hello there am crawling into this android world slowly and following the android bootcamp exercise 2012 edition. I am able to test my application on the AVm with just one layout and one class however on introducing the second class, second layout and coding the button, the application does not open and the log cat error looks like this
06-18 17:22:29.461: D/AndroidRuntime(542): Shutting down VM
06-18 17:22:29.461: W/dalvikvm(542): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
06-18 17:22:29.471: E/AndroidRuntime(542): FATAL EXCEPTION: main
06-18 17:22:29.471: E/AndroidRuntime(542): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloworld/com.example.helloworld.Main}: java.lang.NullPointerException
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.access$600(ActivityThread.java:122)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.os.Looper.loop(Looper.java:137)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.main(ActivityThread.java:4340)
06-18 17:22:29.471: E/AndroidRuntime(542): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 17:22:29.471: E/AndroidRuntime(542): at java.lang.reflect.Method.invoke(Method.java:511)
06-18 17:22:29.471: E/AndroidRuntime(542): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-18 17:22:29.471: E/AndroidRuntime(542): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-18 17:22:29.471: E/AndroidRuntime(542): at dalvik.system.NativeStart.main(Native Method)
06-18 17:22:29.471: E/AndroidRuntime(542): Caused by: java.lang.NullPointerException
06-18 17:22:29.471: E/AndroidRuntime(542): at com.example.helloworld.Main.onCreate(Main.java:24)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.Activity.performCreate(Activity.java:4465)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-18 17:22:29.471: E/AndroidRuntime(542): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
06-18 17:22:29.471: E/AndroidRuntime(542): ... 11 more
this is the main.java
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.btnPlay);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Main.this, Recipe.class));
// TODO Auto-generated method stub
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
this is the new class
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
public class Recipe extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe);
}
}
this is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.helloworld.Main"
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="Recipe"></activity>
</application>
</manifest>
activity_main
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.helloworld.Main"
tools:ignore="MergeRootFrame" />
fragment_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: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.helloworld.Main$PlaceholderFragment" >
<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="28dp"
android:text="#string/mduduzi_games"
android:textSize="30sp" />
<Button
android:id="#+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="28dp"
android:text="#string/play" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:src="#drawable/anim4" />
</RelativeLayout>
From your stack trace, there is a NullPointerException on line 24 of Main.java:
at com.example.helloworld.Main.onCreate(Main.java:24)
This is your problem:
Button b = (Button)findViewById(R.id.btnPlay);
//b is null, so the next line throws a NullPointerException:
b.setOnClickListener(...
b is null, meaning there is no Button with the id "btnPlay" in activity_main.xml
Check to make sure you have something like this in activity_main.xml:
<Button
android:layout_width="wrap_content"
android:text="Some text"
android:id="#+id/btnPlay"
android:layout_height="wrap_content" />
EDIT:
You are calling findViewById from your Activity, which is searching amongst the Views of your Activity defined by activity_main.xml. Since you have defined your Button in your Fragment layout, you must get a reference to the Button from within your Fragment code. Remove the Button code from your Activity class, and stick it into your Fragment:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//find your Button view in rootView
Button b = (Button)rootView.findViewById(R.id.btnPlay);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Main.this, Recipe.class));
// TODO Auto-generated method stub
}
});
return rootView;
}
}
While you are on the right path, you need to change a line slightly in your manifest. Try:
<activity android:name="com.example.helloworld.Recipe"></activity>
Instead of
<activity android:name="Recipe"></activity>
EDIT: Actually, this doesn't seem to be the source of your current problem, but will be a source of a future problem once your current NullPointerException is fixed. As stated in other answers, it looks to deal with the button you set to navigate to your new Activity.
The problem is that btnPlay is defined in your Fragment's layout, but you are trying to find it in your Activity before the Fragment is added to the Activity.
When you call findViewById(R.id.btnPlay);, the only thing that has been added to your Activity's layout is activity_main, which only contains a FrameLayout. The Fragment containing btnPlay doesn't exist until you call
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
One solution would be to move the above three lines to before Button b = (Button)findViewById(R.id.btnPlay);.
However, it is generally a bad practice to reference Views defined in a Fragment from an Activity, because it is a very poor separation of concerns. Your Fragment should handle of the user interaction with Views belonging to that Fragment, and your Activity should only be concerned with Views defined in the Activity's layout.
Related
I'm trying to implement Actionbar-PullToRefresh library into my project. Followed the guide, but couldn't get through it.
XML layout:
<uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ptr_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/clouds" >
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:dividerHeight="1dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#android:id/empty"
android:layout_centerInParent="true"
android:textAlignment="center" />
</uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout>
Fragment:
public class LatestFragment extends ListFragment implements OnScrollListener, OnRefreshListener {
private PullToRefreshLayout mPullToRefreshLayout;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewGroup viewGroup = (ViewGroup) view;
mPullToRefreshLayout = new PullToRefreshLayout(viewGroup.getContext());
ActionBarPullToRefresh.from(getActivity())
.insertLayoutInto(viewGroup)
.theseChildrenArePullable(getListView(), getListView().getEmptyView())
.listener(this)
.setup(mPullToRefreshLayout);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
loadItemList(1);
}
#Override
public void onRefreshStarted(View view) {
loadItemList(1);
}
private void loadItemList(int page) {
...
}
...
}
I'm getting this error:
04-09 18:23:35.739 12681-12681/kedai.cryptomarket.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoSuchMethodError: fr.castorflex.android.smoothprogressbar.SmoothProgressDrawable$Builder.width
at uk.co.senab.actionbarpulltorefresh.library.DefaultHeaderTransformer.applyProgressBarSettings(DefaultHeaderTransformer.java:372)
at uk.co.senab.actionbarpulltorefresh.library.DefaultHeaderTransformer.onViewCreated(DefaultHeaderTransformer.java:104)
at uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher.<init>(PullToRefreshAttacher.java:120)
at uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout.createPullToRefreshAttacher(PullToRefreshLayout.java:223)
at uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh$SetupWizard.setup(ActionBarPullToRefresh.java:92)
at kedai.cryptomarket.app.fragment.drawer.LatestFragment.onViewCreated(LatestFragment.java:65)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:952)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
What's weird is the error indicates it came from SmoothProgressBar which I have already implemented in my project (using version 0.4.0) but didn't use it in this Fragment, however the error is pointing to ActionBarPullToRefresh line in code.
What did I missed?
If you use gradle, try to delete the dependency to smoothprogressbar in your build.gradle file.
The dependency to actionbarpulltorefresh will import smootprogressbar too.
I had the same problem and that worked for me.
ActionBar-PullToRefresh 0.9.3 does not support SmoothProgressBar 0.4.0. Use must use an older version SmoothProgressBar 0.2.2.
I am attempting to complete the Android HelloWorld App using Eclipse and the ADT. However, the app always crashes when I implement the second activity and press the "Send" button. Here are the relevant files (with imports truncated):
fragment_main.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="horizontal"
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.myfirstapp.MainActivity$PlaceholderFragment" >
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
fragment_display_message.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.myfirstapp.DisplayMessageActivity$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
activity_display_message.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myfirstapp.DisplayMessageActivity"
tools:ignore="MergeRootFrame" />
MainActivity.java
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
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);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
DisplayMessageActivity.java
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
setContentView(textView);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
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" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myfirstapp.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.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
And finally, the LogCat file:
03-20 22:25:46.427: E/AndroidRuntime(32293): FATAL EXCEPTION: main
03-20 22:25:46.427: E/AndroidRuntime(32293): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.DisplayMessageActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{4137cd30 #0 id=0x7f05003c}
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1968)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.ActivityThread.access$600(ActivityThread.java:127)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.os.Looper.loop(Looper.java:137)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.ActivityThread.main(ActivityThread.java:4507)
03-20 22:25:46.427: E/AndroidRuntime(32293): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 22:25:46.427: E/AndroidRuntime(32293): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 22:25:46.427: E/AndroidRuntime(32293): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:978)
03-20 22:25:46.427: E/AndroidRuntime(32293): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
03-20 22:25:46.427: E/AndroidRuntime(32293): at dalvik.system.NativeStart.main(Native Method)
03-20 22:25:46.427: E/AndroidRuntime(32293): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{4137cd30 #0 id=0x7f05003c}
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1136)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.Activity.performStart(Activity.java:4479)
03-20 22:25:46.427: E/AndroidRuntime(32293): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1941)
03-20 22:25:46.427: E/AndroidRuntime(32293): ... 11 more
I know the issue lies with the conditional in onCreate in DisplayMessageActivity.java, but I have no idea how to fix it. I'd be grateful for any help in understanding why this simple app - essentially copy-pasted from the Android site - will not run.
I had similar problem. When I rechecked the tutorial from which you are also learning i.e. developer.android, I found that in the onCreate method of DisplayMessageActivity class the following codes of lines are causing disruptions,(I have commented it)
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, PlaceholderFragment.newInstance(message)).commit();
}
Please delete these lines. If you carefully observe the tutorial there they present the code of onCreate at last to cross check, there these line are missing. :)
In displayMessageActivity, you set the content view to a textView, but it should be activity_display_message.xml instead because that's where your container is defined. So that's why the fragment manager can't find any container to add the fragment. You can pass the text to the fragment so that it will handle setting the text to the textView.
Try something like:
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
setContentView(R.layout.activity_display_message);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, PlaceholderFragment.newInstance(message)).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private static final String ARG_MESSAGE = "ARG_MESSAGE";
public static PlaceholderFragment newInstance(String message) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putString(ARG_MESSAGE, message);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
final String message = getArguments().getString(ARG_MESSAGE);
final TextView tv = (TextView) rootView.findViewById( id of your textview );
tv.setText(message);
return rootView;
}
}
According to this line:
No view found for id 0x7f05003c (com.example.myfirstapp:id/container) for fragment PlaceholderFragment{4137cd30 #0 id=0x7f05003c}
You never declare your R.id.container item. And it's right - you never do declare it in your XML layout. I'm not exactly sure what you're trying to do with that, but you should add that to your XML layout, or just remove it (it doesn't really look like you're using it).
It doesn't really look like the fragment you declare is needed. As it's just a simple activity, a fragment shouldn't really be needed.
I would like to begin by saying I know this error has been posted about 2,000 times, but after looking through pages and pages of people with the same issue and trying all of their fixes, none of them have worked so I decided to make a new question. I apologize if there is a thread with a solution for my specific problem, I was not able to locate it.
With that out of the way, I believe the error is that there is a NullPointerException on line 41 of MainActivity.Java, because the Google Map is null and not being initialized.
Line 41 is as follows:
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapU)).getMap();
If I remove all of my code from MainActivity.Java, leaving only the code generated by Android Studio, the app starts up fine and will display a Google Map of the World, so I don't think it has anything to do with my API key or Google Play Services not being updated.
Some stuff I have tried is:
-Switching from FragmentManager to SupportFragmentManager on line 41 (When I did this I changed the map from FragmentMap to SupportMapFragment)
-Adding permissions to the Manifest file, you can see everything I have ended up with.
-Different devices (Doesn't work on a Samsung Galaxy S2 or a Galaxy S4)
-I was originally on minSDK 12, decided to change to 16 just to see if it would help, nothing
NOTE: When I first created this project, for some reason the MainActivity.Java said extends ActionBarActivity instead of FragmentActivity, so I changed it to say FragmentActivity, but I was having this issue both before and after.
Manifest.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hasan.maps" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="com.google.android.providers.gsf.permission.MAPS_RECIEVE"></uses-permission>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<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.hasan.maps.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.maps.v2.API_KEY"
android:value="APIKEY_IS_INSERTED_HERE"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
MainActivity.Java
package com.hasan.maps;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
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.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity {
private GoogleMap map;
private final LatLng Location_NJIT = new LatLng(40.7406517, -74.1792757);
private final LatLng Location_Stevens = new LatLng(40.7469309, -74.0258336);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapU)).getMap();
}
#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);
}
public void onClick_city (View v){
}
public void onClick_njit (View v){
CameraUpdate update = CameraUpdateFactory.newLatLng(Location_NJIT);
map.animateCamera(update);
}
public void onClick_stevens (View v){
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Logcat
Logcat
01-31 00:08:42.050 14353-14353/com.hasan.maps E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hasan.maps/com.hasan.maps.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4938)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.hasan.maps.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:5188)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
at android.app.ActivityThread.access$700(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4938)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
Fragment_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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.hasan.maps.MainActivity$PlaceholderFragment">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mapU"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_below="#+id/stevens" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City"
android:id="#+id/city"
android:layout_above="#+id/map"
android:layout_toRightOf="#+id/header"
android:onClick="onClick_city" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NJIT"
android:id="#+id/njit"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/city"
android:onClick="onClick_njit" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stevens"
android:id="#+id/stevens"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/njit"
android:onClick="onClick_stevens" />
</RelativeLayout>
Thanks in advance!
//Actually you have declared frafment id android:id="#+id/mapU" in layout Fragment_Main.xml
but your are calling in MainActivity.java with layout activity_main.xml
make sure that you are declared map fragment in activity_mail.xml.
or call the map in your
PlaceholderFragment
map = ((SupportMapFragment) getSupportFragmentManager()rootView.findFragmentById(R.id.mapU)).getMap();
ANSWER:
I figured it out finally after hours of tearing my hair out. The code had to be moved under the Fragment Activity Class.
I am trying to add an AdMob ad to my app. I followed the intructions here: https://developers.google.com/mobile-ads-sdk/docs/android/fundamentals and when I try to run it I get these errors:
06-01 19:16:23.337: E/AndroidRuntime(30602): FATAL EXCEPTION: main
06-01 19:16:23.337: E/AndroidRuntime(30602): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ComedyZone/com.ComedyZone.MainActivity}: java.lang.NullPointerException
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1696)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1716)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.access$1500(ActivityThread.java:124)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:968)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.os.Handler.dispatchMessage(Handler.java:99)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.os.Looper.loop(Looper.java:130)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.main(ActivityThread.java:3806)
06-01 19:16:23.337: E/AndroidRuntime(30602): at java.lang.reflect.Method.invokeNative(Native Method)
06-01 19:16:23.337: E/AndroidRuntime(30602): at java.lang.reflect.Method.invoke(Method.java:507)
06-01 19:16:23.337: E/AndroidRuntime(30602): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-01 19:16:23.337: E/AndroidRuntime(30602): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-01 19:16:23.337: E/AndroidRuntime(30602): at dalvik.system.NativeStart.main(Native Method)
06-01 19:16:23.337: E/AndroidRuntime(30602): Caused by: java.lang.NullPointerException
06-01 19:16:23.337: E/AndroidRuntime(30602): at com.ComedyZone.MainActivity.onCreate(MainActivity.java:37)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-01 19:16:23.337: E/AndroidRuntime(30602): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1660)
06-01 19:16:23.337: E/AndroidRuntime(30602): ... 11 more
MainActivity.java:
package com.ComedyZone;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.ads.*;
public class MainActivity extends SherlockListActivity {
public static int THEME = R.style.Theme_Sherlock;
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] countries = getResources().getStringArray(R.array.jokes_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "a14fc778668df3b");
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="#+id/mainLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.mainLayout);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("Options")
.setIcon(R.drawable.ic_options)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, Preferences.class);
startActivity(intent);
return true;
}
}
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="#+id/mainLayout"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ComedyZone"
android:versionCode="1"
android:versionName="1.0.1" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock.Light">
<activity android:name="com.ComedyZone.Preferences" />
<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.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
setContentView(R.layout.your_layout) is missed in your code!!
you get a nullpointer exception when u use
layout.addView(adView);
try to debug your code!!
ListActivity does not require that you assign a layout to it via the setContentView() method, if you only want to show a ListView ListActivity contains per default a ListView.
In case you need to include more Views (that's your case for the ads) then a ListView in your ListActivity you can still assign a layout to your Activity. In this case your layout must contain a ListView with the android:id attribute set to #android:id/list.
your SherlockListActivity extends from ListActivity i suppose and that's what i said above is what you should take care of!!
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
change android:id="#+id/list" to android:id="#android:id/list"
list activity use a default id in the android sdk for listviews it's android:id="#android:id/list" you have to keep that in mind!!
Since you are you using a ListActivity and you are not using setContentView(R.layout.main) your layout will be null and you will get get a NullPointerException.
See with more attention the example in https://developers.google.com/mobile-ads-sdk/docs/android/fundamentals
one solution is by doing that by the XML.
Rather than creating your AdView in Java, it's also possible to set
one up entirely in XML. To do so simply:
https://developers.google.com/mobile-ads-sdk/docs/android/banner_xml
The problem of not seeing the ads is related to the minimum size that it needs. The AdMob view should be at least 320 x 50, if it is not, you will never see an ad in your application.
https://developers.google.com/mobile-ads-sdk/docs/android/intermediate?hl=nl#bannersizes
Try something like this:
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="fill_parent"
android:id="#+id/home_layout"
android:orientation="vertical"
android:layout_height="wrap_content">
<ListView
android:id="#id/android:list"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:id="#+id/ad_layout"
android:layout_height="wrap_content"
android:gravity="bottom"
android:layout_alignParentBottom="true"
android:layout_alignBottom="#+id/home_layout">
<com.google.ads.AdView android:id="#+id/adView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
ads:adUnitId="youaddunitid"
ads:adSize="BANNER"
android:gravity="bottom"
ads:testDevices="TEST_EMULATOR, yourphoneid"
ads:loadAdOnCreate="true"/>
</LinearLayout>
</RelativeLayout>
MainActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] countries = getResources().getStringArray(R.array.jokes_array);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries));
}
This was tested and it is working
I wrote the Get Point application (https://market.android.com/details?id=jv.android.getpoint&feature=search_result) to store GPS coordinates and export a KML file to be opened in Google Earth. That application was created because I need to learn the Android platform.
Because I'm new on Android please forgive me if I'm asking for a dummy question. :)
The Google Marked Developer Console show me there is an error I can't reproduce by myself either in emulator (With Google APU , Galaxy S or Galaxy 5 :(
The error message is: android.view.InflateException: Binary XML file line #3: Error inflating class com.google.android.maps.MapView.
I was looking for a solution, but could not find an answer :(
The Stack is here:
at android.view.InflateException: Binary XML file line #3: Error inflating class com.google.android.maps.MapView
at android.view.LayoutInflater.createView(LayoutInflater.java:513)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:618)
at android.view.LayoutInflater.inflate(LayoutInflater.java:407)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
at jv.android.getpoint.ListaCoordAdapter.getView(ListaCoordAdapter.java:29)
at android.widget.AbsListView.obtainView(AbsListView.java:1315)
at android.widget.ListView.makeAndAddView(ListView.java:1727)
at android.widget.ListView.fillDown(ListView.java:652)
at android.widget.ListView.fillFromTop(ListView.java:709)
at android.widget.ListView.layoutChildren(ListView.java:1580)
at android.widget.AbsListView.onLayout(AbsListView.java:1147)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
at android.view.View.layout(View.java:7035)
at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
at android.view.View.layout(View.java:7035)
at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at com.google.android.maps.MapView.<init>(MapView.java:238)
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:446)
at android.view.LayoutInflater.createView(LayoutInflater.java:500)
... 39 more
Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity.
at com.google.android.maps.MapView.<init>(MapView.java:282)
at com.google.android.maps.MapView.<init>(MapView.java:255)
... 43 more
The main activity has an menu option to call the MapActivity. The XML and code:
To start the map:
Intent intent = new Intent(GetPointActivity.this, PointView.class);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
startActivity(intent);
The PointView class:
public class PointView extends MapActivity {
MapView mv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
mv = (MapView)findViewById(R.id.mvPosicao);
mv.setLongClickable(true);
mv.setBuiltInZoomControls(true);
Intent intent = getIntent();
if (intent != null)
{
Bundle params = intent.getExtras();
if (params != null) {
Double lat = (Double) params.getDouble("latitude");
Double lon = (Double) params.getDouble("longitude");
markPosition (lat, lon);
}
}
registerForContextMenu(mv);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Log.i("MYINFO", "I'm in");
MenuItem mi0 = menu.add(Menu.NONE, 0, 0, getString(R.string.mnVerMapa));
mi0.setIcon(R.drawable.mapview);
MenuItem mi1 = menu.add(Menu.NONE, 1, 1, getString(R.string.mnVerSatelite));
mi1.setIcon(R.drawable.satelliteview);
MenuItem mi2 = menu.add(Menu.NONE, 2, 2, getString(R.string.mnVerStreetView));
mi2.setIcon(R.drawable.streetview);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
mv.setSatellite(false);
break;
case 1:
mv.setSatellite(true);
break;
case 2:
mv.setStreetView(true);
break;
}
return true;
}
public void markPosition (Double lat, Double lon){
int latE6 = (int)(lat*1E6);
int lonE6 = (int)(lon*1E6);
GeoPoint point = new GeoPoint(latE6, lonE6);
ImageOverlay io = new ImageOverlay(new GeoPoint(latE6, lonE6), R.drawable.waypoint2);
mv.getOverlays().add(io);
mv.getController().setCenter(point);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
The PointView XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
android:id="#+id/mvPosicao"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="<my googlemaps key" />
</LinearLayout>
My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="<package>.getpoint"
android:versionCode="1"
android:versionName="1.0.1">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<application android:label="#string/app_name" android:icon="#drawable/maps">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".GetPointActivity" android:label="#string/app_name" android:configChanges="keyboard|keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".PointView" android:configChanges="keyboard|keyboardHidden|orientation" android:label="#string/app_name" android:theme="#android:style/Theme.NoTitleBar"/>
</application>
</manifest>
The option to show the map is called by a context menu displayed when the user long press a ListView. That ListView has a custom Adapter (the highlighted line is displayed in the stack):
public class ListaCoordAdapter extends ArrayAdapter<CoordToShow> {
private List<CoordToShow> items;
Context context;
public ListaCoordAdapter(Context context, int textViewResourceId, List<CoordToShow> items) {
super(context, textViewResourceId, items);
this.items = items;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
**v = vi.inflate(R.layout.rowcoord, null);**
}
CoordToShow it = items.get(position);
if (it != null) {
ImageView iv = (ImageView) v.findViewById(R.id.ivCoord);
TextView l1 = (TextView) v.findViewById(R.id.linha1);
TextView l2 = (TextView) v.findViewById(R.id.linha2);
l1.setText(it.getNome());
l2.setText(it.toString());
if (iv != null) {
if (it.getTipo() == CoordToShow.PONTO)
iv.setImageResource(R.drawable.waypoint2);
else
iv.setImageResource(R.drawable.track);
}
}
return v;
}
}
The rowcoord xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<ImageView android:src="#drawable/waypoint2" android:id="#+id/ivCoord" android:layout_width="32dp" android:layout_height="32dp"></ImageView>
<LinearLayout
android:id="#+id/ll2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical">
<TextView android:id="#+id/linha1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="#+id/linha2"></TextView>
</LinearLayout>
</LinearLayout>
In Default.Property:
target=Google Inc.:Google APIs:8
Any help will be appreciated.
The core of your problem is at the very bottom of the stack trace: MapViews can only be created inside instances of MapActivity. Basically, the inflation is taking place from outside of your PointView for whatever reason.
Is jv.android.getpoint.ListaCoordAdapter one of your classes? It looks from the stack trace that this is the class that's trying to inflate the layout. If this class is yours, does it extend MapActivity?
I fixed it by extend MapActivity instead of Activity in the activity class that calls the MapView