破坏景观模式的活动

时间:2018-02-26 17:06:55

标签: android android-activity destruction

嗨我已经意识到刽子手在Android上的游戏并且它在肖像模式下工作得很好但是当我切换到横向模式时它正在破坏活动而我正在丢失我写的正确字母,而且我写的全部字母(正确和错误)和imageview也是。 我想知道是否有人可以告诉我是否需要将字母存储在外部文本文件中或者是否有其他方式? 有人可以告诉我如何处理imageview吗?

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private LinearLayout container;
private Button btn_send;
private TextView lettres_tapees;
private ImageView image;
private EditText et_letter;
private String word;
private int found;
private int error ;
private List<Character> listOfLetters= new ArrayList<>();
private boolean win;
private List<String> wordlist= new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        container= (LinearLayout) findViewById(R.id.word_container);
        btn_send= (Button)findViewById(R.id.btn_send);
        et_letter= (EditText) findViewById(R.id.et_letter);
        image= (ImageView) findViewById(R.id.iv_pendu);
        lettres_tapees=(TextView)findViewById(R.id.tv_lettres_tapees);
        initGame();
        btn_send.setOnClickListener(this);
    }
    public void initGame(){
        word=generateword();
        win =false;
        error=0;
        found=0;
        lettres_tapees.setText("");
        image.setBackgroundResource(R.drawable.first);
        listOfLetters= new ArrayList<>();
        container.removeAllViews();
        for(int i=0;i<word.length();i++){
            TextView oneletter = (TextView) getLayoutInflater().inflate(R.layout.textview,null);
            container.addView(oneletter);
        }
    }

    @Override
    public void onClick(View view) {
        String letterfrominput= et_letter.getText().toString().toUpperCase();
        et_letter.setText("");
        if(letterfrominput.length()>0){
            if(!letterAlreadyused(letterfrominput.charAt(0),listOfLetters)){
                listOfLetters.add(letterfrominput.charAt(0));
                checkifletterisinword(letterfrominput,word);
            }
            //la partie est gagnée
            if(found==word.length()){
                win=true;
                createDialog(win);
            }
            if(!word.contains(letterfrominput)){
                error++;
            }
            setImage(error);
            if(error==6){
                win=false;
                createDialog(win);
            }
            showAllLetters(listOfLetters);
        }
    }
    public boolean letterAlreadyused(char a , List<Character> listOfletters){
        for (int i =0; i<listOfletters.size();i++){
            if(listOfletters.get(i)==a){
                Toast.makeText(getApplicationContext(),"Vous avez deja affiche cette lettre",Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return false;

    }
    void checkifletterisinword(String letter,String Word){
        for (int i=0; i<word.length();i++){
            if(letter.equals(String.valueOf(word.charAt(i)))){
                TextView tv = (TextView) container.getChildAt(i);
                tv.setText(String.valueOf(word.charAt(i)));
                found++;
            }
        }
    }
    public void showAllLetters(List<Character> listOfletters){
        String chaine= "";
        for(int i=0;i<listOfletters.size();i++){
            chaine += listOfletters.get(i)+"\n";
        }
        if(!chaine.equals("")){
            lettres_tapees.setText(chaine);
        }
    }
    public void setImage(int error){
        switch (error){
            case 1:
            image.setBackgroundResource(R.drawable.second);
            break;
            case 2:
            image.setBackgroundResource(R.drawable.third);
            break;
            case 3:
            image.setBackgroundResource(R.drawable.fourth);
            break;
            case 4:
            image.setBackgroundResource(R.drawable.fifth);
            break;
            case 5:
            image.setBackgroundResource(R.drawable.sixth);
            break;
            case 6:
            image.setBackgroundResource(R.drawable.seventh);
            break;
        }
    }
    public void createDialog(boolean win){
        AlertDialog.Builder builder= new AlertDialog.Builder(this);
        builder.setTitle(" Vous avez gagné");
        if(!win){
            builder.setTitle(" Vous avez perdu");
            builder.setMessage(" Le mot a trouver etait : "+ word );
        }
        builder.setPositiveButton(getResources().getString(R.string.rejouer), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                initGame();
            }
        });
        builder.create().show();
    }
    public List<String> getListOfWords(){
        try {
            BufferedReader buffer= new BufferedReader(new InputStreamReader(getAssets().open("pendu_liste.txt")));
            String line;
            while((line= buffer.readLine())!= null){
                wordlist.add(line);
            }
            buffer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wordlist;
    }
    public String generateword(){
        wordlist= getListOfWords();
        int random = (int) (Math.floor(Math.random()*wordlist.size()));
        String word = wordlist.get(random).trim();
        return word;
    }
}

有代码,用法语写的(顺便说一句,对不起英语不好)。 有人可以帮帮我吗? 我已经尝试过保存和恢复状态的技巧,但不是这样,它不起作用,我实现了这样的代码:

private static final String SELECTED_ITEM_POSITION = "ItemPosition";
private int mPosition;
private int found;
private int error ;
private List<Character> listOfLetters= new ArrayList<>();
private boolean win;
private List<String> wordlist= new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        container= (LinearLayout) findViewById(R.id.word_container);
        btn_send= (Button)findViewById(R.id.btn_send);
        et_letter= (EditText) findViewById(R.id.et_letter);
        image= (ImageView) findViewById(R.id.iv_pendu);
        lettres_tapees=(TextView)findViewById(R.id.tv_lettres_tapees);
        savedInstanceState.putInt(SELECTED_ITEM_POSITION, mPosition);
        initGame();
        btn_send.setOnClickListener(this);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mPosition=savedInstanceState.getInt(SELECTED_ITEM_POSITION);
    }

实际上我有这些错误:

2-26 20:57:20.758 29939-29939/? E/AndroidRuntime: FATAL EXCEPTION: main
                                           Process: com.example.aboukora.pendu, PID: 29939
                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aboukora.pendu/com.example.aboukora.pendu.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.putInt(java.lang.String, int)' on a null object reference
                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                               at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                               at android.os.Looper.loop(Looper.java:154)
                                               at android.app.ActivityThread.main(ActivityThread.java:6186)
                                               at java.lang.reflect.Method.invoke(Native Method)
                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                            Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Bundle.putInt(java.lang.String, int)' on a null object reference
                                               at com.example.aboukora.pendu.MainActivity.onCreate(MainActivity.java:39)
                                               at android.app.Activity.performCreate(Activity.java:6684)
                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751) 
                                               at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496) 
                                               at android.os.Handler.dispatchMessage(Handler.java:102) 
                                               at android.os.Looper.loop(Looper.java:154) 
                                               at android.app.ActivityThread.main(ActivityThread.java:6186) 
                                               at java.lang.reflect.Method.invoke(Native Method) 
                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889) 
                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

1 个答案:

答案 0 :(得分:0)

You need to handle orientation changes in your app using onSaveInstanceState and onRestoreInstanceState; In this example below, I'm saving a ArrayList and populating it back when restoring my activity; You can check this medium post for more information about how to handle orientation changes;

private ArrayList<Character> usedLetters;

private static final String KEY_LETTERS = "key_letters";

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    String usedLettersStringRepresentation = getStringRepresentation(usedLetters);
    outState.putString(KEY_LETTERS, usedLettersStringRepresentation);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    String usedLettersStringRepresentation = savedInstanceState.getString(KEY_LETTERS);
    if (usedLettersStringRepresentation == null) return;
    for (int i = 0; i < usedLettersStringRepresentation.length(); i++) {
        Character character = usedLettersStringRepresentation.charAt(i);
        usedLetters.add(character);


        elements.add(0, new Simple("Letter", character.toString()));
    }

    adapter.updateElements(elements);
}

private String getStringRepresentation(ArrayList<Character> list) {
    StringBuilder builder = new StringBuilder(list.size());
    for (Character ch : list) {
        builder.append(ch);
    }
    return builder.toString();
}