Simone Sessa
Simone Sessa

Reputation: 873

Android - Global variable

I'm new to Android.

In my app, I've two button and a textView: first button add one, second button remove one.

To optimize my app, I should to create a global variable for TextView count and other resource. I've tried with another class, but app crashes when I open it.

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

EDIT
This is the 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)

My 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>

Upvotes: 0

Views: 1336

Answers (2)

pez
pez

Reputation: 4235

Did you forget to define the application in Manifest.xml?

You need something like:

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

In your case:

<?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>

In regard to your question of having more than one class extend Application, please see this Stack Overflow answer. Specifically, it isn't advised to do so.

Upvotes: 1

bGorle
bGorle

Reputation: 1996

In manifest file under the application tag set the name attribute to your MyApp Application class

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

Upvotes: 1

Related Questions