I have a game activity about different alphabet are randomly available user would select some of them that are making a correct word.
i made the string array of word which is answer
but i want to knew how to display this answer word alphabets and adding some randomly other alphabet as a confusion?
like taking the answer for example [World] and divid it's alphabet like that [W , L, D , O] AND make them randomly displayed and the player choose from them ?
TextView guessItTimer;
CountDownTimer timer;
Random r;
String currentWord;
private int presCounter = 0;
private int maxPresCounter = 4;
private String[] keys = {"R", "I", "B", "D", "X"};
String dictionary[] = {
"remember",
"hungry",
"crying",
"sour",
"sleep",
"awesome",
"Seven",
"color",
"began",
"appear",
"weight",
"language"
};
TextView textScreen, textQuestion, textTitle;
Animation smallbigforth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guess_it);
guessItTimer = findViewById(R.id.guessItTimer);
smallbigforth = AnimationUtils.loadAnimation(this, R.anim.smallbigforth);
keys = shuffleArray(keys);
for (String key : keys) {
addView(( findViewById(R.id.layoutParent)), key, findViewById(R.id.et_guess));
}
maxPresCounter = 4;
resetTimer();
}
//CountdownTimer
void resetTimer() {
timer = new CountDownTimer(30150, 1000) {
#Override
public void onTick(long l) {
guessItTimer.setText(String.valueOf(l / 1000));
}
#Override
public void onFinish() {
Toast.makeText(GuessItActivity.this, "Time is over", Toast.LENGTH_SHORT).show();
startActivity(new Intent(GuessItActivity.this, BossFinalActivity.class));
finish();
}
}.start();
}
private String[] shuffleArray(String[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
String a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
private void addView(LinearLayout viewParent, final String text, final EditText editText) {
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
linearLayoutParams.rightMargin = 30;
final TextView textView = new TextView(this);
textView.setLayoutParams(linearLayoutParams);
textView.setBackground(this.getResources().getDrawable(R.drawable.bgpink));
textView.setTextColor(this.getResources().getColor(R.color.colorPurple));
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setClickable(true);
textView.setFocusable(true);
textView.setTextSize(32);
textQuestion = findViewById(R.id.textQuestionBoss);
textScreen = findViewById(R.id.gametitle);
textTitle = findViewById(R.id.Ammo);
textView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
#Override
public void onClick(View v) {
if(presCounter < maxPresCounter) {
if (presCounter == 0)
editText.setText("");
editText.setText(editText.getText().toString() + text);
textView.startAnimation(smallbigforth);
textView.animate().alpha(0).setDuration(300);
presCounter++;
if (presCounter == maxPresCounter)
doValidate();
}
}
});
viewParent.addView(textView);
}
private void doValidate() {
presCounter = 0;
EditText editText = findViewById(R.id.et_guess);
LinearLayout linearLayout = findViewById(R.id.layoutParent);
currentWord = dictionary[r.nextInt(dictionary.length)];
if(editText.getText().toString().equals(currentWord)) {
//Toast.makeText(GuessItActivity.this, "Correct", Toast.LENGTH_SHORT).show();
Intent a = new Intent(GuessItActivity.this,BossFinalActivity.class);
startActivity(a);
editText.setText("");
} else {
Toast.makeText(GuessItActivity.this, "Wrong", Toast.LENGTH_SHORT).show();
editText.setText("");
}
keys = shuffleArray(keys);
linearLayout.removeAllViews();
for (String key : keys) {
addView(linearLayout, key, editText);
}
}
public void onBackPressed() {
timer.cancel();
this.finish();
super.onBackPressed();
}
You can achieve it like this
String a2z = "abcdefghijklmnopqrstuvwxyz";
String answer = "World";
// lets assume you need 16 char to select from
ArrayList<Character> chars = new ArrayList<Character>();
for (int i = 0; i < answer.length(); i++) {
chars.add(answer.charAt(i));
}
int dif = 16 - chars.size();
Random rand = new Random();
for (int i = 0; i < dif; i++) {
int ranIndex = rand.nextInt(a2z.length());
chars.add(a2z.charAt(ranIndex));
}
Collections.sort(chars);
System.out.println("nameArray2" + chars.toString());
Related
I am getting only a single value.how can i get data from all of the editText which i have created dynamically so that i can pass all editText data using comma after every editText .
Here is my code:
Diagnolist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText ed;
Integer count = 1;
final List<EditText> allEds = new ArrayList<EditText>();
for (int i = 0; i < count; i++) {
ed = new EditText(MainActivity.this);
allEds.add(ed);
ed.setId(i);
ed.setHint("add diagonis");
ed.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addDiagnosis.addView(ed);
}
Toast_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[(allEds.size())];
String st = "";
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
st = strings[i]+"," +st;
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
}
});
}
});
do changes as per below code.
final List<EditText> allEds = new ArrayList<EditText>();
declare above list after class define.
Diagnolist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText ed;
Integer count = 1;
for (int i = 0; i < count; i++) {
ed = new EditText(MainActivity.this);
allEds.add(ed);
ed.setId(i);
ed.setHint("add diagonis");
ed.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addDiagnosis.addView(ed);
}
Toast_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String[] strings = new String[(allEds.size())];
String st = "";
for(int i=0; i < allEds.size(); i++){
strings[i] = allEds.get(i).getText().toString();
st += strings[i]+",";
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
}
});
}
});
I'm not sure what you mean, so correct me if i am wrong. I think you want to get a comma-separated String of all values.
I would just change the onClick to following:
#Override
public void onClick(View view) {
String st;
for(EditText ed : allEds){
st += "," + ed.getText().toString();
}
st = st.substring(1); // cut leading comma
Toast.makeText(MainActivity.this, st, Toast.LENGTH_SHORT).show();
}
i have button,on button click it create editText with value, value of edit text is depending on count of total edit texts.for example edittext1 = 100, when user create two edit text then the value will be like this edittext1 = 50,edittext2 = 50 and so on.( value = 100/ total no of edittext) which i set equally to each edit text.now the problem is when user want to change/update any value from edittext, i want to update value of each edittext according to user's newly entered value.
i want to call textwatcher when value changed by only user,in my case when user click on button it will call.
thank you.
here is my code
public class StageForm extends BaseActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stage_form);
spinnerProjectStage = (Spinner) findViewById(R.id.spinnerAddProjectStage);
spinnerProjectList = (Spinner) findViewById(R.id.spinnerProjectList);
stageLinearLayout = (LinearLayout) findViewById(R.id.stageProjectList);
btnAddMoreStage = (Button) findViewById(R.id.btnAddMoreStage);
btnAddMoreStage.setOnClickListener(this);
getProjectStage();
}
public void onClick(View v) {
if (v.getId() == R.id.btnAddMoreStage) {
public void addMoreFields () {
try {
k++;
flag = k;
final LinearLayout.LayoutParams lparams;
lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout[flag] = new LinearLayout(StageForm.this);
layout[flag].setLayoutParams(lparams);
layout[flag].setId(flag);
txtStageName[flag] = new EditText(StageForm.this);
txtStageName[flag].setLayoutParams(lparams);
txtStageName[flag].setHint("stage " + k + "");
txtStageName[flag].setId(flag);
txtStagePercent[flag] = new EditText(StageForm.this);
txtStagePercent[flag].setLayoutParams(lparams);
txtStagePercent[flag].setHint("percent");
txtStagePercent[flag].setId(flag);
txtStagePercent[flag].addTextChangedListener(stagePercentChangeListener);
if (flag == 0) {
txtStagePercent[flag].setText(String.valueOf(totalPercent));
} else {
countEditText = flag + 1;
calculatePercentage(countEditText, flag);
}
} catch (Exception e) {
e.printStackTrace();
}
layout[flag].addView(txtStageName[flag]);
layout[flag].addView(txtStagePercent[flag]);
stageLinearLayout.addView(layout[flag]);
}
}
}
private void calculatePercentage(int countEditText, int flag) {
k = flag;
if (flag == 0) {
// countEditText = flag;
lastTextBox = countEditText;
} else {
// countEditText = flag;
lastTextBox = countEditText - 1;
}
result = totalPercent / countEditText;
convertFloatResult = Math.round(result);
remainingPercent = totalPercent - (convertFloatResult * countEditText);
lastTextValue = convertFloatResult + remainingPercent;
try {
if (remainingPercent == 0) {
for (int j = 0; j <= lastTextBox; j++) {
txtStagePercent[j].setText(String.valueOf(convertFloatResult));
}
txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue));
} else {
for (int j = 0; j < lastTextBox; j++) {
txtStagePercent[j].setText(String.valueOf(convertFloatResult));
}
txtStagePercent[lastTextBox].setText(String.valueOf(lastTextValue));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private TextWatcher stagePercentChangeListener = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (flag == 0) {
} else {
String getbeforValue = String.valueOf(s);
beforeTextChanged = Integer.parseInt(getbeforValue);
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String getchangedValue = String.valueOf(s);
afterTextChanged = Integer.parseInt(getchangedValue);
}
#Override
public void afterTextChanged(Editable s) {
totalPercent = totalPercent - afterTextChanged;
countEditText = countEditText - 1;
calculatePercentage(countEditText, flag);
}
};
}
I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.
here is my code:
public class TrainingActivity extends Activity {
private EditText etIn1, etIn2, etDesired;
private TextView prevInput;
int W[][] = new int[2][];
int X[][] = new int[30][];
int w0=0, w1=0, w2=0, p=1, sum=0, clicks=0;
private Button nxtData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_activity);
View backgroundImage = findViewById(R.id.background);
Drawable background = backgroundImage.getBackground();
background.setAlpha(40);
etIn1= (EditText) findViewById(R.id.etInput1);
etIn2 = (EditText) findViewById(R.id.etInput2);
etDesired = (EditText) findViewById(R.id.etDesired);
prevInput = (TextView) findViewById(R.id.prevInput);
nxtData = (Button) findViewById(R.id.nextData);
nxtData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int sum = 0;
++clicks;
int intetIn1 = Integer.parseInt(etIn1.getText().toString());
int intetIn2 = Integer.parseInt(etIn2.getText().toString());
int intetDesired = Integer.parseInt(etDesired.getText().toString());
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
prevInput.setText("Last Inputs: (" + intetIn1 + ", " + intetIn2 +
", " + intetDesired + ")");
if(clicks == 1) {
if(intetDesired == 1) {
W[0] = new int[] {intetIn1, intetIn2, 1};
W[1] = W[0];
} else if(intetDesired == (-1)){
W[0] = new int[] {-intetIn1, -intetIn2, -1};
W[1] = W[0];
}
} else if(clicks > 1) {
for(int i=0; i<3; i++){
sum = sum + W[clicks-1][i] * X[clicks-1][i];
} if(sum>0 && intetDesired==1) {
W[clicks] = W[clicks-1];
} else if(sum<0 && intetDesired==(-1)) {
W[clicks] = W[clicks-1];
} else if(sum<=0 && intetDesired==1) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] + X[clicks-1][i];
}
} else if(sum>=0 && intetDesired==(-1)) {
for(int i=0; i<3; i++) {
W[clicks][i] = W[clicks-1][i] - X[clicks-1][i];
}
}
}
Toast.makeText(getApplicationContext(), "" + clicks,
Toast.LENGTH_SHORT).show();
System.out.println(X[0][0]);
etIn1.setText("");
etIn2.setText("");
etDesired.setText("");
}
});
}}
and here is the Exception:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
the clicks is the number of times that user click the button. at first it's ok but when i try and add some more inputs it crashes. can you tell why this is happening?
index of array is always less than length as index starts form 0 whereas length from 1 therefore X[clicks-1] is causing the problem
What is the initial value of click variable.
Can you post more code related. And for the first time if click is 0 then
X[clicks-1] = new int[] {intetIn1, intetIn2, 1};
this says you are store these value at click-1 th position which is not even initialized.. so
int X[] = new int[]{intetIn1, intetIn2, 1};
would be better.
I am developing a game program where I want to store images in the buttons. I want to randomize the images shown in the buttons when the users play the game again, but I don't know how to randomize the images.
public class MainActivity extends Activity {
public static final String COME_FROM = "come_from";
private int[] id_mc = new int[16];
private Integer[][] img_mc = new Integer [16][2];
private Button[] myMcs = new Button[16];
private int mc_counter = 0;
private int firstid = 0;
private int secondid = 0;
private Boolean mc_isfirst = false;
private int correctcounter = 0;
private TextView tFeedback;
private MediaPlayer mp;
private Boolean b_snd_inc, b_snd_cor;
Random r = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
initGame();
}
private void initGame() {
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
mc_counter = 0;
firstid = 0;
secondid = 0;
mc_isfirst = false;
correctcounter = 0;
tFeedback = (TextView) findViewById(R.id.mc_feedback);
// setup button listeners
Button startButton = (Button) findViewById(R.id.game_menu);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startMenu();
}
});
Button settingsButton = (Button) findViewById(R.id.game_settings);
settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startPrefs();
}
});
// fill arrays with resources
id_mc[0] = R.id.mc0;
id_mc[1] = R.id.mc1;
id_mc[2] = R.id.mc2;
id_mc[3] = R.id.mc3;
id_mc[4] = R.id.mc4;
id_mc[5] = R.id.mc5;
id_mc[6] = R.id.mc6;
id_mc[7] = R.id.mc7;
id_mc[8] = R.id.mc8;
id_mc[9] = R.id.mc9;
id_mc[10] = R.id.mc10;
id_mc[11] = R.id.mc11;
id_mc[12] = R.id.mc12;
id_mc[13] = R.id.mc13;
id_mc[14] = R.id.mc14;
id_mc[15] = R.id.mc15;
img_mc[0][0] = R.drawable.back1;
img_mc[0][1] = R.drawable.ic_img1;
img_mc[1][0] = R.drawable.back2;
img_mc[1][1] = R.drawable.ic_img2;
img_mc[2][0] = R.drawable.back3;
img_mc[2][1] = R.drawable.ic_img3;
img_mc[3][0] = R.drawable.back4;
img_mc[3][1] = R.drawable.ic_img4;
img_mc[4][0] = R.drawable.back5;
img_mc[4][1] = R.drawable.ic_img5;
img_mc[5][0] = R.drawable.back6;
img_mc[5][1] = R.drawable.ic_img6;
img_mc[6][0] = R.drawable.back7;
img_mc[6][1] = R.drawable.ic_img7;
img_mc[7][0] = R.drawable.back8;
img_mc[7][1] = R.drawable.ic_img8;
img_mc[8][0] = R.drawable.back1;
img_mc[8][1] = R.drawable.ic_img1;
img_mc[9][0] = R.drawable.back2;
img_mc[9][1] = R.drawable.ic_img2;
img_mc[10][0] = R.drawable.back3;
img_mc[10][1] = R.drawable.ic_img3;
img_mc[11][0] = R.drawable.back4;
img_mc[11][1] = R.drawable.ic_img4;
img_mc[12][0] = R.drawable.back5;
img_mc[12][1] = R.drawable.ic_img5;
img_mc[13][0] = R.drawable.back6;
img_mc[13][1] = R.drawable.ic_img6;
img_mc[14][0] = R.drawable.back7;
img_mc[14][1] = R.drawable.ic_img7;
img_mc[15][0] = R.drawable.back8;
img_mc[15][1] = R.drawable.ic_img8;
//Collections.shuffle(Arrays.asList(img_mc));
for (int i = 0; i < 16; i++) {
try{
myMcs[i] = (Button) findViewById(id_mc[i]);
myMcs[i].setBackgroundResource(img_mc[i][0]);
myMcs[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int i = 0;
for (int n = 0; n < 16; n++) {
if (id_mc[n] == view.getId())
i = n;
}
doClickAction(view, i);
}
});
}catch(Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}}
}
private void doClickAction(View v, int i)
{
v.setBackgroundResource(img_mc[i][1]);
mc_isfirst = !mc_isfirst;
// disable all buttons
for (Button b : myMcs) {
b.setEnabled(false);
}
if (mc_isfirst) {
// turning the first card
firstid = i;
// re enable all except this one
for (Button b : myMcs) {
if (b.getId() != firstid) {
b.setEnabled(true);
}
}
} else {
// turning the second card
secondid = i;
doPlayMove();
}
}
private void doPlayMove() {
mc_counter++;
if (img_mc[firstid][1] - img_mc[secondid][1] == 0) {
//correct
if (b_snd_cor) playSound(R.raw.correct);
waiting(200);
myMcs[firstid].setVisibility(View.INVISIBLE);
myMcs[secondid].setVisibility(View.INVISIBLE);
correctcounter++;
} else {
//incorrect
if (b_snd_inc) playSound(R.raw.incorrect);
waiting(400);
}
// reenable and turn cards back
for (Button b : myMcs) {
if (b.getVisibility() != View.INVISIBLE) {
b.setEnabled(true);
b.setBackgroundResource(R.drawable.memory_back);
for (int i = 0; i < 16; i++) {
myMcs[i].setBackgroundResource(img_mc[i][0]);
}
}
}
tFeedback.setText("" + correctcounter + " / " + mc_counter);
if (correctcounter > 7) {
Intent iSc = new Intent(getApplicationContext(), Scoreboard.class);
iSc.putExtra("com.gertrietveld.memorygame.SCORE", mc_counter);
startActivity(iSc);
finish();
}
}
public void playSound(int sound) {
mp = MediaPlayer.create(this, sound);
mp.setVolume((float).5,(float).5);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
public static void waiting(int n) {
long t0, t1;
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ((t1 - t0) < (n));
}
private void startMenu() {
Intent launchMenu = new Intent(this, MenuScreen.class);
launchMenu.putExtra(COME_FROM,"PlayGame");
startActivity(launchMenu);
}
private void startPrefs() {
Intent launchPrefs = new Intent(this, Setting.class);
startActivity(launchPrefs);
}
////////////////////////////////
#Override
protected void onRestart() {
super.onRestart();
//String sender = getIntent().getExtras().getString("SENDER");
//initGame();
Toast.makeText(this, "onRestart-sender is " , Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
////////////////////////////////
}
You had the Collections.shuffle() part right, you just need to get the randomized list back into your array:
private Integer[][] img_mc = new Integer [16][2];
...
List<Integer[]> img_mc_list = new ArrayList<Integer[]>();
for (Integer[] img : img_mc) {
img_mc_list.add(img);
}
Collections.shuffle(img_mc_list);
img_mc_list.toArray(img_mc);
Or use this:
private void randomize(Integer[][] array) {
int index;
Integer[] temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}