简体   繁体   中英

destruction of activity on landscape mode

Hi i've realized the game of hangman over android and it works well on portrait mode but when i'm switching to landscape mode it's destructing the activity and i'm losing the correct letters i've written, and also the entire letters i've written (correct and wrong) and the imageview too. I want to know if somebody can tell me if i need to store the letters on an external text file or if there's another way ? Can somebody tell me how to do with imageview too ?

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

There is the code ,written in french (sorry for the bad english by the way). Could someone help me please ? i've tried the trick to save and restore state but that's not it, it doesn't work, i've implementented the code like this:

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

actually i've got those errors:

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)

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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