-4

Code:

        package com.example.theball;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
@SuppressLint("NewApi") public class MainActivity extends Activity implements SensorEventListener {
        private SensorManager sensorManager;
        private Sensor accelerometer;
        @SuppressWarnings("unused")
        private long lastUpdate;
        AnimatedView animatedView = null;
        ShapeDrawable mDrawable = new ShapeDrawable();
        public static int x;
        public static int y;
        public static final int width = 50;
        public static final int height = 50;
        public boolean firstDraw = true;
        private int screen_width; 
        private int screen_height; 
        private int sensorX;
        private Timer t;
        private int TimeCounter = 0;
        private int sensorY;
        private int score = 0;
        @Override        
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
            accelerometer = sensorManager
                    .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            lastUpdate = System.currentTimeMillis();
            animatedView = new AnimatedView(this);
            setContentView(animatedView);
            t=new Timer();
            t.scheduleAtFixedRate(new TimerTask() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {                 
                            TimeCounter++;      
                        }
                       });
                    }
            }, 0, 1000); 
        }
            public static class MainActivity extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
          View v = inflater.inflate(R.layout.activity_main, container, false);
          TextView highscore_int = (TextView)v.findViewById(R.id.highscore_int );
           SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", 
            Context.MODE_PRIVATE);
           score = prefs.getInt("key", 0);
          highscore_int.setText("Highscore:" + score +" seconds."); 
          return v;
    }
        @Override
        protected void onResume() {

            super.onResume();
            sensorManager.registerListener(this, accelerometer,
                    SensorManager.SENSOR_DELAY_GAME);
        }
        @Override
        protected void onPause() {
            super.onPause();
            sensorManager.unregisterListener(this);
        }
        @Override
        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub
        }
        @Override
        public void onSensorChanged(SensorEvent event) {
            // TODO Auto-generated method stub
            if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                sensorY = (int) event.values[1];
                sensorX = (int) event.values[0];
                x -= sensorX*3;
                y += sensorY*3;
                if(x <= 0 || x >= screen_width || y <= 0 || y >= screen_height) { 
                    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
                     int oldScore = prefs.getInt("key", 0);  
                     if( TimeCounter > oldScore ){
                        Editor edit = prefs.edit();
                        edit.putInt("key", TimeCounter);
                        edit.commit(); }
                    Intent myIntent = new Intent(this, YouLost.class);
                    startActivity(myIntent);
            }
        }
        }
        public class AnimatedView extends ImageView { 

            Display display = getWindowManager().getDefaultDisplay(); 
            Point size = new Point(); 
            static final int width = 50; 
            static final int height = 50; 
            @SuppressLint("NewApi") 
            public AnimatedView(Context context) { 
            super(context); 
            // TODO Auto-generated constructor stub 
            display.getSize(size); 
            screen_width = size.x; 
            screen_height = size.y; 
            mDrawable = new ShapeDrawable(new OvalShape()); 
            mDrawable.getPaint().setColor(0xffffAC23); 
            mDrawable.setBounds(0, 0, screen_width, screen_height); 
            }
            @Override 
            protected void onDraw(Canvas canvas) { 
            mDrawable.setBounds(x, y, x + width, y + height); 
            if(firstDraw) { 
            x = screen_width / 2; 
            y = screen_height / 2; 
            firstDraw = false; 
            } 
            mDrawable.draw(canvas); 
            invalidate(); 
            } 
            }
}

My new problem is , at the Eclipse Graphical Layout I can see the text but at my device I can't.

I don't know why does it happen,anyway, my text set to black and my background is white so it's not the problem.

DavidBalas
  • 333
  • 7
  • 21

3 Answers3

1

textview highscore_int is null because you are referencing highscore_int from fragment_main.xml you will get null because in your activity you are using activity's layout

So use highscore_int in onCreateView of your fragment inflate the view

View v = inflater.inflate(R.layout.fragment_main, container, false);

then use the view to find the textview

TextView highscore_int = (TextView)v.findViewById(R.id.highscore_int );

i.e.

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
          View v = inflater.inflate(R.layout.fragment_main, container, false);
          TextView highscore_int = (TextView)v.findViewById(R.id.highscore_int );
           SharedPreferences prefs = getActivity().getSharedPreferences("myPrefsKey", 
            Context.MODE_PRIVATE);
           score = prefs.getInt("key", 0);
          highscore_int.setText("Highscore:" + score +" seconds."); 
          return v;
    }
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
0

My guess is based on the word fragment_main.xml. I guess the code you pasted is from your activity and the layout is based in your fragment. That means you can only call findViewById() within your fragment class.

Override the fragment method onCreateView() and get the highscore TextView there. Move the code there as well:

//onCreateView() of your fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, null);
    highscore_int = (TextView) view.findViewById(R.id.highscore_int);

    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    score = prefs.getInt("key", 0);
    highscore_int.setText("Highscore:" + score +" seconds.");

    // You lost
    SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    int oldScore = prefs.getInt("key", 0);  
    if( TimeCounter > oldScore ) {
        Editor edit = prefs.edit();
        edit.putInt("key", TimeCounter);
        edit.commit();
    }
}
WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
  • "mView cannot be resolved to a variable" , plus, it's asking me to remove the override. – DavidBalas Jul 07 '14 at 12:22
  • Sorry, mView was from the code I copied. I will edit the code. For the Override: you might want to check that you have it in your Fragment class and that your Java Level is 6, otherwise you get that message (which is based on Java 4 afaik). – WarrenFaith Jul 07 '14 at 12:26
0

because prefs.getInt("key", 0); is returning null and is being stored in score

Use this

score = 0;
if(prefs.getInt("key", 0) != null){
   score = prefs.getInt("key", 0);
}
  • Sorry but it's not working, the line ' if(prefs.getInt("key", 0) != null){ ' gets an error but no suggestions available – DavidBalas Jul 07 '14 at 12:18