开发者

How do i use one string array entry based upon its position within the array (Android)?

I'm trying to produce a simple oracle app where when you ask the app a question it spits out an answer based on a random number.

I've done some research and it seems to me the best practice way of doing things is to create a resource for my answers containing a string array, i can then type my various answers in to the array.

In my Java code in my main activity i can then generate a random number upon the click of a button. This random number can then correspond to the number of the index.

My problem comes when i try to piece the random number and the facility to access the string array together in code.

Here is a copy of my answerStrings.xml file

<?xml version="1.0" encoding="utf-8"?>

<resources>
    <string-array
    name="answers">
    <item>Yes</item>
    <item>No</item>
    <item>Maybe</item>
    <item>Quite possibly</item>
</string-array>
</resources>

Here is my java code:

import java.util.Random;

import android.app.Activity;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

TextView    outputText;
MediaPlayer mpGobble;
Vibrator    vibr;
String[]    answers;
private Random myRandom = new Random();
int         randomNumber;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //find the output text view for use within the activity

    outputText = (TextView)findViewById(R.id.textView01);

    outputText.setOnClickListener(this);

    //Declare an array of outputs
    Resources开发者_开发百科 res = getResources();
    String[] answers = res.getStringArray(R.array.answers);
    //--------^ Problem

    outputText.setText("Ask your question then click me");
}


@Override
public void onClick(View src) {
    switch(src.getId()){
    case R.id.textView01:

        //creates a random number
        int randomNumber = myRandom.nextInt(3);

        String answer = answers[randomNumber];

        outputText.setText(answer);




            break;
    }

}
}

I'm programming in Java with the eclipse IDE and as you have probably guessed i'm new to the game!

All help is much appreciated!!


The below code will put your String resource array into a String[] called answers.

Resources res = getResources();
String[] answers = res.getStringArray(R.array.answers);

You can then select your answer with

String answer = answers[YOUR_RANDOM_WHOLE_NUMBER];

An FYI, string arrays in resources can only be 512 entries long. Some string resource help Some general resource class help

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜