The local variable may not have been initialized - java

ISSUE:
I have a TimePicker which I'd like to use to save the value of the long/string "minutes" which represents the total number of minutes between the current time and the time selected by the timepicker.
For example: If it is currently 7:30 and the user selects 8:30 it will save 60 minutes as the value of minutes.
I've managed to implement the following source code (shown below) however I'm getting a few errors stating:
"The local variable tp may not have been initialized"
Using the method suggested in the comments below - although I'm following the instructions precisely.
COMPILER PROBLEMS:
Description Resource Path Location Type
The local variable tp may not have been initialized AddEditDevice.java line 119 Java Problem
The local variable tp may not have been initialized AddEditDevice.java line 120 Java Problem
SOURCE:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.DecimalFormat;
import android.util.Log;
import java.util.Calendar;
public class AddEditDevice extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TextView ssidTextView;
Calendar cal = Calendar.getInstance();
TimePicker tp;
// #Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssidString = info.getSSID();
if (ssidString.startsWith("\"") && ssidString.endsWith("\"")){
ssidString = ssidString.substring(1, ssidString.length()-1);
}
//TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssidString);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditDevice.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});}
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
TimePicker tp;
cal.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
cal.set(Calendar.MINUTE, tp.getCurrentMinute());
long minutes = (cal.getTimeInMillis() -
Calendar.getInstance().getTimeInMillis()) / 1000 / 60;
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
// Log.i("Test for Null", ""+dbConnector+" "+nameEt+" "+capEt+" "+timeEt+" "+codeEt+" "+ssidTextView);
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
ssidTextView.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
ssidTextView.getText().toString());
}
}
}

Use java.util.Calendar to get current values and subtract.
Calendar cal = Calendar.getInstance();
TimePicker tp;
// ...
cal.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
cal.set(Calendar.MINUTE, tp.getCurrentMinute());
long minutes = (cal.getTimeInMillis() -
Calendar.getInstance().getTimeInMillis()) / 1000 / 60;
Edit: Try this Java console application. A proof that it works.
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 20);
cal.set(Calendar.MINUTE, 58);
long minutes = (cal.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) / 1000 / 60;
System.out.println(minutes);
}
}
Returns 4 at 20:54 of my local time.

Related

How Do I make MPAndroidCharts update only the last X-Axis?

I am creating an app which monitors temperature live from my SQL server. I was also creating a linegraph using MPAndroidCharts by Phil Jay and came across an issue.
I used the X-axis as a label for time(HH:mm:ss) however the time seems to update all the labels instead of only the last one. I have tried many different methods but none of them work. So I thought I would ask you guys for help. Thank You!
Image of isue here
package com.example.boiijek.myapplication;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import static com.example.boiijek.myapplication.SettingsActivity.PREFS_NAME;
public class MainActivity extends AppCompatActivity {
final Context context = this;
String setno, checkinglux, checkingtemp;
Button testbutton;
/**
* Created by Boiijek on 21/10/2017.
*/
TextView textalertsends, tempalertsends, luxalertsends, luxupdate, tempupdate;
BroadcastReceiver updateUIReceiver;
public static final String EXTRA_TEMP = "temp_extra";
private ArrayList<Entry> entries = new ArrayList<>();
LineChart mChart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
mChart = findViewById(R.id.chart);
XAxis xAxis = mChart.getXAxis();
xAxis.setValueFormatter(createDateFormatter());
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
mChart.getAxisLeft().setDrawGridLines(false);
mChart.getXAxis().setDrawGridLines(false);
mChart.getAxisLeft().setDrawAxisLine(false);
mChart.getXAxis().setTextColor(Color.CYAN);
mChart.getAxisLeft().setTextColor(Color.CYAN); // left y-axis
mChart.getLegend().setTextColor(Color.YELLOW);
mChart.getAxisRight().setEnabled(false);
YAxis yAxis = mChart.getAxisLeft();
yAxis = mChart.getAxisRight();
yAxis.setDrawGridLines(false);
Description description = new Description();
description.setTextColor(ColorTemplate.VORDIPLOM_COLORS[2]);
description.setText("Live Temperature Data");
mChart.setDescription(description);
setYAxisValues();
// setData();
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
setno = settings.getString("finalno", "NULL");
checkinglux = settings.getString("checkingtemp", "99999");
checkingtemp = settings.getString("checkingtemp", "0");
textalertsends = (TextView) findViewById(R.id.textalertsends);
tempalertsends = (TextView) findViewById(R.id.tempalertsends);
luxalertsends = (TextView) findViewById(R.id.luxalertsends);
textalertsends.setText("SMS Alerts will be sent to " + setno);
tempalertsends.setText("Alerted when Temp. is over " + checkingtemp + "°C");
luxalertsends.setText("Alerted when Lux is below " + checkinglux + " lux");
testbutton = (Button) findViewById(R.id.button55);
{
if (isMyServiceRunning() == false) {
testbutton.setBackgroundColor(Color.GREEN);
testbutton.setTextColor(Color.BLACK);
testbutton.setText("Start Background Monitoring");
} else {
testbutton.setBackgroundColor(Color.RED);
testbutton.setText("Stop Background Monitoring");
}
}
testbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isMyServiceRunning() == true) {
Intent intent = new Intent(MainActivity.this, TimeService.class);
stopService(intent);
testbutton.setBackgroundColor(Color.GREEN);
testbutton.setTextColor(Color.BLACK);
testbutton.setText("Start Background Monitoring");
} else {
Intent intent = new Intent(MainActivity.this, TimeService.class);
startService(intent);
testbutton.setBackgroundColor(Color.RED);
testbutton.setText("Stop Background Monitoring");
}
}
});
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.nihal.myapplication.UPDATE_DATA");
updateUIReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//UI update here
int temp = intent.getIntExtra(EXTRA_TEMP, 0);
entries.remove(0);
Calendar c = Calendar.getInstance();
int mseconds = c.get(Calendar.MILLISECOND);
entries.add(new Entry(mseconds, temp));
setData();
}
};
registerReceiver(updateUIReceiver, filter);
}
final String[] quarters = new String[] { "Q1", "Q2", "Q3", "Q4" };
IAxisValueFormatter createDateFormatter() {
IAxisValueFormatter formatter = new IAxisValueFormatter() {
#Override
public String getFormattedValue(float value, AxisBase axis) {
Date date = new Date((long) value);
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss");
Date now = new Date();
String strDate = sdfDate.format(now);
Log.d("test", strDate);
return strDate ;
}
public int getDecimalDigits() {
return 0;
}
};
return formatter;
}
private void setYAxisValues() {
entries.add(new Entry(0, 60));
entries.add(new Entry(1, 48));
entries.add(new Entry(2, 70.5f));
entries.add(new Entry(3, 100));
entries.add(new Entry(4, 180.9f));
entries.add(new Entry(5, 210f)); //test
}
private ArrayList<String> setXAxisValues() {
ArrayList<String> xVals = new ArrayList<String>();
xVals.add("10");
xVals.add("20");
xVals.add("30");
xVals.add("30.5");
xVals.add("40");
xVals.add("50"); //test
return xVals;
}
private void setData() {
ArrayList<String> xVals = setXAxisValues();
LineDataSet set1;
set1 = new LineDataSet(entries, "X Axis - Time // Y Axis - Temp");
set1.setFillAlpha(110);
set1.setColor(Color.WHITE);
set1.setCircleColor(Color.WHITE);
set1.setLineWidth(1f);
set1.setCircleRadius(3f);
set1.setDrawCircleHole(false);
set1.setValueTextSize(9f);
set1.setValueTextColor(Color.WHITE);
set1.setDrawFilled(true);
set1.setCubicIntensity(0.5f);
set1.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
// create a data object with the datasets
LineData data = new LineData(set1);
// set data
mChart.setData(data);
mChart.invalidate();
}
public void startService(View view) {
Intent intent = new Intent(this, TimeService.class);
startService(intent);
}
public void stopService(View view) {
Intent intent = new Intent(this, TimeService.class);
stopService(intent);
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (TimeService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(updateUIReceiver);
}
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
}
Add following line in your code:
mChart.setData(data);
mChart.notifyDataSetChanged(); // add this line
mChart.invalidate();

Time Picker is not working when i set time 12:00 or 00:00 its displaying AM instead Pm

when i select 12:00 or i Select 0:00 it showing me only AM not PM tried a lot but not getting the required output and I search same question in stack overflow but not getting the output..
Here the complete code is as follow:-
main.java
package com.Weal.sachin.omcom;
import android.content.DialogInterface;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import java.util.Calendar;
import java.util.Locale;
import android.view.ViewGroup;
import android.widget.EditText;
import android.app.TimePickerDialog;
import android.widget.TimePicker;
public class Daily_Task extends Fragment {
public Daily_Task(){};
boolean isFromClicked = false;
boolean morning = true;
private int hour;
private int minute;
String addtask, adddetail, addstart, addend;
static final int TIME_DIALOG_ID = 999;
View view;
EditText starttime;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_daily__task, container, false);
getActivity().setTitle("Task");
starttime = (EditText) view.findViewById(R.id.start_time);
setCurrentTimeOnView();
addListenerOnButton();
return view;
}
// display current time
public void setCurrentTimeOnView() {
// starttime= (EditText)view.findViewById(R.id.start_time);
// timePicker1 = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR);
minute = c.get(Calendar.MINUTE);
// set current time into textview
starttime.setText(getTimeText(hour, minute));
// set current time into timepicker
//timePicker1.setCurrentHour(hour);
//timePicker1.setCurrentMinute(minute);
}
public void addListenerOnButton() {
// starttime = (EditText) view.findViewById(R.id.start_time);
starttime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog();
isFromClicked = false;
}
});
}
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
// set current time into textview
if (isFromClicked)
starttime.setText(getTimeText(hour, minute));
else{
}
//btnChangeTime.setText(getTimeText(hour, minute));
// set current time into timepicker
// timePicker1.setCurrentHour(hour);
// timePicker1.setCurrentMinute(minute);
}
};
private void showTimePickerDialog() {
new TimePickerDialog(getContext(), timePickerListener, hour, minute, true).show();
}
private String getTimeText(int hourOfDay, int minute) {
int hour = hourOfDay % 12;
if (hour == 0) hour = 12 ;
//then
if (hour >=12 && hour < 24) morning = false;
else morning = true;
String _AM_PM = (hourOfDay > 12) ? "PM" : "AM";
return String.format(Locale.getDefault(), "%02d:%02d %s", hour, minute, _AM_PM);
}
}
I Tried this code and now it is working perfectly for me:-
TimePicker.java
package com.Weal.sachin.omcom;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.TimePickerDialog;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Date;
/**
* Created by sachin on 2/2/2017.
*/
public class TImePickerEndTime extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
// Get a Calendar instance
final Calendar calendar = Calendar.getInstance();
// Get the current hour and minute
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_LIGHT
TimePickerDialog tpd = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,this,hour,minute,false);
// TimePickerDialog Theme : THEME_DEVICE_DEFAULT_DARK
TimePickerDialog tpd2 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_DEVICE_DEFAULT_DARK,this,hour,minute,false);
// TimePickerDialog Theme : THEME_HOLO_DARK
TimePickerDialog tpd3 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_DARK,this,hour,minute,false);
// TimePickerDialog Theme : THEME_HOLO_LIGHT
TimePickerDialog tpd4 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT,this,hour,minute,false);
// TimePickerDialog Theme : THEME_TRADITIONAL
TimePickerDialog tpd5 = new TimePickerDialog(getActivity(),
AlertDialog.THEME_TRADITIONAL,this,hour,minute,false);
// Return the TimePickerDialog
return tpd;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute){
String am_pm = "";
String tm = new SimpleDateFormat("HH:mm").format(new Date(hourOfDay));
Calendar datetime1 = Calendar.getInstance();
datetime1.set(Calendar.HOUR_OF_DAY, hourOfDay);
datetime1.set(Calendar.MINUTE, minute);
String strDate = tm.format(String.valueOf(datetime1.getTime()));
if (datetime1.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (datetime1.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow1 = (datetime1.get(Calendar.HOUR) == 00)?"12":datetime1.get(Calendar.HOUR)+"";
// ((EditText)getActivity().findViewById(R.id.End_time)).setText(String.format("%02d:%02d", strHrsToShow1, datetime1.get(Calendar.MINUTE) + "") +" "+am_pm);
// ((EditText)getActivity().findViewById(R.id.End_time)).setText(String.format("%02d:%02d", strHrsToShow1, datetime1.get(Calendar.MINUTE)));
/*((EditText)getActivity().findViewById(R.id.End_time)
).setText( String.format("%02d:%02d", strHrsToShow1, datetime1.get(Calendar.MINUTE) + "") +" "+am_pm);
*/
int hour = hourOfDay % 12;
((EditText) getActivity().findViewById(R.id.End_time)).setText(String.format("%02d:%02d %s", hour == 0 ? 12 : hour,
minute, hourOfDay < 12 ? "am" : "pm"));
}
}
now in Main.java
//
timepicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Initialize a new time picker dialog fragment
DialogFragment dFragment1 = new TImePicker();
// Show the time picker dialog fragment
dFragment1.show(getActivity().getFragmentManager(),"Time Picker");
}
});

Error coverting Integer variables to Date Object and value returned is always 31-DEC - 1?

I have written this line of code of code:
dateSelected = new GregorianCalendar(tempYear, tempMonth, tempDate,tempHour,tempMinute).getTime();
I got these value from datepicker and timepicker dialogs in android. I am able to get correct values in these integer variables but when I convert them to Date object it will always be 31 dec. I am not able to fix the problem.
I have also tried this approach as well:
Calendar calendar = Calendar.getInstance();
calendar.set(tempYear, tempMonth, tempDate, tempHour, tempMinute);
dateSelected = calendar.getTime();
Whenever Second line is commented out it is working fine. I am perfectly getting current date and time. But when it is uncommented the problem returns.
In case anyone needs my full code:
package com.bignerdranch.android.todolistwithdate;
/**********************************************
* This activity will open new dialog box that will add new
* ToDo list item to the list.
*/
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class AddToDoActivity extends AppCompatActivity {
EditText entryName;
Button dateSelectionButton;
Button addEntry;
Date dateSelected;
Button timeSelectionButton;
private int tempDate, tempMonth, tempYear, tempHour, tempMinute;
String nameToDoItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_do);
entryName = (EditText)findViewById(R.id.new_todo_edittext);
dateSelectionButton = (Button)findViewById(R.id.date_selection_button);
addEntry = (Button)findViewById(R.id.entry_add_button);
timeSelectionButton = (Button)findViewById(R.id.time_selection_button);
//Create date selection Dialog here
//Also add code for modifying dateSelected Variable
dateSelectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePickerDialog = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
super.onDateSet(view, year, monthOfYear, dayOfMonth);
dateSelectionButton.setText(Integer.toString(dayOfMonth) + "/" + Integer.toString(monthOfYear + 1) + "/" + Integer.toString(year));
tempDate = dayOfMonth;
tempMonth = monthOfYear;
tempYear = year;
}
};
datePickerDialog.show(getSupportFragmentManager(), "datePicker");
}
});
timeSelectionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePickerDialog = new TimePickerFragment() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
super.onTimeSet(view, hourOfDay, minute);
timeSelectionButton.setText(Integer.toString(hourOfDay) + ":" + Integer.toString(minute));
tempHour = hourOfDay;
tempMinute = minute;
}
};
timePickerDialog.show(getSupportFragmentManager(), "timePicker");
}
});
//Work here to get calendar working properly
Calendar calendar = Calendar.getInstance();
calendar.set(tempYear, tempMonth, tempDate, tempHour, tempMinute);
dateSelected = calendar.getTime();
entryName = (EditText)findViewById(R.id.new_todo_edittext);
addEntry = (Button)findViewById(R.id.entry_add_button);
addEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameToDoItem = entryName.getText().toString();
Intent resultIntent = new Intent();
resultIntent.putExtra("NameOfItem", nameToDoItem);
resultIntent.putExtra("DateOfItem", dateSelected);
setResult(Activity.RESULT_OK, resultIntent);
Log.i("Date: ", dateSelected.toString() );
finish();
}
});
}
}
When the code works all variables equal to 0 because a user doesn't pick a date and a time at the moment.
Calendar calendar = Calendar.getInstance();
calendar.set(tempYear, tempMonth, tempDate, tempHour, tempMinute);
dateSelected = calendar.getTime();
Move the code in addEntry's onClickListener implementation and it will work 👍

Android TimePickerDialog. app crashes when setting time more than current time

My app getting crash when I try to set the time more than the current time.
Please solve my problem.
The current time is working fine but the app is crashing when I select time more than current time.
Thanks
JavaFile:
package com.example.akshay.eventmanager;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.hardware.input.InputManager;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.widget.Toast;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.model.LatLng;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import android.app.DatePickerDialog.OnDateSetListener;
/**
* Created by Akshay on 7/12/2015.
*/
public class Create extends Activity implements View.OnClickListener {
Button select, create;
EditText title, desc, time;
TextView venueInfo;
PlacePicker.IntentBuilder intentBuilder;
private static final int PLACE_PICKER_REQUEST = 1;
public LatLng gotLatLng;
String placeName;
String plName;
String Addr;
Double gotLat, gotLong;
String LAT, LONG;
DataBaseHelper myDB;
public static final String LOG_TAG = "Create";
String GotTime = " ";
String GotDate = " ";
DatePickerDialog datePicker;
TimePickerDialog myTimePicker;
SimpleDateFormat dateFormatter;
SimpleDateFormat TimeFormatter;
static boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create);
dateFormatter = new SimpleDateFormat("EEEE dd" ,Locale.US);
showDate();
showTime();
casting();
}
public void casting() {
select = (Button) findViewById(R.id.bSelect);
create = (Button) findViewById(R.id.bCreate);
title = (EditText) findViewById(R.id.etTitle);
desc = (EditText) findViewById(R.id.etDescription);
time = (EditText) findViewById(R.id.etTime);
venueInfo = (TextView) findViewById(R.id.tVVenue);
time.setInputType(InputType.TYPE_NULL);
select.setOnClickListener(this);
create.setOnClickListener(this);
time.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.bSelect:
try {
intentBuilder = new PlacePicker.IntentBuilder();
Intent intent = intentBuilder.build(Create.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
Toast.makeText(Create.this, "Google Play Services is not available.",
Toast.LENGTH_LONG)
.show();
}
break;
case R.id.bCreate:
String TITLE = title.getText().toString();
String DESC = desc.getText().toString();
String eventTime = time.getText().toString();
String PLACE = venueInfo.getText().toString();
myDB = new DataBaseHelper(this);
Log.e(LOG_TAG, TITLE);
Log.e(LOG_TAG, DESC);
Log.e(LOG_TAG, PLACE);
Log.e(LOG_TAG, LAT);
Log.e(LOG_TAG, LONG);
Log.e(LOG_TAG, Addr);
Log.e(LOG_TAG, eventTime);
int flag = myDB.InsertValues(TITLE, DESC, PLACE, LAT, LONG, Addr, eventTime);
if (flag == 1) {
Toast.makeText(Create.this, "Sucess", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Create.this, "Error Adding Records", Toast.LENGTH_LONG).show();
}
break;
case R.id.etTime:
myTimePicker.show();
datePicker.show();
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(data, this);
gotLatLng = place.getLatLng();
plName = (String) place.getName();
Addr = (String) place.getAddress();
gotLat = gotLatLng.latitude;
gotLong = gotLatLng.longitude;
LAT = String.valueOf(gotLat);
LONG = String.valueOf(gotLong);
placeName = String.format("Place: %s", place.getName());
Toast.makeText(this, placeName, Toast.LENGTH_LONG).show();
venueInfo.setText(plName);
}
}
}
public void showDate() {
Calendar cal = Calendar.getInstance();
datePicker = new DatePickerDialog(this, new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth ) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
GotDate = dateFormatter.format(newDate.getTime()).toString();
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_WEEK));
flag =true;
}
public void showTime() {
if(flag == true) {
Calendar calender = Calendar.getInstance();
myTimePicker = new TimePickerDialog(this, new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar newTime = Calendar.getInstance();
newTime.set(hourOfDay, minute);
GotTime = GotDate + " At " + String.valueOf(hourOfDay) + " :" + String.valueOf(minute + 1);
time.setText(GotTime);
}
}, calender.get((Calendar.HOUR_OF_DAY)), calender.get(Calendar.MINUTE), true);
}
}
}
LogCat:
07-13 16:43:10.468 478-478/com.example.akshay.eventmanager E/Zygote﹕ MountEmulatedStorage()
07-13 16:43:10.468 478-478/com.example.akshay.eventmanager E/Zygote﹕ v2
07-13 16:43:10.468 478-478/com.example.akshay.eventmanager E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
07-13 16:43:29.338 478-478/com.example.akshay.eventmanager E/ViewRootImpl﹕ sendUserActionEvent() mView == null
07-13 16:43:31.088 478-478/com.example.akshay.eventmanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.akshay.eventmanager, PID: 478
java.lang.ArrayIndexOutOfBoundsException: length=17; index=17
at java.util.Calendar.set(Calendar.java:1122)
at com.example.akshay.eventmanager.Create$2.onTimeSet(Create.java:196)
at android.app.TimePickerDialog.onClick(TimePickerDialog.java:204)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Set the time in calendar in showTime() method as follows:
public void showTime() {
if(flag == true) {
Calendar calender = Calendar.getInstance();
myTimePicker = new TimePickerDialog(this, new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar newTime = Calendar.getInstance();
//newTime.set(hourOfDay, minute); // remove this line
//Add these two line
newTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
newTime.set(Calendar.MINUTE, minute);
GotTime = GotDate + " At " + String.valueOf(hourOfDay) + " :" + String.valueOf(minute + 1);
time.setText(GotTime);
}
}, calender.get((Calendar.HOUR_OF_DAY)), calender.get(Calendar.MINUTE), true);
}
}
EDIT:
To get HourOdDay in am/pm you can do something like this:
String format = "hh:mm a"; // your own format
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
String formated_time = sdf.format(newTime.getTime());
//formated_time would show you time like "hh:mm am/pm".

EROR NullPointerException [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
at this time i need help from u guys, i have this following code, but when i run in eclipse, it's totally eror,(THE ERROR IS SIGN IN THE CODE BELOW)
package com.example.search;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import com.example.database.search.DBDataSource;
import com.example.database.search.Sma;
public class EditData extends Activity implements OnClickListener
{
int hour, minute, mYear,mMonth, mDay;
static final int DATE_DIALOG_ID = 1;
private EditText txtDate;
private String[] arrMonth{"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
private DBDataSource dataSource;
private long id;
private String Nama;
private String Alamat;
private Long Latitude;
private Long Longtitude;
private String Tanggal;
private String Email;
private String Website;
private String Facebook;
private String Twtitter;
private EditText edNama_sma, edAlamat_sma, edLatitude, edLongtitude, edTanggal, edEmail, edWebsite, edFacebook, edTwitter;
private TextView txId;
private Button btnSave;
private Button btnCancel;
private Sma sma;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data);
//inisialisasi variabel
edNama_sma = (EditText) findViewById(R.id.editText_nama);
edAlamat_sma = (EditText) findViewById(R.id.editText_alamat);
edLatitude = (EditText) findViewById(R.id.editText_latitude);
edLongtitude = (EditText) findViewById(R.id.editText_longtitude);
edTanggal = (EditText) findViewById(R.id.editText_Tanggal);
edEmail = (EditText) findViewById(R.id.editText_Email);
edWebsite = (EditText) findViewById(R.id.editText_Website);
edFacebook = (EditText) findViewById(R.id.editText_Facebook);
edTwitter = (EditText) findViewById(R.id.editText_Twitter);
txId = (TextView) findViewById(R.id.text_id_barang);
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
//WHEN I ADD THIS CODE BELOW, then >> ERROR is happend >> java.lang.NullPointerExceptions
//THIS FUNCTION IS USE FOR SHOWING DATETIMEPICKER
txtDate.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
return true;
}
});
//UNTIL THIS LINE
dataSource = new DBDataSource(this);
dataSource.open();
// ambil data sma dari extras
Bundle bun = this.getIntent().getExtras();
id = bun.getLong("id");
Nama = bun.getString("Nama");
Alamat = bun.getString("Alamat");
Latitude = bun.getLong("Latitude");
Longtitude = bun.getLong("Longtitude");
Tanggal = bun.getString("Tanggal");
Email = bun.getString("Email");
Website = bun.getString("Website");
Facebook = bun.getString("Facebook");
Twtitter = bun.getString("Twitter");
txId.append(String.valueOf(id));
edNama_sma.setText(Nama);
edAlamat_sma.setText(Alamat);
edLatitude.setText(Latitude.toString());
edLongtitude.setText(Longtitude.toString());
edTanggal.setText(Tanggal);
edEmail.setText(Email);
edWebsite.setText(Website);
edFacebook.setText(Facebook);
edTwitter.setText(Twtitter);
//set listener pada tombol
btnSave = (Button) findViewById(R.id.button_save_update);
btnSave.setOnClickListener(this);
btnCancel = (Button) findViewById(R.id.button_cancel_update);
btnCancel.setOnClickListener(this);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
{
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
String sdate = arrMonth[mMonth] + " " + LPad(mDay + "", "0", 2) + ", " + mYear;
txtDate.setText(sdate);
}
};
private static String LPad(String schar, String spad, int len)
{
String sret = schar;
for (int i = sret.length(); i < len; i++)
{
sret = spad + sret;
}
return new String(sret);
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch(v.getId())
{
// apabila tombol save diklik (update barang)
case R.id.button_save_update :
String ltd = edLatitude.getText().toString();
String lotd = edLongtitude.getText().toString();
Long latitude = Long.parseLong(ltd);
Long longtitude = Long.parseLong(lotd);
sma = new Sma();
sma.setNama(edNama_sma.getText().toString());
sma.setAlamat(edAlamat_sma.getText().toString());
sma.setLatitude(latitude);
sma.setLongitude(longtitude);
sma.setEmail(edEmail.getText().toString());
sma.setTgl_berdiri(edTanggal.getText().toString());
sma.setWebsite(edWebsite.getText().toString());
sma.setFacebook(edFacebook.getText().toString());
sma.setTwitter(edTwitter.getText().toString());
sma.setId(id);
dataSource.updateBarang(sma);
Intent i = new Intent(this, ViewData.class);
startActivity(i);
EditData.this.finish();
dataSource.close();
break;
case R.id.button_cancel_update :
finish();
dataSource.close();
break;
}
}
}
Anyone please help me from this error, i really want to say thank you to all of u who can resolve this code, Thanks :D
You haven't initialized the txtDate EtidText.
txtDate = (EditText) findViewById(R.id.txtDate);// or what ever you add the id for txtDate
Then you will be fine.

Categories

Resources