So I recently made my first app and went out to test it. When I opened the app on my phone I got 2 problems. The menu off my app does have 3 buttons, 1 to start a "1player game" 1 to start a "2player game" and 1 to exit the app. When I press the button to play a "1player game" there happens nothing. When I press the "2player game" button, the app closes with the error "unfortunately testjk was closed". I have literally no idea what I did wrong in my code. I also have no erros in my problems tab. Some help would be appreciated.
MainMenuScreen.java:
package com.wouter.testjk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainMenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_menu);
//1player
findViewById(R.id.two_player).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("DEBUG", "One Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", true);
startActivityForResult(intent, 0);
}
});
//2players
findViewById(R.id.two_player).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("DEBUG", "Two Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", false);
startActivityForResult(intent, 0);
}
});
//exit game
findViewById(R.id.exit_game).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("DEBUG", "Exit Game Button Pressed!");
MainMenuScreen.this.finish();
}
});
}
}
MainActivity.java:
package com.wouter.testjk;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.wouter.testjk.R;
public class MainActivity extends Activity implements OnClickListener{
private TicTacToeGame mGame;
private Button mBoardButtons[];
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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
boolean mGameType = getIntent().getExtras().getBoolean("gametype");
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);
Button mTen = (Button) findViewById(R.id.ten);
mTen.setOnClickListener(this);
Button mEleven = (Button) findViewById(R.id.eleven);
mEleven.setOnClickListener(this);
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);
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mTieCount.setText(Integer.toString(mTieCounter));
mPlayeroneCount.setText(Integer.toString(mPlayertwoCounter));
mGame = new TicTacToeGame();
startNewGame(mGameType);
}
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));
}
if (mIsSinglePlayer)
{
mPlayeroneText.setText("speler: ");
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(TicTacToeGame.PLAYER_TWO, move);
mPlayeroneFirst = true;
}
}
else
{
mPlayeroneText.setText("speler 1: ");
mPlayertwoText.setText("speler 2: ");
if (mPlayeroneFirst)
{
mInfoTextView.setText(R.string.turn_player_one);
mPlayeroneFirst = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_two);
mPlayeroneFirst = true;
}
}
mGameOver = false;
}
private class ButtonClickListener implements View.OnClickListener
{
int location;
public ButtonClickListener(int location)
{
this.location = location;
}
#Override
public void onClick(View view) {
if (!mGameOver)
{
if(mBoardButtons[location].isEnabled())
{
if(mIsSinglePlayer)
{
setMove(TicTacToeGame.PLAYER_ONE, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(TicTacToeGame.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 if (winner ==3)
{
mInfoTextView.setText(R.string.result_android_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
else
{
if(mIsPlayerOneTurn)
{
setMove(TicTacToeGame.PLAYER_ONE, location);
}
else
{
setMove(TicTacToeGame.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.player_one_wins);
mPlayeroneCounter++;
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mGameOver = true;
}
else if (winner ==3)
{
mInfoTextView.setText(R.string.player_two_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
}
}
}
}
private void setMove(char player, int location)
{
mGame.setMove(player,location);
mBoardButtons[location].setEnabled(false);
if (player == TicTacToeGame.PLAYER_ONE)
mBoardButtons[location].setTextColor(Color.GREEN);
else
{
mBoardButtons[location].setTextColor(Color.RED);
}
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.ten:
startNewGame(mIsSinglePlayer);
return;
case R.id.eleven:
MainActivity.this.finish();
return;
}
}
}
manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wouter.testjk"
android:versionCode="3"
android:versionName="3" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainMenuScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
LogCat: http://textuploader.com/on1k --------
http://imgur.com/d8662NO -----------
I have no idea how else I should upload this
You are assigning both OnClickListeners to the same button R.id.two_player. That is, change the first one to one_player, as
// 1player
findViewById(R.id.one_player).setOnClickListener(new View.OnClickListener() {
// (...)
});
//2players
findViewById(R.id.two_player).setOnClickListener(new View.OnClickListener() {
// (...)
});
EDIT: as I see in the logcat, and also correctly pointed by Spidy in the comments, you need to declare your activity in the manifest.
11-15 23:45:28.227: E/AndroidRuntime(6056): FATAL EXCEPTION: main
11-15 23:45:28.227: E/AndroidRuntime(6056): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.wouter.testjk/com.wouter.testjk.TicTacToeGame}; have you declared this activity in your AndroidManifest.xml?
EDIT2: It's pretty clear from the logs:
11-16 00:39:09.867: E/AndroidRuntime(7124): FATAL EXCEPTION: main
11-16 00:39:09.867: E/AndroidRuntime(7124): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.wouter.testjk/com.wouter.testjk.TicTacToeGame}: java.lang.ClassCastException: com.wouter.testjk.TicTacToeGame cannot be cast to android.app.Activity
You are trying to instantiate the class TicTacToeGame as an activity, but it is not. I guess you wanted to go to the MainActivity. In that case, you must change your intent to something like this
Intent intent = new Intent(MainMenuScreen.this, MainActivity.class);
Hope it helps.
Related
I am completely new to Android Studio and just learned Object-oriented programming. My project requires me to build something on open-source code. I added a new menu item to a menu and want to start another activity once the user clicks the menu item with id: plot. I followed a recipe on the internet but got an error with it. It said 'method call expected' which means Terminal Fragment may be a method. I got confused, as I thought it is a class(an activity). Could anyone give me instructions to start an activity (turn to the next page with a different activity) in this case? What will be the simplest way to do this? Much Appreciated.
I added this in onOptionsItemSelected(MenuItem item).
if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}
TerminalFragment.java (entire code)
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(TerminalFragment.this, MainActivity2.class);
startActivity(intent);
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {
receive(data);
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
menu_terminal.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/plot"
android:title="PLOTDATA"
app:showAsAction="always" />
<item
android:id="#+id/clear"
android:icon="#drawable/ic_delete_white_24dp"
android:title="Clear"
app:showAsAction="always" />
<item
android:id="#+id/newline"
android:title="Newline"
app:showAsAction="never" />
<item
android:id="#+id/hex"
android:title="HEX Mode"
android:checkable="true"
app:showAsAction="never" />
</menu>
Here, TerminalFragment is a fragment, not an activity. And so, instead of using TerminalFragment.this in new Intent(), you should use getActivity().
So, the final code would look something like this:
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
You can also check this: Intent from Fragment to Activity
I am currently developing an Android Game app (Memory Game), in which the objective of the game is to match 2 identical images until all the images in the grid are matched. Only 2 Images are revealed at a time, and if both images match, they will stay, and if they don't, they will flip back. I am still a beginner in Java.
package jimosman311.gmail.com.j39712_co5025_asg;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.os.Handler;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.util.Locale;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class GameActivity extends AppCompatActivity implements
View.OnClickListener {
int count;
Button[] Buttons = new Button[9];
int[] myImageArr = new int[]{R.drawable.apple, R.drawable.apple, R.drawable.grape, R.drawable.grape, R.drawable.orange, R.drawable.orange, R.drawable.watermelon, R.drawable.watermelon};
int[] click1, click2;
Handler handler;
Runnable r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
handler = new Handler();
r = new Runnable() {
public void run() {
flipbacktimer();
}
};
//Randomize Images
randomize(myImageArr, myImageArr.length);
//Reference FindViewID
Buttons[0] = (Button) findViewById(R.id.one);
Buttons[1] = (Button) findViewById(R.id.two);
Buttons[2] = (Button) findViewById(R.id.three);
Buttons[3] = (Button) findViewById(R.id.four);
Buttons[4] = (Button) findViewById(R.id.five);
Buttons[5] = (Button) findViewById(R.id.six);
Buttons[6] = (Button) findViewById(R.id.seven);
Buttons[7] = (Button) findViewById(R.id.eight);
Buttons[8] = (Button) findViewById(R.id.nine);
Button newgameButton = (Button) findViewById(R.id.newgamebutton2);
//Set OnClick Listener
Buttons[0].setOnClickListener(this);
Buttons[1].setOnClickListener(this);
Buttons[2].setOnClickListener(this);
Buttons[3].setOnClickListener(this);
Buttons[4].setOnClickListener(this);
Buttons[5].setOnClickListener(this);
Buttons[6].setOnClickListener(this);
Buttons[7].setOnClickListener(this);
Buttons[8].setOnClickListener(this);
newgameButton.setOnClickListener(this);
//Clear Grid of Numbers
for (int i = 0; i <= 8; i++) {
Buttons[i].setText("");
Buttons[i].setEnabled(true);
}
}
public void onUserInteraction() {
super.onUserInteraction();
stopHandler();//stop first and then start
startHandler();
}
public void stopHandler() {
handler.removeCallbacks(r);
}
public void startHandler() {
handler.postDelayed(r, 3000);
}
public void cleargrid() {
for (int i = 0; i <= 8; i++) {
if (Buttons[i].getResources() != null) {
Buttons[i].setBackgroundResource(0);
Buttons[i].setEnabled(true);
}
randomize(myImageArr, myImageArr.length);
}
}
#Override
public void onClick(View v) {
startHandler();
switch (v.getId()) {
case R.id.one:
count++;
Buttons[0].setEnabled(false);
if (count > 2) flipback();
Buttons[0].setBackgroundResource(myImageArr[0]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.two:
count++;
Buttons[1].setEnabled(false);
if (count > 2) flipback();
Buttons[1].setBackgroundResource(myImageArr[1]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.three:
count++;
Buttons[2].setEnabled(false);
if (count > 2) flipback();
Buttons[2].setBackgroundResource(myImageArr[2]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.four:
count++;
Buttons[3].setEnabled(false);
if (count > 2) flipback();
Buttons[3].setBackgroundResource(myImageArr[3]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.five:
count++;
Buttons[4].setEnabled(false);
if (count > 2) flipback();
Buttons[4].setBackgroundResource(myImageArr[4]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.six:
count++;
Buttons[5].setEnabled(false);
if (count > 2) flipback();
Buttons[5].setBackgroundResource(myImageArr[5]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.seven:
count++;
Buttons[6].setEnabled(false);
if (count > 2) flipback();
Buttons[6].setBackgroundResource(myImageArr[6]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.eight:
count++;
Buttons[7].setEnabled(false);
if (count > 2) flipback();
Buttons[7].setBackgroundResource(myImageArr[7]);
MediaPlayer.create(this, R.raw.buttonsound2).start();
break;
case R.id.nine:
break;
case R.id.newgamebutton2:
cleargrid();
MediaPlayer.create(this, R.raw.buttonsound).start();
break;
}
}
static void randomize(int arr[], int n) {
Random r = new Random();
for (int i = n - 2; i > 1; i--) {
int j = r.nextInt(i);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public void flipbacktimer() {
for (int i = 0; i <= myImageArr.length; i++) {
if (Buttons[i].getResources() != null) {
Buttons[i].setBackgroundResource(0);
Buttons[i].setEnabled(true);
}
}
}
public void flipback() {
for (int i = 0; i <= myImageArr.length; i++){
if(Buttons[i].getResources() != null) {
Buttons[i].setBackgroundResource(0);
Buttons[i].setEnabled(true);
count = 1;
}
}
}
}
You can just leave images as they are, even if they names are different, and just create class to hold them:
public class GameImages {
int image;
boolean isMatched;
public GameImages(int image) {
this.image = image;
this.isMatched = false;
}
public GameImages(int image, int id, isMatched) {
this.image = image;
this.isMatched = isMatched;
}
And now create Array of GameImage's. You will use id to match images with buttons, and check if isMatched(), to leave it, and set button clickable attribute 'false', or flip it back.
Make an object with the image and id ex {"image": your image , "id": id of the image }
put two images with same id's and when they match you are good to go
I'm not android studio developer or java developer but regarding for my graduation project I need to make an android app that connects to HC-05 Bluetooth module "Arduino", then starts to transmit and receive bytes ... I have found a lot of projects that connects to the Bluetooth module by showing you a list of Bluetooth devices then you can choose which one you want to connect ...
but I don't want to use this method I want to find a method that searches for a specific Bluetooth mac address and if it available, start connecting to it, if it not available, the app will continue searching ...
I don't have any experience how can programmatically make this.
so please be patient :D
I have done the XML design...
I want to add the mac address connecting code here
package mdluex.smartx;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
this is the XML design
Activity Design
the full project code on GitHub
I found the solution :D
thanks, guys ...
My full project contains this code:
package mdluex.smartx;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class ActivityControlCenter extends AppCompatActivity {
private int room1_str = 1;
private int room2_str = 0;
private int room3_str = 1;
private int room4_str = 1;
private int room5_str = 1;
private int room6_str = 1;
String deviceName = "HC-05";
BluetoothDevice result = null;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//Serial Port Service ID
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_center);
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
if (devices != null) {
for (BluetoothDevice device : devices) {
if (deviceName.equals(device.getName())) {
Toast.makeText(getApplicationContext(),"SamrtX is available ",Toast.LENGTH_SHORT).show();
result = device;
boolean connected=true;
try {
socket = result.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
connected=false;
Toast.makeText(getApplicationContext(),"SamrtX is not available ",Toast.LENGTH_SHORT).show();
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
}
final RelativeLayout room1_btn = (RelativeLayout) this.findViewById(R.id.room1_btn);
final TextView room1_st = (TextView) this.findViewById(R.id.room1_st);
final ImageView room1_img = (ImageView) this.findViewById(R.id.room1_img);
room1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room1_str == 0){
room1_str = 1;
if (socket!=null)
{
try
{
socket.getOutputStream().write("a".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room1_st.setText("ON");
room1_img.setImageResource(R.drawable.lamp_on);
}
else {
room1_str = 0;
if (socket!=null)
{
try
{
socket.getOutputStream().write("b".toString().getBytes());
}
catch (IOException e)
{
Toast.makeText(getApplicationContext(),"Error ",Toast.LENGTH_SHORT).show();
}
}
room1_btn.setBackgroundResource(R.drawable.btn_grid_off);
room1_st.setText("OFF");
room1_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room2_btn = (RelativeLayout) this.findViewById(R.id.room2_btn);
final TextView room2_st = (TextView) this.findViewById(R.id.room2_st);
final ImageView room2_img = (ImageView) this.findViewById(R.id.room2_img);
room2_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room2_str == 0){
room2_str = 1;
room2_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room2_st.setText("ON");
room2_img.setImageResource(R.drawable.lamp_on);
}
else {
room2_str = 0;
room2_btn.setBackgroundResource(R.drawable.btn_grid_off);
room2_st.setText("OFF");
room2_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room3_btn = (RelativeLayout) this.findViewById(R.id.room3_btn);
final TextView room3_st = (TextView) this.findViewById(R.id.room3_st);
final ImageView room3_img = (ImageView) this.findViewById(R.id.room3_img);
room3_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room3_str == 0){
room3_str = 1;
room3_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room3_st.setText("ON");
room3_img.setImageResource(R.drawable.lamp_on);
}
else {
room3_str = 0;
room3_btn.setBackgroundResource(R.drawable.btn_grid_off);
room3_st.setText("OFF");
room3_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room4_btn = (RelativeLayout) this.findViewById(R.id.room4_btn);
final TextView room4_st = (TextView) this.findViewById(R.id.room4_st);
final ImageView room4_img = (ImageView) this.findViewById(R.id.room4_img);
room4_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room4_str == 0){
room4_str = 1;
room4_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room4_st.setText("ON");
room4_img.setImageResource(R.drawable.lamp_on);
}
else {
room4_str = 0;
room4_btn.setBackgroundResource(R.drawable.btn_grid_off);
room4_st.setText("OFF");
room4_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room5_btn = (RelativeLayout) this.findViewById(R.id.room5_btn);
final TextView room5_st = (TextView) this.findViewById(R.id.room5_st);
final ImageView room5_img = (ImageView) this.findViewById(R.id.room5_img);
room5_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room5_str == 0){
room5_str = 1;
room5_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room5_st.setText("ON");
room5_img.setImageResource(R.drawable.lamp_on);
}
else {
room5_str = 0;
room5_btn.setBackgroundResource(R.drawable.btn_grid_off);
room5_st.setText("OFF");
room5_img.setImageResource(R.drawable.lamp_off);
}
}
});
final RelativeLayout room6_btn = (RelativeLayout) this.findViewById(R.id.room6_btn);
final TextView room6_st = (TextView) this.findViewById(R.id.room6_st);
final ImageView room6_img = (ImageView) this.findViewById(R.id.room6_img);
room6_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (room6_str == 0){
room6_str = 1;
room6_btn.setBackgroundResource(R.drawable.btn_grid_nor);
room6_st.setText("ON");
room6_img.setImageResource(R.drawable.lamp_on);
}
else {
room6_str = 0;
room6_btn.setBackgroundResource(R.drawable.btn_grid_off);
room6_st.setText("OFF");
room6_img.setImageResource(R.drawable.lamp_off);
}
}
});
}
}
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 wrote Android QuizApp which randomly generates questions for users and then displays the result. When I tried to implement user interface where a user would enter the number and difficulty of questions, application started to crash and give me fatal exceptions. I have 4 classes:
package com.example.quizapp;
import java.util.Random;
public class Quiz {
private int difficulty;
private int numberOfQuestions;
private Question[] questions;
public Quiz(String difficulty, int numberOfQuestions) {
setDifficulty(difficulty);
this.numberOfQuestions = numberOfQuestions;
this.questions = new Question[this.numberOfQuestions];
for (int i = 0; i < this.numberOfQuestions; i++) {
this.questions[i] = new Question(this.difficulty);
}
}
public void setDifficulty(String difficulty) {
if (difficulty == "easy") {
this.difficulty = 1;
} else if (difficulty == "medium"){
this.difficulty = 2;
} else if (difficulty == "hard"){
this.difficulty = 3;
} else {
this.difficulty = -1;
}
}
public String getDifficulty() {
switch (difficulty) {
case 1:
return "easy";
case 2:
return "medium";
case 3:
return "hard";
default:
return "Difficulty not set correctly";
}
}
public Question getQuestionInstance(int number) {
return this.questions[number];
}
public String getQuestion(int number) {
return this.questions[number].QUESTION;
}
public int getOptionA(int number) {
return this.questions[number].OPTA;
}
public int getOptionB(int number) {
return this.questions[number].OPTB;
}
public int getOptionC(int number) {
return this.questions[number].OPTC;
}
public int getAnswer(int number) {
return this.questions[number].ANSWER;
}
class Question {
private int firstNumber;
private int secondNumber;
private char sign;
private String QUESTION;
private int OPTA;
private int OPTB;
private int OPTC;
private int ANSWER;
private int difficulty;
private Random rand;
public Question(int difficulty) {
this.difficulty = difficulty;
this.rand = new Random();
this.firstNumber = getRandomNumber();
this.secondNumber = getRandomNumber();
this.sign = getRandomSign();
this.ANSWER = calculateAnswer();
initializeOptions();
this.QUESTION = this.firstNumber + " " + this.sign + " " + this.secondNumber + " = ";
}
public String getQuestion() {
return this.QUESTION;
}
public int getOptionA() {
return this.OPTA;
}
public int getOptionB() {
return this.OPTB;
}
public int getOptionC() {
return this.OPTC;
}
public int getAnswer() {
return this.ANSWER;
}
private void initializeOptions() {
int number = this.rand.nextInt(3) + 1;
switch (number) {
case 1:
this.OPTA = this.ANSWER;
this.OPTB = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTC = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
break;
case 2:
this.OPTA = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTB = this.ANSWER;
this.OPTC = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
break;
case 3:
this.OPTA = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTB = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTC = this.ANSWER;
break;
}
}
private int calculateAnswer() {
int answer = 0;
switch (this.sign) {
case '+':
answer = this.firstNumber + this.secondNumber;
break;
case '-':
answer = this.firstNumber - this.secondNumber;
break;
case '*':
answer = this.firstNumber * this.secondNumber;
break;
case '/':
answer = this.firstNumber / this.secondNumber;
break;
}
return answer;
}
private int getRandomNumber() {
int number;
if (this.difficulty == 1) {
//number = 1 + Math.random()*100;
number = this.rand.nextInt(100) + 1;
} else if (this.difficulty == 2) {
//number = 1 + Math.random()*1000;
number = this.rand.nextInt(1000) + 1;
} else {
//number = 1 + Math.random()*1000;
number = this.rand.nextInt(1000) + 1;
}
return number;
}
private char getRandomSign() {
int number;
char sign;
//easy
if (this.difficulty == 1) {
number = this.rand.nextInt(2) + 1;
sign = convertNumberToSign(number);
//medium
} else if (this.difficulty == 2) {
if (this.firstNumber > 10 && this.secondNumber > 10) {
number = this.rand.nextInt(2) + 1;
sign = convertNumberToSign(number);
} else {
number = this.rand.nextInt(3) + 1;
sign = convertNumberToSign(number);
}
//hard
} else {
if (this.firstNumber / this.secondNumber == (int) (this.firstNumber / this.secondNumber)) {
number = this.rand.nextInt(4) + 1;
sign = convertNumberToSign(number);
} else {
number = this.rand.nextInt(3) + 1;
sign = convertNumberToSign(number);
}
}
return sign;
}
private char convertNumberToSign(int number) {
if (number == 1) {
return '+';
} else if (number == 2) {
return '-';
} else if (number == 3) {
return '*';
} else {
return '/';
}
}
}
}
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class QuizActivity extends Activity
{
Quiz quiz;
RadioButton rb1, rb2, rb3, rb4, rb5, rb6;
Button buttonOK;
String ans;
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
rb1=(RadioButton)findViewById(R.id.radio3);
rb2=(RadioButton)findViewById(R.id.radio4);
rb3=(RadioButton)findViewById(R.id.radio5);
rb4=(RadioButton)findViewById(R.id.radio6);
rb5=(RadioButton)findViewById(R.id.radio7);
rb6=(RadioButton)findViewById(R.id.radio8);
buttonOK=(Button)findViewById(R.id.button2);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup group2=(RadioGroup)findViewById(R.id.radioGroup3);
RadioButton answer2=(RadioButton)findViewById(group2.getCheckedRadioButtonId());
if (answer2.equals(rb4))
{
num = 5;
}
else if (answer2.equals(rb5))
{
num = 10;
}
else
{
num = 15;
}
RadioGroup group1=(RadioGroup)findViewById(R.id.radioGroup2);
RadioButton answer1=(RadioButton)findViewById(group1.getCheckedRadioButtonId());
if (answer1.equals(rb1))
{
ans = "easy";
}
else if (answer1.equals(rb2))
{
ans = "medium";
}
else
{
ans = "hard";
}
}
});
Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
intent.putExtra("answer", ans);
intent.putExtra("question", num);
QuizActivity.this.startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ui, menu);
return true;
}
}
package com.example.quizapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuestActivity extends Activity
{
Quiz quiz;
int score = 0;
int qid = 0;
Quiz.Question currentQuest;
TextView textQuestion;
RadioButton rba, rbb, rbc;
Button buttonNext;
String answer = null;
int numOfQuestion = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent= getIntent();
if (intent != null)
{
answer=intent.getStringExtra("answer");
numOfQuestion=intent.getIntExtra("question", 0);
}
quiz= new Quiz(answer,numOfQuestion);
currentQuest=quiz.getQuestionInstance(qid);
textQuestion=(TextView)findViewById(R.id.textView1);
rba=(RadioButton)findViewById(R.id.radio0);
rbb=(RadioButton)findViewById(R.id.radio1);
rbc=(RadioButton)findViewById(R.id.radio2);
buttonNext=(Button)findViewById(R.id.button1);
setQuestionView();
buttonNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
RadioGroup group=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(group.getCheckedRadioButtonId());
Log.d("yourans", currentQuest.getAnswer() + " " + answer.getText());
if(Integer.toString(currentQuest.getAnswer()).equals(answer.getText()) )
{
score++;
Log.d("score", "Your score" + score);
}
if(qid<numOfQuestion)
{
currentQuest=quiz.getQuestionInstance(qid);
setQuestionView();
}else
{
Intent intent = new Intent(QuestActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
textQuestion.setText(currentQuest.getQuestion());
rba.setText(Integer.toString(currentQuest.getOptionA()));
rbb.setText(Integer.toString(currentQuest.getOptionB()));
rbc.setText(Integer.toString(currentQuest.getOptionC()));
qid++;
}
}
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RatingBar;
import android.widget.TextView;
public class ResultActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
//access rating bar
RatingBar rbar=(RatingBar)findViewById(R.id.ratingBar1);
rbar.setNumStars(5);
rbar.setStepSize(0.5f);
TextView t=(TextView)findViewById(R.id.textResult);
//get and display the score
Bundle b = getIntent().getExtras();
int score= b.getInt("score");
rbar.setRating(score);
switch (score)
{
case 1:
case 2: t.setText("Better Luck Next Time!");
break;
case 3:
case 4:t.setText("Quite average");
break;
case 5:t.setText("Congratulations !");
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}
Edited: I added AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.quizapp.QuizActivity"
android:label="#string/quiz_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.quizapp.QuestActivity"
android:label="#string/title_activity_quiz" >
</activity>
<activity
android:name="com.example.quizapp.ResultActivity"
android:label="#string/title_activity_result" >
</activity>
</application>
</manifest>
Edited: Updated application as suggested, this error pops up and app crashes:
10-23 10:10:32.368: E/AndroidRuntime(827): FATAL EXCEPTION: main
10-23 10:10:32.368: E/AndroidRuntime(827): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.QuestActivity}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.os.Looper.loop(Looper.java:137)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-23 10:10:32.368: E/AndroidRuntime(827): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 10:10:32.368: E/AndroidRuntime(827): at java.lang.reflect.Method.invoke(Method.java:525)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-23 10:10:32.368: E/AndroidRuntime(827): at dalvik.system.NativeStart.main(Native Method)
10-23 10:10:32.368: E/AndroidRuntime(827): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
10-23 10:10:32.368: E/AndroidRuntime(827): at com.example.quizapp.Quiz.getQuestionInstance(Quiz.java:45)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.example.quizapp.QuestActivity.onCreate(QuestActivity.java:52)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.Activity.performCreate(Activity.java:5133)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-23 10:10:32.368: E/AndroidRuntime(827): ... 11 more
check this in manifest:
android:name="com.example.quizapp.QuizApp"
Have you this activity "QuizApp"?
change in manifest to:
android:name="com.example.quizapp.QuizActivity"
HTH.
You told Android that you have an Activity named QuizApp as your Main Activity, by saying
<activity
android:name="com.example.quizapp.QuizApp"
android:label="#string/quiz_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
but you never implemented it. Android looks for that activity in the package, com.example.quizapp, but it fails to find it, as we can see from the ClassNotFoundException in the LogCat messages,
10-21 06:31:26.907: E/AndroidRuntime(816): ... java.lang.ClassNotFoundException: Didn't find class "com.example.quizapp.QuizApp"...
You must implement your QuizApp Activity.
Its look like you have package name mismatch error in Manifest file. Correct it as
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp"
...
</manifest>
And don't forget, you can specify the fully qualified name for each Activity
i.e.
<activity
android:name="com.example.quizapp.Activity_name"
...>
</activity>
Edit As per Requirement
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class QuizActivity extends Activity
{
Quiz quiz;
RadioButton rb1, rb2, rb3, rb4, rb5, rb6;
Button buttonOK;
String ans;
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
rb1=(RadioButton)findViewById(R.id.radio3);
rb2=(RadioButton)findViewById(R.id.radio4);
rb3=(RadioButton)findViewById(R.id.radio5);
rb4=(RadioButton)findViewById(R.id.radio6);
rb5=(RadioButton)findViewById(R.id.radio7);
rb6=(RadioButton)findViewById(R.id.radio8);
buttonOK=(Button)findViewById(R.id.button2);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup group2=(RadioGroup)findViewById(R.id.radioGroup3);
RadioButton answer2=(RadioButton)findViewById(group2.getCheckedRadioButtonId());
if (answer2.equals(rb4))
{
num = 5;
}
else if (answer2.equals(rb5))
{
num = 10;
}
else
{
num = 15;
}
RadioGroup group1=(RadioGroup)findViewById(R.id.radioGroup2);
RadioButton answer1=(RadioButton)findViewById(group1.getCheckedRadioButtonId());
if (answer1.equals(rb1))
{
ans = "easy";
}
else if (answer1.equals(rb2))
{
ans = "medium";
}
else
{
ans = "hard";
}
}
});
//*********Edit
//Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
//QuizActivity.this.startActivity(intent);
//finish();
Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
intent.putExtra("answer", ans);
intent.putExtra("question", num);
QuizActivity.this.startActivity(intent);
finish();
//*******Edit
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ui, menu);
return true;
}
}
Here Next Activity
package com.example.quizapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuestActivity extends Activity
{
Quiz quiz;
int score = 0;
int qid = 0;
Quiz.Question currentQuest;
TextView textQuestion;
RadioButton rba, rbb, rbc;
Button buttonNext;
QuizActivity qa = new QuizActivity();
String ans = qa.ans;
int num = qa.num;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//*********Edit
Intent intent= getActivity().getIntent();
String answer=intent.getStringExtra("answer");
int numOfQuestion=intent.getIntExtra("question", 0);
//quiz= new Quiz(ans, num);
quiz= new Quiz(answer,numOfQuestion);
//*******
currentQuest=quiz.getQuestionInstance(qid);
textQuestion=(TextView)findViewById(R.id.textView1);
rba=(RadioButton)findViewById(R.id.radio0);
rbb=(RadioButton)findViewById(R.id.radio1);
rbc=(RadioButton)findViewById(R.id.radio2);
buttonNext=(Button)findViewById(R.id.button1);
setQuestionView();
buttonNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
RadioGroup group=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(group.getCheckedRadioButtonId());
Log.d("yourans", currentQuest.getAnswer() + " " + answer.getText());
if(Integer.toString(currentQuest.getAnswer()).equals(answer.getText()) )
{
score++;
Log.d("score", "Your score" + score);
}
if(qid<num)
{
currentQuest=quiz.getQuestionInstance(qid);
setQuestionView();
}else
{
Intent intent = new Intent(QuestActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
textQuestion.setText(currentQuest.getQuestion());
rba.setText(Integer.toString(currentQuest.getOptionA()));
rbb.setText(Integer.toString(currentQuest.getOptionB()));
rbc.setText(Integer.toString(currentQuest.getOptionC()));
qid++;
}
}