Android HelloWorld App Crashes On Implementation of Second Activity - android

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.

Related

Error inflating class fragment in Android popular movies app

After i made some changes in an AsynTask i get this error when running the app:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.popularmovies/com.example.android.popularmovies.MainActivity}: android.view.InflateException: Binary XML file line #1: Error inflating class fragment
This is the activity_main.xml file.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="com.example.android.popularmovies.MainActivityFragment"
tools:layout="#layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
And this is the MainActivity.java file:
package com.example.android.popularmovies;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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);
}
}
Thanks for any help you can provide! ;)
I am not sure try the following:
Add
tools:context= ".MainActivity"
or Can you put <fragment> inside a <FrameLayout>.
Clean the code once.

Android Studio: Activity not found exception when using Intents in ALL programming projects

After picking up my projects after a month, I run into a really catastrophic problem: I cannot start new activities anymore! Everytime I use an intent to do that, I get an Activity not found error and Android studio wants me to declare my activities in the manifest. However, I have checked the declarations for what feels like years now and have no idea where the problem is. I have created a (several, rather) new project(s) from scratch to avoid any complications and the problem persists. Among other things, I have tried declaring the activities like this
android:name=".MainActivity"
and like this
android:name="com.example.dorothea.intenttest.MainActivity"
and formulating the intent like this
public final Intent intenttest = new Intent(this, SecondActivity.class);
and this
public final Intent intenttest = new Intent(MainActivity.this, SecondActivity.class);
Also, because this problem persists in even the simplest of projects, I cannot think of a null pointer exception in the construction of the started activity that has escaped me. I am really stumped here and any help would be very appreciated. Probably it is a really dumb error on my part, but I cannot see which one :(
In the following, I attach the logcat and code of a very simple (two blank pages) app that I used to find the problem. I let Android Studio create two blank activities and just added two lines of code to the Java file of the first.
Logcat:
08-24 13:36:32.460 26726-26726/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dorothea.intenttest/com.example.dorothea.intenttest .MainActivity}: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.example.dorothea.intenttest.SecondActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2252)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.access$700(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1286)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5302)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.example.dorothea.intenttest.SecondActivity}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1635)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1434)
at android.app.Activity.startActivityForResult(Activity.java:3434)
at android.app.Activity.startActivityForResult(Activity.java:3395)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:820)
at android.app.Activity.startActivity(Activity.java:3630)
at android.app.Activity.startActivity(Activity.java:3598)
at com.example.dorothea.intenttest.MainActivity.onCreate(MainActivity.java:16)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.access$700(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1286)
at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5302)
            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:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)
08-24 13:36:39.137 26726-26726/? I/Process﹕ Sending signal. PID: 26726 SIG: 9
Java file first activity:
package com.example.dorothea.intenttest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
public final Intent intenttest = new Intent(this, SecondActivity.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startActivity(intenttest);
}
#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);
}
}
The activity to be started is just like android created it:
package com.example.dorothea.intenttest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
#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_second, 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);
}
}
And needless to say, Android Studio has in fact declared the activities in the manifest file, which is here:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dorothea.intenttest" >
<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=".SecondActivity"
android:label="#string/title_activity_second" >
</activity>
</application>
You can't use context before it's initialized during activity lifecycle. Intents can be created after onCreate()
Move this line sowhere inside listener or some method called when activity is running (create it just before use):
public final Intent intenttest = new Intent(this, SecondActivity.class);
Error is in this line of code
public final Intent intenttest = new Intent(this, SecondActivity.class);
You have to move that initialization into onCreate or some other activity method.
You have to pass Activity instance to the Intent constructor and that instance has not yet been created.
you shoud use your package to declare activity in manifest. In your case :
<activity
android:name=".intenttest.SecondActivity"
android:label="#string/title_activity_second" >

How to Fetch data from database and display in text view in android

I am creating an android application that consists of database registration.In the other activity I placed a button to retrieve data from database displayed in a text view. I did some thing to do like this but it was showing an error called NoClassDefFoundError. Please Help me with this. Please excuse if there is any mistakes. Thanks in advance.
This is my main activity:
package com.developer.and;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class Modes extends Activity {
Button auto,manual,adminsettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.modes);
auto = (Button)findViewById(R.id.button_auto);
auto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent auto = new Intent(Modes.this,Auto.class);
startActivity(auto);
}
});
manual = (Button)findViewById(R.id.button_manualmode);
manual.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent manual = new Intent(Modes.this,Manual.class);
startActivity(manual);
}
});
adminsettings = (Button)findViewById(R.id.button_Adminsettings);
savedInstanceState = getIntent().getExtras();
if(savedInstanceState!=null){
String value_username = savedInstanceState.getString("USERNAME"); //getting username key,value pairs sent from previous intents
String value_password = savedInstanceState.getString("PASSWORD"); //getting password key,value pairs sent from previous intents
if(value_username.equals("medequip") && value_password.equals("medequip")){ //Comparing username and password sent from previous intent activity to display admin settings button or not...
adminsettings.setVisibility(View.VISIBLE); //setting visibility for a button
adminsettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent retriving_database = new Intent (Modes.this,AdminSettings.class);
startActivity(retriving_database);
}
});
}
else
adminsettings.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.modes, 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);
}
}
This is my second activity to fetch database results
package com.developer.and;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.developer.milanandroid.LoginDataBaseAdapter;
public class AdminSettings extends ActionBarActivity {
LoginDataBaseAdapter logindatabase_adapter_child;
Button fetch_database;
TextView text_fetched_database_results;
String username,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_settings);
fetch_database = (Button)findViewById(R.id.Button_Fetch_Database);
fetch_database.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Cursor c = logindatabase_adapter_child.db.rawQuery("select * from MilanloginRegistration", null);
text_fetched_database_results.setText("");
c.moveToFirst();
do{
username = c.getString(c.getColumnIndex("USERNAME"));
password = c.getString(1);
text_fetched_database_results.append("USERNAME::-->"+username+"PASSWORD::-->"+password+"\n");
}while(c.moveToNext());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.admin_settings, 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);
}
}
MainActivity.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"
tools:context="com.developer.and.Modes" >
<Button
android:id="#+id/button_Adminsettings"
android:layout_width="450dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Adminsettings" />
</RelativeLayout>
This is my second activity 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"
tools:context="com.developer.and.AdminSettings" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="#dimen/Retriving_database_ll_width"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<Button
android:id="#+id/Button_Fetch_Database"
style="?android:attr/buttonStyleSmall"
android:layout_width="#dimen/Retriving_database_Button_width"
android:layout_height="wrap_content"
android:text="#string/Retriving_database" />
</LinearLayout>
<ScrollView
android:id="#+id/scrollView_db_contacts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/linearLayout1" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView_fetched_database_results"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textSize="20sp" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
This is my logcat:
04-27 11:32:41.910: E/AndroidRuntime(13452): FATAL EXCEPTION: main
04-27 11:32:41.910: E/AndroidRuntime(13452): Process: com.developer.milanandroid, PID: 13452
04-27 11:32:41.910: E/AndroidRuntime(13452): java.lang.NoClassDefFoundError: com.developer.milanandroid.AdminSettings
04-27 11:32:41.910: E/AndroidRuntime(13452): at com.developer.milanandroid.Modes$3.onClick(Modes.java:56)
04-27 11:32:41.910: E/AndroidRuntime(13452): at android.view.View.performClick(View.java:4438)
04-27 11:32:41.910: E/AndroidRuntime(13452): at android.view.View$PerformClick.run(View.java:18422)
04-27 11:32:41.910: E/AndroidRuntime(13452): at android.os.Handler.handleCallback(Handler.java:733)
04-27 11:32:41.910: E/AndroidRuntime(13452): at android.os.Handler.dispatchMessage(Handler.java:95)
04-27 11:32:41.910: E/AndroidRuntime(13452): at android.os.Looper.loop(Looper.java:136)
04-27 11:32:41.910: E/AndroidRuntime(13452): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-27 11:32:41.910: E/AndroidRuntime(13452): at java.lang.reflect.Method.invokeNative(Native Method)
04-27 11:32:41.910: E/AndroidRuntime(13452): at java.lang.reflect.Method.invoke(Method.java:515)
04-27 11:32:41.910: E/AndroidRuntime(13452): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-27 11:32:41.910: E/AndroidRuntime(13452): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-27 11:32:41.910: E/AndroidRuntime(13452): at dalvik.system.NativeStart.main(Native Method)
Your Class AdminSetting and Mode is in package com.developer.and but not com.developer.milanandroid. Change the package name in line 1 of two files, then compiler can find the class.
Your classes AdminSettings and Modes is in package com.developer.and and not in com.developer.milanandroid. So either change package name in your project explore or in AndroidManifest to match each other. Currently in your project you have package com.developer.and but in your AndroidManifest it seems you are using package com.developer.milanandroid.

Android application can not load once a new class is introduced

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.

Android - SupportMapFragment with GoogleMaps API 2.0 giving IllegalArgumentException

I am trying to use the latest Map API 2.0 provided for Android. I am using the Support Library as I want to support Android 2.2. Following is my code:
Main Activity class
public class MainActivity extends FragmentActivity {
public FragmentManager fManager ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fManager = getSupportFragmentManager();
Button showMapButton = (Button) findViewById(R.id.showMapButton);
showMapButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loadMapFragment();
}
});
}
private void loadMapFragment() {
MapPageFragment plotterFragment = new MapPageFragment();
FragmentTransaction ft = fManager.beginTransaction();
ft.replace(R.id.allFragmentsFrameLayout, plotterFragment);
ft.addToBackStack(null);
ft.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Main Activity layout 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"
tools:context=".MainActivity" >
<Button
android:id="#+id/showMapButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Map"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="30dp"
android:layout_alignParentTop="true" />
<FrameLayout
android:id="#+id/allFragmentsFrameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true">
<!-- Put fragments dynamically -->
</FrameLayout>
</RelativeLayout>
Map Fragment Class
public class MapPageFragment extends SupportMapFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.map_fragment_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Map Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"
map:uiCompass="true"
map:mapType= "normal"
map:uiRotateGestures="true"
map:uiScrollGestures="true"
map:uiTiltGestures="true"
map:uiZoomControls="true"
map:uiZoomGestures="true" />
Android Manifest File
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mapfragmentexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="com.plotter.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.plotter.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<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=".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="AIzaSyA5FtIeLQ1gGUihZIZPQVi3Yz_0l4NG9PY"/>
</application>
</manifest>
Everything is working fine for the first time. i.e. When I click on the Show Map button the map fragment gets loaded and displays the map. When I press back button, the map fragment is unloaded and I can see the Show Map button again.
I face an issue when I press the Show Map button again. I get the following error:
FATAL EXCEPTION: main
android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:699)
at android.view.LayoutInflater.inflate(LayoutInflater.java:468)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at com.mapfragmentexample.MapPageFragment.onCreateView(MapPageFragment.java:17)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4503)
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:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #2:
Duplicate id 0x7f040006, tag null, or parent id 0x0 with another fragment
for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:285)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:671)
... 18 more
I am not getting where I am getting wrong or missing anything.
You can fix this, if you delete all nested fragments in onDestroyView(). Don't know if it is a proper solution.
public void onDestroyView() {
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
And inflating them as usual in onCreateView()
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.map, container, false);
}
You need to use getChildFragmentManager() to add SupportMapFragment not not through xml.
For "why", see official documentation: http://developer.android.com/about/versions/android-4.2.html#NestedFragments
Take a look at my answer here: https://stackoverflow.com/a/15512285/2183804
You cannot inflate a layout into a fragment when that layout includes a fragment. Nested fragments are only supported when added to a fragment dynamically. More detail here!
Used this solution (similar to others):
public void onDestroyView() {
FragmentManager fm = getActivity().getSupportFragmentManager();
Fragment fragment = (fm.findFragmentById(R.id.map));
if (fragment.isResumed()) {
FragmentTransaction ft = fm.beginTransaction();
ft.remove(fragment);
ft.commit();
}
super.onDestroyView();
}
I had problems before using the if (fragment.isResumed).
I was facing the same issue in JakeWhartonViewPagerIndicatore along with SherlockFragments. Here is sample TestFragment with solved issue, thanks to Natalia for providing above solution. Your fragment may be a little different from mine.
Reference: Making ActionBarSherlock and ViewPagerIndicator play nice
Good Luck..!!
package com.example.vpiabstest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
public class TestFragment extends SherlockFragment {
private String mContent = "???";
private String text;
private static final String KEY_TAB_NUM = "key.tab.num";
public static TestFragment newInstance(String text) {
TestFragment fragment = new TestFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString(KEY_TAB_NUM, text);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
text = getString(R.string.tab_page_num) + mContent;
View view = null;
if(text.contains("2")) {
view = inflater.inflate(R.layout.pinpoints_list, null);
} else if(text.contains("1")) {
view = inflater.inflate(R.layout.main_fragment_activity, null);
} else {
view = inflater.inflate(R.layout.activity_main, null);
((TextView)view.findViewById(R.id.text)).setText(text);
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContent = getArguments() != null ? getArguments().getString(KEY_TAB_NUM) : "???";
}
public void onDestroyView() {
super.onDestroyView();
// Your Programing skills goes here
if(text == null || !text.contains("1")) {
return;
}
// Do Not Miss this
try {
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map_fragment));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use dialog.SetContentView() method in your activity's onCreate() cause when we tring to load.
Dialog again it loads only dialog not the whole activity life cycle and leads it to exception of Duplicate id.
Try it.
Try this
Maps fragment layout
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
map:uiCompass="true"
map:mapType= "normal"
map:uiRotateGestures="true"
map:uiScrollGestures="true"
map:uiTiltGestures="true"
map:uiZoomControls="true"
map:uiZoomGestures="true"
tools:context="the.package.name.of.mappagefragment.MapPageFragment" />
Map fragment class
public class MapPageFragment extends SupportMapFragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = super.onCreateView(inflater, container, savedInstanceState);
if (rootView == null)
{
rootView = inflater.inflate(R.layout.map_fragment_layout, container, false);
}
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
}
}
I used Natalia response but at times broke the application.
Use this one and it worked perfectly without breaking.
#Override
public void onDestroyView() {
try{
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.remove(nestedFragment);
transaction.commit();
}catch(Exception e){
}
super.onDestroyView();
}
https://stackoverflow.com/a/7953801/3364157
Fragment fragment = (getChildFragmentManager().findFragmentById(R.id.mapview));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
Use this saves the day.
Use intent flags:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
when calling main activity.
I had the same problem. Try adding ...
android:name="com.mapfragmentexample.MapPageFragment"
... to fragment in the layout file!

Categories

Resources