繁体   English   中英

为什么每次重新打开主活动时我的变量都会重置为零

[英]Why are my variables being reset to zero every time I reopen my Main activity

我目前正在为一个大学项目创建一个应用程序。 在应用程序中,我使用了两个 php 脚本 - 一个用于将应用程序中的变量数据设置为 MySQL 数据库,另一个用于从数据库中检索数据并设置应用程序中的变量。 将数据发送到 mySQL 的第一个脚本工作正常,没有任何问题,但是从 mySQL 检索数据以在应用程序内设置变量的脚本仅在通过我的网络服务器运行时才有效。 在我的应用程序中运行时(在 Activity Start 和 create 上),变量都设置为零。 任何帮助都会很棒,我被困了好几个星期了!

<?php

require "conn.php";

$username = "test";

$stmt = $conn->prepare("SELECT gold, goldMulti, xp, xpMulti, xpMax, xpMaxMulti, dmg, dmgMulti, bossCount, bossHp, bossHpMulti, level, backgroundCount FROM users WHERE username = '$username'");

$stmt ->execute();
$stmt ->bind_result($gold, $goldMulti, $xp, $xpMulti, $xpMax, $xpMaxMulti, $dmg, $dmgMulti, $bossCount, $bossHp, $bossHpMulti, $level, $backgroundCount);

$varaibles = array();

$stmt ->fetch();

$temp = array();

$temp['gold'] = $gold;
$temp['goldMulti'] = $goldMulti;
$temp['xp'] = $xp;
$temp['xpMulti'] = $xpMulti;
$temp['xpMax'] = $xpMax;
$temp['xpMaxMulti'] = $xpMaxMulti;
$temp['dmg'] = $dmg;
$temp['dmgMulti'] = $dmgMulti;
$temp['bossCount'] = $bossCount;
$temp['bossHp'] = $bossHp;
$temp['bossHpMulti'] = $bossHpMulti;
$temp['level'] = $level;
$temp['backgroundCount'] = $backgroundCount;


array_push($variables,$temp);

echo json_encode($temp);

?>
public class MainActivity extends AppCompatActivity {
    // int variables for logic and functions ------------------------------------------------------
    public int gold;
    public int goldAwarded;
    public int goldMultiplier;
    public int xp;
    public int xpAwarded;
    public int xpMultiplier;
    public int dmg;
    public int dmgMultiplier;
    public int bossCount;
    public int bossHP;
    public int bossHPMultiplier;
    public int bossHPBase;
    public int level;
    public int xpMax;
    public int bossCountFunc;
    public int backgroundCount;
    public int xpMaxMulti;
    public int baseDmg;


// Widget variables -----------------------------------------------------------------------------
    private TextView bossNumberText;
    private TextView levelText;
    private TextView goldText;
    private TextView bossHealthText;
    private ImageButton tapButton;
    private ImageView bossImage;
    private ImageView playerImage;
    private ImageView bossImage2;
    private ImageView bossImage3;
    private ImageButton shopButton;
    public String LoggedInUser = LogIn.getUser();

// Audio players --------------------------------------------------------------------------------
    MediaPlayer mps;
    MediaPlayer mpb;
    MediaPlayer mpc;
    MediaPlayer mpl;
    MediaPlayer mpp;



// Websever php file URL to retrieve Data from user ----------------------------------------------

    private static final String URL = "http://jg1104.brighton.domains/AppPhp/variablesretrieval.php";

    private void getData(){

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try{

                    JSONArray array = new JSONArray(response);
                    for(int i = 0; i<array.length(); i++){
                        JSONObject object = array.getJSONObject(i);
                            gold = object.getInt("gold");
                            goldMultiplier = object.getInt("goldMulti");
                            xp = object.getInt("xp");
                            xpMultiplier = object.getInt("xpMulti");
                            xpMax = object.getInt("xpMax");
                            xpMaxMulti = object.getInt("xpMaxMulti");
                            dmg = object.getInt("dmg");
                            dmgMultiplier = object.getInt("dmgMulti");
                            bossCount = object.getInt("bossCount");
                            bossHP = object.getInt("bossHp");
                            bossHPMultiplier = object.getInt("bossHpMulti");
                            level = object.getInt("level");
                            backgroundCount = object.getInt("backgroundCount");

                    }

                }catch (Exception e) {

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this,error.toString(), Toast.LENGTH_SHORT).show();
            }

            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> param = new HashMap<>();
                param.put("LoggedInUser", LoggedInUser);


                return param;
            }
        }
        );

        Volley.newRequestQueue(MainActivity.this).add(stringRequest);
    }




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

        bossNumberText = (TextView) findViewById(R.id.bossNumberText);
        levelText = (TextView) findViewById(R.id.levelText);
        goldText = (TextView) findViewById(R.id.goldText);
        bossHealthText = (TextView) findViewById(R.id.bossHealthText);
        tapButton = (ImageButton) findViewById(R.id.TapButton);
        bossImage = (ImageView) findViewById(R.id.bossImage);
        playerImage = (ImageView) findViewById(R.id.playerImage);
        bossImage2 = (ImageView) findViewById(R.id.bossImage2);
        bossImage3 = (ImageView) findViewById(R.id.bossImage3);
        shopButton = (ImageButton) findViewById(R.id.shopButton);

        mpb = MediaPlayer.create(this, R.raw.backgroundmusic);
        mpc = MediaPlayer.create(this, R.raw.coin);
        mpl = MediaPlayer.create(this, R.raw.levelup);
        mpp = MediaPlayer.create(this, R.raw.pain);
        mps = MediaPlayer.create(this, R.raw.shootingsound);

        // retrieving data from database and setting TextViews -----------------------------------
        getData();

        // Set looping and start of background music ---------------------------------------------
        mpb.setLooping(true);
        mpb.start();
        // Initialising variable values on create ------------------------------------------------
        goldAwarded = 100;
        xpAwarded = 100;
        baseDmg = 1;
        bossHPBase = 10;
        bossCountFunc = 1;


        shopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchShop();
            }
        });

    }
    @Override
            protected void onStart() {
        // onclickListener for main button --------------------------------------------------------
        super.onStart();
        getData();
        levelText.setText("Level: " + Integer.toString(level));
        goldText.setText("Gold: " + Integer.toString(gold));
        bossHealthText.setText("HP: " + Integer.toString(bossHP));
        bossNumberText.setText("Boss: " + bossCount);

        tapButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // shooting sound
                mps.start();
                // run method that looks to see if background needs to be changed
                newBackground();
                // handlers for enemy animations
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        bossImage.setImageDrawable(getResources().getDrawable(R.drawable.onezshot));
                        AnimationDrawable oneshotz = (AnimationDrawable) bossImage.getDrawable();
                        oneshotz.start();


                    }
                }, 0);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        bossImage2.setImageDrawable(getResources().getDrawable(R.drawable.twozshot));
                        AnimationDrawable twozshot = (AnimationDrawable) bossImage2.getDrawable();
                        twozshot.start();


                    }
                }, 0);
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        bossImage3.setImageDrawable(getResources().getDrawable(R.drawable.threezshot));
                        AnimationDrawable threezshot = (AnimationDrawable) bossImage3.getDrawable();
                        threezshot.start();


                    }
                }, 0);
                // handler for shooting animation
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        playerImage.setImageDrawable(getResources().getDrawable(R.drawable.shooting));
                        AnimationDrawable shooting = (AnimationDrawable) playerImage.getDrawable();
                        shooting.start();

                    }
                }, 0);

                bossHP -= dmg;
                bossHealthText.setText("HP: " + Integer.toString(bossHP));
                // if boss dies
                if (bossHP <= 1) {
                    mpp.start();
                    bossCount++;
                    bossCountFunc++;
                    backgroundCount++;
                    if (backgroundCount > 9) {
                        backgroundCount = 1;
                    }
                    if (bossCountFunc > 3) {
                        bossCountFunc = 1;
                    }
                    bossNumberText.setText("Boss: " + bossCount);
                    goldMultiplier++;
                    xpMultiplier++;
                    mpc.start();
                    gold += (goldAwarded * goldMultiplier);
                    goldText.setText("Gold: " + Integer.toString(gold));
                    xp += (xpAwarded * xpMultiplier);
                    bossHPMultiplier++;
                    // look for level up
                    if (xp >= xpMax) {
                        mpl.start();
                        level++;
                        dmgMultiplier++;
                        bossHPMultiplier *= 2;
                        dmg = (baseDmg * dmgMultiplier);
                        levelText.setText("lvl: " + Integer.toString(level));
                        xp = 0;
                        xpMax = xpMax * xpMaxMulti;
                    }
                    newBoss();
                }
            }
        });


    }
    // Method to show or hide boss frames
    public void newBoss(){
        bossHP = bossHPBase * bossHPMultiplier;

        if(bossCountFunc==1){
            bossImage.setVisibility(View.VISIBLE);
            bossImage2.setVisibility(View.INVISIBLE);
            bossImage3.setVisibility(View.INVISIBLE);

        }


        if(bossCountFunc==2){
            bossImage.setVisibility(View.INVISIBLE);
            bossImage2.setVisibility(View.VISIBLE);


        }
        if(bossCountFunc==3){
            bossImage2.setVisibility(View.INVISIBLE);
            bossImage3.setVisibility(View.VISIBLE);

        }
    }
    // method to check and change background
    public void newBackground(){
        ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.constraintLayout);

        if(backgroundCount<=3){
            layout.setBackgroundResource(R.drawable.main);
        }
        if(backgroundCount>3 && backgroundCount<=6){
            layout.setBackgroundResource(R.drawable.maintwo);
        }
        if(backgroundCount>6 && backgroundCount<=9){
            layout.setBackgroundResource(R.drawable.mainthree);

        }

    }


    public void launchShop(){

        Intent intent = new Intent(this, Shop.class);
        startActivity(intent);

    }

    private void setData(final String LoggedInUser, final int gold,final int goldMultiplier,final int xp,final int xpMultiplier
            ,final int xpMax,final int xpMaxMulti,final int dmg
            ,final int dmgMultiplier,final int bossCount,final int bossHP
            ,final int bossHPMultiplier,final int level,final int backgroundCount){
        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.setTitle("Setting Data");
        progressDialog.show();
        String uRl = "http://jg1104.brighton.domains/AppPhp/setdata.php";
        StringRequest request = new StringRequest(Request.Method.POST, uRl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.equals("Data set")){
                    progressDialog.dismiss();
                    Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();

                }
                else{
                    progressDialog.dismiss();
                    Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
            }
        }){

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> param = new HashMap<>();
                param.put("LoggedInUser", LoggedInUser);
                param.put("gold", Integer.toString(gold));
                param.put("goldMulti", Integer.toString(goldMultiplier));
                param.put("xp", Integer.toString(xp));
                param.put("xpMulti", Integer.toString(xpMultiplier));
                param.put("xpMax", Integer.toString(xpMax));
                param.put("xpMaxMulti", Integer.toString(xpMaxMulti));
                param.put("dmg", Integer.toString(dmg));
                param.put("dmgMulti", Integer.toString(dmgMultiplier));
                param.put("bossCount", Integer.toString(bossCount));
                param.put("bossHp", Integer.toString(bossHP));
                param.put("bossHpMulti", Integer.toString(bossHPMultiplier));
                param.put("level", Integer.toString(level));
                param.put("backgroundCount", Integer.toString(backgroundCount));
                return param;
            }
        };

        request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        MySingleton.getmInstance(MainActivity.this).addToRequestQueue(request);
    }
    @Override
    protected void onStop() {
        super.onStop();
        setData(LoggedInUser,gold,goldMultiplier,xp,xpMultiplier,xpMax,xpMaxMulti,dmg,dmgMultiplier,bossCount,bossHP,bossHPMultiplier,level,backgroundCount);
    }

}

由于该脚本在我的网络服务器中使用时可以正常工作,因此我确定这与我的 java 编码有关。

这段代码是你的问题:

try{
    JSONArray array = new JSONArray(response);
    for(int i = 0; i<array.length(); i++){
        JSONObject object = array.getJSONObject(i);
        gold = object.getInt("gold");
        goldMultiplier = object.getInt("goldMulti");
        xp = object.getInt("xp");
        xpMultiplier = object.getInt("xpMulti");
        xpMax = object.getInt("xpMax");
        xpMaxMulti = object.getInt("xpMaxMulti");
        dmg = object.getInt("dmg");
        dmgMultiplier = object.getInt("dmgMulti");
        bossCount = object.getInt("bossCount");
        bossHP = object.getInt("bossHp");
        bossHPMultiplier = object.getInt("bossHpMulti");
        level = object.getInt("level");
        backgroundCount = object.getInt("backgroundCount");
    }
} catch (Exception e) {

}

您不应将 catch 块留空。 它可能会抛出并吞下一个错误。

做这个:

    } catch (Exception e) {
        Log.e("MyApp", "Error parsing!", e);
    }

(一些关于 Logcat https://developer.android.com/studio/debug/am-logcat的阅读)或者一起摆脱 try catch 让你的应用程序崩溃(快速失败)!!


您的实际错误(或者我无论如何都能看到的第一个错误)是当您的服务器端响应是 JSONObject 时,您正试图解析 JSONarray。 这行代码:

JSONArray array = new JSONArray(response);

而这个回应:

{
   "gold":600, "goldMulti":3,
   "xp":0, "xpMulti":3, "xpMax":0, "xpMaxMulti":0,
   "dmg":3,"dmgMulti":3,
   "bossCount":3,
   "bossHp":80, 
   "bossHpMulti":14,
   "level":3,
   "backgroundCount":3
}

(从这里) http://jg1104.brighton.domains/AppPhp/variablesretrieval.php

您应该将其解析为JsonObject或将服务器端返回的响应包装在 Array []中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM