Dialog Fragment does not working? - java

Iam getting runtime error at Dialog fragment. At the Runtime of program works smoothly but when it comes to dialog appearence imes the program crashes........... Somebody show me where did the mistake I can't resolve my problem.
I am posting a LogCat Image because of body limit is crossed
MainActivity.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
public static final String GUESSES = "settings_numberOfGuesses";
public static final String ANIMALS_TYPE = "settings_animalType";
public static final String QUIZ_BACKGROUND_COLOR = "settings_quiz_background_color";
public static final String QUIZ_FONT = "settings_quiz_font";
private boolean isSettingsChanged = false;
static Typeface azkiaDemo;
static Typeface chunkFive;
static Typeface fontleroyBrown;
static Typeface hauntedEyes;
static Typeface knightBrushDemo;
static Typeface wonderbarDemo;
MainActivityFragment myAnimalQuizFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
azkiaDemo = Typeface.createFromAsset(getAssets(),"fonts/Azkia demo.otf");
chunkFive = Typeface.createFromAsset(getAssets(),"fonts/Chunkfive.otf");
fontleroyBrown = Typeface.createFromAsset(getAssets(),"fonts/FontleroyBrown.ttf");
hauntedEyes = Typeface.createFromAsset(getAssets(),"fonts/Haunted Eyes.otf");
knightBrushDemo = Typeface.createFromAsset(getAssets(),"fonts/Knight Brush Demo.otf");
wonderbarDemo = Typeface.createFromAsset(getAssets(),"fonts/Wonderbar Demo.otf");
PreferenceManager.setDefaultValues(this, R.xml.quiz_preferences, false);
PreferenceManager.getDefaultSharedPreferences(this).
registerOnSharedPreferenceChangeListener(settingsChangedListener);
myAnimalQuizFragment = (MainActivityFragment) getSupportFragmentManager().findFragmentById(R.id.animalQuizFragment);
myAnimalQuizFragment.modifyAnimalGuessRows(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyTypeofAnimals(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyQuizFont(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.modifyBackgroundColor(PreferenceManager.getDefaultSharedPreferences(this));
myAnimalQuizFragment.resetAnimalQuiz();
isSettingsChanged = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent preferencesIntent = new Intent(this,SettingsActivity.class);
startActivity(preferencesIntent);
return super.onOptionsItemSelected(item);
}
private SharedPreferences.OnSharedPreferenceChangeListener settingsChangedListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
isSettingsChanged = true;
if (key.equals(GUESSES)){
myAnimalQuizFragment.modifyAnimalGuessRows(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(ANIMALS_TYPE)){
Set<String> animalTypes = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
if (animalTypes != null && animalTypes.size() > 0){
myAnimalQuizFragment.modifyTypeofAnimals(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else {
SharedPreferences.Editor editor = sharedPreferences.edit();
animalTypes.add(getString(R.string.default_animal_type));
editor.putStringSet(ANIMALS_TYPE, animalTypes); // here we provided default value also.......
editor.apply();
Toast.makeText(MainActivity.this, R.string.default_animalType_message, Toast.LENGTH_SHORT).show();
}
}else if (key.equals(QUIZ_FONT)){
myAnimalQuizFragment.modifyQuizFont(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}else if (key.equals(QUIZ_BACKGROUND_COLOR)){
myAnimalQuizFragment.modifyBackgroundColor(sharedPreferences);
myAnimalQuizFragment.resetAnimalQuiz();
}
Toast.makeText(MainActivity.this, R.string.toast_message , Toast.LENGTH_SHORT).show();
}
};
public void showDialog(){
ExampleDialog exampleDialog = new ExampleDialog();
exampleDialog.setCancelable(false);
exampleDialog.show(getFragmentManager(),"Animal_Quiz_Result");
}
}
Here is the MainActivityFragment.java class
import android.animation.Animator;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class MainActivityFragment extends Fragment {
public static final int NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ = 10;
private List<String> allAnimalsNameList;
private List<String> animalNamesQuizList;
private Set<String> animalTypesInQuiz;
private String correctAnimalsAnswer;
public static int numberOfAllGuesses;
private int numberOfAnimalGuessRows;
private int numberOfRightAnswers;
private SecureRandom secureRandomNumber;
private Handler handler;
private Animation wrongAnswerAnimation;
private LinearLayout animalQuizLinearLayout;
private TextView txtQuestionNumber;
private ImageView imgAnimal;
private LinearLayout[] rowsOfGuessButtonsInAnimalQuiz;
private TextView txtAnswer;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
allAnimalsNameList = new ArrayList<>();
animalNamesQuizList = new ArrayList<>();
secureRandomNumber = new SecureRandom();
handler = new Handler();
wrongAnswerAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.wrong_animation);
wrongAnswerAnimation.setRepeatCount(1);
animalQuizLinearLayout = view.findViewById(R.id.animalQuizLinearLayout);
txtQuestionNumber = view.findViewById(R.id.txtQuestionNumber);
imgAnimal = view.findViewById(R.id.imgAnimal);
rowsOfGuessButtonsInAnimalQuiz = new LinearLayout[3];
rowsOfGuessButtonsInAnimalQuiz[0] = view.findViewById(R.id.firstRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[1] = view.findViewById(R.id.secondRowLinearLayout);
rowsOfGuessButtonsInAnimalQuiz[2] = view.findViewById(R.id.thirdRowLinearLayout);
txtAnswer = view.findViewById(R.id.txtAnswer);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz) {
for (int column = 0; column < row.getChildCount(); column++) {
Button btnGuess = (Button) row.getChildAt(column);
btnGuess.setOnClickListener(btnGuessListener);
btnGuess.setTextSize(24);
}
}
txtQuestionNumber.setText(getString(R.string.question_text, 1, NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
// getString is extends fragment...........
return view;
}
private View.OnClickListener btnGuessListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Button btnGuess = ((Button) view);
String guessValue = btnGuess.getText().toString();
String answerValue = getTheExactAnimalName(correctAnimalsAnswer);
++numberOfAllGuesses;
if (guessValue.equals(answerValue)) {
++numberOfRightAnswers;
txtAnswer.setText(answerValue + " ! " + " RIGHT");
disableQuizGuessButton();
if (numberOfRightAnswers == NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
} else {
handler.postDelayed(new Runnable() {
#Override
public void run() {
animateAnimalQuiz(true);
}
}, 1000); //1000 milliseconds for 1 second delay.......
}
} else {
imgAnimal.startAnimation(wrongAnswerAnimation);
txtAnswer.setText(R.string.wrong_answer_message);
btnGuess.setEnabled(false);
}
}
};
public static String getTheExactAnimalName(String animalName) {
return animalName.substring(animalName.indexOf('-') + 1).replace('_', ' ');
}// this method changes the actual name of image for example removes or starts after tame_animal- through index of method
// and after that removes _ between the names of animals...........
private void disableQuizGuessButton() {
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
LinearLayout guessRowLinearLayout = rowsOfGuessButtonsInAnimalQuiz[row];
for (int buttonIndex = 0; buttonIndex < guessRowLinearLayout.getChildCount(); buttonIndex++) {
guessRowLinearLayout.getChildAt(buttonIndex).setEnabled(false);
}
}
}
public void resetAnimalQuiz() {
AssetManager assets = getActivity().getAssets();
allAnimalsNameList.clear();
try {
for (String animalType : animalTypesInQuiz) {
String[] animalImagePathsInQuiz = assets.list(animalType);
for (String animalImagePathInQuiz : animalImagePathsInQuiz) {
allAnimalsNameList.add(animalImagePathInQuiz.replace(".png", ""));
}
}
} catch (IOException e) {
Log.e("AnimalQuiz", "Error", e);
}
numberOfRightAnswers = 0; // this variable holds the right guesses must be 0 because we reset the game.
numberOfAllGuesses = 0; // this variable holds no. of all guesses whether it is right or wrong have to be 0.
animalNamesQuizList.clear(); // this variable holds randomly generated quiz paths must be 0 to generate new paths......
int counter = 1;
int numberOfAvailableAnimal = allAnimalsNameList.size();// this variable holds number of available animals or the size or length of paths
while (counter <= NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ) {
int randomIndex = secureRandomNumber.nextInt(numberOfAvailableAnimal);
String animalImageName = allAnimalsNameList.get(randomIndex);
if (!animalNamesQuizList.contains(animalImageName)) {
animalNamesQuizList.add(animalImageName);
++counter;
}
}
showNextAnimal();
}
private void animateAnimalQuiz(boolean animateOutAnimalImage) {
if (numberOfRightAnswers == 0) {
return;
}
int xTopLeft = 0;
int yTopLeft = 0;
int xBottomRight = animalQuizLinearLayout.getLeft() + animalQuizLinearLayout.getRight();
int yBottomRight = animalQuizLinearLayout.getTop() + animalQuizLinearLayout.getBottom();
//Here is max value for radius
int radius = Math.max(animalQuizLinearLayout.getWidth(), animalQuizLinearLayout.getHeight());
Animator animator;
if (animateOutAnimalImage) {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xBottomRight, yBottomRight, radius, 0);
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
showNextAnimal();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
} else {
animator = ViewAnimationUtils.createCircularReveal(animalQuizLinearLayout, xTopLeft, yTopLeft, 0, radius);
}
animator.setDuration(700);
animator.start();
}
private void showNextAnimal() {
String nextAnimalImageName = animalNamesQuizList.remove(0);
correctAnimalsAnswer = nextAnimalImageName;
txtAnswer.setText("");
txtQuestionNumber.setText(getString(R.string.question_text, (numberOfRightAnswers + 1), NUMBER_OF_ANIMALS_INCLUDED_IN_QUIZ));
String animalType = nextAnimalImageName.substring(0, nextAnimalImageName.indexOf("-")); // it holds the animal type whether it is
// Tame animal or Wild Animal
AssetManager assets = getActivity().getAssets();
try (InputStream stream = assets.open(animalType + "/" + nextAnimalImageName + ".png")) {
Drawable animalImage = Drawable.createFromStream(stream, nextAnimalImageName);
imgAnimal.setImageDrawable(animalImage);
animateAnimalQuiz(false);
} catch (IOException e) {
Log.e("AnimalQuiz", "There is an Error Getting" + nextAnimalImageName, e);
}
Collections.shuffle(allAnimalsNameList); // this method is a predefined method in java which helps to shuffle the list of data
int correctAnimalNameIndex = allAnimalsNameList.indexOf(correctAnimalsAnswer);
String correctAnimalName = allAnimalsNameList.remove(correctAnimalNameIndex);
allAnimalsNameList.add(correctAnimalName);
for (int row = 0; row < numberOfAnimalGuessRows; row++) {
for (int column = 0; column < rowsOfGuessButtonsInAnimalQuiz[row].getChildCount(); column++) {
Button btnGuess = (Button) rowsOfGuessButtonsInAnimalQuiz[row].getChildAt(column);
btnGuess.setEnabled(true);
String animalImageName = allAnimalsNameList.get((row * 2) + column);
btnGuess.setText(getTheExactAnimalName(animalImageName));
}
}
int row = secureRandomNumber.nextInt(numberOfAnimalGuessRows);
int column = secureRandomNumber.nextInt(2);
LinearLayout randomRow = rowsOfGuessButtonsInAnimalQuiz[row];
String correctAnimalImageName = getTheExactAnimalName(correctAnimalsAnswer);
((Button) randomRow.getChildAt(column)).setText(correctAnimalImageName);
}
public void modifyAnimalGuessRows(SharedPreferences sharedPreferences){
final String NUMBER_OF_GUESS_OPTION = sharedPreferences.getString(GUESSES,null);
numberOfAnimalGuessRows = Integer.parseInt(NUMBER_OF_GUESS_OPTION)/2;
for (LinearLayout horizontalLinearLayout : rowsOfGuessButtonsInAnimalQuiz){
horizontalLinearLayout.setVisibility(View.GONE);
}
for (int row = 0; row < numberOfAnimalGuessRows; row++){
rowsOfGuessButtonsInAnimalQuiz[row].setVisibility(View.VISIBLE);
}
}
public void modifyTypeofAnimals(SharedPreferences sharedPreferences){
animalTypesInQuiz = sharedPreferences.getStringSet(ANIMALS_TYPE,null);
}
public void modifyQuizFont(SharedPreferences sharedPreferences){
String fontStringValue = sharedPreferences.getString(QUIZ_FONT,null);
switch (fontStringValue){
case "Chunkfive.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(chunkFive);
}
}
break;
case "Azkia demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(azkiaDemo);
}
}
break;
case "FontleroyBrown.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(fontleroyBrown);
}
}
break;
case "Haunted Eyes.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(hauntedEyes);
}
}
break;
case "Knight Brush Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(knightBrushDemo);
}
}
break;
case "Wonderbar Demo.otf":
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++) {
Button button = (Button) row.getChildAt(column);
button.setTypeface(wonderbarDemo);
}
}
break;
}
}
public void modifyBackgroundColor(SharedPreferences sharedPreferences){
String backgroundColor = sharedPreferences.getString(QUIZ_BACKGROUND_COLOR,null);
switch (backgroundColor){
case "White":
animalQuizLinearLayout.setBackgroundColor(Color.WHITE);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.rgb(34,167,240));
break;
case "Black":
animalQuizLinearLayout.setBackgroundColor(Color.BLACK);
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(247,202,24));
button.setTextColor(Color.BLACK);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Green":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(38,166,91));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.rgb(247,202,24));
txtAnswer.setTextColor(Color.WHITE);
break;
case "Yellow":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(247,202,24));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.BLACK);
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.BLACK);
txtAnswer.setTextColor(Color.BLACK);
break;
case "Red":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(240,52,52));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(34,167,240));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
case "Blue":
animalQuizLinearLayout.setBackgroundColor(Color.rgb(34,167,240));
for (LinearLayout row : rowsOfGuessButtonsInAnimalQuiz){
for (int column = 0; column < row.getChildCount(); column++){
Button button = (Button) row.getChildAt(column);
button.setBackgroundColor(Color.rgb(240,52,52));
button.setTextColor(Color.WHITE);
}
}
txtQuestionNumber.setTextColor(Color.WHITE);
txtAnswer.setTextColor(Color.WHITE);
break;
}
}
}
Here is the ExampleDialog.java class
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import static com.example.narayanmaity.app61animal_quiz.MainActivityFragment.numberOfAllGuesses;
/**
* Created by Narayan Maity on 12/14/2017.
*/
public class ExampleDialog extends DialogFragment {
MainActivityFragment myAnimalQuizFragment;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.results_string_value, numberOfAllGuesses,
(1000 / (double) numberOfAllGuesses)));
builder.setPositiveButton(R.string.result_animal_quiz, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myAnimalQuizFragment.resetAnimalQuiz();
}
});
return builder.create();
}
}

The problem is in this line.Remove the line below from your code
MainActivity mainActivity = new MainActivity();
mainActivity.showDialog();
You never ever create an Activity's instance with new operator. Its android Component class it initializes automatically with Intent . All Activities in android must go through a lifecycle so that they have a valid context attached to them. Read Activity.
The solution for this problem.
if(getActivity()!=null){
((MainActivity)getActivity()).showDialog()
}
For your new problem which you mentioned in comments.
You never assign myAnimalQuizFragment so it will give you NullPointerException anyway . Access it from your MainActivity.
((MainActivity)getActivity()).myAnimalQuizFragment.resetAnimalQuiz();
Make myAnimalQuizFragment as public in MainActivity.

Related

Android Image Button to tic tac toe

Currently having an issue having an image button open to another activity when we try the app closes. What we are trying to create is a tic tac toe game that has a splash screen, main activity, and new activity that is the actual game. The splash screen opens to the main but when we try to open the main activity to the board game it closes on us. Any advice?
Here is the current code:
Activity1 :
package com.example.tictactoe_game;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
ImageButton newActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
newActivity = (ImageButton) findViewById(R.id.imageButton_play);
newActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, GameBoard.class);
startActivity(intent);
}
});
}
}
Activity 2:
package com.example.tictactoe_game;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class GameBoard extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean player1Turn = true;
private int roundCount;
private int player1Points;
private int player2Points;
private TextView textViewPlayer1;
private TextView textViewPlayer2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_board);
textViewPlayer1 = findViewById(R.id.text_viewp1);
textViewPlayer2 = findViewById(R.id.text_viewp2);
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);
}
}
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (player1Turn) {
((Button) v).setText("X");
} else {
((Button) v).setText("O");
}
roundCount++;
if (checkForWin()) {
if (player1Turn) {
player1Wins();
} else {
player2Wins();
}
} else if (roundCount == 9) {
draw();
} else {
player1Turn = !player1Turn;
}
}
private boolean checkForWin() {
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() {
player1Points++;
Toast.makeText(this, "Player 1 Wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
player2Points++;
Toast.makeText(this, "Player 2 Wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
}
private void updatePointsText() {
textViewPlayer1.setText("Player 1: " + player1Points);
textViewPlayer2.setText("Player 2: " + player2Points);
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
roundCount = 0;
player1Turn = true;
}
}

How do I make both Images stay when they are matched and flip back when they don't match (Memory Matching Game)?

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

EditText added dynamically does not set invisble in Android

I am adding some EditTexts dynamically, when a button is clicked, the information is entered and displayed on a text View, I need to make invisible all the EditText Views, the problem that I am facing is that only the last EditText added goes invisible. I tried to set a tag to set the EditText invisible but it is not working Am I missing something?
Any assistance with this would be appreciated.
import java.util.ArrayList;
import java.util.List;
import com.juancho.workingout.R;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class TEST extends Fragment {
// Add EditText Dynamically
RelativeLayout containerLayout;
static int exercisesViews = 0; // initial value
public int totalExercisesViews = 15;
Context context;
private int counterExeNumber = 1;
private int margingTopEditTextInitial = 120; // default position
private int margingTopNumberAdd = 130;
private List<EditText> editTextListName = new ArrayList<>();
EditText EditTextName;
String nameResultCardio, nameResult1, nameResult2, nameResult3;
int myTagValueCardio;
int myTagValueYesCardioExe2, myTagValueYesCardioExe3;
boolean cardioViewEnable = false;
boolean exe2IfCardioViewEnable = false;
boolean exe3IfCardioViewEnable = false;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
final View ViewCalendarEditNotesInfo = inflater.inflate(R.layout.logs_add_notes, null);
exercisesViews = 0; // Reset
containerLayout = (RelativeLayout) ViewCalendarEditNotesInfo.findViewById(R.id.layout1);
LogsAddNotes.isExercise1Enable = true;
LogsAddNotes.isExercise2Enable = true;
LogsAddNotes.isExercise3Enable = true;
final Button btnSave = (Button) ViewCalendarEditNotesInfo.findViewById(R.id.btnSave);
btnSave.setVisibility(View.VISIBLE);
if (LogsAddNotes.isExercise1Enable == true) {
// Set Views
editTextName(exercisesViews);
myTagValueCardio = (int) EditTextName.getTag();
cardioViewEnable = true;
}
// --------------------------------------------------------------------------------------------------------------------------------------------
if (LogsAddNotes.isExercise2Enable == true) {
exercisesViews++;
counterExeNumber++;
margingTopEditTextInitial = margingTopEditTextInitial + margingTopNumberAdd;
// Set Views
editTextName(exercisesViews);
// Get information entered
nameResult2 = EditTextName.getText().toString();
myTagValueYesCardioExe2 = (int) EditTextName.getTag();
exe2IfCardioViewEnable = true;
}
// --------------------------------------------------------------------------------------------------------------------------------------------
if (LogsAddNotes.isExercise3Enable == true) {
exercisesViews++;
counterExeNumber++;
margingTopEditTextInitial = margingTopEditTextInitial + margingTopNumberAdd;
// Set Views
editTextName(exercisesViews);
// Get information entered
nameResult3 = EditTextName.getText().toString();
myTagValueYesCardioExe3 = (int) EditTextName.getTag();
exe3IfCardioViewEnable = true;
}
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int index = 0;
while (index < editTextListName.size()) {
// --------------------------------------------------------------------------------------------------
if (cardioViewEnable == true && index == 0) {
nameResultCardio = editTextListName.get(index).getText().toString();
if (myTagValueCardio == index) {
// tToast("B1");
EditTextName.setVisibility(View.INVISIBLE);
}
}
// --------------------------------------------------------------------------------------------------
if (exe2IfCardioViewEnable == true && index == 1) {
nameResult2 = editTextListName.get(index).getText().toString();
if (myTagValueYesCardioExe2 == index) {
// tToast("B2");
EditTextName.setVisibility(View.INVISIBLE);
}
}
// --------------------------------------------------------------------------------------------------
if (exe3IfCardioViewEnable == true && index == 2) {
nameResult3 = editTextListName.get(index).getText().toString();
if (myTagValueYesCardioExe3 == index) {
// tToast(" B3");
EditTextName.setVisibility(View.INVISIBLE);
}
}
// more exercises HERE
index++;
} // end while loop
}// end Click
});
return ViewCalendarEditNotesInfo;
}// end Main
// -----------------------------------------------------------------------------------------
private EditText editTextName(int _intID) {
EditTextName = new EditText(getActivity());
EditTextName.setId(_intID);
EditTextName.setHint("Name");
// CharSequence hint = "\u200F" + editText.getHint();
// editText.setHint(hint);
// Maximum input chars allow
int maxLength = 10;
// Allow only Letters
EditTextName.setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxLength), new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end, Spanned dst, int dstart, int dend) {
if (src.equals("")) { // for backspace
return src;
}
if (src.toString().matches("[a-zA-Z ]+")) {
return src;
}
return "";
}
} });
editTextListName.add(EditTextName);
containerLayout.addView(EditTextName);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) EditTextName.getLayoutParams();
layoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
layoutParams.setMargins(300, margingTopEditTextInitial, 750, 0);
// RelativeLayout.LayoutParams()
EditTextName.setLayoutParams(layoutParams);
// if you want to identify the created editTexts, set a tag, like below
// EditTextName[i].setTag("EditText" + editText.getId());
EditTextName.setTag(_intID);
// tToast("THE TAG= " + _intID);
return EditTextName;
}
}

Android Application Button onclicklistener

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

Issue with checkbox checked

i am use this for setting checkbox in listview i have follow all step as per given tutorial, but there are some critical issue with output, is that when i am select first checkbox and scroll down it will change selected item and automatically appear 3rd.
so i think there are something wrong with getview. so please help me out this ....
here is my code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
public class Favorites extends ListActivity {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
ArrayList alAppName;
float[] rate;
boolean[] bSelected;
ArrayList<Comment> alPackagenm;
Drawable[] alIcon;
ViewHolder holder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
for (int i = 0; i < strAr.length; i++) {
System.out.println("strAr[" + i + "] " + strAr[i]);
}
for (String s : strAr) {
list.add(new RowModel(s));
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
}
});
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.ratingBar1.setOnRatingBarChangeListener(l);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
return (row);
}
}
}
I really don't understand your code exactly what you are trying to do. I haven't seen before this you are checking holder == null where as it should be convertView == null. If you have a scrolling issue you can check my blog post
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
...
}
else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
Use Below Code to your MainActivity.java file.
public class ListViewActivity extends Activity {
ListView mLstView1;
Button mBtn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLstView1 = (ListView) findViewById(R.id.mLstView1);
String[] lv_items = { "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil", "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil" };
;
mLstView1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
mLstView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Using a List to hold the IDs, but could use an array.
List<Integer> checkedIDs = new ArrayList<Integer>();
// Get all of the items that have been clicked - either on or
// off
final SparseBooleanArray checkedItems = mLstView1
.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
// And this tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if (isChecked) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// Put the value of the id in our list
checkedIDs.add(position);
System.out.println("Position is:- " + position);
}
}
}
});
}
}

Categories