inserting value into SQL database using java language in adroid studio - java

i have a code that take start time and stop time by clicking on button and make the difference between two time.
i want to issert this start, stop and difference value into database. But my code didnot insert these value into database. it insert no value. my code is not giving me any error. when i run it databse rows increse but no value shows into table. all column shows empty.
please help me friends.
public class cleaning extends Fragment {
TextView tvstarttime;
Button btn_start;
Button btn_end;
TextView tvend;
TextView diffence;
boolean isStarted = false;
String starttime, endtime, timedifference;
ProgressDialog progressDialog;
Connection conn;
boolean isSucess = false;
NetworkManager networkManager = new NetworkManager();
SharedPrefManager sharedPrefManager = new SharedPrefManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_cleaning, container, false);
tvstarttime = view.findViewById(R.id.txtstarttime);
btn_start = view.findViewById(R.id.btn_start);
tvend = view.findViewById(R.id.txtendtime);
diffence=view.findViewById(R.id.txtdifference);
starttime = tvstarttime.getText().toString().trim();
endtime = tvend.getText().toString().trim();
timedifference = diffence.getText().toString().trim();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time = format.format(calendar.getTime());
tvend.setText(time);
try {
Date date1 = format.parse(tvend.getText().toString());
Date date2 = format.parse(tvstarttime.getText().toString());
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills % (1000*60*60));
String diff = hours + ":" + mins;
diffence.setText(diff);
}
catch (ParseException e) {
e.printStackTrace();
}
btn_start.setText("START");
}else {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time1 = format.format(calendar.getTime());
tvstarttime.setText(time1);
btn_start.setText("STOP");
}
isStarted = !isStarted;
}
});
return view;
}
private class uploadcart extends AsyncTask<Void, Void, Void> {
/* #Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(ProductDetailFragment.this);
progressDialog.setTitle("Creating account please wait!");
progressDialog.show();
super.onPreExecute();
}*/
#Override
protected Void doInBackground(Void... voids) {
try {
ConnectionHelper con = new ConnectionHelper();
conn = con.connectionclasss(Const.DBUserNameStr, Const.DBPasswordStr, Const.db, Const.ip);
String queryStmt = "Insert into CleaningTable" +
" (StartTime, StopTime, TimeTaken) values "
+ "('"
+ starttime
+ "','"
+ endtime
+ "','"
+ timedifference
+ "')";
Statement stmt = conn.createStatement();
isSucess = stmt.execute(queryStmt);
isSucess = true;
conn.close();
// return data;
} catch (Exception e) {
isSucess = false;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (isSucess) {
Toast.makeText(getActivity(), "time added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "time not added", Toast.LENGTH_SHORT).show();
}
super.onPostExecute(aVoid);
}
}
}

Related

inserting Start, Stop and differenece time into sql database an android studio java language

I have wrote a code when I click on button start it show current time and turn text into stop then I click on stop it show me stop current time and calculate difference. after that I made a class to insert all these three start stop and difference into SQL database.
my problem is when I click on stop button it show me toast time added but value not added into database it show blank column into database. my database table column shows no values.
public class cleaning extends Fragment {
TextView tvstarttime;
Button btn_start;
Button btn_end;
TextView tvend;
TextView diffence;
boolean isStarted = false;
String starttime, endtime, timedifference;
ProgressDialog progressDialog;
Connection conn;
boolean isSucess = false;
NetworkManager networkManager = new NetworkManager();
SharedPrefManager sharedPrefManager = new SharedPrefManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_cleaning, container, false);
tvstarttime = view.findViewById(R.id.txtstarttime);
btn_start = view.findViewById(R.id.btn_start);
tvend = view.findViewById(R.id.txtendtime);
uploadcart uploadcart = new uploadcart();
uploadcart.execute();
diffence=view.findViewById(R.id.txtdifference);
starttime = tvstarttime.getText().toString().trim();
endtime = tvend.getText().toString().trim();
timedifference = diffence.getText().toString().trim();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isStarted){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time = format.format(calendar.getTime());
tvend.setText(time);
try {
Date date1 = format.parse(tvend.getText().toString());
Date date2 = format.parse(tvstarttime.getText().toString());
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills % (1000*60*60));
String diff = hours + ":" + mins;
diffence.setText(diff);
} catch (ParseException e) {
e.printStackTrace();
}
btn_start.setText("START");
}else {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
String time1 = format.format(calendar.getTime());
tvstarttime.setText(time1);
btn_start.setText("STOP");
}
isStarted = !isStarted;
}
});
return view;
}
private class uploadcart extends AsyncTask<Void, Void, Void> {
/* #Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(ProductDetailFragment.this);
progressDialog.setTitle("Creating account please wait!");
progressDialog.show();
super.onPreExecute();
}*/
#Override
protected Void doInBackground(Void... voids) {
try {
ConnectionHelper con = new ConnectionHelper();
conn = con.connectionclasss(Const.DBUserNameStr, Const.DBPasswordStr, Const.db, Const.ip);
String queryStmt = "Insert into CleaningTable" +
" (StartTime, StopTime, TimeTaken) values "
+ "('"
+ starttime
+ "','"
+ endtime
+ "','"
+ timedifference
+ "')";
Statement stmt = conn.createStatement();
isSucess = stmt.execute(queryStmt);
isSucess = true;
conn.close();
// return data;
} catch (Exception e) {
isSucess = false;
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (isSucess) {
Toast.makeText(getActivity(), "time added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "time not added", Toast.LENGTH_SHORT).show();
}
super.onPostExecute(aVoid);
}
}
}

java.lang.ClassCastException: Search cannot be cast to android.app.Activity

Hi does anyone know why i am getting this error in runtime? I am unsure how to resolve it and i am new to this. Please help! I have called the Search class in my MainActivity and my app crashes when i click on the button to open it.
Here is the code used to call the Search class:
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Search.class);
startActivity(intent);
}
});
And here is my Search class:
public class Search extends Fragment implements Filterable {
private FilterViewModel mViewModel;
private TextView fromMauritiusTheNearestTxt;
private TextView largestMagnitudeEarthquakeTxt;
private TextView deepestEarthquakeTxt;
private Button chooseByDateBtn;
private String startdateString, enddateString;
private final LatLng mauritiusLatLng = new LatLng(-20.2005136, 56.5541215);
List<String> alldates;
public List<ItemClass> mRssFeedModels;
private List<ItemClass> datafilteredlist;
public static Search newInstance() {
return new Search();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mViewModel = ViewModelProviders.of(this).get(FilterViewModel.class);
View root = inflater.inflate(R.layout.activity_search, container, false);
fromMauritiusTheNearestTxt = root.findViewById(R.id.from_mauritius_the_nearest_txt);
largestMagnitudeEarthquakeTxt = root.findViewById(R.id.largest_magnitude_earthquake_txt);
deepestEarthquakeTxt = root.findViewById(R.id.deepest_earthquake_txt);
chooseByDateBtn = root.findViewById(R.id.choose_by_data_btn);
alldates = new ArrayList<>();
;
mRssFeedModels = mRssFeedModels;
setNearestMagnitudeDeepest();
chooseByDateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder mydialog1 = new AlertDialog.Builder(getContext());
LayoutInflater inflater1 = LayoutInflater.from(getContext());
View myview1 = inflater1.inflate(R.layout.custom_date_range_filter, null);
mydialog1.setView(myview1);
final AlertDialog dialog1 = mydialog1.create();
dialog1.show();
final TextView startdatetxt = myview1.findViewById(R.id.start_date_txt);
final TextView enddatetxt = myview1.findViewById(R.id.end_date_txt);
startdatetxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
final int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
c.set(year, monthOfYear, dayOfMonth);
startdateString = format.format(c.getTime());
startdatetxt.setText(startdateString);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
enddatetxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
final int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
SimpleDateFormat format = new SimpleDateFormat("dd MMM yyyy");
c.set(year, monthOfYear, dayOfMonth);
enddateString = format.format(c.getTime());
enddatetxt.setText(enddateString);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
Button datefilterbtn = myview1.findViewById(R.id.filterbtn);
datefilterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(startdateString)) {
startdatetxt.setError("select date");
}
if (TextUtils.isEmpty(enddateString)) {
enddatetxt.setError("select ");
} else {
//setNearestMagnitudeDeepest();
alldates = getDates(startdateString, enddateString);
for (String date : alldates) {
System.out.println(date);
}
getFilter().filter(startdateString);
dialog1.dismiss();
}
}
});
}
});
return root;
}
// mathod used to set
//from Mauritius The Nearest in Textbox
//largest Magnitude Earthquake in Textbox
//deepest Earthquake in Textbox
public void setNearestMagnitudeDeepest() {
String fromMauritiusTheNearest = "";
String largestMagnitudeEarthquake = "";
String largestMagnitudeEarthquakeLocName = "";
String deepestEarthquakeLocName = "";
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Double.parseDouble(mRssFeedModels.get(i).lat) == findNearestDoubleInList()) {
fromMauritiusTheNearest = mRssFeedModels.get(i).getLocation();
System.out.println(mRssFeedModels.get(i).lat + "------------- " + findNearestDoubleInList() + " " + mRssFeedModels.get(i).getLocation());
}
}
double maxMagnitude = Double.MIN_VALUE;
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Double.parseDouble(mRssFeedModels.get(i).getMagnitude()) > maxMagnitude) {
maxMagnitude = Double.parseDouble(mRssFeedModels.get(i).getMagnitude());
largestMagnitudeEarthquakeLocName = mRssFeedModels.get(i).getLocation();
}
}
String maxDepthStr = null;
int maxDepth = Integer.MIN_VALUE;
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Integer.parseInt(mRssFeedModels.get(i).getDepth().replaceAll("[^0-9]", "")) > maxDepth) {
maxDepth = Integer.parseInt(mRssFeedModels.get(i).getDepth().replaceAll("[^0-9]", ""));
maxDepthStr = mRssFeedModels.get(i).getDepth();
deepestEarthquakeLocName = mRssFeedModels.get(i).getLocation();
}
}
largestMagnitudeEarthquake = String.valueOf(maxMagnitude);
fromMauritiusTheNearestTxt.setText(fromMauritiusTheNearest);
largestMagnitudeEarthquakeTxt.setText(largestMagnitudeEarthquake + " in " + largestMagnitudeEarthquakeLocName);
deepestEarthquakeTxt.setText(maxDepthStr + " in " + deepestEarthquakeLocName);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(FilterViewModel.class);
// TODO: Use the ViewModel
}
//method use to find nearest location from mauritius
private Double findNearestDoubleInList() {
Double answer = Double.parseDouble(mRssFeedModels.get(0).lat);
Double current = Double.MAX_VALUE;
for (int i = 0; i < mRssFeedModels.size(); i++) {
if (Math.abs(Double.parseDouble(mRssFeedModels.get(i).lat) - mauritiusLatLng.latitude) < current) {
answer = Double.parseDouble(mRssFeedModels.get(i).lat);
current = Math.abs(answer - mauritiusLatLng.latitude);
}
}
return answer;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
datafilteredlist = mRssFeedModels;
} else {
List<ItemClass> filteredList = new ArrayList<>();
for (int i = 0; i < alldates.size(); i++) {
charString = alldates.get(i);
for (ItemClass row : mRssFeedModels) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getDescription().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
System.out.println("matched");
}
}
}
datafilteredlist = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = datafilteredlist;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults results) {
mRssFeedModels = (ArrayList<ItemClass>) results.values;
setNearestMagnitudeDeepest();
if (fromMauritiusTheNearestTxt.getText().toString().isEmpty()) {
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getContext());
builder.setMessage("No record found on this date")
.setCancelable(false)
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
mRssFeedModels = mRssFeedModels;
setNearestMagnitudeDeepest();
}
});
final android.app.AlertDialog alert = builder.create();
alert.show();
}
}
};
}
private static List<String> getDates(String dateString1, String dateString2) {
ArrayList<String> dates = new ArrayList<String>();
SimpleDateFormat df1 = new SimpleDateFormat("dd MMM yyyy");
Date date1 = null;
Date date2 = null;
try {
date1 = df1.parse(dateString1);
date2 = df1.parse(dateString2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
while (!cal1.after(cal2)) {
//Date date=cal1.getTime();
//dates.add(cal1.getTime());
dates.add(df1.format(cal1.getTime()));
cal1.add(Calendar.DATE, 1);
}
return dates;
}
}
Your Search class is a Fragment, you cannot start it with the Intent.
Make Search to be Activity or switch between fragments using FragmentManager.
Intent intent = new Intent(MainActivity.this, Search.class);
The Intent constructor doesn't expect a Fragment class as a second Argument, Here you add Search.class which is a Fragment, but you need to have an Activity instead
Fragments can be loaded in activities using a Transaction, not an intent.

How do I pass a variable from an activity to a fragment?

I have tried using the code below but it does not work. it just returns a null value when retrieved from the fragment.
MainActivity.java
setting the bundle:
public class MainActivity extends Activity {
ConnectionClass connectionClass;
EditText edtuserid,edtpass;
Button btnlogin;
ProgressBar pbbar;
int user_id;
int lala;
int test2;
String userIDD;
String user_fname;
String user_lname;
int dept_id;
String test;
String user_email;
String user_password;
String user_username;
Bundle profileBundle;
String userid;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
edtuserid = (EditText) findViewById(R.id.edtuserid);
edtpass = (EditText) findViewById(R.id.edtpass);
btnlogin = (Button) findViewById(R.id.btnlogin);
pbbar = (ProgressBar) findViewById(R.id.pbbar);
pbbar.setVisibility(View.GONE);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userid = edtuserid.getText().toString();
password = edtpass.getText().toString();
int lala = Integer.parseInt(userid);
test2 = lala;
DoLogin doLogin = new DoLogin();
doLogin.execute("");
}
});
}
public class DoLogin extends AsyncTask<String,String,String>
{
String z = "";
Boolean isSuccess = false;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
if(isSuccess) {
//DITO ANG REDIRECTION
Intent base = new Intent(MainActivity.this, OtherActivity.class);
startActivity(base);
finish();
}
}
#Override
public String doInBackground(String... params) {
if(userid.trim().equals("")|| password.trim().equals(""))
z = "Please enter User Id and Password";
else
{
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select user_id, user_fname, user_lname,department_id, user_email, user_password, user_username from users where user_id='" + userid + "' and user_password='" + password + "'";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next())
{
userIDD = rs.getString(1);
user_fname = rs.getString(2);
user_lname = rs.getString(3);
dept_id = rs.getInt(4);
user_email = rs.getString(5);
user_password = rs.getString(6);
user_username = rs.getString(7);
profileBundle = new Bundle();
profileBundle.putInt("userID", user_id);
profileBundle.putInt("deptID", dept_id);
profileBundle.putString("fname", user_fname);
profileBundle.putString("lname", user_lname);
profileBundle.putString("email", user_email);
profileBundle.putString("pass", user_password);
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
//Fragment fragobj = new PathfinderAdd();
//fragobj.setArguments(profileBundle);
z = "Logged In as: " + user_username;
isSuccess=true;
}
else
{
z = "Invalid Credentials";
isSuccess = false;
}
}
}
catch (Exception ex)
{
isSuccess = false;
Log.e("MYAPP", "exception", ex);
z = "Error Somewhere";
}
}
return z;
}
}
public int getMyData() {
int wa = lala;
return wa;
}
}
PahtfinderAdd.java
getting the bundle in the fragment
public class PathfinderAdd extends Fragment {
ConnectionClass connectionClass;
EditText edtideaname, edtbenefit,edtobservation,edtquickwin,targetdate;
Button btnadd;
TextView targettv;
Spinner spinner1, spinner2;
ProgressBar pbbar;
String proid;
CalendarView calendar;
String realDate;
String DAY;
Date targ = null;
String finalDate;
SimpleDateFormat timeFormat;
java.sql.Date sql;
Date date2;
Integer userID;
int user;
public PathfinderAdd(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addpathfinder, container, false);
connectionClass = new ConnectionClass();
edtideaname = (EditText) rootView.findViewById(R.id.edtideaname);
edtbenefit = (EditText) rootView.findViewById(R.id.edtbenefit);
edtobservation = (EditText) rootView.findViewById(R.id.edyobservation);
edtquickwin = (EditText) rootView.findViewById(R.id.edtquickwin);
targetdate = (EditText) rootView.findViewById(R.id.target);
spinner1 = (Spinner) rootView.findViewById(R.id.spinner1);
spinner2 = (Spinner) rootView.findViewById(R.id.spinner2);
btnadd = (Button) rootView.findViewById(R.id.btnadd);
pbbar = (ProgressBar) rootView.findViewById(R.id.pbbar);
targettv = (TextView) rootView.findViewById(R.id.tvtarget);
pbbar.setVisibility(View.GONE);
calendar = (CalendarView) rootView.findViewById(R.id.calendar1);
proid = "";
userID = getArguments().getInt("userID");
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
//String lol = new getMyData().
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPro addPro = new AddPro();
addPro.execute("");
}
});
calendar.setOnDateChangeListener(new OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year_date, int month_date,
int dayOfMonth) {
int day = dayOfMonth;
int month = month_date;
int year = year_date;
DAY=String.valueOf(year)+String.valueOf(month)+String.valueOf(day);
}
});
return rootView;
}
public class AddPro extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
String observation = edtobservation.getText().toString();
String quickwin = edtquickwin.getText().toString();
String ideaname = edtideaname.getText().toString();
String benefit = edtbenefit.getText().toString();
String target_date = targetdate.getText().toString();
String process = spinner1.getSelectedItem().toString();
String benefitType = spinner2.getSelectedItem().toString();
String lol = "2015-11-28";
Integer benefit_type = spinner2.getSelectedItemPosition();
Integer idea_type = spinner1.getSelectedItemPosition();
Integer idea_id;
Integer benefit_id;
Integer pathfinder_id = 1;
Integer pathfinder_status = 9;
Integer pathfinder_prog = 0;
#Override
protected void onPreExecute() {
pbbar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r) {
pbbar.setVisibility(View.GONE);
Toast.makeText(PathfinderAdd.this.getActivity(), r, Toast.LENGTH_SHORT).show();
if(isSuccess==true) {
edtideaname.setText(null);
edtbenefit.setText(null);
edtobservation.setText(null);
edtquickwin.setText(null);
targetdate.setText(null);
}
}
#Override
protected String doInBackground(String... params) {
if (ideaname.trim().equals("") || benefit.isEmpty() || observation.trim().equals("") || quickwin.trim().equals(""))
z = "Please fill all the fields";
else {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
//timeFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
//finalDate = timeFormat.format(targ);
//sql = new java.sql.Date(targ.getTime());
int lol=1;
double benefitInt = Double.parseDouble(benefit);
date2 = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).parse(DAY);
String newDateString = new SimpleDateFormat("yyyy/MM/dd",Locale.ENGLISH).format(date2);
DateFormat format2 = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH);
Date date3 = format2.parse(newDateString);
java.sql.Date finalDt = new java.sql.Date(date3.getTime());
String dates = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
.format(Calendar.getInstance().getTime());
//String date = new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
//.format(calendar.getDate());
switch (idea_type)
{
case 0:
idea_id = 1;
break;
case 1:
idea_id = 2;
break;
case 2:
idea_id = 3;
break;
case 3:
idea_id = 4;
break;
case 4:
idea_id = 5;
break;
default:
idea_id = 1;
break;
}
switch(benefit_type)
{
case 0:
benefit_id = 1;
break;
case 1:
benefit_id = 2;
break;
default:
benefit_id = 1;
break;
}
String query = "insert into pathfinder (pathfinder_id,pathfinder_name,idea_id,benefit_id,pathfinder_potential_eqv,pathfinder_observation,pathfinder_quickwin,pathfinder_target_closure,pathfinder_status,pathfinder_progress,patfinder_actual_closure,pathfinder_date_raised,user_id)" +
"values ('" +pathfinder_id+ "','" +ideaname+ "','" +idea_id+ "','" +benefit_id+ "','" +benefitInt+ "','" +observation+ "','" +quickwin+ "','" +dates+ "','" +pathfinder_status+ "','" +pathfinder_prog+ "','" +dates+ "','" +dates+ "','" + user+"')";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
z = "Added Successfully";
isSuccess = true;
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
Log.e("MYAPP", "exception", ex);
}
}
return z;
}
}
}
You can add or replace Fragment by calling this in your activity
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
more Fragment information check this http://developer.android.com/guide/components/fragments.html
To get data from you activity you can create a method in your activity
public dataType getData() {
return data;
}
in your fragment, you can get data by calling
((YourActivityClass) getActivity()).getData();
Hope this help!!
You are setting the Bundle to the Fragment, but where are you replacing/adding the Fragment? I can't see any FragmentTransaction.
Here you have some examples: http://developer.android.com/reference/android/app/Fragment.html
"DetailsActivity" is what you need, if I'm not wrong.
Example:
When you want to start your Fragment from the Activity:
Fragment fragobj=new PathfinderAdd();
fragobj.setArguments(profileBundle);
getFragmentManager().beginTransaction().add(android.R.id.content, fragobj).commit();
Where android.R.id.content is the container for your Fragments. When you do this your Fragment will be shown and the Bundle will be received.
In your Fragment "onCreate":
if (getArguments() != null) {
Bundle bundle = this.getArguments();
user = bundle.getInt("userID");
}

How to restrict user to set date based on other date from date picker in android

I have 2 date-picker in one activity. What i want to do is when user try to select date from second date-picker then that date should greater than first date-picker's date otherwise it should show alert dialog.
So below is my code.
public class Assignment_Create extends Activity implements OnClickListener {
DataManipulator dataManipulator;
static final int DIALOG_ID = 1;
ImageView imageViewDateAssign, imageViewDueDate, imageViewSubmit;
TextView textViewDtAssign, textViewDueDt;
EditText editTextTitle, editTextDesc;
static final int DATE_DIALOG_ID = 0;
int cDay, cMonth, cYear;
private TextView activeDateDisplay;
private Calendar activeDate;
// Update database
String updateId;
public boolean isEdit;
#Override
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.assignment_create);
imageViewDateAssign = (ImageView) findViewById(R.id.dateassign);
imageViewDueDate = (ImageView) findViewById(R.id.duedate);
imageViewSubmit = (ImageView) findViewById(R.id.submit);
textViewDtAssign = (TextView) findViewById(R.id.textViewDateAssign);
textViewDueDt = (TextView) findViewById(R.id.textViewDueDate);
editTextTitle = (EditText) findViewById(R.id.title);
editTextDesc = (EditText) findViewById(R.id.description);
isEdit = getIntent().getExtras().getBoolean("isEdit");
updateId = getIntent().getExtras().getString("idNo");
if (isEdit) {
editTextTitle.setText(getIntent().getExtras().getString(
"AsmntTitle"));
editTextDesc
.setText(getIntent().getExtras().getString("AsmntDesc"));
}
Code.AssignDate = Calendar.getInstance();
Code.DueDate = Calendar.getInstance();
imageViewDateAssign.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
showDateDialog(textViewDtAssign, Code.AssignDate);
}
});
imageViewDueDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
showDateDialog(textViewDueDt, Code.DueDate);
}
});
imageViewSubmit.setOnClickListener(this);
updateDisplay(textViewDtAssign, Code.AssignDate);
updateDisplay(textViewDueDt, Code.DueDate);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
Code.title = editTextTitle.getText().toString().trim();
Code.description = editTextDesc.getText().toString().trim();
Code.diff = Code.DueDate.getTimeInMillis()
- Code.AssignDate.getTimeInMillis();
Code.days = Code.diff / (24 * 60 * 60 * 1000);
Code.strDays = String.valueOf(Code.days);
Date assignDate = new Date(Code.AssignDate.getTimeInMillis());
Date dueDate = new Date(Code.DueDate.getTimeInMillis());
if (dueDate.before(assignDate) || dueDate.equals(assignDate)) {
AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
Assignment_Create.this);
myDialogBattery.setTitle("How to use Less Battery");
myDialogBattery.setMessage("hahahahahaha");
myDialogBattery.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogBattery.show();
}
if (isEdit) {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.update(updateId);
this.dataManipulator.close();
} else {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.insert(Code.title, Code.description,
Code.strDays);
this.dataManipulator.close();
}
Toast.makeText(getApplicationContext(),
"Details are saved successfully", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Assignment Created Succesfully", Toast.LENGTH_LONG).show();
Assignment_Create.this.finish();
break;
}
}
private void updateDisplay(TextView dateDisplay, Calendar date) {
dateDisplay.setText(new StringBuilder()
// Month is 0 based so add 1
.append(date.get(Calendar.MONTH) + 1).append("-")
.append(date.get(Calendar.DAY_OF_MONTH)).append("-")
.append(date.get(Calendar.YEAR)).append(" "));
}
#SuppressWarnings("deprecation")
public void showDateDialog(TextView dateDisplay, Calendar date) {
activeDateDisplay = dateDisplay;
activeDate = date;
showDialog(DATE_DIALOG_ID);
}
private OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
activeDate.set(Calendar.YEAR, year);
activeDate.set(Calendar.MONTH, monthOfYear);
activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDisplay(activeDateDisplay, activeDate);
unregisterDateDisplay();
}
};
private void unregisterDateDisplay() {
activeDateDisplay = null;
activeDate = null;
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, dateSetListener,
activeDate.get(Calendar.YEAR),
activeDate.get(Calendar.MONTH),
activeDate.get(Calendar.DAY_OF_MONTH));
}
return null;
}
#SuppressWarnings("deprecation")
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(
activeDate.get(Calendar.YEAR),
activeDate.get(Calendar.MONTH),
activeDate.get(Calendar.DAY_OF_MONTH));
break;
}
}
}
I have tried with the following link but not getting solution as i want
how to not allow user select past date in datepicker?
Setting upper and lower date limits to date picker dialog
How to set min-max age limit with datepicker android
Date Picker with max and minimum date in onDateChanged() in Android 1.5?
so i am setting date, now when user click on submit button and if the date-picker2's date is lesser than date-picker1's date then alert dialog should come..
So what i am doing wrong, can anyone help me please. Thanks in advance.
Just compare getTimeInMillis of Calendar
Calendar mCalendarFirst = Calendar.getInstance();
mSelectedCalendar.set(Calendar.YEAR, your_year_from_frist_datepicker);
mSelectedCalendar.set(Calendar.MONTH, your_month_from_frist_datepicker);
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_frist_datepicker);
Calendar mCalendarSecond = Calendar.getInstance();
mSelectedCalendar.set(Calendar.YEAR, your_year_from_second_datepicker);
mSelectedCalendar.set(Calendar.MONTH, your_month_from_seconf_datepicker);
mSelectedCalendar.set(Calendar.DAY_OF_MONTH, your_day_from_second_datepicker);
if(mCalendarSecond.getTimeInMillis() <= mCalendarFirst.getTimeInMillis())
{
//Your second date is less than first date
//Show your dialog here.
}
Update:
For your situation use below:
if(Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis())
{
//Your second date is less than first date
//Show your dialog here.
}
Try Below code:
public void onClick(View v) {
switch (v.getId()) {
case R.id.submit:
Code.title = editTextTitle.getText().toString().trim();
Code.description = editTextDesc.getText().toString().trim();
Code.diff = Code.DueDate.getTimeInMillis()
- Code.AssignDate.getTimeInMillis();
Code.days = Code.diff / (24 * 60 * 60 * 1000);
Code.strDays = String.valueOf(Code.days);
Date assignDate = new Date(Code.AssignDate.getTimeInMillis());
Date dueDate = new Date(Code.DueDate.getTimeInMillis());
if (Code.DueDate.getTimeInMillis() <= Code.AssignDate.getTimeInMillis()){
AlertDialog.Builder myDialogBattery = new AlertDialog.Builder(
Assignment_Create.this);
myDialogBattery.setTitle("How to use Less Battery");
myDialogBattery.setMessage("hahahahahaha");
myDialogBattery.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
myDialogBattery.show();
}else
{
if (isEdit) {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.update(updateId);
this.dataManipulator.close();
} else {
this.dataManipulator = new DataManipulator(this);
this.dataManipulator.insert(Code.title, Code.description,
Code.strDays);
this.dataManipulator.close();
}
Toast.makeText(getApplicationContext(),
"Details are saved successfully", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(),
"Assignment Created Succesfully", Toast.LENGTH_LONG).show();
Assignment_Create.this.finish();
}
break;
}
}
try following code. Here firstDate and secondDate are Date object
if (firstDate.after(secondDate)) { OR //secondDate.before(firstDate)
//display alert here
} else {
}

TextView timer seconds digits jumping

I have this code which simply displays a countdown clock to an event. I am having an issue with it with regards to the last seconds place jumping digits unlike a normal clock. Here is the code I am working with. Could someone please offer some guidance to where this issue may be. Kind regards.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Timer().schedule(new TimerTask() {
File sdcard = Environment.getExternalStorageDirectory();
File cfgFile = new File(sdcard, "TimeTillParis/config.txt");
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
try {
InputStream is = new FileInputStream(cfgFile);
Properties prop = new Properties();
prop.load(is);
int mmY = Integer.parseInt(prop.getProperty("YEAR"));
int mmM = Integer.parseInt(prop.getProperty("MONTH"));
int mmD = Integer.parseInt(prop.getProperty("DAY"));
int mmH = Integer.parseInt(prop.getProperty("HOUR"));
int mmC = Integer.parseInt(prop.getProperty("MINUTE"));
int mmS = Integer.parseInt(prop.getProperty("SECOND"));
Calendar cal = Calendar.getInstance();
Date today = new Date(System.currentTimeMillis());
cal.set(Calendar.YEAR, mmY);
cal.set(Calendar.MONTH, mmM);
cal.set(Calendar.DAY_OF_MONTH, mmD);
cal.set(Calendar.HOUR_OF_DAY, mmH);
cal.set(Calendar.MINUTE, mmC);
cal.set(Calendar.SECOND, mmS);
long milliseconds = (cal.getTimeInMillis() - today.getTime());
String mD="", mH="", mM="", mS="", boxText="";
mD += (milliseconds / (1000*60*60*24));
mH += (milliseconds / (1000*60*60) % 24);
mM += (milliseconds / (1000*60) % 60);
mS += (milliseconds / 1000 % 60);
boxText += "Next visit to Paris in \n\n" +
mD + "d " +
mH + "h " +
mM + "m " +
mS + "s";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(boxText);
} catch (FileNotFoundException e) {
String cfgNotFound="";
cfgNotFound += "config.txt not found!";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(cfgNotFound);
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}, 0, 100);
}
}
I prepared complete solution, let me know if you have some questions:
public class MainActivity extends Activity {
private static final int COUNTDOWN_INTERVAL = 1000;
MyTimer timer;
Calendar eventTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File sdcard = Environment.getExternalStorageDirectory();
File cfgFile = new File(sdcard, "TimeTillParis/config.txt");
try {
InputStream is = new FileInputStream(cfgFile);
Properties prop = new Properties();
prop.load(is);
int mmY = Integer.parseInt(prop.getProperty("YEAR"));
int mmM = Integer.parseInt(prop.getProperty("MONTH"));
int mmD = Integer.parseInt(prop.getProperty("DAY"));
int mmH = Integer.parseInt(prop.getProperty("HOUR"));
int mmC = Integer.parseInt(prop.getProperty("MINUTE"));
int mmS = Integer.parseInt(prop.getProperty("SECOND"));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, mmY);
cal.set(Calendar.MONTH, mmM);
cal.set(Calendar.DAY_OF_MONTH, mmD);
cal.set(Calendar.HOUR_OF_DAY, mmH);
cal.set(Calendar.MINUTE, mmC);
cal.set(Calendar.SECOND, mmS);
eventTime = cal;
} catch (FileNotFoundException e) {
String cfgNotFound="";
cfgNotFound += "config.txt not found!";
TextView textView = (TextView) findViewById(R.id.textView_date_display);
textView.setText(cfgNotFound);
//e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
if(eventTime != null) {
long millisInFuture = (eventTime.getTimeInMillis() - System.currentTimeMillis());
timer = new MyTimer(this, millisInFuture, COUNTDOWN_INTERVAL);
timer.start();
}
}
#Override
protected void onPause() {
super.onPause();
if(timer != null) {
timer.cancel();
}
}
private static class MyTimer extends CountDownTimer {
TextView textView;
public MyTimer(Activity actitivy, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// findViewById is very expansive, so fined it only once
textView = (TextView) actitivy.findViewById(R.id.textView_date_display);
}
#Override
public void onFinish() {
}
#Override
public void onTick(long millisUntilFinished) {
SimpleDateFormat sdf = new SimpleDateFormat("'Next visit to Paris in \n\n'd'd 'h'h 'm'm 's's'");
String boxText = sdf.format(new Date(millisUntilFinished));
textView.setText(boxText);
}
}
}

Categories