Friday, 15 April 2011

java - Add another counter in the system -



java - Add another counter in the system -

i've got 1 counter in project working i'm trying set counter @ bottom of screen same work on count. there gonna 2 counters counting differently, can't work.

xml code:

<textview android:id="@+id/textviewcount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:text="@string/hello_world" /> <button android:id="@+id/buttoncount" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textviewcount" android:layout_alignright="@+id/textviewcount" android:layout_marginbottom="22dp" android:text="count" />

main code:

package com.example.counter; import android.app.activity; import android.content.sharedpreferences; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.textview; public class mainactivity extends activity { // private fellow member field maintain track of count private static int mcount = 0; private textview counttextview; private button countbutton; public static final string prefs_name = "com.example.myapp.mcount"; private sharedpreferences settings = null; private sharedpreferences.editor editor = null; /** add together method **/ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); counttextview = (textview) findviewbyid(r.id.textviewcount); countbutton = (button) findviewbyid(r.id.buttoncount); countbutton.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { mcount++; counttextview.settext("count: " + mcount); editor = settings.edit(); editor.putint("mcount", mcount); editor.commit(); } }); settings = getsharedpreferences(prefs_name, mode_private); } @override public void onpause() { super.onpause(); } @override public void onresume() { super.onresume(); mcount = settings.getint("mcount", 0); counttextview.settext("count: " + mcount); } }

you need threading perform task, each counter must run in individual thread.

do that:

thread t = new thread(new runnable(){ public void run() { thread.sleep(1000); counter++; } }); t.start();

or utilize asynctask

update:

make counter , 2 thread variables:

private static int mcount2 = 0; private static thread mt1, mt2;

then need method, this:

private void startcounter(thread t, counter) { t = new thread(new runnable(){ public void run() { while(true) { thread.sleep(1000); counter++; } } }); t.start(); }

you can phone call method in onclick-method each thread counter, have stop threads in onpause method:

@override public void onpause() { super.onpause(); mt1.stop(); mt2.stop(); }

maybe need if clauses test if thread acutally running.

java android button count

No comments:

Post a Comment