设置AsyncTask来调用其他方法

huangapple 未分类评论44阅读模式
英文:

Setting up AsyncTask to call other methods

问题

以下是已翻译的代码部分:

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.HashMap;
import java.util.Map;

public class PlayGameActivity extends AppCompatActivity implements View.OnClickListener {

    private Button[][] buttons = new Button[3][3];
    private boolean player1Turn = true;
    private int roundCount;
    private int player1Points;
    private int player2Points;
    private TextView textViewPlayer1;
    private TextView textViewPlayer2;
    public String subFolder = "/userdata";
    public String file = "test.ser";
    Map<String, Integer> userList = new HashMap<>();
    String inputName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_game);
        SharedPreferences result = getSharedPreferences("PREFS", MODE_PRIVATE);
        inputName = result.getString("username", "");

        textViewPlayer1 = findViewById(R.id.text_view_p1);
        textViewPlayer2 = findViewById(R.id.text_view_p2);
        textViewPlayer1.setText(inputName + ":");
        textViewPlayer2.setText("Android:");

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                String buttonID = "button_" + i + j;
                int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
                buttons[i][j] = findViewById(resID);
                buttons[i][j].setOnClickListener(this);
            }
        }
        Button buttonReset = findViewById(R.id.button_reset);
        buttonReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetGame();
            }
        });
    }

    // ... (其他未翻译的代码)

    private void player1Wins() {
        player1Points++;
        readSettings(inputName);
        writeSettings(null);
        Toast.makeText(this, inputName + " wins!", Toast.LENGTH_SHORT).show();
        updatePointsText();
        resetBoard();
    }

    private void player2Wins() {
        player2Points++;
        readSettings("android");
        writeSettings(null);
        Toast.makeText(this, "Android wins!", Toast.LENGTH_SHORT).show();
        updatePointsText();
        resetBoard();
    }

    private void draw() {
        Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
        resetBoard();
    }

    private void updatePointsText() {
        textViewPlayer1.setText(inputName + ": " + player1Points);
        textViewPlayer2.setText("Android: " + player2Points);
    }

    private void resetBoard() {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                buttons[i][j].setText("");
            }
        }
        roundCount = 0;
        player1Turn = true;
    }

    /*
    * Close the activity
    * */
    private void resetGame() {
        finish();
    }

    // ... (其他未翻译的代码)
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.tictactoe.PlayGameActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/text_view_p1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:freezesText="true"
            android:text="Player 1: 0"
            android:textSize="30sp" />

        <TextView
            android:id="@+id/text_view_p2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/text_view_p1"
            android:freezesText="true"
            android:text="Player 2: 0"
            android:textSize="30sp" />

        <Button
            android:id="@+id/button_reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:layout_marginEnd="33dp"
            android:text="reset" />

    </RelativeLayout>

    <!-- 其他布局未翻译 -->

</LinearLayout>

请注意,以上是已翻译的代码部分,还有一些未翻译的部分未包含在内。如果您需要完整的翻译,请将整个代码粘贴到翻译工具中。

英文:

I have an app that runs a basic TicTacToe game, stores leaderboard data and saves it to a file. This functionality is all split up across various java files. The TicTacToe game is stored in its own java file/activity. It takes in the username that is set from another activity.

I have to make the game run using AsyncTask. I've implemented the methods and tried passing them void and then calling the game methods from inside the onPreExecute doInBackground and onPostExecute but I cant get it to work properly. I also get errors when passing void as an argument for AsyncTask class.

How can I call the methods inside the AsyncTask to make the game playable?

Included is the full source code for the game, it is fully functional.

PlayGameActivity

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.HashMap;
import java.util.Map;

public class PlayGameActivity extends AppCompatActivity implements View.OnClickListener {

    private Button[][] buttons = new Button[3][3];

    private boolean player1Turn = true;

    private int roundCount;

    private int player1Points;
    private int player2Points;

    private TextView textViewPlayer1;
    private TextView textViewPlayer2;


    //MainMenuActivity MMA = new MainMenuActivity();

    public String subFolder = &quot;/userdata&quot;;
    public String file = &quot;test.ser&quot;;
    Map&lt;String, Integer&gt; userList = new HashMap&lt;&gt;();

    String inputName;

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

        SharedPreferences result = getSharedPreferences(&quot;PREFS&quot;, MODE_PRIVATE);
        inputName = result.getString(&quot;username&quot;, &quot;&quot;);


        textViewPlayer1 = findViewById(R.id.text_view_p1);
        textViewPlayer2 = findViewById(R.id.text_view_p2);

        textViewPlayer1.setText(inputName +&quot;:&quot;);
        textViewPlayer2.setText(&quot;Android:&quot;);

        for (int i = 0; i &lt; 3; i++) {
            for (int j = 0; j &lt; 3; j++) {
                String buttonID = &quot;button_&quot; + i + j;
                int resID = getResources().getIdentifier(buttonID, &quot;id&quot;, getPackageName());
                buttons[i][j] = findViewById(resID);
                buttons[i][j].setOnClickListener(this);
            }
        }

        Button buttonReset = findViewById(R.id.button_reset);
        buttonReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetGame();
            }
        });
    }

    public void startAsyncTask(View v) {

    }
//The void arguments are causing issues
    private class ExampleAsyncTask extends AsyncTask&lt;void, void, void&gt; {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void doInBackground(void... voids) {

        }

        @Override
        protected void onPostExecute(void aVoid) {
            super.onPostExecute(aVoid);
        }

        @Override
        protected void onProgressUpdate(void... values) {
            super.onProgressUpdate(values);
        }
    }

    @Override
    public void onClick(View v) {
        if (!((Button) v).getText().toString().equals(&quot;&quot;)) {
            return;
        }

        if (player1Turn) {
            ((Button) v).setText(&quot;X&quot;);
        } else {
            ((Button) v).setText(&quot;O&quot;);
        }

        roundCount++;

        if (checkForWin()) {
            if (player1Turn) {
                player1Wins();
            } else {
                player2Wins();
            }
        } else if (roundCount == 9) {
            draw();
        } else {
            player1Turn = !player1Turn;
        }

    }

    private boolean checkForWin() {
        String[][] field = new String[3][3];

        for (int i = 0; i &lt; 3; i++) {
            for (int j = 0; j &lt; 3; j++) {
                field[i][j] = buttons[i][j].getText().toString();
            }
        }

        for (int i = 0; i &lt; 3; i++) {
            if (field[i][0].equals(field[i][1])
                    &amp;&amp; field[i][0].equals(field[i][2])
                    &amp;&amp; !field[i][0].equals(&quot;&quot;)) {
                return true;
            }
        }

        for (int i = 0; i &lt; 3; i++) {
            if (field[0][i].equals(field[1][i])
                    &amp;&amp; field[0][i].equals(field[2][i])
                    &amp;&amp; !field[0][i].equals(&quot;&quot;)) {
                return true;
            }
        }

        if (field[0][0].equals(field[1][1])
                &amp;&amp; field[0][0].equals(field[2][2])
                &amp;&amp; !field[0][0].equals(&quot;&quot;)) {
            return true;
        }

        if (field[0][2].equals(field[1][1])
                &amp;&amp; field[0][2].equals(field[2][0])
                &amp;&amp; !field[0][2].equals(&quot;&quot;)) {
            return true;
        }

        return false;
    }

    public void writeSettings(View v) {
        File cacheDir = null;
        File appDirectory = null;

        if (android.os.Environment.getExternalStorageState().
                equals(android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = getApplicationContext().getExternalCacheDir();
            appDirectory = new File(cacheDir + subFolder);

        } else {
            cacheDir = getApplicationContext().getCacheDir();
            String BaseFolder = cacheDir.getAbsolutePath();
            appDirectory = new File(BaseFolder + subFolder);

        }

        if (appDirectory != null &amp;&amp; !appDirectory.exists()) {
            appDirectory.mkdirs();
        }

        File fileName = new File(appDirectory, file);

        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        try {
            fos = new FileOutputStream(fileName);
            out = new ObjectOutputStream(fos);
            out.writeObject(userList);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.flush();
                fos.close();
                if (out != null)
                    out.flush();
                out.close();
            } catch (Exception e) {

            }
        }

    }


    public void readSettings(String userName) {
        File cacheDir = null;
        File appDirectory = null;
        if (android.os.Environment.getExternalStorageState().
                equals(android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = getApplicationContext().getExternalCacheDir();
            appDirectory = new File(cacheDir + subFolder);
        } else {
            cacheDir = getApplicationContext().getCacheDir();
            String BaseFolder = cacheDir.getAbsolutePath();
            appDirectory = new File(BaseFolder + subFolder);
        }

        if (appDirectory != null &amp;&amp; !appDirectory.exists()) return; // File does not exist

        File fileName = new File(appDirectory, file);

        FileInputStream fis = null;
        ObjectInputStream in = null;
        try {
            fis = new FileInputStream(fileName);
            in = new ObjectInputStream(fis);
            Map&lt;String, Integer&gt; myHashMap = (Map&lt;String, Integer&gt;) in.readObject();
            userList = myHashMap;

            if (userList.containsKey(userName.toLowerCase())) {
                int count = userList.containsKey(userName) ? userList.get(userName) : 0;
                userList.put(userName, count + 1);
            } else {
                userList.put(userName.toLowerCase(), 1);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (fis != null) {
                    fis.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void player1Wins() {
        player1Points++;
        readSettings(inputName);
        writeSettings(null);
        Toast.makeText(this, inputName + &quot; wins!&quot;, Toast.LENGTH_SHORT).show();
        updatePointsText();
        resetBoard();
    }

    private void player2Wins() {
        player2Points++;
        readSettings(&quot;android&quot;);
        writeSettings(null);
        Toast.makeText(this, &quot;Android wins!&quot;, Toast.LENGTH_SHORT).show();
        updatePointsText();
        resetBoard();
    }

    private void draw() {
        Toast.makeText(this, &quot;Draw!&quot;, Toast.LENGTH_SHORT).show();
        resetBoard();
    }

    private void updatePointsText() {
        textViewPlayer1.setText(inputName + &quot;: &quot; + player1Points);
        textViewPlayer2.setText(&quot;Android: &quot; + player2Points);
    }

    private void resetBoard() {
        for (int i = 0; i &lt; 3; i++) {
            for (int j = 0; j &lt; 3; j++) {
                buttons[i][j].setText(&quot;&quot;);
            }
        }

        roundCount = 0;
        player1Turn = true;
    }

    /*
    * Close the activity
    * */
    private void resetGame() {
//        player1Points = 0;
//        player2Points = 0;
//        updatePointsText();
//        resetBoard();
        finish();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putInt(&quot;roundCount&quot;, roundCount);
        outState.putInt(&quot;player1Points&quot;, player1Points);
        outState.putInt(&quot;player2Points&quot;, player2Points);
        outState.putBoolean(&quot;player1Turn&quot;, player1Turn);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        roundCount = savedInstanceState.getInt(&quot;roundCount&quot;);
        player1Points = savedInstanceState.getInt(&quot;player1Points&quot;);
        player2Points = savedInstanceState.getInt(&quot;player2Points&quot;);
        player1Turn = savedInstanceState.getBoolean(&quot;player1Turn&quot;);
    }
    
}

activity_play_game.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:orientation=&quot;vertical&quot;
    tools:context=&quot;com.example.tictactoe.PlayGameActivity&quot;&gt;

    &lt;RelativeLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;&gt;

        &lt;TextView
            android:id=&quot;@+id/text_view_p1&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:freezesText=&quot;true&quot;
            android:text=&quot;Player 1: 0&quot;
            android:textSize=&quot;30sp&quot; /&gt;

        &lt;TextView
            android:id=&quot;@+id/text_view_p2&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_below=&quot;@+id/text_view_p1&quot;
            android:freezesText=&quot;true&quot;
            android:text=&quot;Player 2: 0&quot;
            android:textSize=&quot;30sp&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/button_reset&quot;
            android:layout_width=&quot;wrap_content&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:layout_alignParentEnd=&quot;true&quot;
            android:layout_centerVertical=&quot;true&quot;
            android:layout_marginEnd=&quot;33dp&quot;
            android:text=&quot;reset&quot; /&gt;

    &lt;/RelativeLayout&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;0dp&quot;
        android:layout_weight=&quot;1&quot;&gt;

        &lt;Button
            android:id=&quot;@+id/button_00&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/button_01&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/button_02&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

    &lt;/LinearLayout&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;0dp&quot;
        android:layout_weight=&quot;1&quot;&gt;

        &lt;Button
            android:id=&quot;@+id/button_10&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/button_11&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/button_12&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

    &lt;/LinearLayout&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;0dp&quot;
        android:layout_weight=&quot;1&quot;&gt;

        &lt;Button
            android:id=&quot;@+id/button_20&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/button_21&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

        &lt;Button
            android:id=&quot;@+id/button_22&quot;
            android:layout_width=&quot;0dp&quot;
            android:layout_height=&quot;match_parent&quot;
            android:layout_weight=&quot;1&quot;
            android:freezesText=&quot;true&quot;
            android:textSize=&quot;60sp&quot; /&gt;

    &lt;/LinearLayout&gt;

&lt;/LinearLayout&gt;

答案1

得分: 0

AsyncTask 不接受 void 作为参数,而是使用 Void

AsyncTask&lt;Void, Void, Void&gt;
英文:

AsyncTask did not accept void as an argument, it is Void :

AsyncTask&lt;Void, Void, Void&gt;

huangapple
  • 本文由 发表于 2020年4月5日 01:38:38
  • 转载请务必保留本文链接:https://java.coder-hub.com/61032158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定