views:

46

answers:

1

I'm not sure what's wrong here, all i want to do is randomly grab an item from my array. Which is just like a random sentence. Then generate another once the button is pressed. All my code looks good to me but it's causing a crash when i hit the button. any ideas?

package com.my.package;


import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import android.view.View.OnClickListener;

public class Randomsentence extends Activity implements OnClickListener{


    private String[] myString;
    private static final Random rgenerator = new Random();
    private TextView tv;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    Resources res = getResources();

    myString = res.getStringArray(R.array.myArray); 

    String q = myString[rgenerator.nextInt(myString.length)];

    TextView tv = (TextView) findViewById(R.id.text1);
    tv.setText(q);

    View nextButton = findViewById(R.id.next_button);
    nextButton.setOnClickListener(this);

}

    @Override
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.next_button:
        tv.setText(myString[rgenerator.nextInt(myString.length)]);
        break;
    }

}
    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu3, menu);
        return true;
    }

@Override
public boolean onOptionsItemSelected (MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu:
            startActivity(new Intent(this, Main.class));
            return true;
        case R.id.startnhie:
            startActivity(new Intent(this, startnhie.class));
            return true;

}
return false;
    }



}
+3  A: 

In your onCreate(), change

TextView tv = (TextView) findViewById(R.id.text1);

to

tv = (TextView) findViewById(R.id.text1);

since you already declared TextView tv as an instance variable.

Andy Zhang
thank you very much!
brybam