I am working on this small game where each 500 ms an image is set to the image view
so what i want to check is when i click one of the arrow images(left,right,up,down) to check if it is equal to the random image ...if so then the score increases by 1.
here is my layout
https://i.stack.imgur.com/wPxZB.png
and here is my code
package com.andreh.catchthatarrow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class GameActivity extends AppCompatActivity {
ImageView img_up;
ImageView img_down;
ImageView img_left;
ImageView img_right,imgRand;
private int time = 600;
private static int SCORE = 0;
private TextView score;
int pos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
score = (TextView)findViewById(R.id.textView3);
img_up = (ImageView)findViewById(R.id.imgUp);
img_down = (ImageView)findViewById(R.id.imgDown);
img_left = (ImageView)findViewById(R.id.imgLeft);
img_right = (ImageView)findViewById(R.id.imgRight);
imgRand = (ImageView)findViewById(R.id.changeable);
final int [] arrBuckets = {R.drawable.arrow_left,R.drawable.arrow_right,R.drawable.up,R.drawable.down};
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
pos = arrBuckets[(int) (Math.random() * arrBuckets.length)];
imgRand.setImageResource(pos);
if(time>10 || time<20) time=100;
}
});
}
},0,time);
img_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==2){
SCORE++;
score.setText(SCORE+"");
}
}
});
img_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==3){
SCORE++;
score.setText(SCORE+"");
}
}
});
img_left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==0){
SCORE++;
score.setText(SCORE+"");
}
}
});
img_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==1){
SCORE++;
score.setText(SCORE+"");
}
}
});
}
}
You are checking the data in the index and you need the position so use this instead:
pos = Array.asList(arrayBuckets).indexOf((int) (Math.random() * arrBuckets.length));
img_up.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
if(pos==2)
{
SCORE++;
score.setText(SCORE+"");
}
});
Related
I will make this as specific as possible. I've created a Page Which uses RecyclerAdapter to show card items in grid.And I have set a Default Activity for each card using OnclickListner ,So when you click any card item it will take you to that Default Activity Like this Image.And mine one Look Like this click here.My question is how can I open a perticular card in recyler Adapter from a different activity.In my app I want that when I press Go button on popup It will it toggle lvl2 or the next card to open the game activity.
Java file for RecyclerAdapter
package com.example.apptuzzle;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mcontext;
private List<InGameContent> mData;
public RecyclerViewAdapter(Context mcontext, List<InGameContent> mData){
this.mcontext = mcontext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mcontext);
view = mInflater.inflate(R.layout.cardview_items1,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.Title.setText(mData.get(position).getTitle());
holder.Title.setTag(position);
holder.cardview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = (int) getItemId(position) + 1;
Intent intent = new Intent(mcontext,InGame_wrkfunction.class);
intent.putExtra("pos", pos);
//passing data to the InGame_wrkfunction.class
intent.putExtra("Answrr",mData.get(position).getAnswrr());
intent.putExtra("Thumbnail",mData.get(position).getThumbnail());
intent.putExtra("Description",mData.get(position).getDescription());
// start the activity
mcontext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView Title;
CardView cardview;
public MyViewHolder(View itemView) {
super(itemView);
Title = (TextView) itemView.findViewById(R.id.LvL_id1);
cardview = (CardView) itemView.findViewById(R.id.cardview_id);
}
}
}
Default Game Activity
package com.example.apptuzzle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class InGame_wrkfunction extends AppCompatActivity {
private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btndot; //Buttons Declaration
private Button btnclr, btnsubm, popup_g_button1;
private TextView txtv1, txtv2, popup_g_msg1, popup_g_des1,highscore1;
int scores = 0;
private LinearLayout Popup_layout11;
private Animation pop_animation;
private ImageView img,popup_g_img1,popup_b_img; //Question Declaration
private TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_game_wrkfunction);
btn0 = (Button) findViewById(R.id.Btn0);
btn1 = (Button) findViewById(R.id.Btn1);
btn2 = (Button) findViewById(R.id.Btn2);
btn3 = (Button) findViewById(R.id.Btn3);
btn4 = (Button) findViewById(R.id.Btn4);
btn5 = (Button) findViewById(R.id.Btn5);
btn6 = (Button) findViewById(R.id.Btn6);
btn7 = (Button) findViewById(R.id.Btn7);
btn8 = (Button) findViewById(R.id.Btn8);
btn9 = (Button) findViewById(R.id.Btn9);
btndot = (Button) findViewById(R.id.Btndot);
btnclr = (Button) findViewById(R.id.BtnClr);
btnsubm = (Button) findViewById(R.id.BtnSubm);
img = (ImageView) findViewById(R.id.gamethumbnail);
txtv1 = (TextView) findViewById(R.id.TxtV1);
txt = (TextView) findViewById(R.id.TxtV2);
Popup_layout11 = findViewById(R.id.Popup_layout11);
txt = (TextView) findViewById(R.id.TxtV2);
popup_g_button1 = findViewById(R.id.Popup_G_button1);
popup_g_msg1 = findViewById(R.id.Popup_G_msg1);
popup_g_des1 = findViewById(R.id.Popup_G_des1);
popup_g_img1 = findViewById(R.id.Popup_G_Img12);
highscore1 = findViewById(R.id.ScoreCounter1);
pop_animation = AnimationUtils.loadAnimation(this, R.anim.pop_up);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + "9");
}
});
btndot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackgroundResource(R.drawable.input_bttn_colorc);
txtv1.setText(txtv1.getText() + ".");
}
});
btnclr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtv1.setBackground(null);
txtv1.setText(null);
}
});
// Receive data
Intent intent = getIntent();
String Description = intent.getExtras().getString("Description"); //It ll fetch data from Description()
int image = intent.getExtras().getInt("Thumbnail");
int pos = intent.getExtras().getInt("pos");
final String answrr1 = intent.getExtras().getString("Answrr");
//Setting Values
img.setImageResource(image); ////It ll replace the image that was fetched previously
txt.setText(Description);
//Load Scores
SharedPreferences myscores = this.getSharedPreferences("MyAwesomeScores", Context.MODE_PRIVATE);
scores = myscores.getInt("scores", 0); //0 tha phehele
highscore1.setText("Scores:" + scores);
btnsubm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String a = txtv1.getText().toString();
if (a.equals(answrr1)) {
scores += 30;
//Save scores
SharedPreferences myscores = getSharedPreferences("MyAwesomeScores", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myscores.edit();
editor.putInt("scores", scores);
editor.commit();
v.setOnClickListener(null);//Remove setOnClickListener
highscore1.setText("Scores:" + scores);
Popup_layout11.setVisibility(LinearLayout.VISIBLE);
Popup_layout11.setAnimation(pop_animation);
Popup_layout11.animate();
pop_animation.start();
} else {
scores -= 30;
//Save scores
SharedPreferences myscores = getSharedPreferences("MyAwesomeScores", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myscores.edit();
editor.putInt("scores", scores);
editor.commit();
v.setOnClickListener(null);//Remove setOnClickListener
highscore1.setText("Scores:" + scores);
popup_g_img1.setImageResource(R.drawable.sadface11);
popup_g_msg1.setText("Ohh Snap!");
popup_g_des1.setText("Don't worry Kid you just tap the button to move on to the next lesson. REMEMBER 'never waste time'.");
Popup_layout11.setVisibility(LinearLayout.VISIBLE);
Popup_layout11.setAnimation(pop_animation);
Popup_layout11.animate();
pop_animation.start();
}
}
});
}
}
/*Two Ways of Putting One Animation In an activity
* 1st One
* Anim1 = AnimationUtils.loadAnimation(this, R.anim.new_animfile1);
// pop_img1.setVisibility(View.GONE);
Btn1.setOnClickListener(new View.OnClickListener() { <-----In this type you can put animation inside On Click Listener
#Override
public void onClick(View v) {
Layout1.setVisibility(LinearLayout.VISIBLE);
Anim1.setDuration(500);
Layout1.setAnimation(Anim1);
Layout1.animate();
Anim1.start();
}
});
*
*
* 2nd One
* public class MyActivity extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); <-----In this type you can set another class outside the OnCreate Bundle
}
public void animate(View view){
LinearLayout dialog = (LinearLayout)findViewById(R.id.dialog);
dialog.setVisibility(LinearLayout.VISIBLE);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim);
animation.setDuration(500);
dialog.setAnimation(animation);
dialog.animate();
animation.start();
}
}
* */
What I understand is you want to open different activities on each card click.If it's correct then,
use switch inside your onClick and open your activity on a particular item click
#Override
public void onClick(View v) {
final Intent intent;
switch (getAdapterPostion()){
case 0:
intent = new Intent(context, FirstActivity.class);
break;
case 1:
intent = new Intent(context, SecondActivity.class);
break;
...
default:
intent = new Intent(context, DefaultActivity.class);
break;
}
context.startActivity(intent);
}
Or Use:-
#Override
public void onClick(View v) {
final Intent intent;
if (getAdapterPosition() == sth){
intent = new Intent(context, OneActivity.class);
} else if (getPosition() == sth2){
intent = new Intent(context, SecondActivity.class);
} else {
intent = new Intent(context, DifferentActivity.class);
}
context.startActivity(intent);
}
I want to change the TextView of editor activity by clicking on Button buttonExpense which should also open editor activity and show value of the result in
EditText mAmountEditText.
I am getting java.lang.ClassCastException in which it is clearly written that MainActivity cannot be cast to EditorActivity
Calculator.java
package com.example.harshitbahri.expensebook;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends android.support.v4.app.Fragment {
Button button0;
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
Button button6;
Button button7;
Button button8;
Button button9;
Button buttonAdd;
Button buttonSubstract;
Button buttonMul;
Button buttonDiv;
Button buttonClear;
Button buttonEqual;
Button buttonExpense;
String result;
String tmp;
String operator;
TextView resultTextView;
FragmentActivity fa2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fa2 = (FragmentActivity) super.getActivity();
final View RootView= inflater.inflate(R.layout.activity_calculator, container, false);
button0 = (Button)RootView.findViewById(R.id.button0);
button1 = (Button)RootView.findViewById(R.id.button1);
......
buttonAdd = (Button)RootView.findViewById(R.id.buttonAdd);
buttonClear = (Button)RootView.findViewById(R.id.buttonClear);
buttonSubstract = (Button)RootView.findViewById(R.id.buttonSub);
buttonMul = (Button)RootView.findViewById(R.id.buttonMul);
buttonDiv = (Button)RootView.findViewById(R.id.buttonDiv);
buttonEqual = (Button)RootView.findViewById(R.id.buttonEqual);
buttonExpense= (Button)RootView.findViewById(R.id.buttonExp);
resultTextView = (TextView)RootView.findViewById(R.id.text_view_result);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("0");
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("2");
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("3");
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("4");
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("5");
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("6");
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("7");
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("8");
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onNumberButtonClicked("9");
}
});
buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClearButtonClicked();
}
});
buttonSubstract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
onOperatorButtonClicked("-");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("+");
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("X");
}
});
buttonDiv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOperatorButtonClicked("/");
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqualButtonClicked();
}
});
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
startActivity(intent);
((EditorActivity) getActivity()).updateGoldTextView(result);
/*Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra(, result);
final int result2=1;
startActivityForResult(intent, result2);*/
}
});
return RootView;
}
private void onEqualButtonClicked() {
int res = 0;
try {
int number = Integer.valueOf(tmp);
int number2 = Integer.valueOf(resultTextView.getText().toString());
switch (operator) {
case "+":
res = number + number2;
break;
case "/":
res = number / number2;
break;
case "-":
res = number - number2;
break;
case "X":
res = number * number2;
break;
}
result = String.valueOf(res);
resultTextView.setText(result);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void onOperatorButtonClicked(String operator) {
..
}
public void onClearButtonClicked() {
...
}
public void onNumberButtonClicked(String pos) {
..
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}`
EditorActivity.java
package com.example.harshitbahri.expensebook;
import android.app.AlertDialog;
import android.app.LoaderManager;
...
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class EditorActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final int EXISTING_EXPENSE_LOADER = 0;
private Uri mCurrentExpenseUri;
private EditText mAmountEditText;
private EditText mDescEditText;
private Spinner mCategorySpinner;
private String mCategory = ExpenseEntry.CATEGORY_GENERAL;
private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
mExpenseHasChanged = true;
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editor);
// Examine the intent that was used to launch this activity,
// in order to figure out if we're creating a new pet or editing an existing one.
Intent intent = getIntent();
mCurrentExpenseUri = intent.getData();
// If the intent DOES NOT contain a pet content URI, then we know that we are
// creating a new pet.
if (mCurrentExpenseUri == null) {
// This is a new pet, so change the app bar to say "Add a Pet"
setTitle("Add Expense");
yet.)
invalidateOptionsMenu();
} else {
// Otherwise this is an existing pet, so change app bar to say "Edit Pet"
setTitle("Edit Expense");
getLoaderManager().initLoader(EXISTING_EXPENSE_LOADER, null, this);
}
mAmountEditText = (EditText) findViewById(R.id.exp_amount);
mDescEditText = (EditText) findViewById(R.id.description);
mCategorySpinner = (Spinner) findViewById(R.id.spinner_category);
.....
}
......
finish();
}
public void updateGoldTextView(String goldAmount) {
mAmountEditText.setText(goldAmount);
}
}
MainActivity.java
package com.example.harshitbahri.expensebook;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
Calculator.OnFragmentInteractionListener ,
Entries.OnFragmentInteractionListener,Info.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final Pageradapter adapter = new Pageradapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setCurrentItem(1, false);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Your fragment is loaded from MainActivity and not EditorActivity, hence the class cast exception. If you want to pre-fill some data in the editor activity, you can pass that in the intent ( the code you commented on your onclick listener) and retrieve in the EditorActivity and set your UI elements.
Edited
buttonExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(fa2, EditorActivity.class);
intent.putExtra("result", result);
startActivity(intent);
}});
In your EditorActivity class, in on create
String result=getIntent().getStringExtra("result")
updateGoldTextView(result)
This is the line i want to repeat.
handler.postDelayed(runnableCode, 1);
This app is a tycoon app and so the user can buy upgrades and if they tap the button the get $$ and so when they buy upgrades keeping the value up-to-date is required.
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter = 0;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int Test = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler.postDelayed(runnableCode, 1);
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ButtonCounter(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
intent.putExtra("Count", Counter);
startActivity(intent);
finish();
}
});
}
public int ButtonCounter(int Counter){
Counter+=1;
return Counter;
}
public int AutoCounter(int Counter, int add) {
Counter+=add;
return Counter;
}
public void Display(int Counter, TextView myTextView) {
String man = String.valueOf(Counter);
myTextView.setText("$" + man);
}
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
// Do something here on the main thread
Counter = AutoCounter(Counter,Test);
Display(Counter, myTextView);
}
};
}
handler.postDelayed(runnableCode, 1);
call that line inside onResume() method. Make sure your show an AlertDialog to the user whenever he or she hits the button to get $$. Since the AlertDialog pops up everytime the user tries to buy $$. onResume() will be called.
Try this
private void startAnimation() {
countDownTimer = new CountDownTimer(700, 500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
//your code to repeat
}
start();
}
}.start();
}
I have a button that goes from one activity to another activity and its supposed to save the value int Counter, but every time it never saves. What am I doing wrong? I have seen other solutions, but i check and im doing the exact same thing as them.
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
add = savedInstanceState.getInt("Count");
Counter = savedInstanceState.getInt("Add");
}
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Counter = ButtonCounter(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Count", Counter);
startActivity(intent);
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
Counter = AutoCounter(Counter, add);
Display(Counter, myTextView);
handler.postDelayed(this, 100);
}
}, 10);
}
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("Count", Counter);
savedInstanceState.putInt("Add", add);
}
public int ButtonCounter(int Counter) {
Counter += 1;
return Counter;
}
public int AutoCounter(int Counter, int add) {
Counter += add;
return Counter;
}
public void Display(int Counter, TextView myTextView) {
String man = String.valueOf(Counter);
myTextView.setText("$" + man);
}
}
you're not implementing the right method
from the docs:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("Count", Counter);
savedInstanceState.putInt("Add", add);
// call superclass to save any view hierarchy
super.onSaveInstanceState(outState);
}
Source: https://developer.android.com/guide/components/activities/activity-lifecycle.html#oncreate
This is My main activity program :
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static ImageView im1;
private static Button btm,btm2;
private int current_image_index;
int[] images={R.mipmap.mylogo,R.mipmap.picasa,R.mipmap.twitter};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onclk(View v)
{
im1=(ImageView)findViewById(R.id.imageView);
btm=(Button)findViewById(R.id.button);
btm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % (images.length);
im1.setImageResource(images[current_image_index]);
}
});
}
public void onclk2(View v)
{
im1=(ImageView)findViewById(R.id.imageView);
btm2=(Button)findViewById(R.id.button2);
btm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index--;
current_image_index = current_image_index % (images.length);
im1.setImageResource(images[current_image_index]);
}
});
}
}
I desighned two button named as forwardbutton and backward button, i set an onclick property for each buttons, first btton onclik(), second button onclk2() function.....
But while running the app backward button doesnot works
use
btm2.setOnClickListener
insted of
btm.setOnClickListener
in second function
and the complete code is
public void onclk2(View v)
{
im1=(ImageView)findViewById(R.id.imageView);
btm2=(Button)findViewById(R.id.button2);
btm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index--;
current_image_index = current_image_index % (images.length);
im1.setImageResource(images[current_image_index]);
}
});
}
}
Replace this code with your Code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static ImageView im1;
private static Button btm,btm2;
private int current_image_index;
int[] images={R.mipmap.mylogo,R.mipmap.picasa,R.mipmap.twitter};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onclk(View v)
{
im1=(ImageView)findViewById(R.id.imageView);
btm=(Button)findViewById(R.id.button);
btm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index++;
current_image_index = current_image_index % (images.length);
im1.setImageResource(images[current_image_index]);
}
});
}
public void onclk2(View v)
{
im1=(ImageView)findViewById(R.id.imageView);
btm2=(Button)findViewById(R.id.button2);
// Your Error Was Here/in Below Line
btm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index--;
current_image_index = current_image_index % (images.length);
im1.setImageResource(images[current_image_index]);
}
});
}
}
public void onclk2(View v)
{
im1=(ImageView)findViewById(R.id.imageView);
btm2=(Button)findViewById(R.id.button2);
btm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
current_image_index--;
current_image_index = current_image_index % (images.length);
im1.setImageResource(images[current_image_index]);
}
});
}
Hope this will helps...(: