Android - 全局变量

时间:2015-07-26 16:50:22

标签: android

我是Android新手。

在我的应用中,我有两个按钮和一个textView:第一个按钮添加一个,第二个按钮删除一个。

要优化我的应用,我应该为TextView count和其他资源创建一个全局变量。我尝试过另一个班级,但是当我打开它时应用程序崩溃了。

package com.simonesessa.count;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.w3c.dom.Text;

/*class MyCount extends Application{
    private TextView textView;
    public TextView getTextView(){
        return textView;
    }
    public void setTextView(TextView set){
        textView = set;
    }
}*/

class MyApp extends Application {

    private String myState;

    public String getState(){
        return myState;
    }
    public void setState(String s){
        myState = s;
    }
}


public class MainActivity extends AppCompatActivity {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        String num = sharedPref.getString("count", null);

        TextView count = (TextView) findViewById(R.id.textCount);

        /*MyCount appState = ((MyCount)getApplicationContext()); //<-- here I've error
        appState.setTextView(count);
        count = appState.getTextView();*/
        MyApp appState = ((MyApp)getApplicationContext());//<-- here I've error
        appState.setState("TEST");
        String state = appState.getState();
        Log.d("test",state);


        if(num==null){
            num="0";
        }
        count.setText(num);
    }

    @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);
    }

    public void addCount(View view){
        TextView count = (TextView) findViewById(R.id.textCount);
        Integer num = Integer.parseInt(count.getText().toString());
        num++;
        setCount(num);
        /*SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("count", num.toString());
        editor.commit();*/
        count.setText(num.toString());
    }
    public void removeCount(View view){
        TextView count = (TextView) findViewById(R.id.textCount);
        Integer num = Integer.parseInt(count.getText().toString());
        num--;
        setCount(num);
        /*SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("count", num.toString());
        editor.commit();*/
        count.setText(num.toString());
    }
    public void setCount(Integer num){
        SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("count", num.toString());
        editor.commit();
    }
}

修改
这是logcat:

07-26 18:54:02.027    4476-4476/? I/art﹕ Late-enabling -Xcheck:jni
07-26 18:54:02.056    4476-4487/? I/art﹕ Debugger is no longer active
07-26 18:54:02.137    4476-4476/? D/AndroidRuntime﹕ Shutting down VM
07-26 18:54:02.138    4476-4476/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.simonesessa.count, PID: 4476
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.simonesessa.count/com.simonesessa.count.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.simonesessa.count.MyApp
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.simonesessa.count.MyApp
            at com.simonesessa.count.MainActivity.onCreate(MainActivity.java:58)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

我的AndroidMAnifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.simonesessa.count" >

    <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>
    </application>

    </manifest>

2 个答案:

答案 0 :(得分:1)

您是否忘记在Manifest.xml中定义应用程序?

您需要以下内容:

 <application
    android:name="package.AppName"
    ...
 </application>

在你的情况下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.simonesessa.count" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"

    <!-- ADD THIS -->
    android:name="com.simonesessa.count.MyApp" >

    <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>
</application>

</manifest>

关于您有多个课程延长Application的问题,请参阅this Stack Overflow答案。具体而言,不建议这样做。

答案 1 :(得分:1)

application标记下的清单文件中,将name属性设置为MyApp Application

 <application
    android:name="com.simonesessa.count.MyApp"
    ...
 </application>