简体   繁体   中英

How to prevent my activity from launch again?

In my application, I have a list view that shows some level.

I fill the listview with a file in assets. my file in assets is like this:

    <question>
    <image>pic1.png</image>
    <option1>one.png</option1>
    <option2>two.png</option2>
    <option3>three.png</option3>
    <option4>four.png</option4>
    <answer>1</answer>
    <level>1</level>
</question> 

My listview shows the levels and when I click on an item of listview go to another activity, to next activity shows my question and my options as well. every thing is ok, my problem is that when press back button in second activity to go first activity, the first activity launch again and my onCreate method run again, and my listview item increase .(for example if I have 1 question, after clicking press back button show my question become 2 ).

here is my first activity :

public class Home extends Activity {

static SharedPreferences prefs;
Editor editor;
HorizontalListView hListView;
MyArrayAdapter listAdapter;


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

    loadObjects();


    prefs = getSharedPreferences(DataStore.MY_PREFS_NAME, MODE_PRIVATE);
    editor = prefs.edit();
    editor.putInt("l" + 1, Question.KEY_UNLOCK);
    editor.commit();


    hListView = (HorizontalListView) findViewById(R.id.list_view);
    listAdapter = new MyArrayAdapter(this, DataStore.questions);
    hListView.setAdapter(listAdapter);
    hListView.scrollTo(prefs.getInt("level", 0));
    hListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
            int lock = prefs.getInt("l" + DataStore.questions.get(index).level, Question.KEY_LOCK);
            if (lock == Question.KEY_LOCK)
                showLockAction();
            else {
                Intent intent = new Intent(Home.this, MainActivity.class);
                intent.putExtra("selected_level", index);
                startActivity(intent);
            }
        }
    });


}

protected void showLockAction() {
    Toast.makeText(Home.this, "مرحله های قبل و کامل کن", Toast.LENGTH_LONG).show();

}


public void loadObjects() {

    String KEY_QUESTION = "question";
    String KEY_OPTION1 = "option1";
    String KEY_OPTION2 = "option2";
    String KEY_OPTION3 = "option3";
    String KEY_OPTION4 = "option4";
    String KEY_QUESTION_IMAGE = "image";
    String KEY_LOCK = "level";
    String KEY_ANSWER = "answer";

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromAssets(Home.this);
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_QUESTION);
    // looping through all song nodes <song>

    for (int i = 0; i < nl.getLength(); i++) {
        Element e = (Element) nl.item(i);
        Question q = new Question();
        q.image = parser.getValue(e, KEY_QUESTION_IMAGE);
        q.options.add(parser.getValue(e, KEY_OPTION1));
        q.options.add(parser.getValue(e, KEY_OPTION2));
        q.options.add(parser.getValue(e, KEY_OPTION3));
        q.options.add(parser.getValue(e, KEY_OPTION4));
        q.level = Integer.parseInt(parser.getValue(e, KEY_LOCK));
        q.answer = Integer.parseInt(parser.getValue(e, KEY_ANSWER));

        DataStore.questions.add(q);
    }
}

}

my loadObjects method run and run repeatedly.

and here is my second activity:

public class MainActivity extends Activity {

ImageView questionText;
TextView level;
ImageView option1;
ImageView option2;
ImageView option3;
ImageView option4;
ImageView dialog;
Button nextLevel;

LinearLayout mainLayout;
Question curQuestion;
int curQuestionIndex = 0;
int wrongCounter = 1;
SharedPreferences prefs;
Editor editor;
ArrayList<Integer> list;


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


    mainLayout = (LinearLayout) findViewById(R.id.main_lay);
    dialog = (ImageView) findViewById(R.id.dialog);
    level = (TextView) findViewById(R.id.level);
    nextLevel = (Button) findViewById(R.id.next_level);
    nextLevel.setOnClickListener(nextLevelClick);

    questionText = (ImageView) findViewById(R.id.question);
    option1 = (ImageView) findViewById(R.id.option1);
    option2 = (ImageView) findViewById(R.id.option2);
    option3 = (ImageView) findViewById(R.id.option3);
    option4 = (ImageView) findViewById(R.id.option4);

    option1.setOnClickListener(clickListener);
    option2.setOnClickListener(clickListener);
    option3.setOnClickListener(clickListener);
    option4.setOnClickListener(clickListener);


    prefs = getSharedPreferences(DataStore.MY_PREFS_NAME, MODE_PRIVATE);
    editor = prefs.edit();

    curQuestionIndex = getIntent().getIntExtra("selected_level", 0);

    loadNewQuestion();
}


OnClickListener nextLevelClick = new OnClickListener() {

    @Override
    public void onClick(View v) {
        stopCorrectAnswerAction();
        curQuestionIndex++;
        loadNewQuestion();
    }
};

OnClickListener clickListener = new OnClickListener() {

    @Override
    public void onClick(View v) {

        if (curQuestion.isAnswer(v.getId())) {
            correctAnswerAction();

        } else
            wrongAnswerAction();

    }
};


private void loadNewQuestion() {

    Log.e("load", "@------loading------> " + curQuestionIndex);
    if (curQuestionIndex == DataStore.questions.size()) {
        gameFinishedAction();
        curQuestionIndex = 0;
        return;
    }

    curQuestion = DataStore.questions.get(curQuestionIndex);
    editor.putInt("level", curQuestionIndex + 1);
    editor.putInt("l" + curQuestion.level, Question.KEY_UNLOCK);
    editor.commit();

    wrongCounter = 1;


    level.setText("مرحله " + curQuestion.level);
    dialog.setImageResource(R.drawable.cl_q);

    questionText.setImageBitmap(getBitmapFromAsset(curQuestion.image));
    option1.setImageBitmap(getBitmapFromAsset(curQuestion.options.get(0)));
    option2.setImageBitmap(getBitmapFromAsset(curQuestion.options.get(1)));
    option3.setImageBitmap(getBitmapFromAsset(curQuestion.options.get(2)));
    option4.setImageBitmap(getBitmapFromAsset(curQuestion.options.get(3)));

}


private void gameFinishedAction() {
    // TODO Auto-generated method stub

}


protected void wrongAnswerAction() {
    if (wrongCounter % 3 == 1)
        dialog.setImageResource(R.drawable.cl_w1);
    else if (wrongCounter % 3 == 2)
        dialog.setImageResource(R.drawable.cl_w2);
    else if (wrongCounter % 3 == 0)
        dialog.setImageResource(R.drawable.cl_w3);
    wrongCounter++;
}

protected void correctAnswerAction() {
    //mainLayout.setAlpha(0.5f);
    dialog.setImageResource(R.drawable.cl_c);
    nextLevel.setVisibility(View.VISIBLE);

    option1.setOnClickListener(null);
    option2.setOnClickListener(null);
    option3.setOnClickListener(null);
    option4.setOnClickListener(null);


    //Toast.makeText(getApplicationContext(), "درسته",Toast.LENGTH_LONG).show();
}

protected void stopCorrectAnswerAction() {
    //mainLayout.setAlpha(1);
    nextLevel.setVisibility(View.INVISIBLE);

    option1.setOnClickListener(clickListener);
    option2.setOnClickListener(clickListener);
    option3.setOnClickListener(clickListener);
    option4.setOnClickListener(clickListener);
}


private Bitmap getBitmapFromAsset(String strName) {
    AssetManager assetManager = MainActivity.this.getAssets();
    InputStream istr = null;
    try {
        istr = assetManager.open(strName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Bitmap bitmap = BitmapFactory.decodeStream(istr);
    return bitmap;
}

@Override
public void onBackPressed() {
    startActivity(new Intent(MainActivity.this, Home.class));
    this.finish();
}

when I do this method

    @Override
public void onBackPressed() {
    startActivity(new Intent(MainActivity.this, Home.class));
    this.finish();
}

My first activity onCreate run it again. How to prevent from this action?

Remove the line startActivity(new Intent(MainActivity.this, Home.class)); and just leave the call to finish()

Just add below line in your AndroidManifest - <activity> which have ListView

android:launchMode="singleTask"

Like this,

<activity
            android:name=".MainActivity"
            android:launchMode="singleTask"/>

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