android - ((ChuckApplication) getActivity().getApplication()).setCurrentGame(c) 在 fragment 中

标签 android database android-intent android-fragments android-sqlite

我目前正在研究一个琐事风格的应用程序,我正在 fragment 中使用它。如果我使用 Activities 而不是 Fragments,则代码有效:

((ChuckApplication)getApplication()).setCurrentGame(c);

但是一旦我将它转换到一个 Activity 中,它就会不断出错。代码是:

((ChuckApplication)getActivity().getApplication()).setCurrentGame(c);

这个 fragment 的全部代码是:

public class Activity_Home_Language extends Fragment implements OnClickListener{
    Intent intent;
    ImageButton btnToggle;
    Button btnExam,btnReview;
    TextView txtTitle;

    View rootView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.layout_home_language, container, false);
        btnToggle = (ImageButton) rootView.findViewById(R.id.btnToggle);
        btnExam = (Button) rootView.findViewById(R.id.btnExam);
        btnReview = (Button) rootView.findViewById(R.id.btnReview);
        txtTitle = (TextView) rootView.findViewById(R.id.txtTitle);

        btnToggle.setOnClickListener(this);
        btnExam.setOnClickListener(this);
        btnReview.setOnClickListener(this);
        //FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        //transaction.add(R.id.frameContent, new Activity_Home());
        //transaction.add(R.id.framePager2, new ViewPagerMunicipalities());
        //transaction.add(R.id.frameDestPager, new ViewPagerDes());
        //transaction.commit();
      //for fading animation
        return rootView;



    }


    @Override
    public void onClick(View v) {
        if(v==btnToggle){
            Activity_Main.mSlideHolder.open();
        }
        else if(v==btnExam){
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            //transaction.addToBackStack(null);
            transaction.replace(R.id.frameContent, new Activity_Question_Exam_Home()).commit();

        }



        else if(v==btnReview){
            //enable this to move to move to a Activity or fragment activity
            //intent = new Intent(rootView.getContext(), Activity_About.class);
            //startActivityForResult(intent,0);

            //Get Question set //
            List<Question> questions = getQuestionSetFromDb();

            //Initialise Game with retrieved question set ///
            GamePlay c = new GamePlay();
            c.setQuestions(questions);
            c.setNumRounds(getNumQuestions());

            ((ChuckApplication) getActivity().getApplication()).setCurrentGame(c);


            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.frameContent, new Activity_Home_Language_Review()).commit();

            //transaction.addToBackStack(null);
            //transaction.commit();


            //FragmentTransaction transaction = getFragmentManager().beginTransaction();
            //transaction.addToBackStack(null);
            //transaction.replace(R.id.frameContent, new Activity_Question_Review_Home()).commit();
        }
        else {

        }
    }


    /**
     * Method that retrieves a random set of questions from
     * the database for the given difficulty
     * @return
     * @throws Error
     */
    private List<Question> getQuestionSetFromDb() throws Error {
        int diff = getDifficultySettings();
        int numQuestions = getNumQuestions();
        DBHelper myDbHelper = new DBHelper(getActivity());
        try {
            myDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
        try {
            myDbHelper.openDataBase();
        }catch(SQLException sqle){
            throw sqle;
        }

        List<Question> questions = myDbHelper.getQuestionSet(diff, numQuestions);
        //List<Question> questions = myDbHelper.getQuestionSet(diff, 2);
        myDbHelper.close();
        return questions;
    }


    /**
     * Method to return the difficulty settings
     * @return
     */
    private int getDifficultySettings() {
        SharedPreferences settings = getActivity().getSharedPreferences(Constants.SETTINGS, 0);
        int diff = settings.getInt(Constants.DIFFICULTY, Constants.MEDIUM);
        return diff;
    }

    /**
     * Method to return the number of questions for the game
     * @return
     */
    private int getNumQuestions() {
        SharedPreferences settings = getActivity().getSharedPreferences(Constants.SETTINGS, 0);
        int numRounds = settings.getInt(Constants.NUM_ROUNDS, 20);
        return numRounds;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
    }

}

请帮忙。我被困在那条线上。

这是应用程序:

package com.example.civilserviceexamreviewer;

import android.app.Application;

import com.example.civilserviceexamreviewer.quiz.GamePlay;



public class ChuckApplication extends Application{
    private GamePlay currentGame;

    /**
     * @param currentGame the currentGame to set
     */
    public void setCurrentGame(GamePlay currentGame) {
        this.currentGame = currentGame;
    }

    /**
     * @return the currentGame
     */
    public GamePlay getCurrentGame() {
        return currentGame;
    }
}

这是 list 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.civilserviceexamreviewer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
        <activity
            android:name="com.example.civilserviceexamreviewer.Activity_Splash1"
            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="com.example.civilserviceexamreviewer.Activity_Splash2"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name=".Activity_Main"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.example.civilserviceexamreviewer.Activity_Question_Review_Home"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.example.civilserviceexamreviewer.Activity_About"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.example.civilserviceexamreviewer.Activity_Choices"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>




    </application>

            <application 
                android:allowBackup="true"
                android:name="com.example.civilserviceexamreviewer.ChuckApplication" 
                android:icon="@drawable/ic_launcher" 
                android:label="@string/app_name"> 
            </application>  


</manifest>

最佳答案

您从 Fragment 中访问应用程序(或其子类)的方式是正确的。由于您遇到的错误是 ClassCastException,我认为您的问题是您尚未在 AndroidManifest.xml< 中声明您的自定义 Application 子类application 标签。出于这个原因,调用 .getApplication() 实际上会返回一个类型为 android.app.Application 的对象,它不能被类型转换为您的自定义 Application 类。也许您在最初的基于 Activity 的项目中这样做了,但是在创建基于 Fragments 的项目时忘记这样做了?

如何在 list 文件中声明您的 Application 子类的示例:

<application
     android:name="com.example.civilserviceexamreviewer.ChuckApplication" 
     android:icon="..."
     android:label="...">
</application>

因此,您在问题中发布的完整 list 实际上应该是:

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
    android:name="com.example.civilserviceexamreviewer.ChuckApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
    <activity
        android:name="com.example.civilserviceexamreviewer.Activity_Splash1"
        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="com.example.civilserviceexamreviewer.Activity_Splash2"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <activity
        android:name=".Activity_Main"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <activity
        android:name="com.example.civilserviceexamreviewer.Activity_Question_Review_Home"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <activity
        android:name="com.example.civilserviceexamreviewer.Activity_About"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <activity
        android:name="com.example.civilserviceexamreviewer.Activity_Choices"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>




</application>

关于android - ((ChuckApplication) getActivity().getApplication()).setCurrentGame(c) 在 fragment 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21987539/

相关文章:

php - 如何在MySQL表字段中保存化学方程式

android - 环绕图像android的Textview

Android webview 应用程序和 Google Analytics

sql - 作为带有 NOT EXISTS 子句的 SELECT 语句进行查询

database - 光标正在返回表中可用的更多数据

android - 为什么我收到错误 "MyActivity is not an enclosing class?"

android - 如何使用 6 个按钮创建布局,如 Windows 磁贴

android - Android 6.0 未经许可抓拍图片

java - 从 const 方法调用 JNI 函数

Android 通知声音覆盖