class not found exception android for fragment activity

一曲冷凌霜 提交于 2019-12-24 03:25:04

问题


I am working on fragment activity to work on gingerbread OS. when I am trying to run the application on gingerbread emulator the application is getting forced close due to ClassNotFound error. I am providing my main fragment activity code below

A peace of help would be appreciable.

  package com.example.android.effectivenavigation;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
 * three primary sections of the app. We use a {@link android.support.v4.app.FragmentPagerAdapter}
 * derivative, which will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
AppSectionsPagerAdapter mAppSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will display the three primary sections of the app, one at a
 * time.
 */
ViewPager mViewPager;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create the adapter that will return a fragment for each of the three primary sections
    // of the app.
    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();

    // Specify that the Home/Up button should not be enabled, since there is no hierarchical
    // parent.
    actionBar.setHomeButtonEnabled(false);

    // Specify that we will be displaying tabs in the action bar.
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager, attaching the adapter and setting up a listener for when the
    // user swipes between sections.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @SuppressLint("NewApi")
        @Override
        public void onPageSelected(int position) {
            // When swiping between different app sections, select the corresponding tab.
            // We can also use ActionBar.Tab#select() to do this if we have a reference to the
            // Tab.
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by the adapter.
        // Also specify this Activity object, which implements the TabListener interface, as the
        // listener for when this tab is selected.
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
 * sections of the app.
 */
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

    public AppSectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0:
                // The first section of the app is the most interesting -- it offers
                // a launchpad into the other demonstrations in this example application.
                return new LaunchpadSectionFragment();

            default:
                // The other sections of the app are dummy placeholders.
                Fragment fragment = new DummySectionFragment();
                Bundle args = new Bundle();
                args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
                fragment.setArguments(args);
                return fragment;
        }
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "Section " + (position + 1);
    }
}

/**
 * A fragment that launches other parts of the demo application.
 */
public static class LaunchpadSectionFragment extends Fragment {
    ArrayAdapter<String> adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_section_launchpad, container, false);
        ListView listView = (ListView)rootView.findViewById(R.id.listview);
        String[] values = new String[] {"Akshay Borgave","Pramod Mahake","Vishal Lokhande","Vivek Chaudhari","Rahul Borole","Neha Gadekar"};


      adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_2, android.R.id.text1, values);


        listView.setAdapter(adapter);
        // Demonstration of a collection-browsing activity.
        /*rootView.findViewById(R.id.demo_collection_button)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), CollectionDemoActivity.class);
                        startActivity(intent);
                    }
                });*/

        // Demonstration of navigating to external activities.
       /* rootView.findViewById(R.id.demo_external_activity)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Create an intent that asks the user to pick a photo, but using
                        // FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET, ensures that relaunching
                        // the application from the device home screen does not return
                        // to the external activity.
                        Intent externalActivityIntent = new Intent(Intent.ACTION_PICK);
                        externalActivityIntent.setType("image/*");
                        externalActivityIntent.addFlags(
                                Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        startActivity(externalActivityIntent);
                    }
                });*/

        return rootView;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply displays dummy text.
 */
public static class DummySectionFragment extends Fragment {

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}
}

And the Manifest look like this

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.effectivenavigation"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="9" 
    android:targetSdkVersion="10"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.WithActionBar" >
    <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=".CollectionDemoActivity"
        android:label="@string/demo_collection" />
</application>

logcat is

06-12 16:37:17.099: E/AndroidRuntime(378): FATAL EXCEPTION: main
06-12 16:37:17.099: E/AndroidRuntime(378): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.effectivenavigation/com.example.android.effectivenavigation.MainActivity}: java.lang.ClassNotFoundException: com.example.android.effectivenavigation.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.android.effectivenavigation-1.apk]
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.os.Looper.loop(Looper.java:123)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.app.ActivityThread.main(ActivityThread.java:3683)
06-12 16:37:17.099: E/AndroidRuntime(378):  at java.lang.reflect.Method.invokeNative(Native Method)
06-12 16:37:17.099: E/AndroidRuntime(378):  at java.lang.reflect.Method.invoke(Method.java:507)
06-12 16:37:17.099: E/AndroidRuntime(378):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-12 16:37:17.099: E/AndroidRuntime(378):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-12 16:37:17.099: E/AndroidRuntime(378):  at dalvik.system.NativeStart.main(Native Method)
06-12 16:37:17.099: E/AndroidRuntime(378): Caused by: java.lang.ClassNotFoundException: com.example.android.effectivenavigation.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.example.android.effectivenavigation-1.apk]
06-12 16:37:17.099: E/AndroidRuntime(378):  at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
06-12 16:37:17.099: E/AndroidRuntime(378):  at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
06-12 16:37:17.099: E/AndroidRuntime(378):  at  java.lang.ClassLoader.loadClass(ClassLoader.java:511)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
06-12 16:37:17.099: E/AndroidRuntime(378):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
06-12 16:37:17.099: E/AndroidRuntime(378):  ... 11 more

The Xml layout file for the fragment activity is as follows

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

thanks in advance again


回答1:


In your mainfest.xml you have

<uses-sdk android:minSdkVersion="9" 
    android:targetSdkVersion="10"/>

Fragments were introduced in API level 11, i.e. Android 3.0. I think you are getting the ClassNotFoundException as the system has no knowledge about the Fragment class in lower versions.

So you would need to use the Android Support Library to use Fragments in lower API levels.




回答2:


The code seems correct, sounds like an issue with your build system. Try refreshing/clearing your workspace (if you use eclipse) and make sure you add the support library when building the APK



来源:https://stackoverflow.com/questions/17064589/class-not-found-exception-android-for-fragment-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!