It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
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);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(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, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.
Related
I need help with my code. Let me try to explain the problem:
At the first activity I have two fields where I'll set values from an Enum, for this I made a button for each field that basically shows me another activity, calls the value and brings it to the main activity. Still in the first activity I have a button that starts another activity and (at the same time) take all the values from the enum end sends to another activity. The point is, everything is working, but this last button no, when I click it the app crashes. What is happening and how can I solve it?
Here goes the code of the first activity:
public class MenuInicial extends AppCompatActivity {
public static final int CONSTANTE_BANZO = 1;
Button escolherM;
Button escolherB;
Button next;
TextView campoM;
TextView campoB;
Intent intent1;
Intent intent2;
Intent intentBundle;
Intent intentNext;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_inicial);
intent1 = new Intent(MenuInicial.this, Montante.class);
campoM = (TextView) findViewById(R.id.fieldM);
escolherM = (Button) findViewById(R.id.chooseM);
String perfilM = getIntent().getExtras().getString("nameM");
campoM.setText(perfilM);
escolherM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivity(intent1);
}
});
intent2 = new Intent(MenuInicial.this, Banzo.class);
campoB = (TextView) findViewById(R.id.fieldB);
escolherB = (Button) findViewById(R.id.chooseB);
escolherB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivityForResult(intent2, CONSTANTE_BANZO);
}
});
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
}
protected void onActivityResult(int codigo, int resultado, Intent intent){
if(codigo == CONSTANTE_BANZO){
Bundle bundleB = intent.getExtras();
if(bundleB != null){
String perfilB = bundleB.getString("nameB");
campoB.setText(perfilB);
}
}
}
}
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
Which activity do you want to go to? choose one. When you do, you can get those extras then when you need to goto the other activity, you can put those extras there too.
A better way to do it is to create a model (constructor with setters and getters) and put these in a list. At that point you can loop through the list and take what you need. It all depends on what you are doing though as the list will not be instantiated like intent extras would be.
Or, you can use SharedPref which is similar to a HashMap (which is also similar to the Intent Extras). SharedPref will store the key and value on the phones cache and then you can pull from that when you need it. Again, keep in mind that if the user clears the cache on the app, then it'll delete those shared pref.
Finally, you can also use a database such as Parse Server or Firebase.
Learning how to produce random numbers from arrays. The code will pick a random string during the onCreate method, but when the button is clicked there is no change to the string. Am I messing up the scope of my variables somehow? I really do not know what it wrong.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
}
public void onClick(View view){
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
TextView question = (TextView) findViewById(R.id.question);
question.setText(q);
}
});
}
}
First of all you haven't set click listener on button properly you made onClick method which is never called . Also you are getting the references of view multiple times you should do it like this.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
question.setText(q);
}
});
}
}
You either need to set the onClickListener in xml (in which case you don't need to set the listener in code), or you need to set the listener in onCreate. Right now its being set in a function named onClick, which is never called.
First, you never set the onClickListeren. You have a method which adds one, but you never call it. Move the code in the onClick method to your onCreate method. This will probably fix your problem.
If not, don't make your Random final and add this to your #Override onClick():
rgen = new Random(System.currentTimeMillis());
This will use a different seed every time
I am new to Android. I am showing Text in the TextView on Button click Randomly. On 1st Textview the Heading and on 2nd the explaination of that heading. I am able to show the Heading and Explaination Randomly and now I want if the Text is shown once should not be shown again means it will be removed. This is the point where I stuck. I am not able to remove the texts. Any help will be appreciated. I am posting my code here.
MainActivity.java
TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_heading.get(int_text)); //getting error
text_explain(array_explain.get(int_text)); //getting error
array_heading.remove(int_text); //getting error
array_explain.remove(int_text); //getting error
}
});
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer>array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
}
}
I am not able to remove the texts. Any help will be appreciated. I am
posting my code here.
To clean the content of the TextView you could pass null to setText. E.g
text_heading.setText(null);
If you want to change the content every time you click on the button, you have to move
int_text = random.nextInt(array_heading.length);
your onClick callback,
You should be aware of the fact that next int returns an int between [0, n). array_heading.length -1 is necessary only if you want to exclude R.string.source_text9_explain from the possible texts you want to show. Keep also in mind that if array_heading contains more items than array_explain you could get ArrayIndexOutBoundException
I would keep the strings together in an object:
public class Item {
private final int textId;
private final int textExplanationId;
public class Item(int textId, int textExplanationId){
this.textId = textId;
this.textExplanationId = textExplanationId;
}
public int getTextId(){return textId;}
public int getTextExplanationId(){return textExplanationId;}
}
Then I would store those in an ArrayList:
List<Item> items = new ArrayList<Item>(new Item[]{
new Item(R.string.source_text1, R.string.source_text1_explain),
new Item(R.string.source_text2, R.string.source_text2_explain),
//etc
});
Then I would shuffle that array once:
Collections.shuffle(items);
And read from it in order:
Item current = items.get(currentIndex++);
text_heading.setText(current.getTextId());
text_explain.setText(current.getTextExplanationId());
TextView text_heading,text_explain;
Button click;
Random random;
Integer [] array_heading ,array_explain ;
Integer int_text;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_heading = (TextView) findViewById(R.id.text_heading);
text_explain = (TextView) findViewById(R.id.text_explain);
click = (Button) findViewById(R.id.click);
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size() - 1);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text)); //getting error
text_explain.setText(array_explainList.get(int_text)); //getting error
array_headingList.remove(int_text); //getting error
array_explainList.remove(int_text); //getting error
}
});
}
}
You must use ArrayList for it.
ArrayList<Integer> heading = Arrays.asList(array_heading);
ArrayList<Integer> explain = Arrays.asList(array_explain);
Now set text from this arraylists. And when its set once remove it from the arraylist so it cannot be shown again.
Use like this
random = new Random();
array_heading = new Integer []{R.string.source_text1, R.string.source_text2, R.string.source_text3,
R.string.source_text6, R.string.source_text5, R.string.source_text4, R.string.source_text7,
R.string.source_text8, R.string.source_text9};
array_explain = new Integer []{R.string.source_text1_explain, R.string.source_text2_explain,
R.string.source_text3_explain,
R.string.source_text4_explain, R.string.source_text5_explain, R.string.source_text6_explain,
R.string.source_text7_explain,
R.string.source_text8_explain, R.string.source_text9_explain};
ArrayList<Integer> array_headingList = new ArrayList<Integer>(Arrays.asList(array_heading));
ArrayList<Integer> array_explainList = new ArrayList<Integer>(Arrays.asList(array_explain));
int_text = random.nextInt(array_headingList.size());
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text_heading.setText(array_headingList.get(int_text));
text_explain.setText(array_explainList.get(int_text));
array_headingList.remove(int_text);
array_explainList.remove(int_text);
if(array_headingList.size() == 0){
click.setEnabled(false);
Toast.makeText(getApplicationContext(),"All text finished",Toast.LENGTH_SHORT).show();
} else if(array_headingList.size() == 1){
int_text = 0;
} else {
int_text = random.nextInt(array_headingList.size());
}
}
});
Hello as the title state I'm trying to setup a next and previous buttons but I'm still new at coding so this has me a little confused.
I tried to use if statements with an enum within a single button but it defaults to last if statement when the event is handled here's the code-
private enum EVENT{
pe1, pe2, pe3, pe4;
}
EVENT currentEvent = EVENT.pe1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentEvent==EVENT.pe1) {
olText.setText("PE1");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe2;
}
if (currentEvent==EVENT.pe2){
olText.setText("PE2");
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
currentEvent=EVENT.pe3;
}
}
});
}
I tried to use the enumerator to assign a number to each if statement so when the user hit previous it would subtract and when they hit next it would add, each number would have some text or image within its if statement but as I said it defaults to the last if statement- Any help is much appreciated.
How about this?
int eventNum = 0;
int maxEvents = XXX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_liners);
prevBtn = (Button) findViewById(R.id.prevBtn);
nextBtn = (Button) findViewById(R.id.nextBtn);
olText = (TextView) findViewById(R.id.olText);
setEventData(true);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(prevBtn) && eventNum > 0) {
eventNum--;
setEventData(false);
return;
}
if(v.equals(nextBtn) && eventNum < maxEvents - 1) {
eventNum++;
setEventData(true);
return;
}
}
}
nextBtn.setOnClickListener(listener);
prevBtn.setOnClickListener(listener);
}
private void setEventData(boolean animLeft) {
olText.setText("PE" + (eventNum + 1));
if(animLeft) {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_left));
} else {
olText.startAnimation(AnimationUtils.loadAnimation(olText.this, android.R.anim.slide_in_right));
}
}
You'll want to create a class variable that keeps track of which text your TextView is showing. So in the following example, I create a list of Strings that I just store in a String array. Then I create an iterator variable which stores which String from the list I'm currently viewing in the TextView. Every time you click the previous or next button, you simply store your current state in the iterator variable so you can recall it the next time a click event comes in.
String[] labels = {"one", "two", "three", "four"};
int currentView = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onPreviousButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView--; //decrement our iterator
if(currentView < 0) currentView = 0; //check to make sure we didn't go below zero
textView.setText(labels[currentView]);
}
public void onNextButtonClicked(View view) {
TextView textView = (TextView) findViewById(R.id.clickableLink);
currentView++; //increment our iterator
if(currentView > labels.length-1) currentView = labels.length-1; //check to make sure we didn't go outside the array
textView.setText(labels[currentView]);
}
public class Lucenconcept extends Activity {
Button btn1;
EditText mEdit;
String txt2;
public ListAdapter adapter;
private ListView lv;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
File index = new File("/sdcard/index/");
index.mkdir();
mEdit = (EditText)findViewById(R.id.editText1);
lv=(ListView) findViewById(android.R.id.list);
btn1 = (Button)findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Analyzer analyzer = new StandardAnalyzer();
IndexSearcher indexSearcher;
try {
indexSearcher = new IndexSearcher("/sdcard/index/");
QueryParser parser = new QueryParser("text", analyzer);
Hits hits = indexSearcher.search( parser.parse("("+ "text:" +mEdit.getText().toString() + ")"));
String txt2[] =new String[100];
String txt="";
for (int i = 0; i < hits.length(); i++) {
Document hitDoc = hits.doc(i);
Log.i("TestAndroidLuceneActivity", "Lucene: " +hitDoc.get("title")+ hitDoc.get("path"));
txt=hitDoc.get("title");
txt2[i]=txt;
String location=hitDoc.get("path");
}
lv.setAdapter(new ArrayAdapter
<String>
(Lucenconcept.this,android.R.layout.simple_list_item_1 ,txt2));
indexSearcher.close();
}
});
}
}
I m able show title on list view I want to display path hitDoc.get("path") from this string on item selct in next activity ..
Cud any one plz help meam not able to display url in next activty while I have put all the think manifest and all the I think there is mistake in postion plz help me..
Use Intent for passing data between activities
Refer Intent example