i make some checkbox and radiobutton programically in my recyclerview and when i use notifydatasetchanged all of them are replaced with items in mylist
what should i do?
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
public MyRecyclerViewAdapter(Context context, ArrayList<HashMap<String, Object>> hash_all) {
}
#Override
public int getItemCount() {
return hash_all.size();
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
hash_all.size();
hash_get = hash_all.get(position);
Log.d("_hdev",hash_all.get(position) + " ::::::::: " + hash_get+"");
LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(
LinearLayoutCompat.LayoutParams.MATCH_PARENT,
LinearLayoutCompat.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 0, 0, 0);
String s = hash_get.get("ModelShowOption").toString();
String toggle = "";
String direc = "";
String type = "";
String model = "";
String rows = "";
String resize = "";
String[] split = s.split("\\|");
// = new String[0];
String[] split2 = new String[0];
for (int i = 0; i < split.length; i++) {
String s2 = split[i];
split2 = s2.split(":");
if (split2[0].equals("isToggleButton")){
toggle=split2[1];
}else if (split2[0].equals("type")){
type=split2[1];
}else if (split2[0].equals("direction")){
direc=split2[1];
}else if (split2[0].equals("model")){
model=split2[1];
}else if (split2[0].equals("rows")){
rows=split2[1];
}else if (split2[0].equals("resize")){
resize=split2[1];
}
}
String title = hash_get.get("title").toString();
String myValue =hash_get.get("MyValue").toString();
String[] splitValue = myValue.split("\\|");
RadioGroup[] rg;
RadioButton[] rb;
if (toggle.equals("true") && holder.row_list_title.getText().equals("")){
holder.row_list_placeholder.setVisibility(View.GONE);
String multiValue = hash_get.get("MultiValue").toString();
String[] splitMultiValue = multiValue.split(":");
if (splitMultiValue[1].equals("1")){
int p = 0;
rg = new RadioGroup[1];
rb = new RadioButton[splitValue.length];
rg[0] = new RadioGroup(holder.row_list_placeholder.getContext());
rg[0].setOrientation(RadioGroup.VERTICAL);
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
rb[j] = new RadioButton(getApplicationContext());
rg[p].addView(rb[j]);
rb[j].setId(j);
rb[j].setText(splitValue2[0]);
}
holder.linearLayoutCheckBox.addView(rg[p]);
p++;
holder.row_list_title.setText(title);
if (rg[0].getCheckedRadioButtonId() == -1) {
Log.d("RadioString", "Nothing selected");
} else {
for (int r = 0; r < splitValue.length; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
Log.d("RadioString", radioText);
} else {
Log.d("RadioString", "nothing");
}
}
}
}else{
//splitMultiValue[1]
holder.row_list_title.setText(title);
CheckBox[] ch;
final int[] checkd = {0};
ch = new CheckBox[splitValue.length];
for (int j = 0; j < splitValue.length; j++) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
ch[j] = new CheckBox(getApplicationContext());
holder.linearLayoutCheckBox.addView(ch[j]);
ch[j].setId(j);
ch[j].setText(splitValue2[0]);
}
for (int r = 0; r < splitValue.length; r++) {
int finalR = r;
ch[r].setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
Log.d("_hdev", checkd[0] +"");
Log.d("_hdev",Integer.parseInt(splitMultiValue[1])+"");
if (checkd[0] < Integer.parseInt(splitMultiValue[1])){
//CheckBox id = findViewById(ch[finalR].getId());
//String CheckBoxText = id.getText().toString();
//Log.e("CheckBoxString", CheckBoxText);
checkd[0] = checkd[0] +1;
Log.d("_hdevn", "1");
}else{
//CheckBox id = (CheckBox) findViewById(ch[finalR].getId());
ch[finalR].setChecked(false);
//checkd[0] = checkd[0] -1 ;
Log.d("_hdevn", "2");
}
} else {
ch[finalR].setChecked(false);
checkd[0] = checkd[0] -1;
Log.d("_hdevn", "3");
}
});
}
}
}else{
if (myValue.equals("NULL")){
holder.row_list_title.setText(title);
holder.row_list_placeholder.setVisibility(View.VISIBLE);
holder.row_list_placeholder.setHint(hash_get.get("placeholder").toString());
if (type.equals("Text")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_TEXT);
}else if(type.equals("Int")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER);
}else if(type.equals("Float")){
holder.row_list_placeholder.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
}else {
holder.row_list_placeholder.setVisibility(View.GONE);
/*
TextView[] tv;
final int[] checkd = {0};
tv = new TextView[splitValue.length];
for (int j = 0; j < hash_all2.size(); j++) {
Log.d("_hdev", hash_all2.get(j).get("selected"));
if (hash_all2.get(j).get("selected").equals("true")) {
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
tv[j] = new TextView(getApplicationContext());
holder.linearLayoutCheckBox.addView(tv[j]);
tv[j].setId(j);
tv[j].setText(hash_all2.get(j).get("name"));
}
}*/
//list popup
holder.row_list_title.setText(title);
holder.row_list_title.setOnClickListener(v -> {
profileadapter.notifyDataSetChanged();
//get_profiles();
/*if (hash_all2.size() == 0) {
for (int j = 0; j < splitValue.length; j++) {
HashMap<String, String> hash_add2 = new HashMap<>();
String myValue2 = splitValue[j];
String[] splitValue2 = myValue2.split("=");
hash_add2.put("Id", String.valueOf(j));
hash_add2.put("name", String.valueOf(splitValue2[0]));
hash_add2.put("value", String.valueOf(splitValue2[1]));
hash_add2.put("selected", "false");
hash_all2.add(hash_add2);
}
adapt.notifyDataSetChanged();
}
alertDialogSelect();*/
});
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.row_form, parent, false);
return new ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView row_list_title;
EditText row_list_placeholder;
LinearLayout linearLayoutCheckBox;
CardView cardrow;
ViewHolder(View itemView) {
super(itemView);
row_list_title = itemView.findViewById(R.id.row_list_title);
row_list_placeholder = itemView.findViewById(R.id.row_list_placeholder);
linearLayoutCheckBox = itemView.findViewById(R.id.mainrow);
}
}
}
this is what i tryed in many days.
You have to update your hash_all Arraylist before calling notifydatasatChanged()
you can put a boolean in your model to retain the checked and unchecked state of radio button and update the boolean and store the object in ur hash_all.
Note: notifydatasatChanged() is a heavy operation, it will refresh your complete list. try using notifyitemChanged(position) it will refresh only the clicked item.
Related
I am newbie on Android Studio. I have a question.
I am making a match cards application.
After a failed match cards flipping back after 0,5 sec. But while this time, you can still check other cards. I want to disable that. I'm extends Button to a class. I'm posting both of this scripts. Thanks for your helps.
This is my Card Class.
public class kart extends Button {
boolean acikMi = false;
boolean cevrilebilir = true;
int arkaPlanID;
int onPlanID=0;
Drawable on;
Drawable d;
public kart(Context context, int id) {
super(context);
setId(id);
arkaPlanID = R.drawable.arka1;
if(id%8==1)
onPlanID = R.drawable.c1;
if(id%8==2)
onPlanID = R.drawable.c2;
if(id%8==3)
onPlanID = R.drawable.c3;
if(id%8==4)
onPlanID = R.drawable.c4;
if(id%8==5)
onPlanID = R.drawable.c5;
if(id%8==6)
onPlanID = R.drawable.c6;
if(id%8==7)
onPlanID = R.drawable.c7;
if(id%8==0)
onPlanID = R.drawable.c8;
d = AppCompatDrawableManager.get().getDrawable(context,arkaPlanID);
on = AppCompatDrawableManager.get().getDrawable(context, onPlanID);
setBackground(d);
}
public void cevir(){
if (cevrilebilir){
if(!acikMi){
setBackground(on);
acikMi = true;
}
else{
setBackground(d);
acikMi=false;
}
}
}
And this is my Java code.
public class GameScreen extends AppCompatActivity {
int sonKart = 0;
int skor = 0;
int hamle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Intent i = getIntent();
final String s = i.getStringExtra("ad");
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(s);
GridLayout gr = (GridLayout) findViewById(R.id.grid);
kart kartlar[] = new kart[16];
for (int j = 1; j <= 16; j++) {
kartlar[j - 1] = new kart(this, j);
kartlar[j-1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hamle++;
final kart k = (kart)v;
k.cevir();
if (sonKart >0){
final kart k2 = (kart) findViewById(sonKart);
if (k2.onPlanID==k.onPlanID&&k2.getId()!=k.getId()){
k2.cevrilebilir=false;
k.cevrilebilir=false;
sonKart =0;
skor++;
TextView tv = (TextView) findViewById(R.id.textView3);
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv.setText("Score: "+skor);
tv2.setText("Total moves: "+hamle);
if (skor==8){
Intent i = new Intent(GameScreen.this,scoreboard.class);
i.putExtra("ham",hamle);
i.putExtra("isim",s);
startActivity(i);
//oyun bitti
}
}
else{
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
k2.cevir();
k.cevir();
}
},500);
sonKart =0;
TextView tv2 = (TextView) findViewById(R.id.textView5);
tv2.setText("Total moves: "+hamle);
}
}
else{
sonKart = k.getId();
}
}
});
}
for (int j=0;j<16;j++){
int rg =(int) (Math.random()*16);
kart k = kartlar[rg];
kartlar[rg] = kartlar [j];
kartlar[j] = k;
}
for (int j = 0; j < 16; j++)
gr.addView(kartlar[j]);
}
}
to disable click on button
button.setEnabled(false);
I am getting an error :
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
The part where I'm getting an error is in my if statement on my onBindViewHolder, below is my adapter :
public class UserProgramWeekAdapter extends RecyclerView.Adapter<UserProgramWeekAdapter.ViewHolder>{
private Context context;
private ArrayList<ProgramTrackerWrapper> programTrackers;
public UserProgramWeekAdapter(Context context, ArrayList<ProgramTrackerWrapper> programTrackers) {
this.context = context;
this.programTrackers = programTrackers;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_user_program_week_adapter, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(UserProgramWeekAdapter.ViewHolder holder, int position) {
holder.dayTxt.setText(programTrackers.get(position).getDay());
holder.numberofExercises.setText(programTrackers.get(position).getProgramTrackers().size()+ " exercises");
boolean isFinished = false;
for (int i = 0; i < programTrackers.size(); i++){
if ( programTrackers.get(position).getProgramTrackers().get(i).isProgramExerciseFinished()){
isFinished = true;
}
}
String statusTxt = isFinished || programTrackers.size() == 0 ? "Completed" : "Not Completed";
holder.exerciseCompleted.setText(statusTxt);
}
#Override
public int getItemCount() {
return programTrackers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView dayTxt, exerciseCompleted, numberofExercises;
public ViewHolder(View itemView) {
super(itemView);
dayTxt = itemView.findViewById(R.id.dayTxt);
exerciseCompleted = itemView.findViewById(R.id.exerciseCompleted);
numberofExercises = itemView.findViewById(R.id.numberofExercises);
}
}
}
And this one is my activity :
public class StartProgramActivity extends AppCompatActivity {
private Toolbar toolBar;
private TextView weekTitle, weekStateTxt;
private ImageView nextBtn, backBtn;
private Program program;
private DatabaseReference programTrackerReference;
private ArrayList<ProgramTracker> allProgramTrackers = new ArrayList<>();
private ArrayList<ProgramTracker> dayOfWeekExercises = new ArrayList<>();
private String TAG = "StartProgramActivity";
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<ProgramTrackerWrapper> programTrackerWrappers = new ArrayList<>();
private UserProgramWeekAdapter userProgramWeekAdapter;
private int totalWeeks;
private int currentWeek = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_program);
programTrackerReference = FirebaseDatabase.getInstance().getReference("ProgramTracker");
getDataFromPreviousActivity();
getProgramDetails(currentWeek);
findViews();
}
public void getDataFromPreviousActivity(){
if(getIntent().getSerializableExtra("program") != null) {
program = (Program) getIntent().getSerializableExtra("program");
totalWeeks = Integer.parseInt(program.getProgramWeeks());
}
}
private void setUpWeekNavigation(){
if(currentWeek == 1){
backBtn.setVisibility(View.GONE);
}else{
backBtn.setVisibility(View.VISIBLE);
}
if(totalWeeks > 1){
nextBtn.setVisibility(View.VISIBLE);
}
if(currentWeek == totalWeeks){
nextBtn.setVisibility(View.GONE);
}
}
private void determineWeek(int command){
// if 0 is passed, meaning back is pressed
// if 1 is passed, meaning next is pressed
switch (command){
case 0:
currentWeek--;
weekTitle.setText("Week " + currentWeek);
setUpWeekNavigation();
getProgramDetails(currentWeek);
break;
case 1:
currentWeek++;
weekTitle.setText("Week " + currentWeek);
setUpWeekNavigation();
getProgramDetails(currentWeek);
break;
}
}
private void findViews(){
toolBar = findViewById(R.id.toolBar);
setSupportActionBar(toolBar);
weekTitle = findViewById(R.id.weekTitle);
weekStateTxt = findViewById(R.id.weekStateTxt);
nextBtn = findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(StartProgramActivity.this, "next", Toast.LENGTH_SHORT).show();
determineWeek(1);
}
});
backBtn = findViewById(R.id.backBtn);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(StartProgramActivity.this, "back", Toast.LENGTH_SHORT).show();
determineWeek(0);
}
});
setUpWeekNavigation();
recyclerView = findViewById(R.id.weekExercisesRecycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
for(int i = 0 ; i<7; i++){
setWeekExercisesData(i);
}
userProgramWeekAdapter = new UserProgramWeekAdapter(this,programTrackerWrappers);
recyclerView.setAdapter(userProgramWeekAdapter);
}
public void getProgramDetails(int week){
allProgramTrackers = new ArrayList<>();
programTrackerReference
.child(GlobalUser.getmUser().getiD())
.child(program.getProgramsId()).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ProgramTracker programTracker = dataSnapshot.getValue(ProgramTracker.class);
// Log.d("Progra")
if(programTracker.getWeek() == (week-1)) {
allProgramTrackers.add(programTracker);
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setWeekExercisesData(int position){
switch (position){
case 0:
dayOfWeekExercises = new ArrayList<>();
for (int i = 0; i<allProgramTrackers.size(); i++){
if(allProgramTrackers.get(i).getDay().equals("Monday")){
dayOfWeekExercises.add(allProgramTrackers.get(i));
}
}
ProgramTrackerWrapper programTrackerWrapper = new ProgramTrackerWrapper("Monday", allProgramTrackers);
programTrackerWrappers.add(programTrackerWrapper);
Log.d(TAG, "DayOfWeekExercises: " + dayOfWeekExercises.toString());
break;
case 1:
dayOfWeekExercises = new ArrayList<>();
for (int i = 0; i<allProgramTrackers.size(); i++){
if(allProgramTrackers.get(i).getDay().equals("Tuesday")){
dayOfWeekExercises.add(allProgramTrackers.get(i));
}
}
ProgramTrackerWrapper programTrackerWrapper1 = new ProgramTrackerWrapper("Tuesday", allProgramTrackers);
programTrackerWrappers.add(programTrackerWrapper1);
Log.d(TAG, "DayOfWeekExercises: " + dayOfWeekExercises.toString());
break;
case 2:
dayOfWeekExercises = new ArrayList<>();
for (int i = 0; i<allProgramTrackers.size(); i++){
if(allProgramTrackers.get(i).getDay().equals("Wednesday")){
dayOfWeekExercises.add(allProgramTrackers.get(i));
}
}
ProgramTrackerWrapper programTrackerWrapper2 = new ProgramTrackerWrapper("Wednesday", allProgramTrackers);
programTrackerWrappers.add(programTrackerWrapper2);
Log.d(TAG, "DayOfWeekExercises: " + dayOfWeekExercises.toString());
break;
case 3:
dayOfWeekExercises = new ArrayList<>();
for (int i = 0; i<allProgramTrackers.size(); i++){
if(allProgramTrackers.get(i).getDay().equals("Thursday")){
dayOfWeekExercises.add(allProgramTrackers.get(i));
}
}
ProgramTrackerWrapper programTrackerWrapper3 = new ProgramTrackerWrapper("Thursday", allProgramTrackers);
programTrackerWrappers.add(programTrackerWrapper3);
Log.d(TAG, "DayOfWeekExercises: " + dayOfWeekExercises.toString());
break;
case 4:
dayOfWeekExercises = new ArrayList<>();
for (int i = 0; i<allProgramTrackers.size(); i++){
if(allProgramTrackers.get(i).getDay().equals("Friday")){
dayOfWeekExercises.add(allProgramTrackers.get(i));
}
}
ProgramTrackerWrapper programTrackerWrapper4 = new ProgramTrackerWrapper("Friday", allProgramTrackers);
programTrackerWrappers.add(programTrackerWrapper4);
Log.d(TAG, "DayOfWeekExercises: " + dayOfWeekExercises.toString());
break;
case 5:
dayOfWeekExercises = new ArrayList<>();
for (int i = 0; i<allProgramTrackers.size(); i++){
if(allProgramTrackers.get(i).getDay().equals("Saturday")){
dayOfWeekExercises.add(allProgramTrackers.get(i));
}
}
ProgramTrackerWrapper programTrackerWrapper5 = new ProgramTrackerWrapper("Saturday", allProgramTrackers);
programTrackerWrappers.add(programTrackerWrapper5);
Log.d(TAG, "DayOfWeekExercises: " + dayOfWeekExercises.toString());
break;
case 6:
dayOfWeekExercises = new ArrayList<>();
for (int i = 0; i<allProgramTrackers.size(); i++){
if(allProgramTrackers.get(i).getDay().equals("Sunday")){
dayOfWeekExercises.add(allProgramTrackers.get(i));
}
}
ProgramTrackerWrapper programTrackerWrapper6 = new ProgramTrackerWrapper("Sunday", allProgramTrackers);
programTrackerWrappers.add(programTrackerWrapper6);
Log.d(TAG, "DayOfWeekExercises: " + dayOfWeekExercises.toString());
break;
}
}
public ArrayList<ProgramTracker> getDayOfWeekExercises() {
return dayOfWeekExercises;
}
}
This look suspicious:
for (int i = 0; i < programTrackers.size(); i++){
if ( programTrackers.get(position).getProgramTrackers().get(i).isProgramExerciseFinished()){
isFinished = true;
}
}
You check the size of the programTrackers list, but not its sublists, so i could easily point to an incorrect index:
final int sublistSize = programTrackers.get(position).getProgramTrackers().size();
for (int i = 0; i < sublistSize; i++){
if (programTrackers.get(position).getProgramTrackers().get(i).isProgramExerciseFinished()){
isFinished = true;
}
}
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;
}
public class PerformanceDashboard extends MotherActivity {
String dashboardData;
int SELECTED_PAGE, SEARCH_TYPE, TRAY_TYPE;
List<String[]> cachedCounterUpdates = new ArrayList<String[]>();
List<DasDetails> docList = new ArrayList<DasDetails>();
ListView listViewDashboard;
DataAdapter dataAdap = new DataAdapter();
TextView noOfItems, userCount, totalLoginTime;
int itemsTotal = 0, userTotal = 0, totalTime = 0;
String KEYWORD = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (App.isTestVersion) {
Log.e("actName", "StoreOut");
}
if (bgVariableIsNull()) {
this.finish();
return;
}
setContentView(R.layout.dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setProgressBarIndeterminateVisibility(false);
lytBlocker = (LinearLayout) findViewById(R.id.lyt_blocker);
listViewDashboard = (ListView) findViewById(R.id.dashboard_listview);
noOfItems = ((TextView) findViewById(R.id.noOfItems));
userCount = ((TextView) findViewById(R.id.userCount));
totalLoginTime = ((TextView) findViewById(R.id.totalLoginTime));
new DataLoader().start();
listViewDashboard.setAdapter(dataAdap);
System.out.println("PerformanceDashboard. onCreate processOutData() -- item total " + itemsTotal); //0 i am not getting that adapter value i.e. 6
System.out.println("PerformanceDashboard. onCreate processOutData() -- user total " + userTotal); //0 i am not getting that adapter value i.e. 4
System.out.println("PerformanceDashboard. onCreate processOutData() -- total total " + totalTime); //0 i am not getting that adapter value i.e. 310
}
private class DataAdapter extends BaseAdapter {
#Override
public int getCount() {
return docList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.dashboard_item, null);
final DasDetails item = docList.get(position);
((TextView) convertView.findViewById(R.id.cMode))
.setText(item.cMode);
((TextView) convertView.findViewById(R.id.noOfItems))
.setText(item.totPickItemCount);
((TextView) convertView.findViewById(R.id.userCount))
.setText(item.userCount);
((TextView) convertView.findViewById(R.id.totalLoginTime))
.setText(item.totLoginTime);
TextView textView = ((TextView) convertView
.findViewById(R.id.avgSpeed));
Double s = Double.parseDouble(item.avgPickingSpeed);
textView.setText(String.format("%.2f", s));
if (position == 0 || position == 2 || position == 4) {
convertView.setBackgroundColor(getResources().getColor(
R.color.hot_pink));
} else if (position == 1 || position == 3 || position == 5) {
convertView.setBackgroundColor(getResources().getColor(
R.color.lightblue));
}
return convertView;
}
}
class ErrorItem {
String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public ErrorItem(HashMap<String, String> row) {
cMode = row.get(XT.MODE);
dDate = row.get(XT.DATE);
userCount = row.get(XT.USER_COUNT);
totLoginTime = row.get(XT.TOT_LOGIN_TIME);
totPickItemCount = row.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = row.get(XT.AVG_PICKING_SPEED);
}
}
private class DataLoader extends Thread {
#Override
public void run() {
super.run();
System.out.println("DataLoader dashboard");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair(C.PRM_IDX, C.GET_SUMMARY));
param.add(new BasicNameValuePair(C.PRM_HDR_DATA, "2016-07-04")); // yyyy-mm-dd
toggleProgressNoUINoBlock(true);
final String result = callService(C.WS_ST_PERFORMANCE_DASHBOARD,
param);
if (!App.validateXmlResult(actContext, null, result, true))
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Runnable r = new Runnable() {
#Override
public void run() {
dataAdap.notifyDataSetChanged();
toggleProgressNoUINoBlock(false);
}
};
dashboardData = result;
processOutData(r);
}
});
}
}
private String callService(String serviceName, List<NameValuePair> params) {
String result = ws.callService(serviceName, params);
return result;
}
private void processOutData(final Runnable rAfterProcessing) {
if (dashboardData == null || dashboardData.length() == 0)
return;
new Thread() {
#Override
public void run() {
super.run();
final List<HashMap<String, String>> dataList = XMLfunctions
.getDataList(dashboardData, new String[] { XT.MODE,
XT.DATE, XT.USER_COUNT, XT.TOT_LOGIN_TIME,
XT.TOT_PICK_ITEM_COUNT, XT.AVG_PICKING_SPEED });
final List<DasDetails> tempList = new ArrayList<DasDetails>();
for (int i = 0; i < dataList.size(); i++) {
int pos = docExists(tempList, dataList.get(i).get(XT.MODE));
if (pos == -1) {
if (SEARCH_TYPE == 0
|| KEYWORD.equals("")
|| (SEARCH_TYPE == 1 && dataList.get(i)
.get(XT.CUST_NAME).contains(KEYWORD))
|| (SEARCH_TYPE == 2 && dataList.get(i)
.get(XT.DOC_NO).contains(KEYWORD))) {
DasDetails doc = new DasDetails(dataList.get(i));
int cachePos = getPosInCachedCounterUpdates(doc.cMode);
if (cachePos != -1) {
if (cachedCounterUpdates.get(cachePos)[1]
.equals(doc.dDate))
cachedCounterUpdates.remove(cachePos);
else
doc.dDate = cachedCounterUpdates
.get(cachePos)[1];
}
tempList.add(doc);
pos = tempList.size() - 1;
}
}
if (pos == -1)
continue;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
docList = tempList;
rAfterProcessing.run();
logit("processOutData", "Processing OVER");
}
});
for (int i = 0; i < docList.size(); i++) {
itemsTotal = itemsTotal+ Integer.parseInt(docList.get(i).totPickItemCount);
userTotal = userTotal + Integer.parseInt(docList.get(i).userCount);
totalTime = totalTime + Integer.parseInt(docList.get(i).totLoginTime);
}
System.out.println("PerformanceDashboard.processOutData() -- fINAL item TOTAL " + itemsTotal); // 6 i have data here but i need this data in my oncreate but not getting why?????
System.out.println("PerformanceDashboard.processOutData() -- userTotal TOTAL " + userTotal); //4
System.out.println("PerformanceDashboard.processOutData() -- totalTime TOTAL " + totalTime); //310
noOfItems.setText(itemsTotal); // crashing with null pointer exception
// userCount.setText(userTotal);
// totalLoginTime.setText(totalTime);
};
}.start();
}
private class DasDetails {
public String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public DasDetails(HashMap<String, String> data) {
cMode = data.get(XT.MODE);
dDate = data.get(XT.DATE);
userCount = data.get(XT.USER_COUNT);
totLoginTime = data.get(XT.TOT_LOGIN_TIME);
totPickItemCount = data.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = data.get(XT.AVG_PICKING_SPEED);
}
}
public Integer docExists(List<DasDetails> list, String docNo) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).cMode.equals(docNo))
return i;
}
return -1;
}
private int getPosInCachedCounterUpdates(String docNo) {
for (int i = 0; i < cachedCounterUpdates.size(); i++) {
if (cachedCounterUpdates.get(i)[0].equals(docNo))
return i;
}
return -1;
}
}
This is the above code please go through it and let me know if any clarifications are required. I cannot able to set "itemsTotal" value to "noOfIttems" textview. I have added the comments. Please help me in solving this issue.
Thanks in advance.
Please check your noOfItems textView's id. TextView is null.
I defined my method as below and would like to return a 2D array but instead it returns a NULL . Can some one tell me whats wrong with this?
public String[][] parseInput150(String[] inputPercent150, String[][] input150Parsed ) {
String inputPer150fromXML = getResources().getString(R.string.InputPercent150);
inputPercent150 = inputPer150fromXML.split(Pattern.quote("|"));
input150Parsed = new String[inputPercent150.length-1][];
for (int i = 1; i < inputPercent150.length; i++) {
input150Parsed[i-1] = inputPercent150[i].split(Pattern.quote(" "));
}
for (int i = 0; i < input150Parsed.length; i++){
Log.e("TAG","Parsed Array value = " + Arrays.toString(input150Parsed[i]));
}
return input150Parsed;
}
The method call is below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
operationalSoldiers = (EditText) findViewById(R.id.operationalSoldiers);
operationalSoldiers.setText("150");
initialInput = setinitialInput(initialInput);
input150Parsed = parseInput150(inputPercent150, input150Parsed);
listView = (ListView) findViewById(R.id.list);
selectAll = (Button) findViewById(R.id.selectAll);
deselectAll = (Button) findViewById(R.id.deselectAll);
ArrayAdapter<String> adapter;
array = getResources().getStringArray(R.array.facilities);
strings1 = new ArrayList(Arrays.asList(array));
TopicSelectionListAdapter topicSelectionListAdapter = new TopicSelectionListAdapter(
second.this, R.layout.listrow, strings1);
listView.setAdapter(topicSelectionListAdapter);
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
for(int i=0;i<strings1.size();i++){
listView.setItemChecked(i, false);
}
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
CheckedTextView selectedItem = (CheckedTextView) view;
boolean isChecked = selectedItem.isChecked();
Log.e("TAG","item clicked position = " + position + " isChecked = " + isChecked);
for(int i=0; i< strings1.size(); i++){
if(!isChecked){
bArray[i]= 1;
}
else{
bArray[i]= 0;
}
System.out.print(bArray[i]);
}Log.e("TAG","boolean Array value = " + bArray);
}
});
selectAll.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View v) {
for(int i=0;i<strings1.size();i++){
listView.setItemChecked(i, true);
bArray[i]= 1;
}
totalSoldiers = (int) (operationalSoldiers.getAlpha() + (operationalSoldiers.getAlpha() * 0.13));
for (int r=0; r < input150Parsed.length; r++ ){
for(int c=0; c < input150Parsed[r].length; c++){
calculatedParValues[r][c] = ((totalSoldiers * (Integer.valueOf(input150Parsed[r][c]))) * Integer.valueOf(initialInput[c]));
}
}
for (int i = 0; i < calculatedParValues.length; i++){
Log.e("TAG","Parsed parameter value = " + Arrays.toString(calculatedParValues[i]));
}
}
});