Passing data through Intent in Android, just want the number of clicks - android

I have a program that starts on one activity goes to the next and their is button to click, after a certain amount of time it goes back to the starting page and reports the number of clicks.
Here's my code: clickcount is the first activity
public class ClickCountActivity extends Activity {
/** Called when the activity is first created. */
Button next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next=(Button) findViewById(R.id.NextButton);
//---------------------------------------------------------------
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(ClickCountActivity.this, startClickActivity.class);
i.putExtra("comingFrom", "come");
final int result=1;
startActivityForResult(i,result);
}
});
//---------------------------------------------------------------------------
}
}
public class startClickActivity extends Activity {
/** Called when the activity is first created. */
Button clicker;
int counter ;
Timer timer = new Timer(); // use timer to start a new task
MyTimerTask task = new MyTimerTask();
final long seconds = 3;
Intent p = getIntent();
String answer = p.getStringExtra("comingFrom");
class MyTimerTask extends TimerTask {
public void run()
//override run method
{
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", answer);
setResult(RESULT_OK,x);
startActivity(x);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action);
clicker=(Button) findViewById(R.id.Clicker);
//---------------------------------------------------------------
clicker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++; // counts number of clicks
task.cancel(); // cancels current task
task = new MyTimerTask(); //create new task
timer.schedule(task,seconds*1000L); // start a new timer task in 5seconds (timertask, seconds(long))
// System.out.println(counter);
}
});
}
}

Your code in run method should be this:
Intent x = new Intent(startClickActivity.this, ClickCountActivity.class);
x.putExtra("returnStr", counter);
setResult(RESULT_OK,x);
finish();
You need to pass the no. of counts i.e. counter in intent and collect it from onActivityResult(int requestCode, int resultCode, Intent data) method of ClickCountActivity class. The value is passed in the data intent and can be queried using int counterValue = data.getIntegerExtra("returnStr", 0);

Related

Extended class calling function that should not be inherited

i have following problem:
I've made a simple android app that adds 1 to an integer every 1000 ms using a handler, and then display this integer.
The problem is that when i start another activity the same thing happens, which would be fine, if that was intended. The mentioned function is not called in the new activity and yet it seems to be. Please look over my code and show me where it went wrong..
MainActivity:
public class MainActivity extends ActionBarActivity {
protected TextView text;
protected int position;
private Handler handler = new Handler();
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
position=0;
SetButtonCLickListener();
counter();
}
protected void SetButtonCLickListener() {
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SwitchActivity();
}
});
}
private void counter() {
handler.removeCallbacks(count);
handler.postDelayed(count, 1000);
}
private Runnable count = new Runnable() {
public void run() {
i++;
text.setText("Count: " + i);
handler.postDelayed(count, 1000);
}
};
protected void SwitchActivity() {
if (position == 1) {
finish();
} else {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
}
SecondActivity
public class MainActivity2 extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
text = (TextView) findViewById(R.id.text);
SetButtonCLickListener();
position=1;
}
}
MainActivity2 has an onCreate() method. In the onCreate() method, you call super.onCreate(), which triggers the MainActivity implementation of onCreate(). The MainActivity implementation of onCreate() is where you are starting your counter thing, via its call to the counter() method. Hence, when MainActivity2 starts up, its onCreate() calls MainActivity's onCreate(), which calls counter().
My guess is that MainActivity2 should inherit from Activity, not from MainActivity.

How to pass integer variable through intent in android ?

I have tried passing variables through Intent before. But it seems that I am missing something that I cant pass the integer variable time. The question has been asked before by others, but I cant get it to work in this situation.
I want to pass the value of the integer variable time to another class which is aftertap.class through intent.
I have this code.
public class ingame extends Activity {
private TextView textTimer;
int time = 0;
Timer t;
TimerTask task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ingame);
Button button = (Button)findViewById(R.id.my_button);
final RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
params.leftMargin = button.getWidth()+ new Random().nextInt(displaymetrics.widthPixels - 2*button.getWidth());
params.topMargin = button.getHeight()+ new Random().nextInt(displaymetrics.heightPixels - 3*button.getHeight());
Log.v("widthPixels", ""+ displaymetrics.widthPixels);
Log.v("heightPixels", ""+ displaymetrics.heightPixels);
button.setLayoutParams(params);
startTimer();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
t.cancel();
t.purge();
//Starting a new Intent
Intent thirdscreen = new Intent(getApplicationContext(), aftertap.class);
//Sending data to another Activity
thirdscreen.putExtra("time", time);
startActivity(thirdscreen);
}
});
}
public void startTimer(){
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
textTimer = (TextView) findViewById(R.id.textTimer);
textTimer.setText(time + "");
time = time + 1;
}
});
}
};
t.scheduleAtFixedRate(task, 0, 1);
}
}
Aftertap class:
public class aftertap extends Activity{
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aftertap);
TextView gameover = (TextView)findViewById(R.id.gameover);
score = (TextView)findViewById(R.id.score);
Intent i = getIntent();
// Receiving the Data
//I do not know how to get the value of the integer variable time. I want to display the value of time in the TextView score
}
}
You should use getIntExtra() method:
int value = i.getIntExtra("time", 0);
Change the default value parameter (second parameter) to what you want it to be.
And then display the value
score.setText(String.valueOf(value));

Reset countdown timer in Android when switching between activities

Here I have 3 activities: A, B, and C. From Activity A When I click a button it will goes to Activity B. When Activity B loads the countdown timer will start. Again, when I click a button in Activity B it will go to Activity C. Here I Need a Help.
When Activity C starts I need the countdown timer from Activity B to resume.
Again I switch over from Activity C to Activity B the countdown timer should be resumed from Activity C.
Activity A
public class MainActivity extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.actone);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, Act_Two.class);
startActivity(intent);
}
});
}
}
Activity B
public class Act_Two extends Activity{
Button button;
public TextView textView1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.act_two);
textView1=(TextView) findViewById(R.id.textView1);
MyCount counter = new MyCount(61000,1000);
counter.start();
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.acttwo);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, Act_Three.class);
startActivity(intent);
}
});
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
//iFallApp app1 = new iFallApp();
#Override
public void onFinish() {
// TODO Auto-generated method stub
setContentView(R.layout.activity_main);
//textView1.setText("done");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
textView1.setText(Long.toString(millisUntilFinished/1000));
}
}
}
While switching between the activities, try to pass the current count down time with the help of Bundle.
You should save a value of your CountDownTimer in Activty B and stop the CountDownTimer (using the cancel() method) in Activty B's onPause and start that CountDownTimer with saved value in onResume of Activty B. something like (assuming this is an Activity B code):
#Override
public void onPause() {
// turning off the timer
isWihesCountUpdateTimerNeeded = false;
if (wihesCountUpdateTimer!=null)
wihesCountUpdateTimer.cancel();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
// resuming the timer
isWihesCountUpdateTimerNeeded = true;
totalWishesCount = SharedPrefsHelper.getTotalWishesCount(getActivity());
startWihesCountUpdateTimer();
}
// the timer increases some wishes count
private boolean isWihesCountUpdateTimerNeeded;
private CountDownTimer wihesCountUpdateTimer;
protected static final int wihesCountUpdateTimerDuration=5000;
protected int totalWishesCount;
private void startWihesCountUpdateTimer() {
wihesCountUpdateTimer = null;
if (!isWihesCountUpdateTimerNeeded)
return;
final int duration = wihesCountUpdateTimerDuration;
//Log.i(this, "startWihesCountUpdateTimer() duration: "+duration);
wihesCountUpdateTimer = new CountDownTimer(duration, 1000) {
#Override
public void onTick(long millisUntilFinished) {}
#Override
public void onFinish() {
totalWishesCount++;
SharedPrefsHelper.saveTotalWishesCount(getActivity(), totalWishesCount);
startWihesCountUpdateTimer();
}
}.start();
}

How can i code a time limit in my android game

i have a quiz game for my android that has a time limit. what i want is there is a choices button that if you click one of the buttons it you will be automatically intent to the class next level but if you didnt answer or click any of the button you will be intent to the other class, thats why the game has a time limit. my problem is i dont know how to put a time limit that will intent or transfer you in another class automatically if you didnt click any of the button choices. i tried sleep but what happen is even i already clicked the correct answer and im on the next level class it will sleep to the class i intented to my sleep. please help me with my problem. i also try handler but didnt work
public class EasyOne extends Activity {
Button a, b, c;
TextView timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (Button) findViewById(R.id.btn_ea1);
b = (Button) findViewById(R.id.btn_eb1);
c = (Button) findViewById(R.id.btn_ec1);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
private Runnable task = new Runnable() {
public void run() {
Handler handler = new Handler();
handler.postDelayed(task, 5000);
Intent intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
};
You should use a handler but in order to cancel the timeout you must remove the delayed message from the handler in your click listener code.
public class EasyOne extends Activity {
static private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 123) {
((EasyOne) msg.obj).onTimeout();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (Button) findViewById(R.id.btn_ea1);
b = (Button) findViewById(R.id.btn_eb1);
c = (Button) findViewById(R.id.btn_ec1);
Message msg = mHandler.obtainMessage(123,this);
mHandler.sendMessageDelayed(msg,5000);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"CORRECT!",
Toast.LENGTH_SHORT).show();
mHandler.removeMessages(123,this);
Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
startActivity(intent);
}
});
}
private void onTimeout() {
//your code
}
}

startActivityForResult to an activity that only displays a progressdialog

I'm trying to make an activity that is asked for some result. This result is normally returned instantly (in the onCreate), however, sometimes it is nesesary to wait for some internet-content to download which causes the "loader"-activity to show. What I want is that the loader-activity don't display anything more than a progressdialog (and that you can still se the old activity calling the loader-activity in the background) and I'm wondering wheather or not this is possible.
The code I'm using as of now is:
//ListComicsActivity.java
public class ListComicsActivity extends Activity
{
private static final int REQUEST_COMICS = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_comics);
Button button = (Button)findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intents.ACTION_GET_COMICS);
startActivityForResult(intent, REQUEST_COMICS);
}
});
}
/** Called when an activity called by using startActivityForResult finishes. */
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Toast toast = Toast.makeText(this, "The activity finnished", Toast.LENGTH_SHORT);
toast.show();
}
}
//LoaderActivity.java (answers to Intents.ACTION_GET_COMICS action-filter)
public class LoaderActivity extends Activity
{
private Intent result = null;
private ProgressDialog pg = null;
private Runnable returner = new Runnable()
{
public void run()
{
if(pg != null)
pg.dismiss();
LoaderActivity.this.setResult(Activity.RESULT_OK, result);
LoaderActivity.this.finish();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String action = getIntent().getAction();
if(action.equals(Intents.ACTION_GET_COMICS))
{
Runnable loader = new Runnable()
{
public void run()
{
WebProvider.DownloadComicList();
Intent intent = new Intent();
intent.setDataAndType(ComicContentProvider.COMIC_URI, "vnd.android.cursor.dir/vnd.mymir.comic");
returnResult(intent);
}
};
pg = ProgressDialog.show(this, "Downloading", "Please wait, retrieving data....");
Thread thread = new Thread(null, loader, "LoadComicList");
thread.start();
}
else
{
setResult(Activity.RESULT_CANCELED);
finish();
}
}
private void returnResult(Intent intent)
{
result = intent;
runOnUiThread(returner);
}
}
It turns out you can do this by setting the activitys theme-attribute to #android:style/Theme.Dialog and calling this.setVisible(false); in the onCreate-method of the activity.

Categories

Resources