I don't know what I'm making wrong, but my App crash when I launch. I want to implement Tab bar list with FragmentActivity.
I really need help :(
The error returned is :
Unable to start activity ComponentInfo
Caused by: java.lang.NullPointerException
at jardelcompany.bundoransurfco.MainActivity.onCreate(MainActivity.java:79)
(line 79 is actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);)
MainActivity.java :
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(this,
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/mainLayout"
android:background="#FFFFFF"> />
<view
android:layout_width="match_parent"
android:layout_height="match_parent"
class="android.support.v4.view.ViewPager"
android:id="#+id/pager"/>
</RelativeLayout>
I use SectionsPagerAdapter for FragmentPageAdapter
SectionsPagerAdapter.java:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
protected Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new FirstFragment();
case 1:
return new LoginFragment();
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return mContext.getString(R.string.title_section1).toUpperCase(l);
case 1:
return mContext.getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
FirstFragment.java:
public class FirstFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main,
container, false);
return rootView;
}
}
LoginFragment.java :
public class LoginFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_login,
container, false);
return rootView;
}
}
Here is my AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jardelcompany.bundoransurfco" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" /> <!-- To retrieve the account name (email) as part of sign-in: -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<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"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login"
android:parentActivityName=".MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize|stateVisible" >
</activity>
</application>
</manifest>
And my styles.xml :
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
Remove this code into separate method like:
private void initUI(){
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(this,
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
and call this method from onResume() instead of onCreate(). Also you are using getActionBar() and same time getSupportFragmentManager() maybe you should use getSupportActionBar()? What is the min API level of your project?
Try adding this line of code to your manifest file
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="14" />
Related
I'm using Fragments in my app. One of them has a listView, and when I do a setOnItemClickListener, I want to pass the item clicked to the other fragment...
Here's the class OngletCours where I do my Intent:
l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent a = new Intent(getActivity(), OngletNotes.class);
startActivity(a);
}
});
return rootView;
}
I'm getting the following error when I try to do an Intent to go to another Fragment:
E/AndroidRuntime: FATAL EXCEPTION: main
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.dasilvadd.students/com.example.dasilvadd.students.OngletNotes}; have you declared this activity in your AndroidManifest.xml?
Here is my Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Student"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".PageAccueil">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Inscription"
android:label="Student" />
<activity
android:name=".Onglets"
android:label="Student"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Reglages" />
<activity android:name=".MotDePasse" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
I've already tried to add it by myself, but it doesnt recognize the class I created for the Second Fragment (OngletNotes).
Please tell me how to solve this. And thank you in advance !
If you start OngletNotes using startActivity, I assume it's an Activity. In that case you need to add it to the AndroidManifest.xml
<activity
android:name=".OngletNotes"
android:label="Notes" />
If OngletNotes is a Fragment, it should be put inside of the Activity. You can't launch standalone Fragment without an Activity.
You need to create an Activity (don't forget to put it in AndroidManifest.xml)
Put your Fragment inside of the Activity (in xml or programmatically)
Start the Activity using startActivity
# Update: OngletNotes is a fragment
Fragment example:
public static OngletNotes newInstance(/* input parameters if any */) {
OngletNotes fragment = new OngletNotes();
// put values which you want to pass to fragment
// Bundle args = new Bundle();
// fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ongletNotes, container, false);
// if you have passed some data above
// Bundle args = getArguments();
return view;
}
============================================================
# Update:
First, your onCreate in MainActivity,
// create a new instance of OngletCours (example is shown above)
OngletCours OngletCoursFragment = OngletCours.newInstance();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_holder, OngletCoursFragment )
.commit();
// and your OnItemClickListener
l1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
OngletNotes targetFragment = OngletNotes.newInstance();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.fragment_holder, targetFragment)
.commit();
}
});
activity_main.xml: you shoud have a FrameLayout which is used as a container to switch fragments
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
After readed your last comment I have edited my aswer:
Open the fragment:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).setCurrentItem (1, true);
}
});
In your MainActivity which contains ViewPager For example private ViewPager mViewPager; you need setCurrentItem method:
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
I suppose that OngleNotes fragment is the second fragment. That's why I send a 1 as a parameter.
So in my app, when I press the up button, the activity quits instead of going to its parent Activity. What might be wrong here?
SettingsActivity.java:
public class SettingsActivity extends AppCompatPreferenceActivity {
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
LinearLayout content = (LinearLayout) root.getChildAt(0);
LinearLayout toolbarContainer = (LinearLayout) View.inflate(this, R.layout.activity_settings, null);
root.removeAllViews();
toolbarContainer.addView(content);
root.addView(toolbarContainer);
mToolbar = (Toolbar) toolbarContainer.findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
addPreferencesFromResource(R.xml.pref_general);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
NavUtils.navigateUpFromSameTask(this);
}
}
How this activity is called:
private void openSettingsActivity() {
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(intent);
}
And the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pt.bluecover.wearable3d"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="23" />
<android:uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<android:uses-permission android:name="android.permission.READ_PHONE_STATE" />
<android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/female_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".DrawerActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings"
android:parentActivityName=".DrawerActivity"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="pt.bluecover.wearable3d.DrawerActivity" />
</activity>
</application>
</manifest>
So, What might be wrong with this behavior?
Add this in your SettingsActivity
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(menuItem);
}
Don't forget to override onBackPressed and call super.onBackPressed();
#Override
public void onBackPressed() {
super.onBackPressed();
}
try this code
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
//NavUtils.navigateUpFromSameTask(this);
finish();
}
Even after defining com.facebook.LoginActivity in my AndroidManifest.xml file the logcat gives the same error and asks to define com.facebook.LoginActivity as activity. I have followed this https://developers.facebook.com/docs/android/login-with-facebook/v2.2#step2 tutorial.
Here is my androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.log"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.log.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.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name="com.facebook.loginActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
MainActivity.java
package com.example.log;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.fragment_main);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
#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 MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
return view;
}
}
}
fragment_main.xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
</LinearLayout>
The facebook login activity is com.facebook.LoginActivity with a capital 'L'. You're using a lower case l.
I have searched around but none of the solutions worked for my specific case. If I add
QuickContactBadge contactBadge = (QuickContactBadge) findViewById(R.id.quickContactBadge);
I it crashes. Then I changed it to:
QuickContactBadge contactBadge;
protected void onCreate(Bundle savedInstanceState) {
...
contactBadge = (QuickContactBadge) findViewById(R.id.quickContactBadge);
}
And it doesn't crash. But if I add contactBadge.Anything(); it crashes. No matter what
method it crashes. I.E. contactBadge.assignContactFromEmail("foo#foo.com", true);
Android Activity:
public class MainActivity extends Activity {
QuickContactBadge contactBadge;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit();
}
contactBadge = (QuickContactBadge) findViewById(R.id.quickContactBadge);
contactBadge.assignContactFromEmail("pointlightproductions.net#gmail.com", true);
}
public static class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pointlight.android.kingdomcraft"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/android:Theme.Holo.NoActionBar" >
<activity
android:name="com.pointlight.android.kingdomcraft.MainActivity"
android:label="#string/app_name"
android:screenOrientation="landscape" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Layout:
<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.pointlight.android.kingdomcraft.MainActivity$MainFragment" >
<QuickContactBadge
android:id="#+id/quickContactBadge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
First method: You're calling findViewById() when the activity is instantiated and its member variables are initialized. The activity won't have a Window yet and it will NPE. Call findViewById() only in onCreate() or later, after setContentView().
Second method: You don't have setContentView() with a view hierarchy that has a view with the given id. null is returned and invoking method on it will NPE.
From the code you later added, it seems the view is in your fragment layout and not the activity layout. It won't be a part of the activity view hierarchy in onCreate(). You should move the code to the fragment's onCreateView() instead:
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
contactBadge = (QuickContactBadge) rootView.findViewById(R.id.quickContactBadge);
contactBadge.assignContactFromEmail("pointlightproductions.net#gmail.com", true);
I was going through the tutorial by google and couldn't figure out how to place search icon on action bar.
this is the main_activity_actions.xml code :-
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="always" />
<!-- Settings, should always be in the overflow -->
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:showAsAction="never" />
</menu>
this is the MainActivity.java :-
public class MainActivity extends ActionBarActivity
{
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null)
{
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
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;
}
}
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);
}
public void openSearch()
{
}
public void openSettings()
{
}
}
Manifest.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="7"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:theme="#style/Theme.AppCompat.Light"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<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>
</manifest>
I have already seen few answers and posted an the stack overflow and tried them and it still doesn't work
the search icon never shows up while I try to run it
can someone suggest what to do?
in activity_action.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:(YOUR_PROJECT_NAME)="http://schemas.android.com/apk/res-auto"
>
<!-- Search, should appear as action button -->
<item android:id="#+id/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
YOUR_PROJECT_NAME:showAsAction="always" />