I have 2 activities, on the second one i read and make some changes to a local JSON file and it works for everything i need but when i go to the mainActivity and then come back to the second one it seems that the file just resets and looks like i didn't apply any changes. I don't know what to do...
I hope there is something to do here...
Here's the code for the second activity:
package com.example.plasticopedia;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class calculator extends AppCompatActivity {
int buttonClicked = MainActivity.buttonClicked;
Button plus;
Button minus;
public int amountTrash;
/public boolean openingActivity = true;
public boolean clickedPlus = true;/
public int clickedPlus;
String firstParagraph;
String secondParagraph;
String thirdParagraph;
String fourthParagraph;
String fifthParagraph;
String[] nameArray = {"BAG", "BOTTLE", "STRAW", "DETERGENT_CONTAINER", "BOTTLE_CAP", "FOOD_CONTAINER", "CUTLERY", "CRISPS_PACKET"};
String[] titleArray = {"Plastic Bag", "Water Bottle", "Straw", "Detergent Container", "Bottle Cap", "Food Container", "Cutlery", "Crisps Packet"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
getJSON();
changeImageTitleText();
plus = findViewById(R.id.plus);
minus = findViewById(R.id.minus);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickedPlus = 1;
getJSON();
clickedPlus = 0;
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickedPlus = 2;
getJSON();
clickedPlus = 0;
}
});
}
public void changeImageTitleText(){
TextView title = findViewById(R.id.title);
TextView P1 = findViewById(R.id.firstParagraph);
TextView P2 = findViewById(R.id.secondParagraph);
TextView P3 = findViewById(R.id.thirdParagraph);
TextView P4 = findViewById(R.id.fourthParagraph);
TextView P5 = findViewById(R.id.fifthParagraph);
for(int i = 0; i < titleArray.length; i++){
if(buttonClicked == i){
title.setText(titleArray[i]);
P1.setText(firstParagraph);
P2.setText(secondParagraph);
P3.setText(thirdParagraph);
P4.setText(fourthParagraph);
P5.setText(fifthParagraph);
changeImage(i);
}
}
}
private void changeImage(int i){
Button image = findViewById(R.id.image);
if(i == 0){
image.setBackgroundResource(R.drawable.button_plastic_bag);
} else if (i == 1){
image.setBackgroundResource(R.drawable.button_plastic_bottle);
} else if (i == 2){
image.setBackgroundResource(R.drawable.button_plastic_straw);
} else if (i == 3){
image.setBackgroundResource(R.drawable.button_plastic_detergent_container);
} else if (i == 4){
image.setBackgroundResource(R.drawable.button_plastic_bottle_cap);
} else if (i == 5){
image.setBackgroundResource(R.drawable.button_plastic_food_container);
} else if (i == 6){
image.setBackgroundResource(R.drawable.button_plastic_cutlery);
} else if (i == 7){
image.setBackgroundResource(R.drawable.button_plastic_crisps_packet);
}
}
public void getJSON(){
String json;
try{
InputStream is = getAssets().open("plastic.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
JSONArray jsonArray = new JSONArray(json);
if(clickedPlus == 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
for (int j = 0; j < nameArray.length; j++) {
if (buttonClicked == j) {
if (obj.getString("name").equals(nameArray[j])) {
Log.e("TrashOpening", "" + amountTrash);
//((JSONObject)jsonArray.get(i)).put("amountTrash", "20");
TextView tv = findViewById(R.id.number);
tv.setText(obj.getString("amountTrash"));
Log.e("TrashOpeningSecond", "" + amountTrash);
firstParagraph = obj.getString("1");
secondParagraph = obj.getString("2");
thirdParagraph = obj.getString("3");
fourthParagraph = obj.getString("4");
fifthParagraph = obj.getString("5");
}
}
}
}
}
if(clickedPlus == 1){
//changing the values
for(int i = 0; i < jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
for(int j = 0; j < nameArray.length; j++){
if(buttonClicked == j){
if(obj.getString("name").equals(nameArray[j])){
amountTrash ++;
Log.e("TrashClickedPlus", "" + amountTrash);
((JSONObject)jsonArray.get(i)).put("amountTrash", "" + amountTrash);
TextView tv = findViewById(R.id.number);
tv.setText(obj.getString("amountTrash"));
Log.e("TrashAfterChangingJSON", "" + Integer.parseInt(obj.getString("amountTrash")));
}
}
}
}
}else if(clickedPlus == 2){
for(int i = 0; i < jsonArray.length(); i++){
JSONObject obj = jsonArray.getJSONObject(i);
for(int j = 0; j < nameArray.length; j++){
if(buttonClicked == j){
if(obj.getString("name").equals(nameArray[j])){
if(amountTrash > 0){
amountTrash --;
((JSONObject)jsonArray.get(i)).put("amountTrash", "" + amountTrash);
TextView tv = findViewById(R.id.number);
tv.setText(obj.getString("amountTrash"));
}
}
}
}
}
}
}catch(IOException e){
e.printStackTrace();
}catch(JSONException e){
e.printStackTrace();
}
}
}
Assets are read only por accomplish that use shared preferences or a local database
Related
In my MainActivity.Java, I have an onClickListener in a button that will show an Alert Dialog when it's clicked
scanbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View scanPopup = getLayoutInflater().inflate(R.layout.scan_tab, null);
forScan.setView(scanPopup);
dialog = forScan.create();
dialog.show();
}
});
This is is the ScanTab.Java wherein the AlertDialog will have its functions
package com.example.AppDraft1.activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.AppDraft1.MainActivity;
import com.example.AppDraft1.R;
import com.example.AppDraft1.parser.NdefMessageParser;
import com.example.AppDraft1.record.ParsedNdefRecord;
import java.util.List;
public class ScanTab extends AppCompatActivity {
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private TextView text;
private String first, surname, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_tab);
text = (TextView) findViewById(R.id.text);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, this.getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
#Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
if (!nfcAdapter.isEnabled())
showWirelessSettings();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
#Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null){
nfcAdapter.disableForegroundDispatch(this);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
resolveIntent(intent);
}
private void resolveIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
} else {
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
}
displayMsgs(msgs);
}
}
private void displayMsgs(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0)
return;
StringBuilder builder = new StringBuilder();
List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for (int i = 0; i < size; i++) {
ParsedNdefRecord record = records.get(i);
String str = record.str();
builder.append(str).append("\n");
}
text.setText(builder.toString());
Toast.makeText(this, "NFC Tag Detected", Toast.LENGTH_SHORT).show();
sndData();
}
public void sndData(){
String theText = text.getText().toString();
//split data
String[] split = theText.split("/",3);
first = split[0]; //first name
surname = split[1]; //surname
id = split[2]; //id number
Intent intent = new Intent(ScanTab.this, MainActivity.class);
intent.putExtra("FName", first);
intent.putExtra("SName", surname);
intent.putExtra("ID", id);
startActivity(intent);
}
private void showWirelessSettings() {
Toast.makeText(this, "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
private String dumpTagData(Tag tag) {
StringBuilder sb = new StringBuilder();
byte[] id = tag.getId();
sb.append("ID (hex): ").append(toHex(id)).append('\n');
sb.append("ID (reversed hex): ").append(toReversedHex(id)).append('\n');
sb.append("ID (dec): ").append(toDec(id)).append('\n');
sb.append("ID (reversed dec): ").append(toReversedDec(id)).append('\n');
String prefix = "android.nfc.tech.";
sb.append("Technologies: ");
for (String tech : tag.getTechList()) {
sb.append(tech.substring(prefix.length()));
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
for (String tech : tag.getTechList()) {
if (tech.equals(MifareClassic.class.getName())) {
sb.append('\n');
String type = "Unknown";
try {
MifareClassic mifareTag = MifareClassic.get(tag);
switch (mifareTag.getType()) {
case MifareClassic.TYPE_CLASSIC:
type = "Classic";
break;
case MifareClassic.TYPE_PLUS:
type = "Plus";
break;
case MifareClassic.TYPE_PRO:
type = "Pro";
break;
}
sb.append("Mifare Classic type: ");
sb.append(type);
sb.append('\n');
sb.append("Mifare size: ");
sb.append(mifareTag.getSize() + " bytes");
sb.append('\n');
sb.append("Mifare sectors: ");
sb.append(mifareTag.getSectorCount());
sb.append('\n');
sb.append("Mifare blocks: ");
sb.append(mifareTag.getBlockCount());
} catch (Exception e) {
sb.append("Mifare classic error: " + e.getMessage());
}
}
if (tech.equals(MifareUltralight.class.getName())) {
sb.append('\n');
MifareUltralight mifareUlTag = MifareUltralight.get(tag);
String type = "Unknown";
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
type = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
type = "Ultralight C";
break;
}
sb.append("Mifare Ultralight type: ");
sb.append(type);
}
}
return sb.toString();
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
private String toReversedHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
if (i > 0) {
sb.append(" ");
}
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
}
return sb.toString();
}
private long toDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private long toReversedDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = bytes.length - 1; i >= 0; --i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
}
When I tested it, the view is working but the functions are absent. How do I embed or make the functions work in the AlertDialog?
Alert Dialogs are meant to 'alert' the user of something, or run code based on input from user in case of input dialog.
If you want to run code in the alert dialog, you can run it before setView of dialog.
Additionally it is not recommended to block user from interacting with app using an Alert Dialog.
If you want to run code from one activity in another, in your case run code in ScanActivity from MainActivity the best way I can think of is Activity RESULTS API which replaced StartActivityForResult [read here]
But I would just recommended you start ScanActivity and show the dialog from there, then you can easily call all methods of ScanActivity.
I have a functionality for tic tac toe where basically when the player clicks a button to place their X, the computer's O is placed at the same time within the first empty button available.
However what I prefer is after the player places an X, the computer places their O on the first empty button available, not the same time. Is there a way to get the computer to click on an empty button by itself?
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
computerMove();
}
}
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j] == "") {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
UPDATE
Whole code snippet:
public class MainActivityPlayer1 extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean playerOneMove = true;
private int turnsCount;
private int playerOnePoints;
private int playerTwoPoints;
private TextView textViewPlayerOne;
private TextView textViewPlayerTwo;
private TextView textViewPlayerOneTurn;
private TextView textViewPlayerTwoTurn;
int playerX = Color.parseColor("#e8e5e5");
int playerO = Color.parseColor("#737374");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_player2);
textViewPlayerOne = findViewById(R.id.textView_player1);
textViewPlayerTwo = findViewById(R.id.textView_player2);
textViewPlayerOneTurn = findViewById(R.id.textView_player1Turn);
textViewPlayerTwoTurn = findViewById(R.id.textView_player2Turn);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
if (savedInstanceState != null) {
String btnState = savedInstanceState.getCharSequence(buttonID).toString();
if (btnState.equals("X")) {
buttons[i][j].setTextColor(playerX);
} else {
buttons[i][j].setTextColor(playerO);
}
}
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetGame();
}
});
Button buttonExit = findViewById(R.id.button_exit);
buttonExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
backToMainActivity();
}
});
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (playerOneMove) {
((Button) v).setText("X");
((Button) v).setTextColor(playerX);
playerOneMove = false;
computerMove();
}
turnsCount++;
if (checkGameIsWon()) {
if (playerOneMove) {
player1Wins();
} else {
player2Wins();
}
} else if (turnsCount == 9) {
draw();
} else {
playerOneMove = !playerOneMove;
switchPlayerTurn();
}
}
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j] == "") {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
private boolean checkGameIsWon() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
private void player1Wins() {
playerOnePoints++;
Toast.makeText(this, "Player 1 wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
playerTwoPoints++;
Toast.makeText(this, "Computer wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
}
#SuppressLint("SetTextI18n")
private void updatePointsText() {
textViewPlayerOne.setText("Player 1: " + playerOnePoints + " ");
textViewPlayerTwo.setText("Computer: " + playerTwoPoints + " ");
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
turnsCount = 0;
switchPlayerTurn();
}
private void resetGame() {
playerOnePoints = 0;
playerTwoPoints = 0;
turnsCount = 0;
playerOneMove = true;
updatePointsText();
resetBoard();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("turnsCount", turnsCount);
outState.putInt("playerOnePoints", playerOnePoints);
outState.putInt("playerTwoPoints", playerTwoPoints);
outState.putBoolean("playerOneMove", playerOneMove);
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
outState.putCharSequence(buttonID, btn.getText());
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { ;
super.onRestoreInstanceState(savedInstanceState);
turnsCount = savedInstanceState.getInt("turnsCount");
playerOnePoints = savedInstanceState.getInt("playerOnePoints");
playerTwoPoints = savedInstanceState.getInt("playerTwoPoints");
playerOneMove = savedInstanceState.getBoolean("playerOneMove");
switchPlayerTurn();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
Button btn = buttons[i][j];
savedInstanceState.putCharSequence(buttonID, btn.getText());
}
}
}
private void switchPlayerTurn(){
if (playerOneMove){
textViewPlayerOneTurn.setVisibility(View.VISIBLE);
textViewPlayerTwoTurn.setVisibility(View.INVISIBLE);
}
else{
textViewPlayerOneTurn.setVisibility(View.INVISIBLE);
textViewPlayerTwoTurn.setVisibility(View.VISIBLE);
}
}
private void backToMainActivity(){
Intent intentMainActivity = new Intent(this, MainActivity.class);
startActivity(intentMainActivity);
}
}
Try this
button.performClick();
UPDATE after going through op's code:
Your code was perfectly fine but had one small bug. In your computerMove() function, you had compared strings using == which is prone to cause problems in Java. I replaced it with String.equals(String) and played a game. Works fine.
private boolean computerMove() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
if (field[i][j].equals("")) {
buttons[i][j].setText("O");
buttons[i][j].setTextColor(playerO);
return true;
}
}
}
return false;
}
I'm having a activity which has question and answer section with a question with 4 choices in a radio group. On choosing answer it must change the background of answer to green or red(based on right or wrong).
I have a activity which calls a BaseAdapter class which listens the setOnCheckedListener.
PreviewAdapter.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import technibits.com.pme.R;
import technibits.com.pme.activity.AsyncTaskCall;
import technibits.com.pme.activity.MasterDownload;
import technibits.com.pme.activity.PreviewActivity;
import technibits.com.pme.activity.ReviewFragment;
import technibits.com.pme.data.Quizdata;
import technibits.com.pme.data.ResultData;
public class PreviewAdapter extends BaseAdapter {
private Context context;
ReviewFragment activity;
Quizdata data;
String formID;
EditText dateText;
public ViewHolderA viewHolder;
int queNo;
int size;
String select;
public ResultData resData;
String urlMark = "xx.com/mark-for-review.php";
String urlRemove = "xx.com/mark-for-review-delete.php";
public RadioButton rButton = null;
HashMap<String, String> editTextvalue = new HashMap<String, String>();
MasterDownload httpRequest;
public String ansOption;
PreviewActivity previewActivity;
public PreviewAdapter(Context conte, Quizdata form, int qNO, int device, String strSelect ) {
super();
context = conte;
data = form;
queNo = qNO + 1;
size = device;
select = strSelect;
// previewActivity=pv;
}
#Override
public int getCount() {
return 3;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (size == 7) {
row = mInflater.inflate(R.layout.quiz_layout_seven, parent, false);
} else {
row = mInflater.inflate(R.layout.quiz_layout, parent, false);
}
if (row != null) {
viewHolder = new ViewHolderA();
viewHolder.reviewLayout = (LinearLayout) row.findViewById(R.id.review);
viewHolder.questionLayout = (LinearLayout) row.findViewById(R.id.question);
viewHolder.answerLayout = (LinearLayout) row.findViewById(R.id.answer);
viewHolder.questionView = (TextView) viewHolder.questionLayout.findViewById(R.id.questionView);
viewHolder.textQno = (TextView) row.findViewById(R.id.qNo);
viewHolder.radioGroup = (RadioGroup) row.findViewById(R.id.radioGroup);
viewHolder.rButton1 = (RadioButton) row.findViewById(R.id.RadioButton01);
viewHolder.rButton2 = (RadioButton) row.findViewById(R.id.RadioButton02);
viewHolder.rButton3 = (RadioButton) row.findViewById(R.id.RadioButton03);
viewHolder.rButton4 = (RadioButton) row.findViewById(R.id.RadioButton04);
viewHolder.reviewBox = (CheckBox) row.findViewById(R.id.rCheckBox);
viewHolder.showReview = (Button) row.findViewById(R.id.showReview);
// viewHolder.infoButton = (Button) row.findViewById(R.id.info);
} else {
viewHolder = (ViewHolderA) row.getTag();
}
if (position == 0) {
viewHolder.reviewLayout.setVisibility(View.VISIBLE);
viewHolder.questionLayout.setVisibility(View.GONE);
viewHolder.answerLayout.setVisibility(View.GONE);
int check = data.getISchecked();
if (check == 1) {
viewHolder.reviewBox.setChecked(true);
} else {
viewHolder.reviewBox.setChecked(false);
}
// String review = data.getStatus();
// if (review != null) {
// if (review.equals("A")) {
viewHolder.reviewBox.setEnabled(false);
// }
// }
if (select != null) {
viewHolder.reviewLayout.setVisibility(View.GONE);
}
} else if (position == 1) {
viewHolder.questionLayout.setVisibility(View.VISIBLE);
viewHolder.reviewLayout.setVisibility(View.GONE);
viewHolder.answerLayout.setVisibility(View.GONE);
viewHolder.questionView.setText(data.getQuestion());
viewHolder.textQno.setText("Q." + String.valueOf(queNo));
} else if (position == 2) {
viewHolder.answerLayout.setVisibility(View.VISIBLE);
viewHolder.questionLayout.setVisibility(View.GONE);
viewHolder.reviewLayout.setVisibility(View.GONE);
viewHolder.radioGroup.setEnabled(true);
viewHolder.rButton1.setText(data.getOptionA());
viewHolder.rButton2.setText(data.getOptionB());
viewHolder.rButton3.setText(data.getOptionC());
viewHolder.rButton4.setText(data.getOptionD());
final View uiview = row;
// viewHolder.rButton1.setBackgroundColor(Color.YELLOW);-------> Here color changes occur
if (select != null) {
viewHolder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
ansOption = "yes";
data.setIsAnswer(1);
int answer = Integer.valueOf(data.getAnswer());
int selected = -1;
if (checkedId == R.id.RadioButton01) {
selected = 1;
rButton = viewHolder.rButton1;
viewHolder.rButton1.setBackgroundColor(Color.YELLOW);
} else if (checkedId == R.id.RadioButton02) {
selected = 2;
rButton = viewHolder.rButton2;
} else if (checkedId == R.id.RadioButton03) {
selected = 3;
rButton = viewHolder.rButton3;
} else if (checkedId == R.id.RadioButton04) {
selected = 4;
rButton = viewHolder.rButton4;
}
if (rButton != null) {
if (answer + 1 == selected) {
rButton.setBackgroundColor(Color.GREEN);-------> Here color changes is not working
String dd = rButton.getText().toString();
rButton.setText("Correct answer");
} else {
rButton.setBackgroundColor(Color.RED);
data.setWrongAnswer(selected);
String dd = rButton.getText().toString();
System.out.println(dd);
}
}
if (answer == 0) {
viewHolder.rButton1.setBackgroundColor(Color.GREEN);
} else if (answer == 1) {
viewHolder.rButton2.setBackgroundColor(Color.GREEN);
} else if (answer == 2) {
viewHolder.rButton3.setBackgroundColor(Color.GREEN);
} else if (answer == 3) {
viewHolder.rButton4.setBackgroundColor(Color.GREEN);
}
for (int i = 0; i < viewHolder.radioGroup.getChildCount(); i++) {
viewHolder.radioGroup.getChildAt(i).setEnabled(false);
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userid", "android#gmail.com"));
params.add(new BasicNameValuePair("qid", data.getQuestionID()));
AsyncTaskCall ask = new AsyncTaskCall(context, "review", params);
ask.execute(urlRemove);
}
});
} else {
System.out.println("data.getIsAnswer() " + data.getIsAnswer());
if (data.getIsAnswer() == 1) {
int wrong = data.getWrongAnswer();
int selected = -1;
if (wrong == 1) {
selected = 1;
rButton = viewHolder.rButton1;
setcolorGreen(viewHolder.rButton1);
} else if (wrong == 2) {
selected = 2;
rButton = viewHolder.rButton2;
} else if (wrong == 3) {
selected = 3;
rButton = viewHolder.rButton3;
} else if (wrong == 4) {
selected = 4;
rButton = viewHolder.rButton4;
}
int answer = Integer.valueOf(data.getAnswer());
if (rButton != null) {
if (answer + 1 == selected) {
rButton.setBackgroundColor(Color.GREEN);
} else {
rButton.setBackgroundColor(Color.RED);
}
}
if (answer == 0) {
viewHolder.rButton1.setBackgroundColor(Color.GREEN);
} else if (answer == 1) {
viewHolder.rButton2.setBackgroundColor(Color.GREEN);
} else if (answer == 2) {
viewHolder.rButton3.setBackgroundColor(Color.GREEN);
} else if (answer == 3) {
viewHolder.rButton4.setBackgroundColor(Color.GREEN);
}
for (int i = 0; i < viewHolder.radioGroup.getChildCount(); i++) {
viewHolder.radioGroup.getChildAt(i).setEnabled(false);
}
}
}
}
else
{
viewHolder.answerLayout.setVisibility(View.GONE);
viewHolder.questionLayout.setVisibility(View.GONE);
viewHolder.reviewLayout.setVisibility(View.GONE);
}
return row;
}
static class ViewHolderA {
LinearLayout reviewLayout;
LinearLayout questionLayout;
LinearLayout answerLayout;
Button showReview;
TextView questionView;
TextView textQno;
RadioGroup radioGroup;
public RadioButton rButton1;
public RadioButton rButton2;
public RadioButton rButton3;
public RadioButton rButton4;
CheckBox reviewBox;
}
void setcolorGreen(RadioButton rb){
rb.setBackgroundColor(Color.GREEN);
Toast.makeText(context,"Correct",Toast.LENGTH_SHORT).show();
}
void setcolorRed(RadioButton rb){
rb.setBackgroundColor(Color.RED);
Toast.makeText(context,"Wrong",Toast.LENGTH_SHORT).show();
}
}
The class calling this is
PreviewActivity.java
public class PreviewActivity extends Activity {
int device;
Button priv;
Button next;
boolean pCheck;
boolean nCheck;
Quizdata dataSource;
int count, position;
String select;
int iNext = 0;
ListView list;
ArrayList<Quizdata> data;
Context context;
TestAdapter adapter;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
float heightDp = heightPixels / scaleFactor;
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
device = 10;
} else if (smallestWidth >= 600) {
device = 7; //Device is a 7" tablet
setContentView(R.layout.study_mode_seven);
} else {
setContentView(R.layout.study_mode);
}
// Bundle bundle = getIntent().getExtras();
list = (ListView) findViewById(R.id.listView1);
data = (ArrayList<Quizdata>) getIntent().getSerializableExtra("data");
count = getIntent().getExtras().getInt("count");
select = getIntent().getExtras().getString("review");
position = getIntent().getExtras().getInt("question_no");
// count = data.size();
if (data.size() > 0) {
dataSource = data.get(position);
adapter = new TestAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
}
priv = (Button) findViewById(R.id.prev);
next = (Button) findViewById(R.id.next);
Button exp = (Button) findViewById(R.id.exp);
list = (ListView) findViewById(R.id.listView1);
priv.setEnabled(false);
if (select != null) {
priv.setVisibility(View.GONE);
exp.setVisibility(View.GONE);
next.setVisibility(View.GONE);
}
exp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Explanation");
alert.setMessage(dataSource.getDescription());
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do something with value!
}
});
alert.show();
}
});
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (next.getText().toString().equals("Next")) {
priv.setEnabled(true);
if (iNext == 0) {
iNext = 1;
pCheck = true;
}
if (nCheck) {
iNext++;
}
if (iNext < count) {
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
list.setAdapter(adapter);
priv.setEnabled(true);
iNext++;
pCheck = true;
nCheck = false;
}
if (iNext == count) {
// next.setEnabled(false);
next.setText("Finish");
// next.setBackgroundColor(Color.RED);
iNext = count - 1;
pCheck = false;
}
} else {
finish();
}
}
});
priv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (iNext == count) {
iNext = count - 1;
}
if (pCheck) {
iNext--;
}
if (iNext > 0) {
iNext--;
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
next.setEnabled(true);
if (next.getText().toString().equals("Finish")) {
next.setText("Next");
// next.setBackgroundDrawable(priv.getBackground());
}
nCheck = true;
pCheck = false;
}
if (iNext == 0) {
priv.setEnabled(false);
iNext = 0;
nCheck = false;
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
sendMessage();
}
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", adapter.ansOption);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
The Activity calling above is
PreviewActivity.java
package technibits.com.pme.activity;
import java.util.ArrayList;
import technibits.com.pme.R;
import technibits.com.pme.adapter.PreviewAdapter;
import technibits.com.pme.adapter.TestAdapter;
import technibits.com.pme.data.Quizdata;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class PreviewActivity extends Activity {
int device;
Button priv;
Button next;
boolean pCheck;
boolean nCheck;
Quizdata dataSource;
int count, position;
String select;
int iNext = 0;
ListView list;
ArrayList<Quizdata> data;
Context context;
TestAdapter adapter;
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
int heightPixels = metrics.heightPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
float heightDp = heightPixels / scaleFactor;
float smallestWidth = Math.min(widthDp, heightDp);
if (smallestWidth > 720) {
device = 10;
} else if (smallestWidth >= 600) {
device = 7; //Device is a 7" tablet
setContentView(R.layout.study_mode_seven);
} else {
setContentView(R.layout.study_mode);
}
// Bundle bundle = getIntent().getExtras();
list = (ListView) findViewById(R.id.listView1);
data = (ArrayList<Quizdata>) getIntent().getSerializableExtra("data");
count = getIntent().getExtras().getInt("count");
select = getIntent().getExtras().getString("review");
position = getIntent().getExtras().getInt("question_no");
// count = data.size();
if (data.size() > 0) {
dataSource = data.get(position);
adapter = new TestAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
}
priv = (Button) findViewById(R.id.prev);
next = (Button) findViewById(R.id.next);
Button exp = (Button) findViewById(R.id.exp);
list = (ListView) findViewById(R.id.listView1);
priv.setEnabled(false);
if (select != null) {
priv.setVisibility(View.GONE);
exp.setVisibility(View.GONE);
next.setVisibility(View.GONE);
}
exp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Explanation");
alert.setMessage(dataSource.getDescription());
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do something with value!
}
});
alert.show();
}
});
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (next.getText().toString().equals("Next")) {
priv.setEnabled(true);
if (iNext == 0) {
iNext = 1;
pCheck = true;
}
if (nCheck) {
iNext++;
}
if (iNext < count) {
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
list.setAdapter(adapter);
priv.setEnabled(true);
iNext++;
pCheck = true;
nCheck = false;
}
if (iNext == count) {
// next.setEnabled(false);
next.setText("Finish");
// next.setBackgroundColor(Color.RED);
iNext = count - 1;
pCheck = false;
}
} else {
finish();
}
}
});
priv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (iNext == count) {
iNext = count - 1;
}
if (pCheck) {
iNext--;
}
if (iNext > 0) {
iNext--;
dataSource = data.get(iNext);
PreviewAdapter adapter = new PreviewAdapter(context, dataSource, iNext, device, select);
// adapter.resData = resData;
list.setAdapter(adapter);
next.setEnabled(true);
if (next.getText().toString().equals("Finish")) {
next.setText("Next");
// next.setBackgroundDrawable(priv.getBackground());
}
nCheck = true;
pCheck = false;
}
if (iNext == 0) {
priv.setEnabled(false);
iNext = 0;
nCheck = false;
}
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
sendMessage();
}
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", adapter.ansOption);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
When i debugged the Adapter class, it perfectly goes as per logic of app. but the color alone is not changing.
What is the problem possibly occured?
The view(row) did not have scope inside the listener. so i declared that view to a final view(uiview) which did have scope inside the onChecklistener. after that it works cool. But still i didn't know the reason for not working of the previous method .
I developed one application, in that i have roulette, roulette is rotating very well but,
Problem 1 : roulette have inner image of start, when i click to start , roulette rotate : when roulette rotate i want my start image to go away, and when roulette stop, i want to make it visible again,
Problem 2: i have one image of fix sized roulette, but when roulette rotates it automatically resize, i don't want that, i don't know why roulette is automatically resizing. i want to fix this.
my code is following :
Code is as per below...
package com.example.roulette_project;
import java.util.Random;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class SpinActivity extends Activity {
boolean clickcount = false;
ImageView switchon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spin);
switchon = (ImageView) findViewById(R.id.imageSwitchOn);
final ImageView roullete = (ImageView) findViewById(R.id.wheel_image);
final ImageView innerroullete = (ImageView) findViewById(R.id.innerroullete);
final Animation anim1 = AnimationUtils.loadAnimation(SpinActivity.this,
R.anim.wheel_spin_anim);
final Animation anim2 = AnimationUtils.loadAnimation(SpinActivity.this,
R.anim.innner_roullete_animation);
final Animation anim3 = AnimationUtils.loadAnimation(SpinActivity.this,
R.anim.from_middle);
final View l = findViewById(R.id.flipId);
final TextView team1 = (TextView) findViewById(R.id.textView1);
final TextView team2 = (TextView) findViewById(R.id.textView2);
final View full = findViewById(R.id.full_view);
full.setRotationX(30);
// innerroullete.setRotationY(30);
// innerroullete.setRotationX(20);
// Display display = getWindowManager().getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// int width = size.x;
// int height = size.y;
// roullete.getLayoutParams().height=height/2;
// roullete.getLayoutParams().width=width/2;
switchon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// int SPLASH_TIME_OUT = 3000;
//
//
// new Handler().postDelayed(new Runnable() {
//
// /*
// * Showing splash screen with a timer. This will be useful when you
// * want to show case your app logo / company
// */
//
// #Override
// public void run() {
// switchon.setVisibility(View.GONE);
// }
// }, SPLASH_TIME_OUT);
// switchon.setVisibility(View.VISIBLE);
roullete.startAnimation(anim1);
// innerroullete.startAnimation(anim2);
roullete.animate().rotation(2);
// switchon.setVisibility(View.GONE);
int i2, i1 = 0;
Random r = new Random();
i2 = r.nextInt(2);
i1 = r.nextInt(360);
Toast.makeText(getApplicationContext(),
"angle = " + getAnswer(i1), Toast.LENGTH_LONG).show();
// float i2 = 360/i1;
// Toast.makeText(getApplicationContext(), "angle = " +i1,
// Toast.LENGTH_LONG).show();
Bitmap myImg = BitmapFactory.decodeResource(getResources(),
R.drawable.roulete_hd);
roullete.setImageBitmap(myImg);
Matrix matrix = new Matrix();
matrix.postRotate(i1);
l.startAnimation(anim2);
l.startAnimation(anim3);
Log.d("ROTATIING :- ", i1 + ": start");
Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0,
myImg.getWidth(), myImg.getHeight(), matrix, true);
roullete.setImageBitmap(rotated);
// for (int i = 0; i < 10; i++) {
// if (i % 2 == 0) {
// try {
// new Thread().sleep(1000);
// team1.setText("IND");
// team2.setText("PAK");
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// } else {
// team1.setText("PAK");
// team2.setText("IND");
// }
//
// }
if (i2 == 1) {
team1.setText("IND");
team2.setText("PAK");
} else {
team1.setText("PAK");
team2.setText("IND");
}
}
});
}
public int getAnswer(int i) {
if (i >= 17 && i <= 49) {
return 5;
} else if (i >= 50 && i <= 81) {
return 4;
} else if (i >= 82 && i <= 114) {
return 3;
} else if (i >= 115 && i <= 147) {
return 2;
} else if (i >= 148 && i <= 180) {
return 1;
} else if (i >= 181 && i <= 212) {
return 11;
} else if (i >= 213 && i <= 245) {
return 10;
} else if (i >= 246 && i <= 278) {
return 9;
} else if (i >= 279 && i <= 310) {
return 8;
} else if (i >= 311 && i <= 343) {
return 7;
} else {
return 6;
}
}
}
that's pretty simple, just add a listener to the end of the animation
private OnClickListener onClick = new OnClickListener(){
#Override
public void onClick(View v){
v.setOnClickListener = null;
wheel.animate().addListener(animatorListener)... the rest of your animation
}
};
and then at the end of the animation, remove the listener and re-add the click listener
private AnimatorListenerAdapter animatorListener = new AnimatorListenerAdapter(){
#Override
public void onAnimationEnd (Animator animation){
animation.removeListener(this);
button.setOnClickListener(onClick);
}
}
I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];