Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private long sTime = 0L;
private Handler myHandler = new Handler();
private long wait2 = 1000000000;
private int telnum2;`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button butt = (Button) findViewById(R.id.butt);
Button buttstop = (Button) findViewById(R.id.buttstop);
if (butt != null) {
butt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText wait = (EditText) findViewById(R.id.editText2);
wait2 = Integer.parseInt(wait.getText().toString()) * 1000;
EditText telnum = (EditText) findViewById(R.id.editText);
telnum2 = Integer.parseInt(telnum.getText().toString());
sTime = SystemClock.uptimeMillis();
myHandler.removeCallbacks(AutoCaller);
myHandler.postDelayed(AutoCaller, wait2);
}
});
}
buttstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myHandler.removeCallbacks(AutoCaller);
}
});
}
private Runnable AutoCaller = new Runnable() {
#Override
public void run() {
final long start = sTime;
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + telnum2)));
myHandler.postDelayed(this, wait2);
}
};
#Override
protected void onPause() {
myHandler.removeCallbacks(AutoCaller);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
myHandler.postDelayed(AutoCaller, wait2);
}}
layout_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
It creates 2 EditText and 2 Buttons.
I type number (0111) in first and (1) in second.
I click 1st button (id:butt) and it calls number 111 (i typed 0111).
Thanks!
Thats logic: You parse the String "0111" to an Integer, but numbers never start with zero if it isnt zero itself or a float/double value. So Java removes the zero when parsing, because the zero is useless for a number, because it doesnt change the value of the number.
The problem is, you are parsing the number as an Integer
telnum2 = Integer.parseInt(telnum.getText().toString());
Leading Zeros in Numbers are stripped (0100 is the same number as 100 for example). You have to keep the number as String to preserve the leading zero.
Change the Variable type to String and Dont parse it to Integer.
"Phone numbers" are not actually numbers, they are sequences of digits. They have no numeric magnitude ("my phone number is higher than yours!"), and in particular, leading zeros are significant, which is not the case for numbers. So you should always treat them as strings, not as numbers.
Related
I tried to populate RadioGroup's RadioButtons on "onCreateMethod" rather than using XML because my purpose is to get it from some sort of database or other business objects model that works with randomicity. RadioButtons are fine, but nothing happens when I click them otherwise when I created in XML activity file, not a log message neither a test toast. By the way, as I said, I need to create the buttons by code, thanks, is my first steps in Android.
My Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
My Code:
public class ListaAlunosActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = view.getId();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
Buttons are okay!
using onClick for finding selected radio button is not the best solution but because you want to use onClick i will show you how to do it with minimum changes to your code. make these three changes to your code:
public class ListaAlunosActivity extends AppCompatActivity
implements View.OnClickListener {// <------ 1. implement OnClickListener
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setOnClickListener(this);// <---------- 2.add this line
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
#Override
public abstract void onClick (View v){ //<-------- 3. override onClick
boolean checked = ((RadioButton) v).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = v.getId();// your radio buttons have no id thus use title instead of id:
String title = ((RadioButton) v).getText();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
If you look keenly, your onRadioButtonClicked is just a method that is never called. Now what you have to do is make the Activity implement RadioGroup.OnCheckedChangeListener. And in onCheckedChanged method, do the Toast and it will work. Here is the code.
public class ListaAlunosActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alnus);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setId(i);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
listaDeQuestoes.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast toast2 = Toast.makeText(this, "toast working for id "+ checkedId, Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
I did this and it works perfectly
Not completely sure what your code is meant to do, but I would use a setOnCheckedChangeListener rather than onClick.
Something like this
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
final String TAG = "MyActivity"; // not used?
Log.v("On clicked working", "clicado");
// Note checkedId is +1 when accessing the arraylist so needs to be decremented to get a list item
Toast toast2 = Toast.makeText(ListaAlunosActivity.this, "toast working clicked (" + checkedId + ") [" + dataList.get(checkedId - 1) + "]", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
});
The Toast is working and I showed how you can determine which button was clicked and how to access your data array with it, if desired.
The main reason for this, as BAHMAN points out, is that you haven't set any listener. HOWEVER. Setting a listener on the buttons themselves is not a very good idea. It is better to set it on the radio group. And it's better to have your layout elements in your layout file. This makes them easier to modify and understand.
Another thing that is personal preference: I prefer implementing the listener as an anonymous class where it is set. The solutions where the class implements the listener make it harder to read for large classes where it can be annoying to go looking for listeners. I might make an exception if the listener is very complex or if it something that might be used more than once.
I also cleaned up the code a bit. Comments added where I did
Anyway, here's how I would write this code:
Main Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio_button_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Main Activity Code:
public class ListaAlunosActivity extends AppCompatActivity {
// I put your tag at the top of the class so it's more useful
public static final String TAG = "ListaAlunosActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
// You didn't really need an arraylist here for this static content.
// I just made it an array
String[] dataList = {"sup1", "sup2", "sup3"};
// Get this from your layout instead of adding it manually.
// It's a cleaner way to set up the layout that makes the
// code more maintainable
RadioGroup listaDeQuestoes = findViewById(R.id.radio_button_list);
// I changed this to a for each loop because it's a little cleaner
for (String name : dataList){
RadioButton botao = new RadioButton(this);
botao.setText(name);
listaDeQuestoes.addView(botao);
}
// This is the code that will react to the new radio button being selected
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Either way we do it, we need to grab the view to get the name
RadioButton buttonView = group.findViewById(checkedId);
// You can use this code to get the index if you need it
int checkedIndex = group.indexOfChild(buttonView);
// And you can use either of these methods to get the name:
String buttonNameFromView = buttonView.getText().toString();
String buttonNameFromDataSource = dataList[checkedIndex];
String output = "Button with Id: " + checkedId + " and Name: " + buttonNameFromView + " was clicked";
Log.v(TAG, output);
Toast toast = Toast.makeText(ListaAlunosActivity.this, output, Toast.LENGTH_LONG);
// I set gravity to just center here. This is the same as center_vertical | center_horizontal. Personally, I wouldn't set it at all.
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
}
I am trying to make an app and I have the code for a button inside of a different class. When I start my app and click the first button it brings me to a different layout where the button is located. But when I click this button it doesn't do anything, just the little click down animation.
First Button Code:
public class TextAdd extends AppCompatActivity {
public static EditText Text;
public static Button Set;
public static String[] Checkagainst = new String[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Text_Checker);
Text = (EditText) findViewById(R.id.LPN);
Set = (Button) findViewById(R.id.Set);
Set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Text_Value = Text.getText().toString();
if (!Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.add);
for (int i = 0; i < Checkagainst.length; i++) {
if (Checkagainst[i] == null) {
Checkagainst[i] = Text_Value;
break;
}
}
} else if (Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.have);
}
}
});
}
}
Second Button Code:
public class Have extends AppCompatActivity {
private Button HaveBack;
private TextView Have;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.have);
HaveBack = (Button) findViewById(R.id.HaveBack);
Have= (TextView) findViewById(R.id.Have);
String Text_Value= TextAdd.License.getText().toString();
String Extra = Text_Value + " is already part of Your license plates";
Have.setText(Extra);
HaveBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.Text_Checker);
}
});
}
}
Does anyone know what is wrong? If so can you please help me.
You should use setContentView() only once in your onCreate() method. Calling it multiple times is not correct. If you want to show a small layout above your current layout, you should use a Dialog and if you want to show a completely different layout above everything, you have to use Intents to go to another activity and do the rest of the work in that one.
besides, use lowercase letters at start of your variables' and objects' names and start Class names with Uppercase letters. That's the standard for knowing what is a class and what is an object. e.g.
Button firstButton, secondButton;
I am working on an Android calculator app not using any of the built in timer based classes in Android, but instead using Handlers and Threads to update the UI. I'm not sure if there is a problem with my logic or not, but for whatever reason when I set a time and hit the Start button, nothing happens on the screen at all. The targeted TextView does not decrease as it should. Again, I may have made a simple errors (or a few), but I am posting my java and xml files for you all to look at. Thanks in advance for any responses.
TimerActivity.java
package com.example.stins.intentsandtimer;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import android.content.Context;
import android.os.Vibrator;
public class TimerActivity extends AppCompatActivity implements View.OnClickListener {
TextView hours, minutes, seconds;
Button numberPicker;
private int hrs, min, sec;
private boolean start;
Handler timerHandler = new Handler(){
/**
* Handler for the timer class. It receives the onStart runnable to allow the textviews
* to be updated. It checks to see if all textviews are empty and only updates them if
* they follow the conditions of a traditional timer. Including moving from 1 hour to 59 minutes.
* The handler also sends the Vibrator function once the timer is complete.
* #param msg
*/
#Override
public void handleMessage(Message msg){
super.handleMessage(msg);
TextView txtSeconds = (TextView) findViewById(R.id.textview_seconds);
TextView txtMinutes = (TextView) findViewById(R.id.textview_minutes);
TextView txtHours = (TextView) findViewById(R.id.textview_hours);
int zeroCheck = Integer.parseInt(txtSeconds.getText().toString());
if (zeroCheck > 0) {
sec -= 1;
txtSeconds.setText(sec + "");
} else if (min > 0 && sec == 0) {
min -= 1;
txtMinutes.setText(min + "");
sec = 59;
txtSeconds.setText(sec + "");
} else if (hrs > 0 && min == 0 && sec == 0) {
hrs -= 1;
txtHours.setText(hrs + "");
min = 59;
txtMinutes.setText(min + "");
sec = 59;
txtSeconds.setText(sec + "");
} else {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
this.setTitle("Timer");
Button btnStart = (Button) findViewById(R.id.start_button);
Button btnStop = (Button) findViewById(R.id.stop_button);
Button btnReset = (Button) findViewById(R.id.reset_button);
hours = (TextView) findViewById(R.id.textview_hours);
numberPicker = (Button) findViewById(R.id.btn_set_hours);
numberPicker.setOnClickListener(this);
minutes = (TextView) findViewById(R.id.textview_minutes);
numberPicker = (Button) findViewById(R.id.btn_set_minutes);
numberPicker.setOnClickListener(this);
seconds = (TextView) findViewById(R.id.textview_seconds);
numberPicker = (Button) findViewById(R.id.btn_set_seconds);
numberPicker.setOnClickListener(this);
btnReset.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
TextView txtSeconds = (TextView) findViewById(R.id.textview_seconds);
TextView txtMinutes = (TextView) findViewById(R.id.textview_minutes);
TextView txtHours = (TextView) findViewById(R.id.textview_hours);
sec = 0;
min = 0;
hrs = 0;
txtSeconds.setText(sec+"");
txtMinutes.setText(min+"");
txtHours.setText(hrs+"");
}
}
);
btnStart.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
start = true;
onStart();
}
}
);
btnStop.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
start = false;
}
}
);
}
protected void onStart(){
super.onStart();
final Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
while (sec > 0 || min > 0 || hrs > 0) {
if(start) {
try {
Thread.sleep(1000);
timerHandler.sendMessage(timerHandler.obtainMessage());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else{
}
}
}
});
myThread.start();
}
public void onClick (View v){
switch (v.getId()) {
case R.id.btn_set_hours:
hourPickerDialog();
break;
case R.id.btn_set_minutes:
minutePickerDialog();
break;
case R.id.btn_set_seconds:
secondPickerDialog();
break;
default:
break;
}
}
private void hourPickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(99);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
hours.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Hours");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
private void minutePickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(59);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
minutes.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Minutes");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
private void secondPickerDialog(){
NumberPicker myNumberPicker = new NumberPicker(this);
myNumberPicker.setMaxValue(59);
myNumberPicker.setMinValue(0);
NumberPicker.OnValueChangeListener myValChangedListener = new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
seconds.setText(""+newVal);
}
};
myNumberPicker.setOnValueChangedListener(myValChangedListener);
AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(myNumberPicker);
builder.setTitle("Set Seconds");
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
}
activity_timer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/textview_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text=":"
android:textSize="70sp"/>
<TextView
android:id="#+id/textview_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text=":"
android:textSize="70sp"/>
<TextView
android:id="#+id/textview_seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="00"
android:textSize="70sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:id="#+id/btn_set_hours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hours"/>
<Button
android:id="#+id/btn_set_minutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Minutes"/>
<Button
android:id="#+id/btn_set_seconds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Seconds"/>
</LinearLayout>
<Button
android:id="#+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_start"
style="#style/MyButton"
/>
<Button
android:id="#+id/stop_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_stop"
style="#style/MyButton"/>
<Button
android:id="#+id/reset_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="?selectableItemBackgroundBorderless"
android:text="#string/timer_reset"
style="#style/MyButton"/>
</LinearLayout>
There's several things going on in your code. I won't try to address them all but just some to get your code doing about what it should. I've copied & tried your code & it actually changes the display for me. I skipped your time picker dialogs & just set sec=20 to start. If you're not getting any changing display, is the display being set initially from the time pickers?
Anyway, 1st let's talk about debugging. One way to do this is to put Log statements in your code. Start by putting this at the top of the file
private final static String TAG = "TimerActivity";
Then in the code have things like this:
// put this in the start button click listener
Log.d(TAG, "Start clicked");
// or this in handleMessage
Log.d(TAG, "handleMessage(), seconds = " + sec);
Having these Log message can help you know what your program has done & what it hasn't, plus show you some variable values. You could also use the debugger which I won't get into now.
Now for your code. onStart() is a lifecycle method. You should not call it yourself. Rename your method (maybe something like onStartButton()). As you have it now, you have 2 instances of your thread running and your counter goes down twice in each second.
In handleMessage(), you have variables (hrs, min, sec) that you use to track the time but you also have zeroCheck that you read from the text on the display. The better thing to do would be use the variables you're already keeping anyway (if(sec > 0) { sec -= 1;...). I didn't verify your logic in the rest of these conditions. Once the display is updating, I'll leave that for you.
Lastly, txtSeconds.setText(sec + ""); is not a good way to use setText() (it's probably OK for Log messages but it's better to get accustomed to using text in other ways). There is more than 1 good way to display text but for this instance, you need special formatting. That is you want your display to show a leading 0 for each number "00:09:07" not "0:9:7". You can get that with
txtSeconds.setText(String.format("%02d", sec));
This way always gives a 2 digit display, from 0 to 59. Other useful formatters are "%08x" for 32 bit hexadecimal or "%.2f" which limits display to 2 places past the decimal place like for showing dollars and cents.
So, none of these will fix the problem in your post but they will get your final code closer to what it needs to be. As I said, your code updates the display as it is for me (not using the time pickers). You can start by setting sec to a fixed number then hit the "Start" button to see what happens. If there are problems in your time pickers, you can use Log messages to track down the bugs & fix them.
EDIT:
So what's happening with your timer not starting is that, while you change the display in your number picker, you don't set the underlying variables (sec etc.) Define some variables to use as temp storage (temp_sec etc.) then set this in onValueChange(),
temp_sec = newVal;
Now in your positiveButton onClick(), you'll have
sec = temp_sec;
I keep getting "Application not responding" when trying to implement a CountDownTimer. Here's what I have:
private TextView mTextField;
private EditText secText;
private int secs;
private Button buttonStart, buttonStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextField = (TextView) findViewById(R.id.textView1);
secText = (EditText) findViewById(R.id.segText);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
secs = Integer.parseInt(secText.getText().toString());
final CountDownTimer count = new CountDownTimer((secs*1000), 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("Seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("FINISHED!");
}
};
The problem is with this line when it tries to parse, if I put a number it works:
secs = Integer.parseInt(secText.getText().toString());
Make sure you know the sequence of actions you need to perform. Here's some pseudo code
if buttonstart_clicked
get text from sectext
if text is empty
show error
else if text is notANumber
show error
else
parse text AND start timer
You forgot your starting point is the button click, not the start of the application, because your edittext is still empty by then.
You need to handle all the cases when trying to get the text from the EditText.
What if the EditText is empty?
What if the value in the EditText is not an Integer? ("1bs25", or "hello")
You need to consider these things and handle them properly before trying to parse the value into an Integer and start the timer.
I know this is a simpleton question, but I am not going to school for java, just learning it online.
how to a have a textview with an initial value of 0. and then everytime you press a button it ads 25 points to the score board.
At first I wanted the button press to add a random number between 42-57 to the score board.
And then how to do convert that int or long to a string to make it fit into a textview and keep the current score, and then add a new score.
EDIT: ok so someone said I should post the code so here it is.. where do i put this..
TextView txv182 = (TextView) findViewById(R.id.welcome);
txv182.setText(toString(finalScore));
Because when I do it, I get an error: The method toString() in the type Object is not applicable for the arguments (int)
public class MainActivity extends Activity {
// Create the Chartboost object
private Chartboost cb;
MediaPlayer mp = new MediaPlayer();
SoundPool sp;
int counter;
int db1 = 0;
Button bdub1;
TextView txv182;
int finalScore;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txv182 = (TextView) findViewById(R.id.welcome);
finalScore = 100;
sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
db1 = sp.load(this, R.raw.snd1, 1);
bdub1 = (Button) findViewById(R.id.b4DUB1);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (db1 != 0)
sp.play(db1, 1, 1, 0, 0, 1);
txv182.setText(finalScore);
}
});
First you need to store your score to certain integer variable say score and set it to any initial value you want and use.
TextView tv = (TextView) findViewById(R.id.myTextView);
tv.setText(toString(score));
you do not need to initialize the textview with value just in onclick() of button do score+=25and add text to your textview as above.
hope this helps
It's actually like this..
pernts+=25;
txv182.setText(String.valueOf(pernts));
in android, after the
public class MainActivity extends Activity {
but before..
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i wrote..
int pernts;
String strI;
so then after the above #Override majigy, i wrote..
strI = "" + pernts;
pernts = 0;
because when i wrote it like.. int pernts = 0; it never worked, forcing me to add final and what not..
any way.. How to convert an integer value to string? anSwered the question..
and so the end was like this
pernts+=25;
txv182.setText(String.valueOf(pernts));
i figured out you have to add a value to the int variable not the string.. i kept wanting to add 25 and i was getting 25252525252525.., instead of 25 50 75 100.. kinda cool actually.. separating the logic of how to "add" 25 .. anyway thanks.. SOF!
30 minutes later... found this.. How can I generate random number in specific range in Android?
..
import android.app.Activity;
public class InsMenu extends Activity {
static TextView txv182;
static int pernts;
Button bdub1;
public static void addPernts() {
int min = 37;
int max = 77;
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;
pernts+=i1;
txv182.setText(String.valueOf(pernts));
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.BLAHBLAH);
bdub1 = (Button) findViewById(R.id.b4DUB1);
txv182 = (TextView) findViewById(R.id.welcome);
bdub1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
addPernts();
}
--- i created my first objekt thanks to this too.. http://www.tutorialspoint.com/java/java_methods.htm ..