0

I'm programming a tiny application. Just for your background knowledge: If you click on the image, the counter decreases. Attending to that my 2 questions are the following.

  1. How can I manage it with some code of lines that my counter doesen't fall back to the startpoint when I leave the app. E.g. if I leave at point 5 and come back later, I want to continue at point 5 and not 10.
  2. I want that a completelly new picture appears when the counter reaches 0 but I do not know how to manage that.

To point 2: I have tried with the following lines but it doesn't work. The app crashes when I leave, e.g. at point 6.

@Override 
    protected void onPause() { 
        SharedPreferences mPrefs = getSharedPreferences("data", 0); 
        counter = mPrefs.getInt("counter", 0);
        SharedPreferences.Editor 
        mEditor = mPrefs.edit(); 
        mEditor.putInt("counter", counter).commit(); 
        onWindowFocusChanged(true);
        }

Here is the whole code. I hope someone is able to help me. :)

    package com.first.app;

import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

    public class MainActivity extends Activity {

    int counter = 10;
    public static String TAG = "Debug";
    @Override 
    protected void onPause() { 
        SharedPreferences mPrefs = getSharedPreferences("data", 0); 
        SharedPreferences.Editor 
        mEditor = mPrefs.edit(); 
        mEditor.putInt("counter", counter).commit(); 
        onWindowFocusChanged(true);
        super.onPause(); 
        }

    @Override
    protected void onStop() {
        Log.w(TAG, "App stopped");
        //also do your savings here to be sure
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.w(TAG, "App destoryed");
        //also do your savings here to be sure
        super.onDestroy();
    }

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

        final TextView text = (TextView) findViewById(R.id.TextView01);
        final ImageView apfel = (ImageView) findViewById(R.id.appel);
        final ImageView image = (ImageView) findViewById(R.id.smiley);

        apfel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (counter > 0) {
                    counter--;
                    text.setText("" + counter);
                }
                if (counter == 0) {
                    image.setImageResource(R.drawable.smiley);
                    text.setText("You finished!");
                }
            }
        });

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

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

}

The things after the following codeline were automatically'installed' when I created the project.

if (counter == 0) {
                    text.setText("Congratulations you finished!");

1 Answers1

0

You can write it to a file and read it again if the app opens. But I think that the best way is to use the SharedPreferences.

You can find an example here: example

I have tried with the following lines but it doesn't work. The app crashes when I leave, e.g. at point 6.

could you generate your error log and post it?

Edit2: you need the onStop and onDestroy in your methods. Like this

public static string TAG = "Debug";
@Override
protected void onStop() {
    Log.w(TAG, "App stopped");
    //also do your savings here to be sure
    super.onStop();
}

@Override
protected void onDestroy() {
    Log.w(TAG, "App destoryed");
    //also do your savings here to be sure
    super.onDestroy();
}

Your code will be:

    package com.first.app;

import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    int counter;
    public static string TAG = "Debug";
    @Override 
    protected void onPause() { 
        SharedPreferences mPrefs = getSharedPreferences("data", 0); 
        SharedPreferences.Editor 
        mEditor = mPrefs.edit(); 
        mEditor.putInt("counter", counter).commit(); 
        onWindowFocusChanged(true);
        super.onPause(); 
        }

    @Override
    protected void onStop() {
        Log.w(TAG, "App stopped");
        SharedPreferences mPrefs = getSharedPreferences("data", 0); 
        SharedPreferences.Editor 
        mEditor = mPrefs.edit(); 
        mEditor.putInt("counter", counter).commit(); 
        onWindowFocusChanged(true);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.w(TAG, "App destoryed");
        SharedPreferences mPrefs = getSharedPreferences("data", 0); 
        SharedPreferences.Editor 
        mEditor = mPrefs.edit(); 
        mEditor.putInt("counter", counter).commit(); 
        onWindowFocusChanged(true);
        super.onDestroy();
    }

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

    SharedPreferences settings = getSharedPreferences("data", 0);
    counter = settings.getInt("counter", 10);

        final TextView text = (TextView) findViewById(R.id.TextView01);
        final ImageView apfel = (ImageView) findViewById(R.id.appel);
        final ImageView image = (ImageView) findViewById(R.id.smiley);

        apfel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (counter > 0) {
                    counter--;
                    text.setText("" + counter);
                }
                if (counter == 0) {
                    image.setImageResource(R.drawable.smiley);
                    text.setText("You finished!");
                    SharedPreferences mPrefs = getSharedPreferences("data", 0); 
                    SharedPreferences.Editor 
                    mEditor = mPrefs.edit(); 
                    mEditor.putInt("counter", 10).commit(); 
                }
            }
        });

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

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

}
Community
  • 1
  • 1
DeGoosseZ
  • 628
  • 5
  • 20
  • Here is a link to a screenshot: http://s7.directupload.net/images/140402/i698yjf7.jpg – user3420083 Apr 02 '14 at 06:59
  • Mhm ok but what does TAG mean? Eclipse underlines it read for me.. here is a screenshot: http://s7.directupload.net/images/140403/zmiav85y.jpg – user3420083 Apr 03 '14 at 11:42
  • It is a string with a tag for your logcat output, you dont need that line or can replace it whatever string you want to use. Ex "debug" – DeGoosseZ Apr 03 '14 at 11:44
  • I updatet my code (see above). Mhm I cannot run the application because it still underlines TAG and says TAG CANNOT BE RESOLVED TO A VARIABLE .... – user3420083 Apr 05 '14 at 10:47
  • create a global variable, I updated my code example. The line on top is what you need. – DeGoosseZ Apr 05 '14 at 10:48
  • I added your code in my post, that's how it should look like – DeGoosseZ Apr 05 '14 at 11:00
  • Mhm okay.. I changed it like you wrote it here but if I leave the app e.g. at 4 it still crashes -.- Here is the screen: http://s1.directupload.net/images/140405/a34djqfd.jpg – user3420083 Apr 05 '14 at 12:12
  • added super.onPause(); in the onPause(); function. Try it at the place where it's now and if that does not work, at the beginning of the function – DeGoosseZ Apr 05 '14 at 12:16
  • Okay cool I added super.onPause(); in the onPause(); function. Look at my code above. Now it does not crash when I close the app. Unfortunately, if I reopen the app, the countdown starts again at 10 and not at the point I had left. – user3420083 Apr 05 '14 at 13:50
  • I changed the code a bit, how about now? Can you check your logcat and see what gets printed? Do you see "App stopped" or "App destoryed"? – DeGoosseZ Apr 06 '14 at 11:55
  • Yes I see "App stopped" and "App destoryed" but many errors,too. Mhm it still does not work. Here is the LogCat: http://s14.directupload.net/images/140406/obutzffs.jpg – user3420083 Apr 06 '14 at 15:00
  • You forgot to load the int you saved into your counter integer. I added 2 lines in the onCreate but I'm not sure that this will fix it. You'll have to tweak it yourself some more. – DeGoosseZ Apr 06 '14 at 15:10
  • If I klick on the image now, it does not decrease 1 but immediately switches to "You Finished!" – user3420083 Apr 06 '14 at 15:21
  • I edited again, to make the prefs change to 10 again when the game finished. Try working with some Log.i functions to find out where your counter changes to what and when. – DeGoosseZ Apr 06 '14 at 15:32