Why is It happining this error when I run the app? - java

I want to create an app on that the idea is click on the button and changing an image. every time I click on the button an imageview change (dynamic imageview). I'm trying to do that but when I run the code below the first imageview is loaded and when I press the button, the first imageview jump to last imageview, ignoring two imageviews among them. What's wrong?
This is my code:
SEGUNDATELA. JAVA:
public class SegundaTela extends AppCompatActivity {
private Integer [] imagens = new Integer[]{R.drawable.tabeladia2, R.drawable.tabeladia3, R.drawable.tabeladia4, R.drawable.tabeladia5};
private RadioGroup radioGroup;
private RadioButton sim;
private RadioButton nao;
private Button proxima;
private ImageView img;
private int i=0;
private Integer [] dados= new Integer[4];
private int soma =0;
private int j;
private int inicio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_segunda_tela);
img = findViewById(R.id.imageView);
proxima = findViewById(R.id.proximaId);
radioGroup = findViewById(R.id.RadioGroupId);
sim = findViewById(R.id.simId);
nao = findViewById(R.id.naoId);
if (sim.isChecked()) {
inicio = 1;
} else if (nao.isChecked()) {
inicio = 0;
}
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i < 4) {
++i;
j = (i - 1);
switch (j) {
case 0:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 2;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 1:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 4;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 2:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 8;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
case 3:
if (sim.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 16;
} else if (nao.isChecked()) {
img.setImageResource(imagens[j]);
dados[j] = 0;
}
break;
}
radioGroup.clearCheck();
} else {
soma = dados[0] + dados[1] + dados[2] + dados[3] + inicio;
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
}
}
});
}
}
SEGUNDATELA.MML
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/proximaId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="proxima"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:scaleType="fitXY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/tabeladia1" />
<RadioGroup
android:id="#+id/RadioGroupId"
android:layout_width="98dp"
android:layout_height="86dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/imageView"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<RadioButton
android:id="#+id/simId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Sim" />
<RadioButton
android:id="#+id/naoId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Não" />
</RadioGroup>

Ever time you execute onClick() the entire for loop will execute. That is why. If you only want it to proceed one image at the time you need to find a different solution that allows you to keep state (knowing current image) between the "clicks".

You need to remove the for loop and increment everytime the button is clicked.
Use this if you want the images to be shown in a loop.
public class MainActivity extends AppCompatActivity {
private int [] imagens = {R.drawable.tabeladia2, R.drawable.tabeladia3,
R.drawable.tabeladia4, R.drawable.tabeladia5};
private Button proxima;
private ImageView img;
private Integer currentImg;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
proxima = findViewById(R.id.proximaId);
img = findViewById(R.id.imageView);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentImg != null && currentImg < 3) {
currentImg++;
} else {
currentImg = 0;
}
img.setImageResource(imagens[currentImg]);
}
});
}
}
Use this if you don't want the images to be looped
public class MainActivity extends AppCompatActivity {
private int [] imagens = {R.drawable.tabeladia2, R.drawable.tabeladia3,
R.drawable.tabeladia4, R.drawable.tabeladia5};
private Button proxima;
private ImageView img;
private Integer currentImg;
private int[] intArray = new int[4];
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
proxima = findViewById(R.id.proximaId);
img = findViewById(R.id.imageView);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentImg != null) {
if (currentImg < 3) {
currentImg++;
if(currentImg == 1){
intArray[1] = 2;
}else if(currentImg == 2){
intArray[2] = 4;
}else if(currentImg == 3){
intArray[3] = 8;}
img.setImageResource(imagens[currentImg]);
}else{
//handle last image reached condition
Toast.makeText(MainActivity.this, "Last image reached", Toast.LENGTH_SHORT).show();
}
} else {
currentImg = 0;
intArray[0] = 1;
img.setImageResource(imagens[currentImg]);
}
}
});
}
}
Using Case Statement and RadioButtons.
public class SegundaTela extends AppCompatActivity {
private Integer[] imagens = new Integer[]{R.drawable.tabeladia2, R.drawable.tabeladia3, R.drawable.tabeladia4, R.drawable.tabeladia5};
private RadioGroup radioGroup;
private RadioButton sim;
private RadioButton nao;
private Button proxima;
private ImageView img;
private Integer i;
private int soma = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_segunda_tela);
img = findViewById(R.id.imageView);
proxima = findViewById(R.id.proximaId);
radioGroup = findViewById(R.id.RadioGroupId);
sim = findViewById(R.id.simId);
nao = findViewById(R.id.naoId);
proxima.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!sim.isChecked() && !nao.isChecked()) {
Toast.makeText(SegundaTela.this, "Select an option", Toast.LENGTH_SHORT).show();
return;
}
if (i != null) {
if (i < 5) {
switch (i) {
case 0:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 2;
soma = soma + 2;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 1:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 4;
soma = soma + 4;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 2:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 8;
soma = soma + 8;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 3:
if (sim.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 16;
soma = soma + 16;
} else if (nao.isChecked()) {
img.setImageResource(imagens[i]);
//dados[j] = 0;
soma = soma + 0;
}
break;
case 4:
/*if (sim.isChecked()) {
//dados[j] = 16;
soma = soma + 32;
} else if (nao.isChecked()) {
//dados[j] = 0;
soma = soma + 0;
}*/
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
break;
}
++i;
Toast.makeText(SegundaTela.this, "soma: " + soma, Toast.LENGTH_SHORT).show();
radioGroup.clearCheck();
} /*else {
//soma = dados[0] + dados[1] + dados[2] + dados[3] + inicio;
Intent i = new Intent(SegundaTela.this, MainActivity.class);
i.putExtra("soma", soma);
startActivity(i);
}*/
}else {
if (sim.isChecked()) {
//inicio = 1;
soma = soma + 1;
} else if (nao.isChecked()) {
//inicio = 0;
soma = soma + 0;
}
i = 0;
radioGroup.clearCheck();
}
}
});
}
}

Related

Show hide alternate LinearLayouts when selecting RadioButton in 2 RadioGroups

Six RadioButtons aligned as 3 columns and 2 rows in a RadioGroup, so 6 RB-s in RG. If user selects a RB, right under it image1 and text1 are shown and under alternated RB-s image1 and text2 are also shown. User may select any RB. The proper behavior looks like that https://photos.app.goo.gl/NEqTaxsY6daxD3kJA
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg">
<include layout="#layout/app_bar" />
<fragment
android:id="#+id/refreshLayoutFragment"
class="kz.fingram.RefreshLayoutFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_refresh_layout" />
<LinearLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/activity_margin"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:paddingStart="#dimen/activity_margin"
android:paddingTop="#dimen/activity_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/when_u_want_money"
android:textAppearance="#style/TextAppearance.Medium" />
<RadioGroup
android:id="#+id/months"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener}" />
<LinearLayout
android:id="#+id/thisIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<RadioGroup
android:id="#+id/months2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener2}" />
<LinearLayout
android:id="#+id/thatIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<Button
style="#style/Button.Primary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:enabled="#{viewModel.mIsNextEnabled}"
android:onClick="#{viewModel::nextOnClick}"
android:text="#string/next" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Java code:
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
public final class OptionsActivity extends BaseAppCompatActivity {
private ActivityOptionsBinding mBinding;
public static void show(#NonNull final Context ctx) {
StorageHelper.getInstance().setInvited(false);
BaseAppCompatActivity.show(ctx, OptionsActivity.class, true, false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_options);
setupToolbar();
mBinding.setViewModel(new ViewModel());
}
public final class ViewModel extends BaseObservable {
private static final int TERM_6_MONTH_ID = 1;
private static final int INSTALLMENT_10000_ID = 1;
private final RefreshLayoutFragment mRefreshLayout;
public boolean mIsNextEnabled;
public TeamFreeMonth mMonth;
private TeamFreeMonth[] mMonths;
ViewModel() {
mMonth = null;
mMonths = null;
mRefreshLayout = (RefreshLayoutFragment) getSupportFragmentManager()
.findFragmentById(R.id.refreshLayoutFragment);
mRefreshLayout.setup(mBinding.root, new RefreshLayoutFragment.Callback() {
#Override
public void reload() {
try {
loadData();
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
});
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg2 = findViewById(R.id.months2);
rg2.setOnCheckedChangeListener(null);
rg2.clearCheck();
rg2.setOnCheckedChangeListener(mMonthOnCheckedChangeListener2);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener2 =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
private void refreshMonths() {
mBinding.months.removeAllViews();
mBinding.months.clearCheck();
mBinding.months2.removeAllViews();
mBinding.months2.clearCheck();
mBinding.thisIs.removeAllViews();
mBinding.thatIs.removeAllViews();
final TeamFreeMonth oldMonth = mMonth;
mMonth = null;
checkButtonsState();
if (mMonths == null) {
return;
}
final TeamFreeMonth[] months = mMonths;
if (months.length == 0) {
return;
}
int halfMonths = months.length / 2;
for (int i = 0; i < halfMonths; i++) {
final String date = UtilitiesHelper.dateToStr(months[i].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
final String date2 = UtilitiesHelper.dateToStr(months[i + halfMonths].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
if (TextUtils.isEmpty(date) || TextUtils.isEmpty(date2)) {
continue;
}
final RadioButton rb = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months, false);
rb.setId(i);
rb.setTag(months[i]);
final SpannableString btnCaption = new SpannableString(date);
btnCaption.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date.length(), 0);
rb.setText(btnCaption);
final RadioButton rb2 = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months2, false);
rb2.setId(i + halfMonths);
rb2.setTag(months[i + halfMonths]);
final SpannableString btnCaption2 = new SpannableString(date2);
btnCaption2.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date2.length(), 0);
rb2.setText(btnCaption2);
if (i == 0) {
rb.setBackgroundResource(R.drawable.ll_radio_button_start);
rb2.setBackgroundResource(R.drawable.ll_radio_button_start);
} else if (i == halfMonths - 1) {
rb.setBackgroundResource(R.drawable.ll_radio_button_end);
rb2.setBackgroundResource(R.drawable.ll_radio_button_end);
}
mBinding.months.addView(rb);
mBinding.months2.addView(rb2);
TextView thisIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_this_is_item, mBinding.thisIs, false);
thisIs.setId(rb.getId());
thisIs.setText(getString(R.string.thisIs));
thisIs.setVisibility(View.INVISIBLE);
mBinding.thisIs.addView(thisIs);
TextView thatIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_that_is_item, mBinding.thatIs, false);
thatIs.setId(rb2.getId());
thatIs.setText(getString(R.string.thatIs));
thatIs.setVisibility(View.INVISIBLE);
mBinding.thatIs.addView(thatIs);
if (oldMonth != null && UtilitiesHelper.isDateEquals(oldMonth.getDate(), months[i].getDate())) {
mBinding.months.check(rb.getId());
mBinding.months2.check(rb2.getId());
}
}
selectMonth();
}
private void selectMonth()
{
int selectedId1 = mBinding.months.getCheckedRadioButtonId();
int selectedId = selectedId1 !=-1 ? selectedId1 : mBinding.months2.getCheckedRadioButtonId();
int n = mBinding.months.getChildCount();
List<TextView> views = new ArrayList<TextView>();
for (int i = 0; i < n; i++) {
views.add(i, (TextView) mBinding.thisIs.getChildAt(i));
views.add(i+3, (TextView) mBinding.thatIs.getChildAt(i));
}
int length = views.size();
for (int i = 0; i < length; i++) {
TextView child = views.get(i);
}
private void checkButtonsState() {
mIsNextEnabled = mMonth != null;
notifyChange();
}
public void nextOnClick(final View view) {
try {
final TeamFreeMonth[] months = mMonths;
if (mMonth == null || months == null || months.length == 0) {
throw new Exception(getString(R.string.enter_month));
}
SettingsHelper.setTermId(OptionsActivity.this, TERM_6_MONTH_ID);//
SettingsHelper.setTermRateId(OptionsActivity.this, mMonth.getTermRateId());//
SettingsHelper.setInstallmentId(OptionsActivity.this, INSTALLMENT_10000_ID);
SettingsHelper.setGoalDateInMillis(OptionsActivity.this, mMonth.getDate().getTime());//дата получения
SettingsHelper.setFirstGoalDateInMillis(OptionsActivity.this, months[0].getDate().getTime());
SettingsHelper.setGoalSum(OptionsActivity.this, mMonth.getSum());
BaseAppCompatActivity.show(OptionsActivity.this, SetGoalActivity.class, true, false);
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
private void loadData() {
try {
final AsyncTask<Void, Void, TeamFreeMonth[]> task = new AsyncTask<Void, Void, TeamFreeMonth[]>() {
private Exception mError = null;
#Override
protected void onPreExecute() {
mRefreshLayout.setRefreshing(true);
}
#Override
protected TeamFreeMonth[] doInBackground(Void... params) {
try {
TeamFreeMonth[] months = ServerHelper.getInstance().syncGetOptionMonths(OptionsActivity.this, TERM_6_MONTH_ID, INSTALLMENT_10000_ID);
if (months != null && months.length > 0)
return months;
} catch (Exception e) {
mError = e;
}
return null;
}
#Override
protected void onPostExecute(TeamFreeMonth[] result) {
try {
if (mError != null) {
throw mError;
}
mMonths = result;
refreshMonths();
checkButtonsState();
mRefreshLayout.setRefreshing(false);
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
};
task.execute();
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
}
}
Image1 is always the same, while text1 and text2 differ. Text1 'You' is shown under the selected RB and text2 'Your friend' - under alternating RB-s.
The quetion still is how to show/hide image1 and text 1 or text 2 alternatively?
I can show/hide image1 and text-s under RB-s which is in the same column, but not alternating RB-s.

Buttons in a tic tac toe app are only recognizing certain columns

I have 9 buttons in an array and when I click a Button, the turn variable is set to the opposite boolean value to maintain turns.
When I run the app and click 3 X's or O's in all three rows it works and displays a toast message with the winner.
The problem is the columns: it only recognizes when I click 3 X's or O's in the 3rd column and displays a toast, but when I do the same with the first and second column, no toast/message is displayed.
The showWinner() method uses the determineWinner() method in order to display the message.
I need to find how to display the winner when they are in the 1st and 2nd columns.
my MainActivity:
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
//declaring instance variables to keep track of the button views and user turns
private Button[] btns;
private boolean turn = false;
private Button[][] btnsWin;
//creating an array of buttons in order to easily reference them
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create a toolbar and set it as the action bar
Toolbar myToolBar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolBar);
btns = new Button[9];
btnsWin = new Button[3][3];
int id = R.id.button1;
for(int i = 0; i < btns.length; i++)
{
btns[i] = (Button)findViewById(id);
id++;
}
id = R.id.button1;
for(int col = 0; col < btnsWin.length; col++)
for(int row = 0; row < btnsWin[0].length; row++)
{
btnsWin[col][row] = (Button)findViewById(id);
id++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem spinnerItem = menu.findItem(R.id.color_spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(spinnerItem);
spinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.colors_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return true;
}
#Override
public void onClick(View v) {
//get a handle on the textview in the xml
switch (v.getId()) {
case R.id.button1:
//checks what turn the user is on and sets the text in the button to either an X or an O
//depending on the turn. Then it sets the turn to the opposite boolean value.
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button2:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button3:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button4:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button5:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button6:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button7:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button8:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
case R.id.button9:
if (turn == false) {
((Button) v).setText("X");
turn = !turn;
} else {
((Button) v).setText("O");
turn = !turn;
}
showWinner();
v.setEnabled(false);
break;
}
}
public void showWinner()
{
Toast toast1 = null;
if(determineWinner().equals("X is the winner"))
{
toast1 = Toast.makeText(getApplicationContext(), "X is the winner", Toast.LENGTH_SHORT);
toast1.show();
}
else if(determineWinner().equals("O is the winner"))
{
toast1 = Toast.makeText(getApplicationContext(), "O is the winner", Toast.LENGTH_SHORT);
toast1.show();
}
}
public void resetBtns()
{
for(int i = 0; i < btns.length; i++)
{
btns[i].setEnabled(true);
btns[i].setText(R.string.space);
}
}
public void disableBtns()
{
for(int j = 0; j < btns.length; j++)
{
btns[j].setText("");
btns[j].setEnabled(false);
}
}
public String determineWinner()
{
String winner = " ";
int xHorizontal = 0;
int oHorizontal = 0;
int xVertical = 0;
int oVertical = 0;
// checking for x's and o's vertically
for(int x = 0; x < 3; x++)
{
if ((btns[x]).getText().equals("X") && (btns[x+3]).getText().equals("X") && (btns[x+6]).getText().equals("X")) {
xVertical = 3;
break;
}
else if ((btns[x]).getText().equals("O") && (btns[x+3]).getText().equals("O") && (btns[x+6]).getText().equals("O")) {
oVertical = 3;
break;
}
}
// checking for x's and o's horizontally
for(int i = 0; i < 9; i++)
{
if ((btns[i]).getText().equals("X") && (btns[i+1]).getText().equals("X") && (btns[i+2]).getText().equals("X")) {
xHorizontal = 3;
break;
}
else if ((btns[i]).getText().equals("O") && (btns[i+1]).getText().equals("O") && (btns[i+2]).getText().equals("O")) {
oHorizontal = 3;
break;
}
else
i = i + 2;
}
if(oHorizontal == 3 || oVertical == 3)
{
winner = "O is the winner";
}
if(xHorizontal == 3 || xVertical == 3)
{
winner = "X is the winner";
}
return winner;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast toast;
switch(item.getItemId())
{
case R.id.color_spinner:
toast = Toast.makeText(getApplicationContext(), "Select which color for X's or O's", Toast.LENGTH_SHORT);
toast.show();
break;
case R.id.action_favorite:
resetBtns();
toast = Toast.makeText(getApplicationContext(), "Buttons have been reset", Toast.LENGTH_LONG);
toast.show();
break;
}
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
switch(i)
{
case 0:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("X"))
btns[j].setTextColor(Color.BLACK);
break;
case 1:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("O"))
btns[j].setTextColor(Color.BLACK);
break;
case 2:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("X"))
btns[j].setTextColor(Color.MAGENTA);
break;
case 3:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("O"))
btns[j].setTextColor(Color.MAGENTA);
break;
case 4:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("X"))
btns[j].setTextColor(Color.CYAN);
break;
case 5:
for(int j = 0; j < btns.length; j++)
if(btns[j].getText().equals("O"))
btns[j].setTextColor(Color.CYAN);
break;
}
}
}
my layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="edu.ncc.tictactoe.MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<Button
android:id="#+id/button1"
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_toLeftOf="#+id/button2"
android:layout_below="#id/my_toolbar"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick" />
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button2"
android:textSize="35sp"
android:text=""
android:layout_below="#+id/my_toolbar"
android:layout_centerHorizontal="true"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_below="#id/my_toolbar"
android:id="#+id/button3"
android:textSize="35sp"
android:text="#string/space"
android:layout_toRightOf="#id/button2"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_below="#id/button1"
android:layout_toLeftOf="#+id/button5"
android:id="#+id/button4"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button5"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"
android:layout_below="#+id/button2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button6"
android:textSize="35sp"
android:text="#string/space"
android:layout_below="#id/button3"
android:layout_toRightOf="#id/button5"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:layout_below="#id/button4"
android:layout_toLeftOf="#+id/button8"
android:id="#+id/button7"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"/>
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button8"
android:textSize="35sp"
android:text="#string/space"
android:onClick="onClick"
android:layout_below="#+id/button5"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="116sp"
android:layout_height="110sp"
android:id="#+id/button9"
android:textSize="35sp"
android:text="#string/space"
android:layout_toRightOf="#id/button8"
android:layout_below="#id/button6"
android:onClick="onClick"/>
</RelativeLayout>
You need to access your views differently. id++ cannot be guaranteed to go from button1 to button2.
So, try something like this
btns = new Button[9];
btnsWin = new Button[3][3];
for(int i = 0; i < btns.length; i++)
{
int resID = getResources().getIdentifier("button"+(i+1), "id", getPackageName());
Button b = (Button) findViewById(resId);
btns[i] = b;
// I think this math is right...
btnsWin[i / 3][i % 3] = b;
}
For more information see Android, getting resource ID from string?

how to get id's of textviews and settextcolor to all textviews

java code
package"";
import yuku.ambilwarna.AmbilWarnaDialog;
/**
* Created by pc-4 on 5/31/2016.
*/
public class EditWindow extends ActionBarActivity implements View.OnClickListener {
private static final int SELECT_FILE = 1;
ImageView iv1,iv2,iv3,iv4,iv5,iv6,iv7,iv8,iv9,iv10,iv11,iv12;
Bitmap myBitmap;
ArrayList<Integer> vericalArrayList = new ArrayList<Integer>();
private LinearLayout hv;
int color = 0xffffff00;
LinearLayout linear_popup;
Context context = this;
String name, meaning;
int j = 0;
LinearLayout[] linearlayout;
LinearLayout ll_main;
String[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_window);
FinBtViewIds();
ll_main.setBackgroundResource(R.drawable.page_back_ground);
linear_popup = (LinearLayout) findViewById(R.id.linear_popup);
Bundle bundle = getIntent().getExtras();
name = bundle.getString("name");
meaning = bundle.getString("meaning");
j = name.length();
linearlayout = new LinearLayout[j];
items = meaning.split("\\s+");
verical_linear();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(EditWindow.this, "FAILES TO SET PIC", Toast.LENGTH_SHORT).show();
}
Drawable drawable = (Drawable) new BitmapDrawable(getResources(), bm);
LinearLayout ll_main = (LinearLayout) findViewById(R.id.linear);
ll_main.setBackground(drawable);
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_background:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.VISIBLE);
break;
case R.id.iv_gallery:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
galleryIntent();
break;
case R.id.iv_text:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
openDialog(true);
break;
case R.id.iv_edit_back:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
onBackPressed();
super.onBackPressed();
break;
case R.id.iv_edit_done:
linear_popup.setVisibility(View.GONE);
hv.setVisibility(View.GONE);
ll_main.post(new Runnable() {
public void run() {
//take screenshot
myBitmap = captureScreen(ll_main);
Toast.makeText(getApplicationContext(), "Screenshot captured..!", Toast.LENGTH_LONG).show();
try {
if(myBitmap!=null){
//save image to SD card
saveImage(myBitmap);
Intent i=new Intent(EditWindow.this,SaveActivity.class);
startActivity(i);
}
Toast.makeText(getApplicationContext(), "Screenshot saved..!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
break;
case R.id.iv_style:
hv.setVisibility(View.GONE);
if (linear_popup.getVisibility() == View.VISIBLE)
linear_popup.setVisibility(View.GONE);
else {
linear_popup.setVisibility(View.VISIBLE);
}
break;
case R.id.tv_horizontal:
hv.setVisibility(View.GONE);
horizontal_linear();
linear_popup.setVisibility(View.GONE);
break;
case R.id.tv_vertical:
hv.setVisibility(View.GONE);
verical_linear();
linear_popup.setVisibility(View.GONE);
break;
}
}
public void verical_linear() {
ll_main.setOrientation(LinearLayout.VERTICAL);
ll_main.setGravity(Gravity.CENTER);
ll_main.setVisibility(View.VISIBLE);
ll_main.removeAllViews();
int j = name.length();
final LinearLayout[] linearlayout = new LinearLayout[j];
String[] items = meaning.split("\\s+");
for (int i = 0; i < j; i++) {
LinearLayout parent = new LinearLayout(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
param.weight = 1;
parent.setLayoutParams(param);
parent.setOrientation(LinearLayout.HORIZONTAL);
TextView tv = new TextView(this);
int text_id;
Random r = new Random();
text_id = r.nextInt();
if (text_id < 0) {
text_id = text_id - (text_id * 2);
}
tv.setId(text_id);
Toast.makeText(EditWindow.this, String.valueOf(text_id), Toast.LENGTH_SHORT).show();
vericalArrayList.add(text_id);
Character c = name.charAt(i);
tv.setText(c.toString().toUpperCase());
Typeface face = Typeface.createFromAsset(getAssets(), "font/a.TTF");
tv.setTypeface(face);
tv.setTextSize(60);
TextView t2 = new TextView(this);
t2.setGravity(Gravity.END | Gravity.CENTER);
t2.setTypeface(Typeface.DEFAULT);
t2.setSingleLine(true);
t2.setMaxLines(2);
t2.setTextSize(20);
t2.setTypeface(face);
t2.setText(items[i]);
parent.addView(tv);
parent.addView(t2);
linearlayout[i] = parent;
ll_main.addView(parent);
}
}
public void horizontal_linear() {
ll_main.setOrientation(LinearLayout.HORIZONTAL);
ll_main.setGravity(Gravity.CENTER);
ll_main.setVisibility(View.VISIBLE);
ll_main.removeAllViews();
for (int i = 0; i < j; i++) {
LinearLayout parent = new LinearLayout(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
param.weight = 1;
parent.setLayoutParams(param);
parent.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
int text_id;
tv.setTag(tv.getId());
/*
Random r = new Random();
text_id = r.nextInt();
if (text_id < 0) {
text_id = text_id - (text_id * 2);
}*/
tv.setGravity(Gravity.CENTER);
Character c = name.charAt(i);
tv.setText(c.toString().toUpperCase());
Typeface face = Typeface.createFromAsset(getAssets(), "font/a.TTF");
tv.setTypeface(face);
tv.setTextSize(60);
TextView t2 = new TextView(this);
/* int text_id2;
Random r1 = new Random();
text_id2 = r1.nextInt();
if (text_id2 < 0) {
text_id2 = text_id2 - (text_id2 * 2);
}*/
t2.setTag(t2.getId());
t2.setGravity(Gravity.CENTER);
t2.setTypeface(Typeface.DEFAULT);
t2.setSingleLine(true);
t2.setMaxLines(1);
t2.setTypeface(face);
t2.setText(items[i]);
int id=t2.getId();
int id1=tv.getId();
vericalArrayList.add(id);
vericalArrayList.add(id1);
Toast.makeText(EditWindow.this, String.valueOf("1"+id), Toast.LENGTH_SHORT).show();
Toast.makeText(EditWindow.this, String.valueOf("2"+id1), Toast.LENGTH_SHORT).show();
parent.addView(tv);
parent.addView(t2);
linearlayout[i] = parent;
ll_main.addView(parent);
}
}
public void FinBtViewIds() {
final ImageView tv_horizontal;
final ImageView tv_vertical;
final ImageView iv_edit_back;
final ImageView iv_done;
final ImageView iv_gallery;
final ImageView iv_background;
final ImageView iv_style;
final ImageView iv_text;
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
iv4=(ImageView)findViewById(R.id.iv4);
iv5=(ImageView)findViewById(R.id.iv5);
iv6=(ImageView)findViewById(R.id.iv6);
iv7=(ImageView)findViewById(R.id.iv7);
iv8=(ImageView)findViewById(R.id.iv8);
iv9=(ImageView)findViewById(R.id.iv9);
iv10=(ImageView)findViewById(R.id.iv10);
iv11=(ImageView)findViewById(R.id.iv11);
iv12=(ImageView)findViewById(R.id.iv12);
ll_main = (LinearLayout) findViewById(R.id.linear);
hv = (LinearLayout) findViewById(R.id.hv);
iv_edit_back = (ImageView) findViewById(R.id.iv_edit_back);
tv_horizontal = (ImageView) findViewById(R.id.tv_horizontal);
tv_vertical = (ImageView) findViewById(R.id.tv_vertical);
iv_done = (ImageView) findViewById(R.id.iv_edit_done);
iv_gallery = (ImageView) findViewById(R.id.iv_gallery);
iv_background = (ImageView) findViewById(R.id.iv_background);
iv_style = (ImageView) findViewById(R.id.iv_style);
iv_text = (ImageView) findViewById(R.id.iv_text);
iv_edit_back.setOnClickListener(this);
iv_done.setOnClickListener(this);
iv_gallery.setOnClickListener(this);
iv_background.setOnClickListener(this);
iv_style.setOnClickListener(this);
iv_text.setOnClickListener(this);
tv_horizontal.setOnClickListener(this);
tv_vertical.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
}
}
void openDialog(boolean supportsAlpha) {
AmbilWarnaDialog dialog = new AmbilWarnaDialog(EditWindow.this, color, supportsAlpha, new AmbilWarnaDialog.OnAmbilWarnaListener() {
#Override
public void onOk(AmbilWarnaDialog dialog, int color) {
//Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_SHORT).show();
EditWindow.this.color = color;
displayColor();
}
#Override
public void onCancel(AmbilWarnaDialog dialog) {
// Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
dialog.show();
}
void displayColor() {
for (int i = 0; i < vericalArrayList.size(); i++) {
String id = vericalArrayList.get(i).toString();
TextView text = (TextView) findViewById(vericalArrayList.get(i));
text.setTextColor(color);
Toast.makeText(EditWindow.this, id + "/n" + i, Toast.LENGTH_SHORT).show();
}
}
public void Onclick(View v)
{
switch (v.getId())
{
case R.id.iv1:
ll_main.setBackgroundResource(R.drawable.n1);
break;
case R.id.iv2:
ll_main.setBackgroundResource(R.drawable.n2);
break;
case R.id.iv3:
ll_main.setBackgroundResource(R.drawable.n3);
break;
case R.id.iv4:
ll_main.setBackgroundResource(R.drawable.n4);
break;
case R.id.iv5:
ll_main.setBackgroundResource(R.drawable.n5);
break;
case R.id.iv6:
ll_main.setBackgroundResource(R.drawable.n6);
break;
case R.id.iv7:
ll_main.setBackgroundResource(R.drawable.n7);
break;
case R.id.iv8:
ll_main.setBackgroundResource(R.drawable.n8);
break;
case R.id.iv9:
ll_main.setBackgroundResource(R.drawable.n9);
break;
case R.id.iv10:
ll_main.setBackgroundResource(R.drawable.n10);
break;
case R.id.iv11:
ll_main.setBackgroundResource(R.drawable.n11);
break;
case R.id.iv12:
ll_main.setBackgroundResource(R.drawable.n12);
break;
}
}
public static void saveImage(Bitmap bitmap) throws IOException{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.png");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}
public static Bitmap captureScreen(View v) {
Bitmap screenshot = null;
try {
if(v!=null) {
screenshot = Bitmap.createBitmap(v.getMeasuredWidth(),v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(screenshot);
v.draw(canvas);
}
}catch (Exception e){
Log.d("ScreenShotActivity", "Failed to capture screenshot because:" + e.getMessage());
}
return screenshot;
}
}
xml
<LinearLayout
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:background="#color/white"
android:orientation="horizontal"
android:padding="#dimen/value_10"
android:visibility="visible">
</LinearLayout>
i didn't post imports
WHOLE XML DOENOT MATTER HERE SO I JUST here playing with single linearlayout so have added only that
have added full codes
error
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTextColor(int)' on a null object reference
As you are storing all TextView ids in array list and the only thing you need to do is cast that view to TextView and set text color.
TextView text = (TextView) findViewById(integerArrayList.get(i));
text.setTextColor(Color.RED);

[Android-Java]Learning android, layout work only once

I am learning how to make an android app, as my first project I'm trying to build a stupid game haha.
when I get to my second activity, The game runs as it has to (picture down)
http://i.imgur.com/BBllAJU.png?1
Than nothing changes, the score, the numbers, but all the toasts still coming.
package com.example.moshik.whatisbigger;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.DynamicLayout;
import android.text.Layout;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
Random rnd = new Random();
while (counter < 5) {
int Number1 = rnd.nextInt(99) + 1;
TextView X = (TextView) findViewById(R.id.XNumber);
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
TextView Y = (TextView) findViewById(R.id.YNumber);
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
TextView score = (TextView) findViewById(R.id.ScoreDisplay);
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.moshik.whatisbigger.NormalModeActivity1">
<include layout="#layout/content_normal_mode1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:id="#+id/ScoreDisplay"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/XNumber"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/ScoreDisplay"
android:layout_toStartOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/YNumber"
android:layout_alignTop="#+id/XNumber"
android:layout_toRightOf="#+id/ScoreDisplay"
android:layout_toEndOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Bigger"
android:layout_marginTop="121dp"
android:hint="#string/BIG"
android:layout_below="#+id/XNumber"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Equal"
android:layout_alignTop="#+id/Bigger"
android:layout_centerHorizontal="true"
android:hint="#string/EQUAL">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Smaller"
android:hint="#string/SMALL"
android:layout_alignTop="#+id/Equal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</Button>
Here is the layout and the activity itself.
Can you find what the problem here or what I miss?, thank you very much :)
You are never updating your score TextView. Change it to a class field first so it is easier to access in your callbacks.
private TextView score;
and then in your onCreate method:
score = (TextView) findViewById(R.id.ScoreDisplay);
Then update the text in each callback click listener after incrementing Score:
Score++;
score.setText("Your Score Is: " + Score);
Also, I would update your variable names to be more different as using Score for an int and score for a TextView is confusing.
Update Showing class field:
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
TextView X;
TextView Y;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
// set class fields
X = (TextView) findViewById(R.id.XNumber);
Y = (TextView) findViewById(R.id.YNumber);
score = (TextView) findViewById(R.id.ScoreDisplay);
Random rnd = new Random();
int Number1 = rnd.nextInt(99) + 1;
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
}
private void incrementAndCheckCounter() {
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}

Delete interface open camera on Android studio

I really need help here. I have project which call MyHeartRate, I downloaded the source code of heart rate project at Github. So I try to run that source code and there is no error. In the interface layout, it display the "camera". Example, when you open your camera then you will see the screen focus on what area that you want to take the picture. So my problem is, I want to remove that "camera" in my layout. I need to know which code need to be delete so then the "camera" not in my layout.
here's my code
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout">
<LinearLayout android:id="#+id/top"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="50dp">
<TextView android:id="#+id/text"
android:text="#string/default_text"
android:textSize="32dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.jwetherell.heart_rate_monitor.HeartbeatView android:id="#+id/image"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.jwetherell.heart_rate_monitor.HeartbeatView>
</RelativeLayout>
</LinearLayout>
<SurfaceView android:id="#+id/preview"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="0dp">
</SurfaceView>
java file(HeartRateMonitor)
public class HeartRateMonitor extends Activity {
private static final String TAG = "HeartRateMonitor";
private static final AtomicBoolean processing = new AtomicBoolean(false);
private static SurfaceView preview = null;
private static SurfaceHolder previewHolder = null;
private static Camera camera = null;
private static View image = null;
private static TextView text = null;
private static WakeLock wakeLock = null;
private static int averageIndex = 0;
private static final int averageArraySize = 4;
private static final int[] averageArray = new int[averageArraySize];
public static enum TYPE {
GREEN, RED
};
private static TYPE currentType = TYPE.GREEN;
public static TYPE getCurrent() {
return currentType;
}
private static int beatsIndex = 0;
private static final int beatsArraySize = 3;
private static final int[] beatsArray = new int[beatsArraySize];
private static double beats = 0;
private static long startTime = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preview = (SurfaceView) findViewById(R.id.preview);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
image = findViewById(R.id.image);
text = (TextView) findViewById(R.id.text);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onResume() {
super.onResume();
wakeLock.acquire();
camera = Camera.open();
startTime = System.currentTimeMillis();
}
#Override
public void onPause() {
super.onPause();
wakeLock.release();
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
private static PreviewCallback previewCallback = new PreviewCallback() {
#Override
public void onPreviewFrame(byte[] data, Camera cam) {
if (data == null) throw new NullPointerException();
Camera.Size size = cam.getParameters().getPreviewSize();
if (size == null) throw new NullPointerException();
if (!processing.compareAndSet(false, true)) return;
int width = size.width;
int height = size.height;
int imgAvg = ImageProcessing.decodeYUV420SPtoRedAvg(data.clone(), height, width);
// Log.i(TAG, "imgAvg="+imgAvg);
if (imgAvg == 0 || imgAvg == 255) {
processing.set(false);
return;
}
int averageArrayAvg = 0;
int averageArrayCnt = 0;
for (int i = 0; i < averageArray.length; i++) {
if (averageArray[i] > 0) {
averageArrayAvg += averageArray[i];
averageArrayCnt++;
}
}
int rollingAverage = (averageArrayCnt > 0) ? (averageArrayAvg / averageArrayCnt) : 0;
TYPE newType = currentType;
if (imgAvg < rollingAverage) {
newType = TYPE.RED;
if (newType != currentType) {
beats++;
// Log.d(TAG, "BEAT!! beats="+beats);
}
} else if (imgAvg > rollingAverage) {
newType = TYPE.GREEN;
}
if (averageIndex == averageArraySize) averageIndex = 0;
averageArray[averageIndex] = imgAvg;
averageIndex++;
// Transitioned from one state to another to the same
if (newType != currentType) {
currentType = newType;
image.postInvalidate();
}
long endTime = System.currentTimeMillis();
double totalTimeInSecs = (endTime - startTime) / 1000d;
if (totalTimeInSecs >= 10) {
double bps = (beats / totalTimeInSecs);
int dpm = (int) (bps * 60d);
if (dpm < 30 || dpm > 180) {
startTime = System.currentTimeMillis();
beats = 0;
processing.set(false);
return;
}
// Log.d(TAG,
// "totalTimeInSecs="+totalTimeInSecs+" beats="+beats);
if (beatsIndex == beatsArraySize) beatsIndex = 0;
beatsArray[beatsIndex] = dpm;
beatsIndex++;
int beatsArrayAvg = 0;
int beatsArrayCnt = 0;
for (int i = 0; i < beatsArray.length; i++) {
if (beatsArray[i] > 0) {
beatsArrayAvg += beatsArray[i];
beatsArrayCnt++;
}
}
int beatsAvg = (beatsArrayAvg / beatsArrayCnt);
text.setText(String.valueOf(beatsAvg));
startTime = System.currentTimeMillis();
beats = 0;
}
processing.set(false);
}
};
private static SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
camera.setPreviewCallback(previewCallback);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback", "Exception in setPreviewDisplay()", t);
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
Camera.Size size = getSmallestPreviewSize(width, height, parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
Log.d(TAG, "Using width=" + size.width + " height=" + size.height);
}
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Ignore
}
};
private static Camera.Size getSmallestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea < resultArea) result = size;
}
}
}
return result;
}
}
tq,
faizal
I found the answer. just comment this code
//preview = (SurfaceView) findViewById(R.id.preview);
//previewHolder = preview.getHolder();
//previewHolder.addCallback(surfaceCallback);
//previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
done.

Categories