So basically I would like this to allow the user to input text (their name). Then to click the submit button which will store that name into an array and erase the writing in the EditText (as well as make a counter for players). After they are done submitting players names I want them to be able to click the play button (titled done i believe) and continue to the next page with all the information being sent over.
My problem currently is when i enter in a name and click submit it force closes. If i click the play button it force closes. Think you could help me out? Thanks
Class 1:
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < players; i++)
{
names[i] = input.getText().toString();
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Class2.class);
done.putExtra("players", players);
done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Your program crashes because you're trying to access non-initialized array. You must create array object using
String names[] = new String[MAX_COUNT]
.You're not allocating for variable
names
anywhere. You should do this:If you're not sure about
NO_OF_PLAYERS
, then useand use it:
I'm not sure this could be the reason but needs attention:
your onclick method of submit button:
Here you increase
players
counter. Then loop from 0 to players counter. In loop you assign the input text in names array. Finally you clear the input.This is not the right way to do. You have not initialized names array. Also you should not loop every time. It will override the old values in names array. And next time in loop input.getText() will return blank cause you have erased text from input already in first time you entered the loop.
It should be
if you debug your code you will better understand what I'm trying to say.
Please try this edited code,