Hello I'm a college student studying Java. I'm working on a android application. It compiles and shows no error. However when it runs, there's a unexpected close error.
Here's my application. When you click on the calculate ws you purpose to change to this screen.
Here's my code:
package com.warhammerdicerrolleralpha;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class myMain extends Activity
{
EditText enternumberofdice;
final TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
ImageView i = new ImageView(this);
{
i.setAdjustViewBounds(true);
}
private int myFaceValue;
int myNum;
/**
* Called when the activity is first created.
*
* #return
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void go()
{
while (myNum > 0)
{
// TODO Auto-generated method stub
textGenerateNumber.setText(String.valueOf(enternumberofdice));
--myNum;
return;
}
}
public int roll()
{
int val = (int) (6 * Math.random() + 1); // Range 1-6
setValue(val);
return val;
}
{
try
{
myNum = Integer.parseInt(enternumberofdice.getText().toString());
}
catch (NumberFormatException nfe)
{
enternumberofdice.setText("Does not work");
}
}
public int getValue()
{
return myFaceValue;
}
public void setValue(int myFaceValue)
{
this.myFaceValue = myFaceValue;
}
{
switch (myFaceValue)
{
case 5:
i.setImageResource(R.drawable.dicefive);
break;
case 1:
i.setImageResource(R.drawable.diceone);
break;
case 3:
i.setImageResource(R.drawable.dicethree);
break;
case 2:
i.setImageResource(R.drawable.dicetwo);
break;
case 4:
i.setImageResource(R.drawable.dicefour);
break;
case 6:
i.setImageResource(R.drawable.dicesix);
break;
default:
i.setImageResource(R.drawable.error);
break;
}
text = (EditText) findViewById(R.id.editText1);
text2 =(EditText) findViewById(R.id.editText2);
text3 = (EditText) findViewById(R.id.editText3);
btutorial1 = (Button) findViewById(R.id.button1);
btutorial1.setOnClickListener((OnClickListener) this);
Button buttonGenerate = (Button) findViewById(R.id.button1);
enternumberofdice = (EditText) findViewById(R.id.enternumberofdice);
Button buttonGenerate2 = (Button) findViewById(R.id.battlecalculate);
buttonGenerate2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
setContentView(R.layout.main2);
}
});
buttonGenerate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
go();
roll();
}
});
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.button1:
if (number1 > number2)
{
text3.setText("Three and above");
return;
}
else if (number1 < number2)
{
text3.setText("Five and above");
return;
}
else if (number1 == number2)
{
text3.setText("Four and above");
return;
}
else
{
text3.setText("Not Working");
return;
}
}
}
}
Look at your stack trace, but I think it may be because of this block:
private EditText text, text2, text3;
private Button btutorial1;
int number1 = Integer.parseInt(text.getText().toString());
int number2 = Integer.parseInt(text2.getText().toString());
It looks as though you are trying to parseInt over null values. You need to specify where text, text2, text3 are in your form using similar code to:
TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
Hope that helps.
Related
I am working on a side project in android studio and need to store some long term data to a file that can be written and readable, I am able to do this outside of android studio, but when I try to do it within, it sows a error saying
public void onClick(View v) 'onClick(View)' in 'Anonymous class derived from android.view.View.OnClickListener' clashes with 'onClick(View)' in 'android.view.View.OnClickListener'; overridden method does not throw 'java.io.FileNotFoundException'{
I have a function in a separate file that writes to a string from a file, but when I try to access that string from one of my main view pages, its asking for an exception, but will not work with said exception, I've tried try and catch but with no success
File being initialized and written:
package com.example.stellarisspeciesrandomizer;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class DLCPage extends AppCompatActivity {
public static int[] DLCArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.dlc_page);
try {
File myObj = new File("hasDLC.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
DLCArray = new int[1];
Button doneButton = (Button) findViewById(R.id.button_done);
doneButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws IOException {
writeToFile();
finish();
}});
ImageButton aquaticsCheckbox = (ImageButton) findViewById(R.id.aquatic_checkbox);
aquaticsCheckbox.setTag("1");
//hello
aquaticsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (aquaticsCheckbox.getTag() == "1") {
aquaticsCheckbox.setImageResource(R.drawable.checked);
aquaticsCheckbox.setTag("2");
DLCArray[0] = 1;
} else if (aquaticsCheckbox.getTag() == "2") {
aquaticsCheckbox.setImageResource(R.drawable.checkmark);
aquaticsCheckbox.setTag("1");
DLCArray[0] = 0;
}
}
});
ImageButton humanoidCheckbox = (ImageButton) findViewById(R.id.humanoid_checkbox);
humanoidCheckbox.setTag("1");
humanoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (humanoidCheckbox.getTag() == "1") {
humanoidCheckbox.setImageResource(R.drawable.checked);
humanoidCheckbox.setTag("2");
DLCArray[1] = 1;
} else if (humanoidCheckbox.getTag() == "2") {
humanoidCheckbox.setImageResource(R.drawable.checkmark);
humanoidCheckbox.setTag("1");
DLCArray[1] = 0;
}
}
});
ImageButton plantoidCheckbox = (ImageButton) findViewById(R.id.plantoid_checkbox);
plantoidCheckbox.setTag("1");
plantoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (plantoidCheckbox.getTag() == "1") {
plantoidCheckbox.setImageResource(R.drawable.checked);
plantoidCheckbox.setTag("2");
DLCArray[2] = 1;
} else if (plantoidCheckbox.getTag() == "2") {
plantoidCheckbox.setImageResource(R.drawable.checkmark);
plantoidCheckbox.setTag("1");
DLCArray[2] = 0;
}
}
});
ImageButton syntheticCheckbox = (ImageButton) findViewById(R.id.synthetic_checkbox);
syntheticCheckbox.setTag("1");
syntheticCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (syntheticCheckbox.getTag() == "1") {
syntheticCheckbox.setImageResource(R.drawable.checked);
syntheticCheckbox.setTag("2");
DLCArray[3] = 1;
} else if (syntheticCheckbox.getTag() == "2") {
syntheticCheckbox.setImageResource(R.drawable.checkmark);
syntheticCheckbox.setTag("1");
DLCArray[3] = 0;
}
}
});
ImageButton necroidCheckbox = (ImageButton) findViewById(R.id.necroids_checkbox);
necroidCheckbox.setTag("1");
necroidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (necroidCheckbox.getTag() == "1") {
necroidCheckbox.setImageResource(R.drawable.checked);
necroidCheckbox.setTag("2");
DLCArray[4] = 1;
} else if (necroidCheckbox.getTag() == "2") {
necroidCheckbox.setImageResource(R.drawable.checkmark);
necroidCheckbox.setTag("1");
DLCArray[4] = 0;
}
}
});
ImageButton lithoidCheckbox = (ImageButton) findViewById(R.id.lithoids_checkbox);
lithoidCheckbox.setTag("1");
lithoidCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (lithoidCheckbox.getTag() == "1") {
lithoidCheckbox.setImageResource(R.drawable.checked);
lithoidCheckbox.setTag("2");
DLCArray[5] = 1;
} else if (lithoidCheckbox.getTag() == "2") {
lithoidCheckbox.setImageResource(R.drawable.checkmark);
lithoidCheckbox.setTag("1");
DLCArray[5] = 0;
}
}
});
ImageButton ancientCheckbox = (ImageButton) findViewById(R.id.ancient_checkbox);
ancientCheckbox.setTag("1");
ancientCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (ancientCheckbox.getTag() == "1") {
ancientCheckbox.setImageResource(R.drawable.checked);
ancientCheckbox.setTag("2");
DLCArray[6] = 1;
} else if (ancientCheckbox.getTag() == "2") {
ancientCheckbox.setImageResource(R.drawable.checkmark);
ancientCheckbox.setTag("1");
DLCArray[6] = 0;
}
}
});
ImageButton federationsCheckbox = (ImageButton) findViewById(R.id.federations_checkbox);
federationsCheckbox.setTag("1");
federationsCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (federationsCheckbox.getTag() == "1") {
federationsCheckbox.setImageResource(R.drawable.checked);
federationsCheckbox.setTag("2");
DLCArray[7] = 1;
} else if (federationsCheckbox.getTag() == "2") {
federationsCheckbox.setImageResource(R.drawable.checkmark);
federationsCheckbox.setTag("1");
DLCArray[7] = 0;
}
}
});
ImageButton apocalypseCheckbox = (ImageButton) findViewById(R.id.apocalypse_checkbox);
apocalypseCheckbox.setTag("1");
apocalypseCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (apocalypseCheckbox.getTag() == "1") {
apocalypseCheckbox.setImageResource(R.drawable.checked);
apocalypseCheckbox.setTag("2");
DLCArray[8] = 1;
} else if (apocalypseCheckbox.getTag() == "2") {
apocalypseCheckbox.setImageResource(R.drawable.checkmark);
apocalypseCheckbox.setTag("1");
DLCArray[8] = 0;
}
}
});
ImageButton utopiaCheckbox = (ImageButton) findViewById(R.id.utopia_checkbox);
utopiaCheckbox.setTag("1");
utopiaCheckbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (utopiaCheckbox.getTag() == "1") {
utopiaCheckbox.setImageResource(R.drawable.checked);
utopiaCheckbox.setTag("2");
DLCArray[9] = 1;
} else if (utopiaCheckbox.getTag() == "2") {
utopiaCheckbox.setImageResource(R.drawable.checkmark);
utopiaCheckbox.setTag("1");
DLCArray[9] = 0;
}
}
});
}
public static void writeToFile() throws IOException {
int len = DLCArray.length;
for (int i = 0; i < len; i++) {
FileWriter writer = new FileWriter("hasDLC.txt");
writer.write(DLCArray[i] + "\t"+ "");
}
}
}
second page
package com.example.stellarisspeciesrandomizer;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Randomizer {
private static int[] tall= new int[3] ;
public static String RandomSpecies(String origin) throws FileNotFoundException {
readFile();
Random random = new Random();
ArrayList<String> originArray = new ArrayList<String>();
String origins1 = "Prosperous Unification";
String origins2 = "Galactic Doorstep";
String origins3 = "Lost Colony";
String origins4 = "Here Be Dragons";
String origins5 = "Ocean Paradise";
String origins6 = "Clone Army";
String origins7 = "Necrophage";
String origins18 = "Resource Consolidation";
String origins19 = "Remnants";
String origins16 = "Life Seeded";
String origins17 = "Post-Apocalyptic";
String origins8 = "Remnants";
String origins9 = "Shattered Ring";
String origins10 = "Void Dwellers";
String origins11 = "Scion";
String origins12 = "On The Shoulders of Giants";
String origins13 = "Common Ground";
String origins14 = "Hegemon";
String origins15 = "Doomsday";
String origin20 = "Syncretic Evolution";
String origin21 = "Mechanist";
String origin22 = "String of Life";
originArray.add(origins4);
originArray.add(origins5);
originArray.add(origins6);
originArray.add(origins7);
originArray.add(origins18);
originArray.add(origins19);
originArray.remove(origins17);
originArray.remove(origins16);
originArray.add(origins8);
originArray.add(origins9);
originArray.add(origins10);
originArray.add(origins11);
originArray.add(origins12);
originArray.add(origins13);
originArray.add(origins14);
originArray.add(origins15);
originArray.add(origin20);
originArray.add(origin21);
originArray.add(origin22);
originArray.add(origins1);
originArray.add(origins2);
originArray.add(origins3);
origin = originArray.get(random.nextInt(originArray.size()));
return origin;
}
public static void readFile() throws FileNotFoundException {
Scanner scanner = new Scanner(new File("hasDLC.txt"));
tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
System.out.println(tall);
}
}
last page
package com.example.stellarisspeciesrandomizer;
import static com.example.stellarisspeciesrandomizer.Randomizer.RandomSpecies;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.FileNotFoundException;
public class RandomizerHome extends AppCompatActivity {
String hi = "hi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
setContentView(R.layout.randomizer_layout);
ImageView originImageView =(ImageView) findViewById(R.id.originImageView);
Intent dlcIntent = new Intent(this, DLCPage.class);
Button dlcButton = (Button) findViewById(R.id.dlc_button);
dlcButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dlcIntent);
}
});
Button randomizeButton = (Button) findViewById(R.id.randomize_button);
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
String originTrue = "hi";
originTrue = RandomSpecies(hi);
switch(originTrue){
case ("Prosperous Unification"): originImageView.setImageResource(R.drawable.prosperousunification);break;
case ("Galactic Doorstep"): originImageView.setImageResource(R.drawable.galacticdoorstep);break;
case ("Lost Colony"): originImageView.setImageResource(R.drawable.lostcolony);break;
case ("Here Be Dragons"): originImageView.setImageResource(R.drawable.here_be_dragons);break;
case ("Ocean Paradise"): originImageView.setImageResource(R.drawable.ocean_paradise);break;
case ("Clone Army"): originImageView.setImageResource(R.drawable.clones);break;
case ("Necrophage"): originImageView.setImageResource(R.drawable.necrophage);break;
case ("Resource Consolidation"): originImageView.setImageResource(R.drawable.resource_consolidation);break;
case ("Remnants"): originImageView.setImageResource(R.drawable.remnant);break;
case ("Life Seeded"): originImageView.setImageResource(R.drawable.life_seeded);break;
case ("Post-Apocalyptic"): originImageView.setImageResource(R.drawable.post_apocalyptic);break;
case ("Shattered Ring"): originImageView.setImageResource(R.drawable.shattered_ring);break;
case ("Void Dwellers"): originImageView.setImageResource(R.drawable.void_dwellers);break;
case ("Scion"): originImageView.setImageResource(R.drawable.scion);break;
case ("On The Shoulders of Giants"): originImageView.setImageResource(R.drawable.on_the_shoulders_of_giant);break;
case ("Common Ground"): originImageView.setImageResource(R.drawable.common_ground);break;
case ("Hegemon"): originImageView.setImageResource(R.drawable.hegemon);break;
case ("Doomsday"): originImageView.setImageResource(R.drawable.doomsday);break;
case ("Syncretic Evolution"): originImageView.setImageResource(R.drawable.syncretic_evolution);break;
case ("Mechanist"): originImageView.setImageResource(R.drawable.mechanist);break;
case ("Tree of Life"): originImageView.setImageResource(R.drawable.tree_of_life);break;
}
System.out.println(originTrue);
}
});
}
}
Here:
randomizeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws FileNotFoundException {
What you are doing here: define an anonymous subclass of View.OnClickListener. And when you check the documentation for that class, it says:
public abstract void onClick (View v)
Now read the compiler message again you got. overridden method does not throw 'java.io.FileNotFoundException'
Thus the real answer here is: A) you have to understand what you are doing and B) you have to read compiler error messages really carefully.
Long story short, you can not override an inherited method and add checked exceptions such as FileNotFoundException to the signature of your method. So, the solution is to step back and to really learn/understand how exception handling works in Java. One possibility here: use try/catch in your readFile(), catch the FileNotFoundException and rethrow it as (unchecked) RuntimeException. Then you do not need to have throws FileNotFoundException on your method signatures, and the compiler won't complain any more.
I am trying to make a simple quiz app and I want to display the score value in another activity(another screen) i.e. when I press the submit button the score activity should open and display the total score.
I have tried using intents but it hasn't worked. I am new at android programming and there could be some silly mistakes.
This is the MainActivity.java file.
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Question 1 Methods
public void question1_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.haibara:
if (checked) {
String correct = "Right Answer";
display_answer1(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q1_o1);
display_answer1(wrong);
}
break;
}
}
private void display_answer1(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_1);
quantityTextView.setText(answer);
}
//Question 2 Methods
public void question2_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.true_op:
if (checked) {
String correct = "Right Answer";
display_answer2(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q2_o1);
display_answer2(wrong);
}
break;
}
}
private void display_answer2(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_2);
quantityTextView.setText(answer);
}
//Question 3 Methods
public void question3_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q3_op3:
if (checked) {
String correct = "Right Answer";
display_answer3(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q3_o3);
display_answer3(wrong);
}
break;
}
}
private void display_answer3(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_3);
quantityTextView.setText(answer);
}
//Question 4 Methods
public void question4_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q4_op1:
if (checked) {
String correct = "Right Answer";
display_answer4(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q4_o1);
display_answer4(wrong);
}
break;
}
}
private void display_answer4(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_4);
quantityTextView.setText(answer);
}
//Question 5 Methods
public void question5_click(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.q5_op3:
if (checked) {
String correct = "Right Answer";
display_answer5(correct);
score++;
}
break;
default: {
String wrong = "Wrong Answer" + "\n" + "The right answer is " + getString(R.string.q5_o3);
display_answer5(wrong);
}
break;
}
}
private void display_answer5(String answer) {
TextView quantityTextView = (TextView) findViewById(R.id.answer_5);
quantityTextView.setText(answer);
}
//Submit Button
public void onClickSubmit(View view){
Intent scoreActivity = new Intent(MainActivity.this,Score.class);
scoreActivity.putExtra("sendScore", score);
startActivity(scoreActivity);
}
}
This is the other activity java(Score.java) file
package com.example.android.conanquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class Score extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
Intent scoreActivity = getIntent();
int totalScore = scoreActivity.getIntExtra("sendScore", 0);
displayScore(totalScore);
}
public void displayScore(int score) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(score);
}
}
Try to print score on button click using log. if score is not null than write below code.
From Activity
Intent intent = new Intent(getBaseContext(), Score.class);
intent.putExtra("EXTRA_SCORE", score);
startActivity(intent);
To Activity
Intent intent = getIntent();
int intValue = intent.getIntExtra("EXTRA_SCORE", 0);
I need your help to find an error in my "test" android application.
Until I create the second function "setProgessBar" the app runs without error, but now the error occur everytime. To comment the function call out has no effect.
Here is the code:
package my.timer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Timer1 extends AppCompatActivity {
private int arrayPosition = 0;
private long timeValue = 0;
private boolean indicator = false;
private double progress;
private final String[] actions = {"Phase1" , "Phase2" , "Phase3" , "Phase4"};
private final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer1);
final Button startButton = (Button) findViewById(R.id.startButton);
final TextView text1 = (TextView) findViewById(R.id.textView3);
final TextView text2 = (TextView) findViewById(R.id.actionParameter);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text2.setText(actions[arrayPosition]);
text1.setText("" + timeValue + "");
new CountDownTimer(240000, 100) {
public void onTick(long millisUntilFinished) {
timeValue = (millisUntilFinished / 1000) % 4;
text1.setText("" + timeValue + "");
if (timeValue == 3 && indicator){
if (arrayPosition < 3){
arrayPosition++;
} else {
arrayPosition = 0;
}
indicator = false;
setProgressBar(arrayPosition);
text2.setText(actions[arrayPosition]);
}
if (timeValue == 1){
indicator = true;
}
}
public void onFinish() {
text1.setText("Geschafft :)");
}
}.start();
}
});
}
private void setProgressBar(int progressStatus) {
switch (progressStatus){
case 0:
progress = progress + 0.25;
break;
case 2:
progress = progress - 0.25;
break;
}
progressBar.setProgress((int)progress);
}
}
Many thanks in advance
Tim
Hi there i've been constructing this code for a week but i still cant get it to work. It has no errors but when i run it on the AVD it terminates suddenly.
package com.tryout.sample;
import java.util.Random;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements View.OnClickListener{
Random number = new Random();
int Low = 1;
int High = 13;
int RandomNumber = number.nextInt(High-Low) + Low;
int current = 0;
int points=0;
final Integer[] cardid = { R.drawable.card1,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
};
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView score = (TextView) findViewById(R.id.textView2);
Button high = (Button) findViewById(R.id.button1);
Button low = (Button) findViewById(R.id.button2);
final ImageView pic = (ImageView) findViewById(R.id.imageView1);
low.setOnClickListener(new view.OnClickListener() {
public void onClick(View v) {
int resource = cardid[RandomNumber];
if(current < RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
high.setOnClickListener(new View.OnClickListener() {
public void higher(View v) {
int resource = cardid[RandomNumber];
if(current > RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
int resource = cardid[RandomNumber];
pic.setImageResource(resource);
current = RandomNumber;
}
}
I cant figure out where my problem is, kindly check out my code. THanks for any help
put this:
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
in you onCreate method after the call setContentView(R.layout.activity_main);.
How should R.id.imageView1 assigned if the content is not specified like in your case?
ImageView pic2;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic2 = (ImageView) findViewById(R.id.imageView1);
score = (TextView) findViewById(R.id.textView2);
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class minigame_cardpairing extends Activity implements View.OnClickListener {
private static final int TOTAL_CARD_NUM = 16;
private int[] cardId = {R.id.card01, R.id.card02, R.id.card03, R.id.card04, R.id.card05, R.id.card06, R.id.card07, R.id.card08,
R.id.card09, R.id.card10, R.id.card11, R.id.card12, R.id.card13, R.id.card14, R.id.card15, R.id.card16};
private Card[] cardArray = new Card[TOTAL_CARD_NUM];
private int CLICK_CNT = 0;
private Card first, second;
private int SUCCESS_CNT = 0;
private boolean INPLAY = false;
//----------- Activity widget -----------//
private Button start;
//-----------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.minigame_cardpairing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for(int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i] = new Card(i/2);
findViewById(cardId[i]).setOnClickListener(this);
cardArray[i].card = (ImageButton) findViewById(cardId[i]); // Card assignment
cardArray[i].onBack();
}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startGame();
//start.setBackgroundDrawable(background);
}
});
findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
} // end of onCreate
protected void startDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("The match-card game. Please remember to flip the cards two by two card hand is a pair Hit. Hit all pairs are completed.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Game Description");
alt2.show();
}
protected void clearDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("It fits all the cards in pairs. Congratulations.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Match-complete");
alt2.show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
startDialog();
}
public void onClick(View v) {
if (INPLAY) {
switch (CLICK_CNT) {
case 0:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
first = cardArray[i];
break;
}
}
if (first.isBack) {
first.onFront();
CLICK_CNT = 1;
}
break;
case 1:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
second = cardArray[i];
break;
}
}
if (second.isBack) {
second.onFront();
if (first.value == second.value) {
SUCCESS_CNT++;
Log.v("SUCCESS_CNT", "" + SUCCESS_CNT);
if (SUCCESS_CNT == TOTAL_CARD_NUM/2) {
clearDialog();
}
}
else {
Timer t = new Timer(0);
t.start();
}
CLICK_CNT = 0;
}
break;
}
}
}
void startGame() {
int[] random = new int[TOTAL_CARD_NUM];
int x;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (!cardArray[i].isBack)
cardArray[i].onBack();
}
boolean dup;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
while(true) {
dup = false;
x = (int) (Math.random() * TOTAL_CARD_NUM);
for (int j=0; j<i; j++) {
if (random[j] == x) {
dup = true;
break;
}
}
if (!dup) break;
}
random[i] = x;
}
start.setClickable(false);
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].card = (ImageButton) findViewById(cardId[random[i]]);
cardArray[i].onFront();
}
Log.v("timer", "start");
Timer t = new Timer(1);
//flag = false;
t.start();
/*
while(true) {
if (flag) break;
//Log.v("flag", "" + flag);
}
Log.v("timer", "end");
*/
SUCCESS_CNT = 0;
CLICK_CNT = 0;
INPLAY = true;
}
class Timer extends Thread {
int kind;
Timer (int kind) {
super();
this.kind = kind;
}
#Override
public void run() {
INPLAY = false;
// TODO Auto-generated method stub
try {
if (kind == 0) {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
}
else if (kind == 1) {
Thread.sleep(3000);
mHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INPLAY = true;
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
first.onBack();
second.onBack();
first.isBack = true;
second.isBack = true;
}
else if (msg.what == 1) {
//flag = true;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].onBack();
}
start.setClickable(true);
}
}
};
}
class Card { // start of Card class
private final static int backImageID = R.drawable.cardback;
private final static int[] frontImageID = {R.drawable.card1, R.drawable.card2,
R.drawable.card3, R.drawable.card4,
R.drawable.card5, R.drawable.card6,
R.drawable.card7, R.drawable.card8};
int value;
boolean isBack;
ImageButton card;
Card(int value) {
this.value = value;
}
public void onBack() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
}
public void flip() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
else {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
public void onFront() {
if (isBack) {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
} // end of Card class
I'm creating an android application. It compiles well and eclipse does not spot any errors. However when I run it I get this in the stack trace.
<disconnected>DalvikVM[localhost:8639]
Here is my code:
package com.warhammerdicerrolleralpha;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class myMain extends Activity
{
EditText enternumberofdice;
TextView textGenerateNumber;
int number1;
int number2;
ImageView i;
private EditText text, text2, text3;
private Button btutorial1;
private int myFaceValue;
int myNum;
/**
* Called when the activity is first created.
*
* #return
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textGenerateNumber = (TextView) findViewById(R.id.text4);
number1 = Integer.parseInt(text.getText().toString());
number2 = Integer.parseInt(text2.getText().toString());
ImageView i = new ImageView(this);
i.setAdjustViewBounds(true);
}
public void go()
{
while (myNum > 0)
{
textGenerateNumber.setText(String.valueOf(enternumberofdice));
--myNum;
return;
}
}
public int roll()
{
int val = (int) (6 * Math.random() + 1); // Range 1-6
setValue(val);
return val;
}
{
try
{
myNum = Integer.parseInt(enternumberofdice.getText().toString());
}
catch (NumberFormatException nfe)
{
enternumberofdice.setText("Does not work");
}
}
public int getValue()
{
return myFaceValue;
}
public void setValue(int myFaceValue)
{
this.myFaceValue = myFaceValue;
}
{
switch (myFaceValue)
{
case 5:
i.setImageResource(R.drawable.dicefive);
break;
case 1:
i.setImageResource(R.drawable.diceone);
break;
case 3:
i.setImageResource(R.drawable.dicethree);
break;
case 2:
i.setImageResource(R.drawable.dicetwo);
break;
case 4:
i.setImageResource(R.drawable.dicefour);
break;
case 6:
i.setImageResource(R.drawable.dicesix);
break;
default:
i.setImageResource(R.drawable.error);
break;
}
text = (EditText) findViewById(R.id.editText1);
text2 =(EditText) findViewById(R.id.editText2);
text3 = (EditText) findViewById(R.id.editText3);
btutorial1 = (Button) findViewById(R.id.button1);
btutorial1.setOnClickListener((OnClickListener) this);
Button buttonGenerate = (Button) findViewById(R.id.button1);
enternumberofdice = (EditText) findViewById(R.id.enternumberofdice);
Button buttonGenerate2 = (Button) findViewById(R.id.battlecalculate);
buttonGenerate2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
setContentView(R.layout.main2);
}
});
buttonGenerate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
go();
roll();
}
});
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.button1:
if (number1 > number2)
{
text3.setText("Three and above");
return;
}
else if (number1 < number2)
{
text3.setText("Five and above");
return;
}
else if (number1 == number2)
{
text3.setText("Four and above");
return;
}
else
{
text3.setText("Not Working");
return;
}
}
}
}
P.S. How do you add xml code to your post. When I add xml code to my post, it doesn't appear in the preview page.
Here is my stack trace.
DalvikVM[localhost:8695]
Thread [<1> main] (Suspended (exception RuntimeException))
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2585
ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2679
ActivityThread.access$2300(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 125
ActivityThread$H.handleMessage(Message) line: 2033
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4627
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 868
ZygoteInit.main(String[]) line: 626
NativeStart.main(String[]) line: not available [native method]
Thread [<6> Binder Thread #2] (Running)
Thread [<5> Binder Thread #1] (Running)
The class-level variable initialization you do, e.g. textGenerateNumber, must be done after the call to to setContentView in the onCreate method.
Update: restructuring the code you should have something like this. Though, the number1 and number2 assignments doesn't make sense since you haven't initialized the text and text2 variables.
....
EditText enternumberofdice;
TextView textGenerateNumber;
private EditText text, text2, text3;
private Button btutorial1;
int number1;
int number2;
ImageView i;
private int myFaceValue;
int myNum;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textGenerateNumber = (TextView) findViewById(R.id.text4);
//BUG: will fail since text/text2 isn't initialized
//number1 = Integer.parseInt(text.getText().toString());
//number2 = Integer.parseInt(text2.getText().toString());
i = new ImageView(this);
i.setAdjustViewBounds(true);
}
final TextView textGenerateNumber = (TextView) findViewById(R.id.text4);
is run before the onCreate method so your views don't exist yet. Add all code to retrieve views after your call to setContentView().