Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i am developing android simple calculator it works fine but only one issue when i press 0 again and again it result 00000000 it should be only one 0 my activity file is:
package com.example.droidcalc;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
enter code here
public class MainActivity extends ActionBarActivity {
int first,second,result;
char operation;
EditText disp;
boolean newValue = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
disp = (EditText) findViewById(R.id.editText1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void button1(View sender){
if(newValue == true)
disp.setText("1");
else
disp.setText(disp.getText().toString() + "1");
newValue = false;
}
public void button2(View sender){
if(newValue == true)
disp.setText("2");
else
disp.setText(disp.getText().toString() + "2");
newValue = false;
}
public void button3(View sender){
if(newValue == true)
disp.setText("3");
else
disp.setText(disp.getText().toString() + "3");
newValue = false;
}
public void button4(View sender){
if(newValue == true)
disp.setText("4");
else
disp.setText(disp.getText().toString() + "4");
newValue = false;
}
public void button5(View sender){
if(newValue == true)
disp.setText("5");
else
disp.setText(disp.getText().toString() + "5");
newValue = false;
}
public void button6(View sender){
if(newValue == true)
disp.setText("6");
else
disp.setText(disp.getText().toString() + "6");
newValue = false;
}
public void button7(View sender){
if(newValue == true)
disp.setText("7");
else
disp.setText(disp.getText().toString() + "7");
newValue = false;
}
public void button8(View sender){
if(newValue == true)
disp.setText("8");
else
disp.setText(disp.getText().toString() + "8");
newValue = false;
}
public void button9(View sender){
if(newValue == true)
disp.setText("9");
else
disp.setText(disp.getText().toString() + "9");
newValue = false;
}
public void button0(View sender){
/*if(newValue == true)
disp.setText("0");
else
disp.setText(disp.getText().toString() + "0");
newValue = false;*/
disp.append("0");
//newValue = true;
}
public void add(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '+';
newValue=true;
}
public void sub(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '-';
newValue=true;
}
public void mul(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '*';
newValue=true;
}
public void div(View sender){
first = Integer.parseInt(disp.getText().toString());
disp.setText("0");
operation = '/';
newValue=true;
}
public void equal(View sender){
second = Integer.parseInt(disp.getText().toString());
switch (operation){
case '+':
result = first + second;
disp.setText(Integer.toString(result));
break;
case '-':
result = first - second;
disp.setText(Integer.toString(result));
break;
case '*':
result = first * second;
disp.setText(Integer.toString(result));
break;
case '/':
result = first / second;
disp.setText(Integer.toString(result));
break;
}
}
public void clr(View sender){
disp.setText("0");
newValue=true;
first = 0;
result = 0;
}
}
You could keep track of what your first number is, and check if it is zero, then do nothing.
if(newValue == true)
disp.setText("0");
else
{
if (!firstNumber.equals("0")
disp.setText(disp.getText().toString() + "0");
newValue = false;
}
Related
I am currently doing a quiz app and the question should be coming out based on the answer. The below is my code. I have been looking online to try various options and cannot find a way to resolve it without making lots of errors. The code for my quiz activity is below. Thanks.
quiz.java
public class quiz extends AppCompatActivity implements View.OnClickListener {
TextView questionNo, question;
RadioGroup rg;
Button quiz_nextBtn, quiz_PrevBtn;
RadioButton rb1, rb2;
int current_question = 0;
int next_question=0;
private quizAdapter[] questionBank = new quizAdapter[]{
new quizAdapter(R.string.q1, R.string.q1_a1, R.string.q1_a2),
new quizAdapter(R.string.q2, R.string.q2_a1, R.string.q2_a2),
new quizAdapter(R.string.q3, R.string.q3_a1, R.string.q3_a2),
new quizAdapter(R.string.q4, R.string.q4_a1, R.string.q4_a2),
new quizAdapter(R.string.q5, R.string.q5_a1, R.string.q5_a2),
new quizAdapter(R.string.q6, R.string.q6_a1, R.string.q6_a2),
new quizAdapter(R.string.q7, R.string.q7_a1, R.string.q7_a2)
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
rg = findViewById(R.id.quiz_answer);
rb1 = findViewById(R.id.rb1);
rb2 = findViewById(R.id.rb2);
questionNo = findViewById(R.id.quiz_questionNo);
question = findViewById(R.id.quiz_question);
quiz_nextBtn = findViewById(R.id.quiz_nextBtn);
quiz_PrevBtn = findViewById(R.id.quiz_PrevBtn);
quiz_nextBtn.setOnClickListener(this);
quiz_PrevBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.quiz_nextBtn:
if(current_question<7){
current_question++;
if(current_question == 6){
question.setText("We are finish");
}
else {
if(current_question == 0 && rb1.isChecked()){
current_question = 1;
}
else if (current_question == 0 && rb2.isChecked()){
current_question = 4;
}
else if (current_question == 1 && rb1.isChecked()){
current_question = 2;
}
else if (current_question == 1 && rb2.isChecked()){
current_question = 3;
}
else if (current_question == 4 && rb1.isChecked()){
current_question = 5;
}
else if (current_question == 4 && rb2.isChecked()){
current_question = 6;
}
updateQuestion();
}
}
break;
case R.id.quiz_PrevBtn:
if (current_question > 0) {
current_question = (current_question - 1) % questionBank.length;
updateQuestion();
}
}
}
private void updateQuestion() {
Log.d("Current", "onClick: " + current_question);
question.setText(questionBank[current_question].getQuestion());
rb1.setText(questionBank[current_question].getRb1());
rb2.setText(questionBank[current_question].getRb2());
}
}
quizAdapter.java
public class quizAdapter {
private int question;
private int rb1;
private int rb2;
public quizAdapter(int question, int rb1, int rb2)
{
this.question = question;
this.rb1 = rb1;
this.rb2 = rb2;
}
public int getQuestion()
{
return question;
}
public int getRb1()
{
return rb1;
}
public int getRb2()
{
return rb2;
}
}
I think a better way would be to use a HashMap and set the quiz answers and questions as key value pairs, for what your trying to implement you will have multiple keys (the value of the current question and option chosen) for a single value(the next question to be shown).
one way to do it would be to create a custom HashMap like below
import java.util.HashMap;
import java.util.Map;
class Key<K1, K2> {
public K1 key1;
public K2 key2;
public Key(K1 key1, K2 key2) {
this.key1 = key1;
this.key2 = key2;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
if (key1 != null ? !key1.equals(key.key1) : key.key1 != null) return false;
if (key2 != null ? !key2.equals(key.key2) : key.key2 != null) return false;
return true;
}
#Override
public int hashCode() {
int result = key1 != null ? key1.hashCode() : 0;
result = 31 * result + (key2 != null ? key2.hashCode() : 0);
return result;
}
#Override
public String toString() {
return "[" + key1 + ", " + key2 + "]";
}
}
class Main
{
public static void main(String[] args) {
// Create a HashMap with Key as key
Map<Key, String> multiKeyMap = new HashMap<>();
// [key1, key2] -> value1
Key k12 = new Key("key1", "key2");
multiKeyMap.put(k12, "value1");
// [key3, key4] -> value2
Key k34 = new Key("key3", "key4");
multiKeyMap.put(k34, "value2");
// print multi-key map
System.out.println(multiKeyMap);
// print value corresponding to key1 and key2
System.out.println(multiKeyMap.get(k12));
}
}
more explanation can be found in this link
https://www.techiedelight.com/implement-map-with-multiple-keys-multikeymap-java/
I'm making a tictactoe app where corresponding messages reflect whose (Player X or Player Y) turn it is and who wins. This worked with no issues. Then I added a feature using Preferences and Fragments, where the user could add specific names to Player X and Player Y and the messages would implement their names. However, now everytime I open the app it remembers a previous session of the game. I think it loads the game as it was the previous time it was paused. How can I get it to load a new game everytime the emulator opens?
I'm sure it's something simple, I'm just new to AndroidStudio and I'm out of ideas. Thank you!
This is my Activity code
package com.asebastian.tictactoe;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
public class TictactoeActivity extends Activity implements OnClickListener {
private Button btn1;
private Button btn2;
private Button btn3;
private Button btn4;
private Button btn5;
private Button btn6;
private Button btn7;
private Button btn8;
private Button btn9;
private TextView txtmsg;
private int r = 0;
private String btn1txt = " ";
private String btn2txt = " ";
private String btn3txt = " ";
private String btn4txt = " ";
private String btn5txt = " ";
private String btn6txt = " ";
private String btn7txt = " ";
private String btn8txt = " ";
private String btn9txt = " ";
private String Xname = " ";
private String Yname = " ";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tictactoe);
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
txtmsg = (TextView)findViewById(R.id.txtMessage);
txtmsg.setText("Player X's turn");
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.tictactoe,menu);
return true;
}
#Override
public void onPause(){
SharedPreferences.Editor editor = prefs.edit();
editor.putString("btn1txt",btn1.getText().toString());
editor.putString("btn2txt",btn2.getText().toString());
editor.putString("btn3txt",btn3.getText().toString());
editor.putString("btn4txt",btn4.getText().toString());
editor.putString("btn5txt",btn5.getText().toString());
editor.putString("btn6txt",btn6.getText().toString());
editor.putString("btn7txt",btn7.getText().toString());
editor.putString("btn8txt",btn8.getText().toString());
editor.putString("btn9txt",btn9.getText().toString());
editor.putInt("r",r);
editor.commit();
super.onPause();
}
#Override
public void onResume(){
super.onResume();
btn1.setText(prefs.getString("btn1txt",""));
btn2.setText(prefs.getString("btn2txt",""));
btn3.setText(prefs.getString("btn3txt",""));
btn4.setText(prefs.getString("btn4txt",""));
btn5.setText(prefs.getString("btn5txt",""));
btn6.setText(prefs.getString("btn6txt",""));
btn7.setText(prefs.getString("btn7txt",""));
btn8.setText(prefs.getString("btn8txt",""));
btn9.setText(prefs.getString("btn9txt",""));
Xname = prefs.getString("pref_edittextX","");
Yname = prefs.getString("pref_edittextY","");
txtmsg.setText(Xname + "'s turn");
r = prefs.getInt("r",0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.new_game){
btn1.setEnabled(true);
btn2.setEnabled(true);
btn3.setEnabled(true);
btn4.setEnabled(true);
btn5.setEnabled(true);
btn6.setEnabled(true);
btn7.setEnabled(true);
btn8.setEnabled(true);
btn9.setEnabled(true);
btn1.setText("");
btn2.setText("");
btn3.setText("");
btn4.setText("");
btn5.setText("");
btn6.setText("");
btn7.setText("");
btn8.setText("");
btn9.setText("");
r = 0;
txtmsg.setText("Player X's turn");
}
else if (item.getItemId() == R.id.action_settings) {
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn1) {
r++;
if ((r % 2) == 0) {
btn1.setText("O");
} else {
btn1.setText("X");
}
}
if (v.getId() == R.id.btn2) {
r++;
if ((r % 2) == 0) {
btn2.setText("O");
} else {
btn2.setText("X");
}
}
if (v.getId() == R.id.btn3) {
r++;
if ((r % 2) == 0) {
btn3.setText("O");
} else {
btn3.setText("X");
}
}
if (v.getId() == R.id.btn4) {
r++;
if ((r % 2) == 0) {
btn4.setText("O");
} else {
btn4.setText("X");
}
}
if (v.getId() == R.id.btn5) {
r++;
if ((r % 2) == 0) {
btn5.setText("O");
} else {
btn5.setText("X");
}
}
if (v.getId() == R.id.btn6) {
r++;
if ((r % 2) == 0) {
btn6.setText("O");
} else {
btn6.setText("X");
}
}
if (v.getId() == R.id.btn7) {
r++;
if ((r % 2) == 0) {
btn7.setText("O");
} else {
btn7.setText("X");
}
}
if (v.getId() == R.id.btn8) {
r++;
if ((r % 2) == 0) {
btn8.setText("O");
} else {
btn8.setText("X");
}
}
if (v.getId() == R.id.btn9) {
r++;
if ((r % 2) == 0) {
btn9.setText("O");
} else {
btn9.setText("X");
}
}
if (Xname.isEmpty() && Yname.isEmpty()) {
if ((r % 2) == 0) {
txtmsg.setText("Player X's turn");
} else {
txtmsg.setText("Player Y's turn");
}
} else {
if ((r % 2) == 0) {
txtmsg.setText(Xname + "'s turn");
} else {
txtmsg.setText(Yname + "'s turn");
}
}
btn1txt = btn1.getText().toString();
btn2txt = btn2.getText().toString();
btn3txt = btn3.getText().toString();
btn4txt = btn4.getText().toString();
btn5txt = btn5.getText().toString();
btn6txt = btn6.getText().toString();
btn7txt = btn7.getText().toString();
btn8txt = btn8.getText().toString();
btn9txt = btn9.getText().toString();
calcWinner();
}
public void calcWinner() {
if (btn1txt == "X" && btn2txt == "X" && btn3txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn2txt == "O" && btn3txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn4txt == "X" && btn5txt == "X" && btn6txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn4txt == "O" && btn5txt == "O" && btn6txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn7txt == "X" && btn8txt == "X" && btn8txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn7txt == "O" && btn8txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn1txt == "X" && btn4txt == "X" && btn7txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn4txt == "O" && btn7txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn2txt == "X" && btn5txt == "X" && btn8txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn2txt == "O" && btn5txt == "O" && btn8txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn3txt == "X" && btn6txt == "X" && btn9txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn3txt == "O" && btn6txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn1txt == "X" && btn5txt == "X" && btn9txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn1txt == "O" && btn5txt == "O" && btn9txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (btn3txt == "X" && btn5txt == "X" && btn7txt == "X") {
txtmsg.setText("Player X wins!");
disableButtons();
}
if (btn3txt == "O" && btn5txt == "O" && btn7txt == "O") {
txtmsg.setText("Player Y wins!");
disableButtons();
}
if (r == 9) {
txtmsg.setText("Tie Game!");
disableButtons();
}
}
public void disableButtons(){
btn1.setEnabled(false);
btn2.setEnabled(false);
btn3.setEnabled(false);
btn4.setEnabled(false);
btn5.setEnabled(false);
btn6.setEnabled(false);
btn7.setEnabled(false);
btn8.setEnabled(false);
btn9.setEnabled(false);
}
}
This is my Fragment code:
package com.asebastian.tictactoe;
import android.os.Bundle;
import android.preference.PreferenceFragment;
/**
* A simple {#link Fragment} subclass.
*/
public class SettingsFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
This is the code to add the Fragment:
package com.asebastian.tictactoe;
import android.app.Activity;
import android.os.Bundle;
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,new
SettingsFragment()).commit();
}
}
So i guess by Storing/Restoring to/from SharedPreferences that you are trying to save the state of the activity!
And that is wrong (unless you deleted the SharedPreferences saved content in onDestroy()) becuase every time you open the app again the on onResume() will be called and hence state will be restored from SharedPreferences.
See The Activity Lifecycle
So, The solution is not to use SharedPreferences to save/restore activity state but instead override the methods onSaveInstanceState & onRestoreInstanceState like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString("btn1txt",btn1.getText().toString());
// and So on
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
and
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
btn1.setText(savedInstanceState.getString("btn1txt"));
// and so on
}
Note:
The system calls onRestoreInstanceState() after the onStart()method.
Also The system calls onRestoreInstanceState() only if there is a saved state to restore.
See Saving and restoring activity state
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wrote a code for tictactoe game, however it it showing me this error at run time:
Exception: Unable to instantiate activity ComponentInfo{com.tictactoe.ajaykulkarni.tictactoe/com.tictactoe.ajaykulkarni.tictactoe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
My MainActivity is:
package com.tictactoe.ajaykulkarni.tictactoe;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//protected DrawerLayout mdrawerLayout;
/*Game plan*/
private TicTacToeGame mGame;
// Buttons making up the board
private Button mBoardButtons[];
private Button mNewGame;
// Various text displayed
private TextView mInfoTextView;
private TextView mPlayerOneCount;
private TextView mTieCount;
private TextView mPlayerTwoCount;
private TextView mPlayerOneText;
private TextView mPlayerTwoText;
private int mPlayerOneCounter = 0;
private int mTieCounter = 0;
private int mPlayerTwoCounter = 0;
private boolean mPlayerOneFirst = true;
private boolean mIsSinglePlayer = false;
private boolean mIsPlayerOneTurn = true;
private boolean mGameOver = false;
boolean mGameType = getIntent().getExtras().getBoolean("gameType");
private Button[] getmBoardButtons() {
mBoardButtons = new Button[mGame.getBOARD_SIZE()];
mBoardButtons[0] = (Button) findViewById(R.id.one);
mBoardButtons[1] = (Button) findViewById(R.id.two);
mBoardButtons[2] = (Button) findViewById(R.id.three);
mBoardButtons[3] = (Button) findViewById(R.id.four);
mBoardButtons[4] = (Button) findViewById(R.id.five);
mBoardButtons[5] = (Button) findViewById(R.id.six);
mBoardButtons[6] = (Button) findViewById(R.id.seven);
mBoardButtons[7] = (Button) findViewById(R.id.eight);
mBoardButtons[8] = (Button) findViewById(R.id.nine);
addListenerOnButton();
// setup the textviews
mInfoTextView = (TextView) findViewById(R.id.information);
mPlayerOneCount = (TextView) findViewById(R.id.humanCount);
mTieCount = (TextView) findViewById(R.id.tiesCount);
mPlayerTwoCount = (TextView) findViewById(R.id.androidCount);
mPlayerOneText = (TextView) findViewById(R.id.human);
mPlayerTwoText = (TextView) findViewById(R.id.android);
// set the initial counter display values
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mTieCount.setText(Integer.toString(mTieCounter));
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
// create a new game object
mGame = new TicTacToeGame();
// start a new game
startNewGame(mGameType);
return mBoardButtons;
}
//mBoardButtons = new Button[mGame.getBOARD_SIZE()];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.play) {
Log.d("DEBUG", "Play option selected!");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
} else if (id == R.id.exit) {
Log.d("DEBUG", "Exit option selected!");
MainActivity.this.finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void addListenerOnButton(){
mNewGame = (Button) findViewById(R.id.NewGame);
mNewGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startNewGame(mIsSinglePlayer);
}
});
}
// start a new game
// clears the board and resets all buttons / text
// sets game over to be false
private void startNewGame(boolean isSingle)
{
this.mIsSinglePlayer = isSingle;
mGame.clearBoard();
for (int i = 0; i < mBoardButtons.length; i++)
{
mBoardButtons[i].setText("");
mBoardButtons[i].setEnabled(true);
mBoardButtons[i].setOnClickListener(new ButtonClickListener(i));
///mBoardButtons[i].setBackgroundDrawable(getResources().getDrawable(R.drawable.blank));
}
if (mIsSinglePlayer)
{
mPlayerOneText.setText("User:");
mPlayerTwoText.setText("Android:");
if (mPlayerOneFirst)
{
mInfoTextView.setText(R.string.first_human);
mPlayerOneFirst = false;
}
else
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
mPlayerOneFirst = true;
}
}
mGameOver = false;
}
private class ButtonClickListener implements View.OnClickListener
{
int location;
public ButtonClickListener(int location)
{
this.location = location;
}
public void onClick(View view)
{
if (!mGameOver)
{
if (mBoardButtons[location].isEnabled())
{
if (mIsSinglePlayer)
{
setMove(mGame.PLAYER_ONE, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(mGame.PLAYER_TWO, move);
winner = mGame.checkForWinner();
}
if (winner == 0)
mInfoTextView.setText(R.string.turn_human);
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner == 2)
{
mInfoTextView.setText(R.string.result_human_wins);
mPlayerOneCounter++;
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mGameOver = true;
}
else
{
mInfoTextView.setText(R.string.result_android_wins);
mPlayerTwoCounter++;
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
mGameOver = true;
}
}
else
{
if (mIsPlayerOneTurn)
setMove(mGame.PLAYER_ONE, location);
else
setMove(mGame.PLAYER_TWO, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
if (mIsPlayerOneTurn)
{
mInfoTextView.setText(R.string.turn_player_two);
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_one);
mIsPlayerOneTurn = true;
}
}
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner == 2)
{
mInfoTextView.setText(R.string.result_player_one_wins);
mPlayerOneCounter++;
mPlayerOneCount.setText(Integer.toString(mPlayerOneCounter));
mGameOver = true;
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.result_player_two_wins);
mPlayerTwoCounter++;
mPlayerTwoCount.setText(Integer.toString(mPlayerTwoCounter));
mGameOver = true;
mIsPlayerOneTurn = true;
}
}
}
}
}
}
// set move for the current player
private void setMove(char player, int location)
{
mGame.setMove(player, location);
mBoardButtons[location].setEnabled(false);
if (player == mGame.PLAYER_ONE)
mBoardButtons[location].setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_x));
else
mBoardButtons[location].setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_o));
}
}
and TicTacToeGame.class is:
package com.tictactoe.ajaykulkarni.tictactoe;
/**
* Created by Ajay Kulkarni-enEXL on 02/16/2017.
*/
import java.util.Random;
public class TicTacToeGame {
private char mBoard[];
private final static int BOARD_SIZE = 9;
public static final char PLAYER_ONE = 'X';
public static final char PLAYER_TWO = '0';
public static final char EMPTY_SPACE = ' ';
private Random mRand;
public static int getBOARD_SIZE() {
// Return the size of the board
return BOARD_SIZE;
}
public TicTacToeGame(){
mBoard = new char[BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
mBoard[i] = EMPTY_SPACE;
mRand = new Random();
}
// Clear the board of all X's and O's
public void clearBoard()
{
for (int i = 0; i < BOARD_SIZE; i++)
{
mBoard[i] = EMPTY_SPACE;
}
}
// set the given player at the given location on the game board.
// the location must be available, or the board will not be changed.
public void setMove(char player, int location)
{
mBoard[location] = player;
}
// Return the best move for the computer to make. You must call setMove()
// to actually make the computer move to that location.
public int getComputerMove()
{
int move;
// First see if there's a move O can make to win
for (int i = 0; i < getBOARD_SIZE(); i++)
{
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
{
char curr = mBoard[i];
mBoard[i] = PLAYER_TWO;
if (checkForWinner() == 3)
{
setMove(PLAYER_TWO, i);
return i;
}
else
mBoard[i] = curr;
}
}
// See if there's a move O can make to block X from winning
for (int i = 0; i < getBOARD_SIZE(); i++)
{
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
{
char curr = mBoard[i];
mBoard[i] = PLAYER_ONE;
if (checkForWinner() == 2)
{
setMove(PLAYER_TWO, i);
return i;
}
else
mBoard[i] = curr;
}
}
// Generate random move
do
{
move = mRand.nextInt(getBOARD_SIZE());
} while (mBoard[move] == PLAYER_ONE || mBoard[move] == PLAYER_TWO);
setMove(PLAYER_TWO, move);
return move;
}
// Check for a winner and return a status value indicating who has won.
// Return 0 if no winner or tie yet, 1 if it's a tie, 2 if X won, or 3
// if O won.
public int checkForWinner()
{
// Check horizontal wins
for (int i = 0; i <= 6; i += 3)
{
if (mBoard[i] == PLAYER_ONE &&
mBoard[i+1] == PLAYER_ONE &&
mBoard[i+2] == PLAYER_ONE)
return 2;
if (mBoard[i] == PLAYER_TWO &&
mBoard[i+1] == PLAYER_TWO &&
mBoard[i+2] == PLAYER_TWO)
return 3;
}
// Check vertical wins
for (int i = 0; i <= 2; i++)
{
if (mBoard[i] == PLAYER_ONE &&
mBoard[i+3] == PLAYER_ONE &&
mBoard[i+6] == PLAYER_ONE)
return 2;
if (mBoard[i] == PLAYER_TWO &&
mBoard[i+3] == PLAYER_TWO &&
mBoard[i+6] == PLAYER_TWO)
return 3;
}
// Check for diagonal wins
if ((mBoard[0] == PLAYER_ONE &&
mBoard[4] == PLAYER_ONE &&
mBoard[8] == PLAYER_ONE) ||
mBoard[2] == PLAYER_ONE &&
mBoard[4] == PLAYER_ONE &&
mBoard[6] == PLAYER_ONE)
return 2;
if ((mBoard[0] == PLAYER_TWO &&
mBoard[4] == PLAYER_TWO &&
mBoard[8] == PLAYER_TWO) ||
mBoard[2] == PLAYER_TWO &&
mBoard[4] == PLAYER_TWO &&
mBoard[6] == PLAYER_TWO)
return 3;
// Check for a tie
for (int i = 0; i < getBOARD_SIZE(); i++)
{
// if we find a number, then no one has won yet
if (mBoard[i] != PLAYER_ONE && mBoard[i] != PLAYER_TWO)
return 0;
}
// If we make it through the previous loop, all places are taken, so it's a tie
return 1;
}
}
How can I fix that error?
You are trying to get extras from a field in the Activity, i.e. you are trying to get the extras before the Activity is created. If you get the extras from the onCreate method, it won't be a null value.
Example:
boolean mGameType;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGameType = getIntent().getExtras().getBoolean("gameType");
...
}
EDIT: If you want to send extra from one Activity to another, you should start it this way:
startActivity(new Intent(SenderActivity.this, MainActivity.class)
.putExtra("gameType", true));
i have downloaded a android game program from internet and i tried to run it gives error on Method and goto statement.
i know goto statement is not support in java..
i dont know they are any other tool or language .
i want to know which technology or tool or language they are used.
this is the code
package com.infraredpixel.drop.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.*;
import android.util.Log;
import android.view.*;
import com.infraredpixel.drop.*;
import java.lang.reflect.Method;
import java.util.List;
// Referenced classes of package com.infraredpixel.drop.activities:
// ProfilingActivity, DebugActivity, MainMenuActivity
public class OpenGLDropActivity extends Activity
{
public OpenGLDropActivity()
{
}
private int getDefaultRotation()
{
int i;
WindowManager windowmanager;
Method amethod[];
String s;
int j;
i = 0;
windowmanager = (WindowManager)getSystemService("window");
amethod = windowmanager.getDefaultDisplay().getClass().getDeclaredMethods();
s = new String("getRotation");
j = amethod.length;
_L2:
Method method = null;
Display display;
if(i < j)
{
label0:
{
Method method1 = amethod[i];
Log.d("Methods", method1.getName());
if(!method1.getName().equals(s))
break label0;
method = method1;
}
}
display = windowmanager.getDefaultDisplay();
if(method != null)
{
int k;
try
{
k = ((Integer)method.invoke(display, new Object[0])).intValue();
}
catch(Exception exception)
{
return 0;
}
return k;
} else
{
return display.getOrientation();
}
i++;
if(true){ goto _L2;} else{ goto _L1;}
_L1:
}
protected void handleScore()
{
int i;
int j;
SharedPreferences sharedpreferences;
int k;
String s;
i = (int)(0.49F + (float)_StatusManager.dropDist());
j = (int)(0.49F + (float)_StatusManager.getStars());
sharedpreferences = getSharedPreferences("DropSettings", 0);
k = sharedpreferences.getInt("highScore", -1);
s = "";
if(2 != _ControlMode) goto _L2; else goto _L1;
_L1:
s = "tiltHighScore";
_L4:
int l = sharedpreferences.getInt(s, 0);
if(i + j > k && i + j > l)
{
_DeathDetector.setCurrentHighScore(i + j);
android.content.SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("highScore", -1);
editor.putInt(s, i + j);
editor.commit();
}
return;
_L2:
if(1 == _ControlMode || _ControlMode == 0)
s = "touchHighScore";
if(true) goto _L4; else goto _L3
_L3:
}
public void onCreate(Bundle bundle)
{
SharedPreferences sharedpreferences;
super.onCreate(bundle);
sharedpreferences = getSharedPreferences("DropSettings", 0);
spriteRenderer = new GLRenderer(getApplicationContext());
int i = sharedpreferences.getInt("fullScreenWidth", 480);
widthPixels = i;
int j = sharedpreferences.getInt("fullScreenHeight", 640);
RectF rectf = new RectF(0.0F, j, i, 0.0F);
boolean flag = sharedpreferences.getBoolean("useVibration", true);
boolean flag1 = sharedpreferences.getBoolean("godMode", false);
int k = sharedpreferences.getInt("ballType", 0);
int l = Math.max(sharedpreferences.getInt("highScore", 0), Math.max(sharedpreferences.getInt("tiltHighScore", 0), sharedpreferences.getInt("touchHighScore", 0)));
_ControlMode = sharedpreferences.getInt("controlMode", 2);
boolean flag2 = sharedpreferences.getBoolean("testModeDropSettings", false);
boolean flag3 = sharedpreferences.getBoolean("testModeMainSettings", false);
DropSettingsGroup adropsettingsgroup[];
DropManager dropmanager;
Handler handler;
Runnable runnable;
boolean flag4;
boolean flag5;
boolean flag6;
Runnable runnable1;
int k1;
float f;
float f1;
float f2;
float f3;
float f4;
float f5;
if(flag2)
{
adropsettingsgroup = new DropSettingsGroup[1];
adropsettingsgroup[0] = new DropSettingsGroup();
adropsettingsgroup[0].scrollSpeed = -sharedpreferences.getInt("scrollSpeed", getResources().getInteger(0x7f010000));
adropsettingsgroup[0].platformHeight = sharedpreferences.getInt("platformHeight", getResources().getInteger(0x7f050006));
adropsettingsgroup[0].platformHoleWidth = 70;
adropsettingsgroup[0].yAccel = sharedpreferences.getInt("yAcceleration", getResources().getInteger(0x7f050001));
adropsettingsgroup[0].yMaxSpeed = sharedpreferences.getInt("yMaxSpeed", getResources().getInteger(0x7f050002));
adropsettingsgroup[0].yBounce = 0.7F;
adropsettingsgroup[0].xAccel = sharedpreferences.getInt("xAcceleration", getResources().getInteger(0x7f050003));
adropsettingsgroup[0].xMaxSpeed = sharedpreferences.getInt("xMaxSpeed", getResources().getInteger(0x7f050004));
adropsettingsgroup[0].xBounce = sharedpreferences.getFloat("xBounce", 0.5F);
adropsettingsgroup[0].duration = 20F;
adropsettingsgroup[0].transitionTiles = false;
} else
if(_ControlMode == 0 || _ControlMode == 1)
adropsettingsgroup = DropSettingsGroup.getTestSettingsA();
else
adropsettingsgroup = DropSettingsGroup.getTestSettingsB();
dropmanager = new DropManager(rectf, adropsettingsgroup);
_DropManager = dropmanager;
if(flag)
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, (Vibrator)getSystemService("vibrator"));
else
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, null);
_StatusManager = new StatusManager();
_StatusManager.init(spriteRenderer, getBaseContext(), (float)widthPixels / 320F, rectf);
_GameOverLayer = new GameOverLayer();
_GameOverLayer.init(spriteRenderer, rectf);
handler = new Handler();
runnable = new Runnable() {
public void run()
{
handleScore();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
_DeathDetector = new DeathDetector(rectf, _DropManager, _StatusManager, _GameOverLayer, handler, runnable);
_DeathDetector.setCurrentHighScore(l);
if(_ControlMode != 0) goto _L2; else goto _L1
_L1:
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
_L4:
if(flag3)
{
k1 = sharedpreferences.getInt("movingAverageValue", 10);
f = sharedpreferences.getFloat("sensorCutoffX", 5F);
f1 = sharedpreferences.getFloat("inAirBreak", 0.3F);
f2 = sharedpreferences.getFloat("inAirMemory", 0.08F);
f3 = sharedpreferences.getFloat("gameSpeed", 1.0F);
f4 = sharedpreferences.getFloat("tiltAccelFactor", 1.0F);
f5 = sharedpreferences.getFloat("tiltAccelDiffFactor", 1.0F);
MySensorEventListener.SENSOR_CUTOFF_X = f;
MySensorEventListener.kFilteringFactor = 1.0F / (float)k1;
MySensorEventListener.accelFactor = f4;
MySensorEventListener.diffFactor = f5;
ControlComponent.inAirMovementFactor = 1.0F - f1;
ControlComponent.inAirMemoryMovementFactor = f2;
DropManager.speed = f3;
}
flag4 = sharedpreferences.getBoolean("canUseDrawTexture", true);
flag5 = sharedpreferences.getBoolean("canUseVBO", true);
GLSprite.shouldUseDrawTexture = flag4;
spriteRenderer.setVertMode(flag5);
ProfileRecorder.sSingleton.resetAll();
_StatusManager.setBall(_DropManager.getBall());
_DropManager.getCollisionComponent().setStatusManager(_StatusManager);
_ControlComponent = _DropManager.getControlComponent();
spriteRenderer.endInit();
simulationRuntime = new MainLoop();
if(!flag1)
simulationRuntime.addGameObject(_DeathDetector);
simulationRuntime.addGameObject(_DropManager);
simulationRuntime.addGameObject(_StatusManager);
simulationRuntime.addGameObject(_GameOverLayer);
setContentView(0x7f030001);
flag6 = sharedpreferences.getBoolean("glSafeMode", false);
mGLSurfaceView = (GLSurfaceView)findViewById(0x7f08001f);
mGLSurfaceView.setRenderer(spriteRenderer);
mGLSurfaceView.setEvent(simulationRuntime);
mGLSurfaceView.setSafeMode(flag6);
runnable1 = new Runnable() {
public void run()
{
android.content.SharedPreferences.Editor editor = getSharedPreferences("DropSettings", 0).edit();
editor.putString("testError", mGLSurfaceView.getLastError());
editor.commit();
Intent intent = new Intent(getApplicationContext(), com/infraredpixel/drop/activities/MainMenuActivity);
intent.putExtra("justCrashed", true);
startActivity(intent);
finish();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
mGLSurfaceView.setErrorMethod(runnable1);
sResetFlag = false;
Runtime.getRuntime().gc();
return;
_L2:
if(_ControlMode == 1)
{
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
} else
if(_ControlMode == 2)
{
mWakeLock = ((PowerManager)getSystemService("power")).newWakeLock(10, "Drop");
mWakeLock.acquire();
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i1 = list.size();
Sensor sensor = null;
if(i1 > 0)
sensor = (Sensor)list.get(0);
int j1 = getDefaultRotation();
MySensorEventListener mysensoreventlistener = new MySensorEventListener(_DropManager, _DeathDetector, j1);
_MyMotionListener = mysensoreventlistener;
sensormanager.registerListener(_MyMotionListener, sensor, 1);
MySensorEventListener.SENSOR_CUTOFF_X = 8.3F + 4.5F * (1.0F - sharedpreferences.getFloat("tiltSensitivity", 0.3F));
MySensorEventListener.kFilteringFactor = 1.0F;
ControlComponent.inAirMovementFactor = 1.0F;
ControlComponent.inAirMemoryMovementFactor = 0.0F;
DropManager.speed = 1.0F;
MySensorEventListener.accelFactor = 1.0F;
MySensorEventListener.diffFactor = 2.0F;
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onCreateOptionsMenu(Menu menu)
{
if(!TESTING)
{
return super.onCreateOptionsMenu(menu);
} else
{
menu.add(0, 1, 0, "profile");
menu.add(0, 2, 0, "debug/test");
menu.add(0, 3, 0, "main menu");
menu.add(0, 4, 0, "pause/resume");
return true;
}
}
protected void onDestroy()
{
if(mWakeLock != null && mWakeLock.isHeld())
{
mWakeLock.release();
mWakeLock = null;
}
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
{
sensormanager.unregisterListener(_MyMotionListener);
_MyMotionListener = null;
}
mGLSurfaceView = null;
_DropManager = null;
_StatusManager = null;
_DeathDetector = null;
_GameOverLayer = null;
simulationRuntime = null;
_ControlComponent = null;
super.onDestroy();
}
public boolean onKeyDown(int i, KeyEvent keyevent)
{
if(_ControlMode == 1)
{
if(i == 82 || i == 21)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveLeft();
_LeftPressed = true;
return true;
}
if(i == 84 || i == 22)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveRight();
_RightPressed = true;
return true;
} else
{
return super.onKeyDown(i, keyevent);
}
} else
{
return super.onKeyDown(i, keyevent);
}
}
public boolean onKeyUp(int i, KeyEvent keyevent)
{
if(_ControlMode != 1)
break MISSING_BLOCK_LABEL_102;
if(i != 82 && i != 21) goto _L2; else goto _L1
_L1:
boolean flag;
_LeftPressed = false;
flag = true;
_L5:
if(!_LeftPressed && !_RightPressed)
_ControlComponent.stopMovement();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
if(flag)
return true;
else
return super.onKeyUp(i, keyevent);
_L2:
if(i == 84) goto _L4; else goto _L3
_L3:
flag = false;
if(i != 22) goto _L5; else goto _L4
_L4:
_RightPressed = false;
flag = true;
goto _L5
return super.onKeyUp(i, keyevent);
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
switch(menuitem.getItemId())
{
default:
return false;
case 1: // '\001'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/ProfilingActivity));
return true;
case 2: // '\002'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/DebugActivity));
return true;
case 3: // '\003'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/MainMenuActivity));
return true;
case 4: // '\004'
break;
}
if(simulationRuntime.isPaused())
{
simulationRuntime.unPause();
mGLSurfaceView.onResume();
} else
{
simulationRuntime.pause();
mGLSurfaceView.onPause();
}
return true;
}
protected void onPause()
{
mGLSurfaceView.onPause();
if(mWakeLock != null && mWakeLock.isHeld())
mWakeLock.release();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
sensormanager.unregisterListener(_MyMotionListener);
}
super.onPause();
}
protected void onResume()
{
mGLSurfaceView.onResume();
if(sResetFlag)
{
handleScore();
_DropManager.reset();
sResetFlag = false;
}
if(mWakeLock != null && !mWakeLock.isHeld())
mWakeLock.acquire();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i = list.size();
Sensor sensor = null;
if(i > 0)
sensor = (Sensor)list.get(0);
sensormanager.registerListener(_MyMotionListener, sensor, 1);
}
super.onResume();
}
protected void onStart()
{
super.onStart();
}
public boolean onTouchEvent(MotionEvent motionevent)
{
if(!_GameOverLayer.isEnabled()) goto _L2; else goto _L1
_L1:
boolean flag;
int k = motionevent.getAction();
flag = false;
if(k == 0)
{
_GameOverLayer.doNextStep();
flag = true;
}
_L4:
int i;
ControlComponent controlcomponent;
int j;
float f;
try
{
Thread.sleep(20L);
}
catch(InterruptedException interruptedexception)
{
interruptedexception.printStackTrace();
return flag;
}
return flag;
_L2:
i = _ControlMode;
flag = false;
if(i == 0)
{
controlcomponent = _ControlComponent;
flag = false;
if(controlcomponent != null)
{
j = motionevent.getAction();
f = motionevent.getX();
if(j == 2)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
flag = true;
} else
if(j == 0)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
flag = true;
} else
{
flag = false;
if(j == 1)
{
_ControlComponent.stopMovement();
flag = true;
}
}
}
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onTrackballEvent(MotionEvent motionevent)
{
if(_ControlMode == 1)
{
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
float f = motionevent.getX();
_ControlComponent.autoBreak = true;
_ControlComponent.moveSideways(3.5F * f);
return true;
} else
{
return super.onTrackballEvent(motionevent);
}
}
public static final int CONTROL_MODE_KEYS = 1;
public static final int CONTROL_MODE_TILT = 2;
public static final int CONTROL_MODE_TOUCH = 0;
public static final String PREFS_NAME = "DropSettings";
private static boolean TESTING = false;
protected static boolean sResetFlag;
private ControlComponent _ControlComponent;
private int _ControlMode;
DeathDetector _DeathDetector;
DropManager _DropManager;
private GameOverLayer _GameOverLayer;
private boolean _LeftPressed;
MySensorEventListener _MyMotionListener;
private boolean _RightPressed;
StatusManager _StatusManager;
private GLSurfaceView mGLSurfaceView;
protected android.os.PowerManager.WakeLock mWakeLock;
MainLoop simulationRuntime;
private GLRenderer spriteRenderer;
private int widthPixels;
}
the program gives many error..
What you have here is not real Java, and you should not be using it as an example to learn Java programming from.
So what actually is this stuff?
It looks to me like someone has attempted to decompile an Android app, and the decompiler was unable to turn some of the code back into real Java. Instead, the decompiler has inserted goto "statements" in an attempt to convey the meaning of the code to the (human) reader.
This is obviously the output of a decompilation. While this is a good way to gain specific insight into programs, it's not beginner-level material just like #Jägermeister said, because jads lack the clarity and brevity of standard Java source code.
For example, the goto keyword is not supported on the source code side of the JDK, but it is used inside the byte code in the form of jump instructions. Breaks, continues, loops, ifs etc. may be turned into jumps in surjective ways. The decompiler cannot restore the original construct and resorts to just putting the gotos and labels in the jad. It's up to the programmer to restore reasonable, compilable flow constructs.
That said, the comprehensive answer to your question would be: it's java, but rather an image of the byte code stuff, not a strict restoration of the source code, and requires a manual touch-up to be compilable again.
I needed help with this but didn't really find clear instructions. How to create a button that will fast forward and rewind current song on hold.
private Handler repeatUpdateHandler = new Handler();
public int mValue; //increment
private boolean mAutoIncrement = false; //for fast foward in real time
private boolean mAutoDecrement = false; // for rewind in real time
private class RptUpdater implements Runnable {
public void run() {
if( mAutoIncrement ){
mValue += 30; //change this value to control how much to forward
mediaPlayer.seekTo(getCurrentPosition()+ mValue);
repeatUpdateHandler.postDelayed( new RptUpdater(), 50 );
} else if( mAutoDecrement ){
mValue -= 30; //change this value to control how much to rewind
seekTo(getCurrentPosition()- mValue);
repeatUpdateHandler.postDelayed( new RptUpdater(), 50 );
}
}
}
btnPrev.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
v.setPressed(true);
mAutoDecrement = true;
repeatUpdateHandler.post( new RptUpdater() );
return false;
}
else if(event.getAction() == MotionEvent.ACTION_UP) {
v.setPressed(false);
if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL)
&& mAutoDecrement ){
mAutoDecrement = false;
}
return false;
}
return false;
}
});
btnNext.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
v.setPressed(true);
mAutoIncrement = true;
repeatUpdateHandler.post( new RptUpdater() );
return false;
}
else if(event.getAction() == MotionEvent.ACTION_UP) {
v.setPressed(false);
if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL)
&& mAutoIncrement ){
mAutoIncrement = false;
}
return false;
}
return false;
}
});