How to return a value from void in android - android-timepicker

Hello I m new to android development I m developing an app which requires to get the hour and minute from timePicker so I did like this to get it:
public class MainActivity extends Activity {
TimePicker timePicker;
int hour, changedHour;
int minute, changedMinute;
TextView tv, tv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView1);
tv1 = (TextView) findViewById(R.id.textView2);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
setCurrentTime();
timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker arg0, int hourOfDay,
int minuteOf) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Time set!",
Toast.LENGTH_SHORT).show();
changedHour = hourOfDay;
changedMinute = minuteOf;
tv.setText("Hour of Day is " + changedHour + " and Minute is "
+ changedMinute);
}
});
tv1.setText("Hour of Day is " + changedHour + " and Minute is "
+ changedMinute);
}
public void setCurrentTime() {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}`
The problem is here
changedHour = hourOfDay;
changedMinute = minuteOf;
tv.setText("Hour of Day is " + changedHour + " and Minute is "
+ changedMinute);
I got the changed time and I set it like hour would be in hourOfDay = changedHour and same for minute now outside the method when I m trying to use the variables the problem is its set to 0 HERE
tv1.setText("Hour of Day is " + changedHour + " and Minute is "
+ changedMinute);
Please help me!

You never actually assign to the changedHour or changedMinute variables before you print them using tv1.setText, since it's very likely that onTimeChanged hasn't ever fired by that point. For this reason, they'll have their default values of 0, since they haven't been assigned anything else yet.
Anyway, you can't return values out of a void function. By definition, void is a lack of a type.
How to fix this depends on how exactly you want the code to work. The path of least resistance would be to set changedHour and changedMinute from within setCurrentTime, e.g.
public void setCurrentTime() {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// NEW CODE
changedHour = hour;
changedMinute = minute;
// END NEW CODE
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
You could return the hour and minute through some other mechanism (return a struct or use out parameters), but given that you update changedHour/Minute in your onTImeChanged callback, it probably wouldn't fit well with the existing flow.
On a re-read though, this could all just be because you're using the wrong variable in tv1.setText. You assign to the class variables hour and minute in setCurrentTime, so you could just print those rather than changedHour and changedMinute, e.g.
tv1.setText("Hour of Day is " + hour + " and Minute is "
+ minute);

Related

Countdown Timer on Android Java

I have a quiz application which I have a function that a certain category will only be available once every 24hours in just 15mins. Now I am planning to put a timer same on the flash sale of the eCommerce Application.
Been looking on the internet but those timer are not fix and it will start again from the top if you refresh your Activity. anyone can give me some advice on this matter it will also base the timer for the server time not device time :)
I have found some here in stackoverflow. I want this countdown will always start at 11:15AM and will ends at 11:00AM on the following day and start the countdown again at 11:15AM. It would be better if I can use timezone also that even they change their device time the timer won`t be affected.
private void start_countdown_timer()
{
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
formatter.setLenient(false);
String endTime = "18.09.2017, 15:05:36";
long milliseconds=0;
final CountDownTimer mCountDownTimer;
Date endDate;
try {
endDate = formatter.parse(endTime);
milliseconds = endDate.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startTime = System.currentTimeMillis();
mCountDownTimer = new CountDownTimer(milliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
startTime=startTime-1;
Long serverUptimeSeconds =
(millisUntilFinished - startTime) / 1000;
String daysLeft = String.format("%d", serverUptimeSeconds / 86400);
//txtViewDays.setText(daysLeft);
Log.d("daysLeft",daysLeft);
String hoursLeft = String.format("%d", (serverUptimeSeconds % 86400) / 3600);
//txtViewHours.setText(hoursLeft);
Log.d("hoursLeft",hoursLeft);
String minutesLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) / 60);
//txtViewMinutes.setText(minutesLeft);
Log.d("minutesLeft",minutesLeft);
String secondsLeft = String.format("%d", ((serverUptimeSeconds % 86400) % 3600) % 60);
//txtViewSecond.setText(secondsLeft);
Log.d("secondsLeft",secondsLeft);
}
#Override
public void onFinish() {
}
}.start();
}
You can store your timer state in local storage (eg. shared preference ) at the time of refreshing your activity. You need to do it activity life cycle onPause method. Then in onResume method, you need to check the timer state whether it is already started or not and update the timer based on that.

Processing 'Search' in an Arraylist

I'm stuck with the following problem within Processing for a school assignment.
I'm using a dataset in a tab seperated format, This is being read and parsed to my Activity class. The (menuAnswer, "Subagency") is used so I only get the data I need.
for(TableRow singleRow : trafficTable.findRows(menuAnswer, "SubAgency")){
Activity singleActivity = new Activity();
singleActivity.parseRow(singleRow);
activities.add(singleActivity);
}
The Activity class looks this:
class Activity{
String violationType;
String subAgency;
String race;
String gender;
Date readDate;
void parseRow(TableRow row){
this.subAgency = row.getString("SubAgency");
this.violationType = row.getString("Violation Type");
this.race = row.getString("Race");
this.gender = row.getString("Gender");
this.readDate = parseDate(row.getString("Time Of Stop") + " " + row.getString("Date"), "HH:mm:ss dd-MM-yyyy");
}
void printInfo(){
println(subAgency + " / " + race + " / " + readDate + " / " + violationType);
}
}
Every (usefull) piece of my dataset is inserted into an variable.
In my main class I want to search in the violationType String and count the ammount of "Warning"s within this String. I use the following code, which is not working:
for (Activity singleActivity : activities)
if(singleActivity.violationType == "Warning"){
warningCount++;
println("is it working?");
}
What am I doing wrong?
Mello
After searching I found my answer:
for (Activity singleActivity : activities)
if(singleActivity.violationType == "Warning"){
warningCount++;
println("is it working?");
}
My notation of my If statement is wrong and should be with .equals instead of == operator, like this:
void countWarning(){
for (Activity singleActivity : activities){
if(singleActivity.violationType.equals("Warning")){
warningCount++;
}
}
}

Second part of program is not running c#

when i run this program, static void Main2() runs but not static void Main4(), im not sure why. also, i have multiple c# class files in my visual studio 2015rc console application and only one of them runs but i have multiple c classes, how does anyone run multiple c classes? and how do i control which class runs first?
using System;
namespace ConsoleApplication1.Examples
{
class ExampleOne
{
static void Main2()
{
Console.Write("Please Enter Name 1 ");
string name1 = Console.ReadLine();
Console.Write("Please Enter Name 2 ");
string name2 = Console.ReadLine();
Console.Write("The First Name is " + name1 +" "+ name2);
Console.ReadKey();
}
static void Main4()
{
Console.Write("Please Enter Number 1 ");
int x = int.Parse(Console.ReadLine());
Console.Write("Please Enter Number 2 ");
int y = int.Parse(Console.ReadLine());
int z = x + y;
Console.Write("The numbers are: " + x + " " + y);
Console.ReadKey();
Console.Write(z);
}
}
}
why dont you create functions instead of Main() classes.
if you want to pursue that Main() classes, remove the "static" variable before the Main() classes, use public instead

Exception in thread "Thread-4" java.lang.NullPointerException?

i have a problem with this exception.
I'm trying to make a function to display data from database on a table, every keystroke i made at jtextfield. So its like the table automatically refreshed with new data everytime i type in the jtextfield.
Here's the code :
First i have this variable :
private Statement stmt;
List<Barang> dataSBarang =new LinkedList();
boolean searchBarang=true;
Searching sBarang;
And this is how i call the function :
private void inputkodeTFMouseClicked(java.awt.event.MouseEvent evt){
sBarang = new Searching( stmt, dataSBarang, modelDetail, tabelDetailBarang, inputkodeTF, searchBarang);
sBarang.start();
}
And this is the Searching Object
public class Searching extends Thread{
private Statement stmt;
private List<Barang> dataBarang;
private JTable jTabelBarang;
private JTextField tf;
private boolean cari;
private DefaultTableModel modelBarang;
public Searching(Statement stmt, List<Barang> dataBarang, DefaultTableModel tm, JTable jTabelBarang, JTextField tf, boolean cari){
this.stmt=stmt;
this.dataBarang=dataBarang;
this.modelBarang=tm;
this.jTabelBarang=jTabelBarang;
this.tf=tf;
this.cari=cari;
}
#Override
public void run(){
String temp="";
while(cari==true){
//System.out.println("jalan");
try{
String masukan = tf.getText();
System.out.println(masukan);
if(!masukan.equals("")&&!masukan.equals(temp)){
clearTableBarang();
//System.out.println("Mencari "+ masukan);
ResultSet rs = stmt.executeQuery("select kode_barang, nama_barang, jumlah_stok, " +
"minimal_stok, harga_jual, deskripsi_barang from BARANG WHERE (kode_barang LIKE " +
"'"+masukan+"%')");
System.out.println(rs);
while(rs.next()){
String kode_barang = rs.getString ("kode_barang");
String nama_barang = rs.getString ("nama_barang");
int jumlah_stok = rs.getInt("jumlah_stok");
int minimal_stok = rs.getInt("minimal_stok");
int harga_jual = rs.getInt("harga_jual");
String deskripsi_barang = rs.getString ("deskripsi_barang");
//System.out.println(kode_barang+" "+deskripsi_barang);
dataBarang.add(new Barang(kode_barang,nama_barang,jumlah_stok,minimal_stok,harga_jual,deskripsi_barang));
((DefaultTableModel) jTabelBarang.getModel()).insertRow(jTabelBarang.getRowCount(), new Object[]{kode_barang, nama_barang, jumlah_stok, minimal_stok, harga_jual, deskripsi_barang});
}
temp = masukan;
}
else if(masukan.equals("")&&!masukan.equals(temp)) {
clearTableBarang();
showTableBarang();
temp = masukan;
}
} catch(SQLException s){s.printStackTrace();}
catch(ArrayIndexOutOfBoundsException s){s.printStackTrace();}
try {
sleep(500);
} catch(InterruptedException e){}
}
}
public void clearTableBarang(){
int numrows = modelBarang.getRowCount();
for(int i = numrows - 1; i >=0; i--){
modelBarang.removeRow(i);
}
dataBarang.clear();
}
public void showTableBarang(){
try{
ResultSet rs = stmt.executeQuery("select kode_barang, nama_barang, jumlah_stok, minimal_stok, harga_jual, deskripsi_barang from barang");
while(rs.next()){
String kode_barang = rs.getString ("kode_barang");
String nama_barang = rs.getString ("nama_barang");
int jumlah_stok = rs.getInt("jumlah_stok");
int minimal_stok = rs.getInt("minimal_stok");
int harga_jual = rs.getInt("harga_jual");
String deskripsi_barang = rs.getString ("deskripsi_barang");
//System.out.println(kode_barang+" "+deskripsi_barang);
dataBarang.add(new Barang(kode_barang,nama_barang,jumlah_stok,minimal_stok,harga_jual,deskripsi_barang));
((DefaultTableModel)jTabelBarang.getModel()).insertRow(jTabelBarang.getRowCount(), new Object[]{kode_barang, nama_barang, jumlah_stok, minimal_stok, harga_jual, deskripsi_barang});
}
} catch(SQLException s){s.printStackTrace();}
}
public void delay(){
try {
sleep(1000000000);
} catch(InterruptedException e){}
}
}
This is the error :
Exception in thread "Thread-4" java.lang.NullPointerException
at mypkg.Searching.run(Searching.java:47)
FYI : Line 47 is pointing to
ResultSet rs = stmt.executeQuery("select kode_barang, nama_barang, jumlah_stok, " +
"minimal_stok, harga_jual, deskripsi_barang from BARANG WHERE (kode_barang LIKE " +
"'"+masukan+"%')");
Please help me solve the problem. Thank you very much. :D
NullPointerExceptions are the most easy ones to fix with a debugger. Just place a breakpoint on that line and see what is null.
If the line you posted is correct, you do not even need a debugger since the only thing that can throw the exception is stmt which will be null.
Note:
It is a good thing to run your DB query in a separate Thread to avoid blocking the UI. However, in your case you are updating the UI from that Thread which is not allowed and will cause weird issues. All Swing components must be accessed on the Event Dispatch Thread (EDT). Consult the Swing concurrency tutorial for more information
I do hope you are not starting up a separate Thread on each keystroke in the textfield as you indicated in your question. Looking at the code in the Thread, you remove all elements from the table and then re-add rows. So if a users types in 5 characters at a normal typing speed, you will launch 5 threads which most likely run all at the same time (since a DB connection might not be that fast if your network is lagging). That means that with your current code 5 Threads are, at the same time, removing the table model and adding rows. Even if you put all the Swing code on the EDT (see my first point), you still end up with 5 threads posting runnables on the EDT messing with your table model. I do not know what the resulting table model will be, but probably not what you want
Clearly stmt is null.
You declare it here:
private Statement stmt;
List<Barang> dataSBarang =new LinkedList();
boolean searchBarang=true;
Searching sBarang;
But I don't see any initialization code anywhere, so most likely it remains null for this method call:
private void inputkodeTFMouseClicked(java.awt.event.MouseEvent evt){
sBarang = new Searching( stmt, dataSBarang, modelDetail, tabelDetailBarang, inputkodeTF, searchBarang);
sBarang.start();
}

One JTextField stores and updates text, the other doesn't

So, I made a class that takes arrays and calculates a value from them. I then decided (unknowingly) to incorporate it into a GUI interface. All went well until I noticed this strange error; one of the jtextfields (prarie) would not store text while the other (yard) does.
I looked around and found my problem similiar to mine on this site;
Updating text in a JTextField
But he had one that doesn't work at all, where I have one that works and one that doesn't.
The Code is here (it's a bit long, but most of it is GUI), so hold your breath!:
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Window {
/**
* #param args
*/
private static int numb;
private static double micro, centi;
private static JTextField[] yard,prarie;
private static double[] charges,distances;
public static void main(String[] args)
{
//create a small dialog window to take in number of charged objects
JPanel startup = new JPanel();
JTextField many = new JTextField(5);
startup.add(many);
int result = JOptionPane.showConfirmDialog(null,startup , "Please Enter How Many Charged Objects are Being Evaluated", JOptionPane.OK_CANCEL_OPTION);
many.requestFocusInWindow();
//once ok is clicked, then the number input will be stored under 'numb'
//then proceed to inputFields
if (result == JOptionPane.OK_OPTION)
{
numb = Integer.parseInt(many.getText());
inputFields();
}
}
//this window opens the various JTextFields for input
public static void inputFields()
{
//top JTextFields
yard = new JTextField[numb];
JPanel chargePanel = new JPanel();
for(int x=0;x<numb;x++)
{
yard[x] =new JTextField(5);
chargePanel.add(new JLabel("Charge "+ Integer.toString(x+1)+":"));
chargePanel.add(yard[x]);
chargePanel.add(Box.createVerticalStrut(15)); // a spacer
}
//bottom JTextFields
prarie = new JTextField[numb-1];
JPanel meterPanel = new JPanel();
for(int x=0;x<numb-1;x++)
{
prarie[x]=new JTextField(5);
meterPanel.add(new JLabel("Meters "+ Integer.toString(x+1)+":"));
meterPanel.add(new JTextField(5));
meterPanel.add(Box.createVerticalStrut(15)); // a spacer
}
//JCheckBoxes
JCheckBox isMicro = new JCheckBox("Charges are in terms of microCoulombs");
JCheckBox isCm = new JCheckBox("Distances are in terms of centiMeters");
JPanel chechBox = new JPanel();
chechBox.add(isMicro);
chechBox.add(Box.createVerticalStrut(20));
chechBox.add(isCm);
//Paste them all together into one window
GridLayout gufi = new GridLayout(3,1);
JPanel host = new JPanel(gufi);
host.add(chargePanel);
host.add(meterPanel);
host.add(chechBox);
int result1 = JOptionPane.showConfirmDialog(null, host, "Please Enter Charge and Distance Values", JOptionPane.OK_CANCEL_OPTION);
//if ok is clicked, then go to 'printArr()' to print the JTextFields
//then go to assign the values from the JTextFields to private double arrays 'yard' and 'prarie'
if (result1 == JOptionPane.OK_OPTION)
{
micro = (isMicro.isSelected())? Math.pow(10, -6): 1;
centi = (isCm.isSelected())? .01: 1;
printArr();
assign();
}
}
//a makeshift method to print the value from the JTextFields
//to fix the problem of why prarie wouldn't store numbers
public static void printArr()
{
System.out.println("Charges are:");
for(int x=0;x<numb;x++)
System.out.print(yard[x].getText() + " ");
System.out.println("Distances are:");
for(int x=0;x<numb-1;x++)
System.out.print(prarie[x].getText() + " ");
}
//assigns values from JTextFields to the private double arrays 'yard' and 'prarie'
public static void assign()
{
try {
charges = new double[numb];
for(int x=0;x<numb;x++)
charges[x]=micro*Double.parseDouble(yard[x].getText().trim());
distances = new double[numb-1];
for(int x=0;x<numb-1;x++)
distances[x]=centi*Double.parseDouble(prarie[x].getText().trim());
} catch (NumberFormatException e) {
e.printStackTrace();
//inputFields();
}
calculate();
}
public static void calculate()
{
JPanel sample = new JPanel();
JTextField whichOne = new JTextField(5);
sample.add(whichOne);
int result = JOptionPane.showConfirmDialog(null,sample , "Please Enter Which Charged Object thy Wishs For", JOptionPane.OK_CANCEL_OPTION);
whichOne.requestFocusInWindow();
if (result == JOptionPane.OK_OPTION)
{
int target = Integer.parseInt(whichOne.getText());
}
}
}
Anyone who runs the code and takes the time to enter dummy values will see that 'yard' stores values while 'prarie' does not. Why is this?
*I'm pretty sure I'm overlooking obvious (as always).
Change:
meterPanel.add(new JTextField(5));
to:
meterPanel.add(prarie[x]);
in the for loop for the prarie textfields

Resources