How can I adjust the gridview of my customized calendar - java

I've *been able to make a customized calendar that can hold events but I cant help but notice the "1" under the days of the calendar
[Here's the picture][1]
[1]: https://i.stack.imgur.com/tUppW.png
Here is the code for my customized calendar:
package com.example.projecttweeta;
import android.app.TimePickerDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import static android.icu.text.DateFormat.MONTH;
import static android.icu.text.DateFormat.YEAR;
public class CustomCalenderView extends LinearLayout {
// Created instances for the code to run...
ImageButton NextButton, PreviousButton;
TextView CurrentDate;
GridView gridView;
private DBOpenHelper dbOpenHelper;
public static final int MAX_CALENDER_DAYS = 42;
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
Context context;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM", Locale.ENGLISH);
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.ENGLISH);
SimpleDateFormat taskDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
GridAdapter myGridAdapter;
AlertDialog alertDialog;
List<Date> dates = new ArrayList<>();
List<Tasks> tasksList = new ArrayList<>();
public CustomCalenderView(Context context) {
super(context);
}
public CustomCalenderView(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
InitializeLayout();
setUpCalender();
PreviousButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, -1);
setUpCalender();
}
});
NextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calendar.add(Calendar.MONTH, 1);
setUpCalender();
}
});
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// an alert dialog; might change later...
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
View addView =
LayoutInflater.from(parent.getContext()).inflate(R.layout.set_reminder_layout, null);
EditText taskTitle = addView.findViewById(R.id.title_edit_text);
EditText taskDescription = addView.findViewById(R.id.description_edit_text);
TextView taskTime = addView.findViewById(R.id.time_edit_text_view);
taskTime.setInputType(InputType.TYPE_NULL);
// Find a way to include settings or something around here
Button saveTask = addView.findViewById(R.id.save_button);
taskTime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(addView.getContext(),
R.style.DatePickerTheme, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar1.set(Calendar.MINUTE, minute);
calendar1.setTimeZone(TimeZone.getDefault());
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a", Locale.ENGLISH);
String plannedTime = sdf.format(calendar1.getTime());
CurrentDate.setText(plannedTime);
}
}, hours, minute, false);
timePickerDialog.show();
}
});
String date = taskDateFormat.format(dates.get(position));
String month = monthFormat.format(dates.get(position));
String year = yearFormat.format(dates.get(position));
saveTask.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
saveTaskEvent(taskTitle.getText().toString(),
taskDescription.getText().toString(), taskTime.getText().toString(), date, month, year);
setUpCalender();
alertDialog.dismiss();
}
});
builder.setView(addView);
alertDialog = builder.create();
alertDialog.show();
}
});
}
public CustomCalenderView(Context context, #Nullable AttributeSet attrs, int defStyleAttr, Context
context1) {
super(context, attrs, defStyleAttr);
}
private void saveTaskEvent(String title, String description, String time, String date, String Mmonth, String mYear) {
dbOpenHelper = new DBOpenHelper(context);
SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
dbOpenHelper.SaveTask(title, description, time, date, Mmonth, mYear, database); // supposed to put database here but... meh
dbOpenHelper.close();
Toast.makeText(context, "Task saved", Toast.LENGTH_SHORT).show();
}
private void InitializeLayout() {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.calender_layout, this);
NextButton = view.findViewById(R.id.next_btn);
PreviousButton = view.findViewById(R.id.prev_btn);
CurrentDate = view.findViewById(R.id.current_date);
gridView = view.findViewById(R.id.gridview);
}
private void setUpCalender() {
String currentDate = simpleDateFormat.format(calendar.getTime());
CurrentDate.setText(currentDate);
dates.clear();
Calendar monthCalender = (Calendar) calendar.clone();
monthCalender.set(Calendar.DAY_OF_MONTH, 1);
int firstDayOfMonth = monthCalender.get(Calendar.DAY_OF_WEEK) - 1;
monthCalender.add(Calendar.DAY_OF_MONTH, -firstDayOfMonth);
collectTasksPerMonth(monthFormat.format(calendar.getTime()), yearFormat.format(calendar.getTime()));
while (dates.size() < MAX_CALENDER_DAYS) {
dates.add(monthCalender.getTime());
monthCalender.add(Calendar.DAY_OF_MONTH, 1);
}
myGridAdapter = new GridAdapter(context, dates, calendar, tasksList);
gridView.setAdapter(myGridAdapter);
}
private void collectTasksPerMonth(String month, String year) {
tasksList.clear();
dbOpenHelper = new DBOpenHelper(context);
SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
Cursor cursor = dbOpenHelper.ReadTasksPerMonth(month, year, database);
while (cursor.moveToNext()) {
String title = cursor.getString(cursor.getColumnIndex(DBStructure.TITLE));
String description = cursor.getString(cursor.getColumnIndex(DBStructure.DESCRIPTION));
String time = cursor.getString(cursor.getColumnIndex(DBStructure.TIME));
String date = cursor.getString(cursor.getColumnIndex(DBStructure.DATE));
String Mmonth = cursor.getString(cursor.getColumnIndex(DBStructure.DMONTH));
String mYear = cursor.getString(cursor.getColumnIndex(DBStructure.DYEAR));
// Tasks tasks = new Tasks(title,description,time,date,month,year);
Tasks maketask = new Tasks(title, description, time, date, Mmonth, mYear);
tasksList.add(maketask);
}
cursor.close();
dbOpenHelper.close();
}
}
And here is my grid adapter...
package com.example.projecttweeta;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class GridAdapter extends ArrayAdapter {
List<Date> dates;
Calendar currentDate;
List<Tasks> tasks;
LayoutInflater inflater;
public GridAdapter(#NonNull Context context, List<Date> dates, Calendar currentDate, List<Tasks> tasks) {
super(context, R.layout.single_cell_layout); // work on that after this...
this.tasks = tasks;
this.dates = dates;
this.currentDate = currentDate;
inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Date monthDate = dates.get(position);
TextView tv;
Calendar dateCalender = Calendar.getInstance();
dateCalender.setTime(monthDate);
int dayNo = dateCalender.get(Calendar.DAY_OF_MONTH);
int displayMonth = dateCalender.get(Calendar.MONTH) + 1;
int displayYear = dateCalender.get(Calendar.YEAR);
int currentYear = currentDate.get(Calendar.YEAR);
int currentMonth = currentDate.get(Calendar.MONTH) + 1;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.single_cell_layout, parent, false);
}
if (displayMonth == currentMonth && displayYear == currentYear) {
view.setBackgroundColor(Color.parseColor("#60DDED"));
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
TextView day_number = view.findViewById(R.id.calender_day);
TextView task_number = view.findViewById(R.id.task_id);
day_number.setText(String.valueOf(dayNo));
Calendar taskCalender = Calendar.getInstance();
ArrayList<String> arrayList = new ArrayList<>();
// SOLVED!!!!
for (int i = 0; i < tasks.size(); i++) {
taskCalender.setTime(convertStringToDate(tasks.get(i).getDATE()));
if (dayNo == taskCalender.get(Calendar.DAY_OF_MONTH) && displayMonth == taskCalender.get(Calendar.MONTH) + 1 && displayYear == taskCalender.get(Calendar.YEAR)) {
arrayList.add(tasks.get(i).getTITLE());
task_number.setText(arrayList.size() + " Tasks");
}
}
return view;
}
#Override
public int getCount() {
return dates.size();
}
private Date convertStringToDate(String taskDate) {
java.text.SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd", Locale.ENGLISH);
Date date = null;
try {
date = format.parse(taskDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return date;
}
#Override
public int getPosition(#Nullable Object item) {
return dates.indexOf(item);
}
#Nullable
#Override
public Object getItem(int position) {
return dates.get(position);
}
}
Please I'd need a response ; I'm on a deadline. Thanks a lot!!

Related

How do you check if the time (hour) is equal to?

Basically I created a text (TextView) where the current time of the device is shown.
i want to put the time in a variable. And then check if the time is equal to (a specific time eg 14:15) when you click on the text a music starts singing.
CODE ⬇️
package com.example.simplecalculatorbyvalentinlearningapp;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class SeccondScreen extends AppCompatActivity {
TextView h;
TextView d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seccond_screen);
//Sound
final MediaPlayer betaaudio = MediaPlayer.create (this, R.raw.betaaudio);
h = (TextView) findViewById(R.id.hour);
d = (TextView) findViewById(R.id.date);
//hour BETA CODE
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
String dateTime = SimpleDateFormat.getTimeInstance().format(calendar.getTime());
h.setText(dateTime);
//date BETA CODE
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
dateTime = SimpleDateFormat.getDateInstance().format(calendar.getTime());
d.setText(dateTime);
//start sound
String vhour = ;
if(vhour == "trad" ) {
h.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
betaaudio.start();
}
});
}
}
}
This is all the code.
I managed to do almost everything but I am stuck to the vhour variable to put the current time inside and then check with (if) if the time is equal to 14:15 for example, to make the code work inside the if, how can i do this?
you want to substring current hour from datatime variable
like this:
String dateTime = SimpleDateFormat.getDateInstance().format(calendar.getTime());
String currentTime = dateTime.substring(10,16);
and you want put check statement inside onClickListener not out side it :
h.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentTile.equals("14:43") {
betaaudio.start();
}
}
});
package com.example.simplecalculatorbyvalentinlearningapp;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class SeccondScreen extends AppCompatActivity {
TextView h;
TextView d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seccond_screen);
//Sound
final MediaPlayer betaaudio = MediaPlayer.create (this, R.raw.betaaudio);
h = (TextView) findViewById(R.id.hour);
d = (TextView) findViewById(R.id.date);
//hour BETA CODE
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm");
String dateTime = SimpleDateFormat.getTimeInstance().format(calendar.getTime());
h.setText(dateTime);
//date BETA CODE
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
dateTime = SimpleDateFormat.getDateInstance().format(calendar.getTime());
d.setText(dateTime);
//start sound
String currentTime = dateTime.substring(10,16);
h.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentTime.equals("14:43")) {
betaaudio.start();
}
}
});
}
}

How to get data from a Dialog RecyclerView to its Hosted Activity?

Hi there I am having a trouble to get back text from the recycler View inside the dialog.
Somebody please help to get the data from dialog view to the same activity.
My data flow is:
MainActivity --> UserDetailsActivity --> dialog (RecyclerView)--->UserDetailsActivity ---> Updatebutton
what happening now is :
MainActivity --> UserDetailsActivity --> dialog (RecyclerView)--->App Crashes!!
what i want is to return the Tax include Money to the rent TextView
Below is my code to UserDetailsActivity.
UserDetailsActivity.Java
package com.ancorp.aplo.activity;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.telephony.SmsManager;
import android.widget.Toast;
import com.ancorp.aplo.R;
import com.ancorp.aplo.adapter.ChannelAdapter;
import com.ancorp.aplo.database.SqliteDatabase;
import com.ancorp.aplo.model.Contacts;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.time.Month;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class UserDetailsActivity extends AppCompatActivity {
private final static int SEND_SMS_PERMISSION_REQ=1;
public TextView textView ;
EditText name_edit;
EditText jacode_edit;
EditText phone_edit;
EditText balance_edit , paidDate_edit, paidAmount_edit, rent_edit, zone_edit;
SqliteDatabase myDB;
String header,data1,data2,timeStamp;
String month;
private Context context;
float amount;
Integer d1,d2;
Integer y;
TextView phone_text,btnRecharge, Activation, Deactivation , rent_text , zone_text,plan_text,name_text,jacode_text, Status_text, id_text;
TextView balance_text, LastPaidAmount,LastPaidDate;
int deactive = Color.RED;
int activeg = Color.GREEN;
Button btnEdit;
String id,balance, Lpdate, LpAmount,zone,rent;
String phoneNo,message;
String Status;
Button btndelete ;
ImageView editimgbtn,addimgbtn;
Spinner pkgname;
String SpinnerData;
String planAmount,chName,chId,chMoney;
private static int ACTIVE_CODE = 0;
private static int DEACTIVE_CODE = 0;
private SqliteDatabase mDatabase;
private ArrayList<Contacts> userData;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
Button recharges;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
mDatabase = new SqliteDatabase(this);
// getUserData(id);
ActionBar actionBar = getSupportActionBar();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
actionBar.setTitle("Customer Details");
name_edit = findViewById(R.id.user_name);
jacode_edit = findViewById(R.id.name_jacode);
phone_edit = findViewById(R.id.name_phone);
balance_edit = findViewById(R.id.name_balance);
paidAmount_edit = findViewById(R.id.LastPaidAmount_edit);
paidDate_edit = findViewById(R.id.lastPaidDate_edit);
rent_edit = findViewById(R.id.name_rent);
zone_edit =findViewById(R.id.name_zone);
pkgname= findViewById(R.id.name_package);
id_text = findViewById(R.id.id);
name_text= findViewById(R.id.user_name_text);
Status_text = findViewById(R.id.cid);
phone_text= findViewById(R.id.name_phone_text);
jacode_text= findViewById(R.id.name_jacode_text);
balance_text =findViewById(R.id.name_balance_text);
LastPaidAmount = findViewById(R.id.LastPaidAmount_text);
LastPaidDate = findViewById(R.id.lastPaidDate_text);
rent_text = findViewById(R.id.name_rent_text);
zone_text = findViewById(R.id.name_zone_text);
plan_text = findViewById(R.id.name_package_text);
Activation = findViewById(R.id.Activate);
Deactivation = findViewById(R.id.DeActivate);
//rent_edit = findViewById(R.id.name_rent);
//zone_edit = findViewById(R.id.name_zone);
addimgbtn = findViewById(R.id.addimgbtn);
btnEdit=findViewById(R.id.btnEdit);
btndelete = findViewById(R.id.btnDelete);
btnRecharge = findViewById(R.id.btnRecharge);
editimgbtn = findViewById(R.id.editbtnimg);
addimgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddChannel(UserDetailsActivity.this);
}
});
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTask();
}
});
btnRecharge.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View v) {
rechargeUser();
}
});
editimgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadSpinnerData();
name_edit.setVisibility(View.VISIBLE);
phone_edit.setVisibility(View.VISIBLE);
jacode_edit.setVisibility(View.VISIBLE);
balance_edit.setVisibility(View.VISIBLE);
paidAmount_edit.setVisibility(View.VISIBLE);
paidDate_edit.setVisibility(View.VISIBLE);
btndelete.setVisibility(View.VISIBLE);
btnEdit.setVisibility(View.VISIBLE);
rent_edit.setVisibility(View.VISIBLE);
zone_edit.setVisibility(View.VISIBLE);
pkgname.setVisibility(View.VISIBLE);
name_text.setVisibility(View.GONE);
phone_text.setVisibility(View.GONE);
jacode_text.setVisibility(View.GONE);
balance_text.setVisibility(View.GONE);
LastPaidAmount.setVisibility(View.GONE);
LastPaidDate.setVisibility(View.GONE);
btnRecharge.setVisibility(View.GONE);
rent_text.setVisibility(View.GONE);
zone_text.setVisibility(View.GONE);
plan_text.setVisibility(View.GONE);
// rechargebtn.setVisibility(View.GONE);
}
});
Intent intent =getIntent();
if (intent.getExtras() != null){
Contacts contacts = (Contacts) intent.getSerializableExtra("data");
id = getIntent().getStringExtra("id");
balance = getIntent().getStringExtra("balance");
Lpdate = getIntent().getStringExtra("LPDATE");
LpAmount = getIntent().getStringExtra("lpAmount");
zone = getIntent().getStringExtra("zone");
rent = getIntent().getStringExtra("rent");
Status_text.setText(contacts.getStatus());
Status = contacts.getStatus();
chId=getIntent().getStringExtra("channelID");
chName = getIntent().getStringExtra("channelName");
chMoney = getIntent().getStringExtra("channelMoney");
Toast.makeText(getApplicationContext(), chId , Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), chName , Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), chMoney , Toast.LENGTH_SHORT).show();
id_text.setText(id);
name_edit.setText(contacts.getName());
phone_edit.setText(contacts.getPhno());
jacode_edit.setText(contacts.getJacode());
balance_edit.setText(contacts.getBalance());
rent_edit.setText(rent);
zone_edit.setText(zone);
// plan_edit.setText(contacts.getCplan());
// balance_edit.setText(balance);
// paidDate_edit.setText(contacts.getPaidDate());
paidDate_edit.setText(Lpdate);
// paidAmount_edit.setText(contacts.getPaidAmount());
paidAmount_edit.setText(LpAmount);
// LastPaidDate.setText(contacts.getPaidDate());
LastPaidDate.setText(Lpdate);
//LastPaidAmount.setText(contacts.getPaidAmount());
LastPaidAmount.setText(LpAmount);
name_text.setText(contacts.getName());
phone_text.setText(contacts.getPhno());
jacode_text.setText(contacts.getJacode());
balance_text.setText(contacts.getBalance());
rent_text.setText(rent);
zone_text.setText(zone);
plan_text.setText(contacts.getCplan());
//balance_text.setText(balance);
header = name_edit.getText().toString();
}
pkgname.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
SqliteDatabase mydb = new SqliteDatabase(UserDetailsActivity.this);
SpinnerData = (String) adapterView.getItemAtPosition(i).toString();
planAmount = mydb.getPlanAmount(SpinnerData);
// Toast.makeText(getApplicationContext(),planAmount,Toast.LENGTH_SHORT).show();
rent_edit.setText(planAmount);
rent_text.setText(planAmount);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
String active ="Active";
String deac = "Deactive";
if (Status.equals(active) == true){
Activation.setVisibility(View.GONE);
Deactivation.setVisibility(View.VISIBLE);
ACTIVE_CODE =1;
}
else {
ACTIVE_CODE =2;
Activation.setVisibility(View.VISIBLE);
Deactivation.setVisibility(View.GONE);
}
Activation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
String timeStamps = simpleDateFormat.format(new Date()) ;
String statu ="Active";
String stats = "Activated On ";
String name = name_text.getText().toString();
mDatabase.statusUpdate(id ,statu);
mDatabase.statusDetails(id , name,stats,timeStamps);
Status_text.setText(statu);
Activation.setVisibility(View.GONE);
Deactivation.setVisibility(View.VISIBLE);
}
});
Deactivation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String statu ="Deactive";
String stats = "DeActivated On ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
String timeStamps = simpleDateFormat.format(new Date()) ;
String name = name_text.getText().toString();
mDatabase.statusUpdate(id ,statu);
mDatabase.statusDetails(id , name,stats,timeStamps);
Status_text.setText(statu);
Activation.setVisibility(View.VISIBLE);
Deactivation.setVisibility(View.GONE);
}
});
}
private void AddChannel(UserDetailsActivity activity) {
dialog = new Dialog(activity);
// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.channel_selection);
myDB = new SqliteDatabase(this);
// myDB.getChannel();
channel_id = new ArrayList<>();
channel_name = new ArrayList<>();
channel_ntMoney = new ArrayList<>();
channel_tMoney = new ArrayList<>();
Cursor cursor = myDB.getChannel();
if (cursor.getCount()==0){
Toast.makeText(this, "No Plans Have Added yet ", Toast.LENGTH_SHORT).show();
}else {
while (cursor.moveToNext()){
channel_id.add(cursor.getString(0));
channel_name.add(cursor.getString(1));
channel_ntMoney.add(cursor.getString(2));
channel_tMoney.add(cursor.getString(3));
}
}
RecyclerView recyclerView = dialog.findViewById(R.id.channelRecyclerView);
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney);
recyclerView.setAdapter(cAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
dialog.show();
}
private void editTask() {
final String name = name_edit.getText().toString();
final String id = id_text.getText().toString();
final String rent = rent_edit.getText().toString();
final String zone = zone_edit.getText().toString();
final String ph_no = phone_edit.getText().toString();
final String jacode = jacode_edit.getText().toString();
final String balance = balance_edit.getText().toString();
final String plan = SpinnerData;
if (TextUtils.isEmpty(name)) {
Toast.makeText(getApplicationContext(),"Something Went Wrong",Toast.LENGTH_SHORT).show();
} else {
// Contacts newContact = new Contacts(Objects.requireNonNull(contacts).getId(),name, ph_no,jacode,balance);
//mDatabase.updateContacts(newContact);
mDatabase.updateContacts(id,name, ph_no,jacode,balance,rent,zone,plan);
name_edit.setText(name);name_text.setText(name);
phone_edit.setText(ph_no);phone_text.setText(ph_no);
rent_text.setText(rent);rent_edit.setText(rent);
jacode_edit.setText(jacode);jacode_text.setText(jacode);
balance_edit.setText(balance);balance_text.setText(balance);
zone_text.setText(zone);zone_edit.setText(zone);
plan_text.setText(plan);//pkgname.set(plan);
name_edit.setVisibility(View.GONE);
phone_edit.setVisibility(View.GONE);
jacode_edit.setVisibility(View.GONE);
rent_edit.setVisibility(View.GONE);
balance_edit.setVisibility(View.GONE);
paidAmount_edit.setVisibility(View.GONE);
paidDate_edit.setVisibility(View.GONE);
btndelete.setVisibility(View.GONE);
btnEdit.setVisibility(View.GONE);
zone_edit.setVisibility(View.GONE);
pkgname.setVisibility(View.GONE);
name_text.setVisibility(View.VISIBLE);
rent_text.setVisibility(View.VISIBLE);
zone_text.setVisibility(View.VISIBLE);
phone_text.setVisibility(View.VISIBLE);
jacode_text.setVisibility(View.VISIBLE);
balance_text.setVisibility(View.VISIBLE);
LastPaidAmount.setVisibility(View.VISIBLE);
LastPaidDate.setVisibility(View.VISIBLE);
btnRecharge.setVisibility(View.VISIBLE);
plan_text.setVisibility(View.VISIBLE);
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void rechargeUser() {
final AlertDialog builder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.recharge,null);
builder.setTitle("Recharge " + header);
final EditText rechargeField = (EditText) dialogView.findViewById(R.id.rechargeEditText);
final Button cancel = (Button) dialogView.findViewById(R.id.btnCancelRecharge);
recharges = (Button) dialogView.findViewById(R.id.btnRechargeSucess);
recharges.setEnabled(false);
if(checkPermission(Manifest.permission.SEND_SMS))
{
recharges.setEnabled(true);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQ);
}
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Cancelled Recharge !!",Toast.LENGTH_LONG).show();
builder.dismiss();
}
});
recharges.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d1 = Integer.valueOf(rechargeField.getText().toString().trim());
d2 = Integer.valueOf(balance_edit.getText().toString().trim());
amount= d2 - d1;
data1 = String.valueOf(amount);
data2 = String.valueOf(d1);
String name = String.valueOf(name_text.getText().toString().trim());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
timeStamp = simpleDateFormat.format(new Date()) ;
String cdate = date.format(new Date());
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH,Calendar.LONG, Locale.UK);
int year = Calendar.getInstance().get(Calendar.YEAR);
String due= balance_text.getText().toString().trim();
String paid = String.valueOf(d1);
//Toast.makeText(getApplicationContext(),month,Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),String.valueOf(year),Toast.LENGTH_SHORT).show();
mDatabase.rechargeUser(id, (int) amount,d1,timeStamp);
mDatabase.InsertPaymentDetails(id,month,year,timeStamp,paid,due);
mDatabase.collectionDetails(id,name,d1,cdate,month,year);
reloadData();
sendSms();
builder.dismiss();
}
});
builder.setView(dialogView);
builder.show();
}
private void sendSms() {
String names = name_text.getText().toString();
String s1=phone_text.getText().toString();
String s2=("Hi "+names+", You have Successfully recharged ₹ " +d1 +" to your SKY VISION Cable account on "+timeStamp+". Your current balance is ₹ "+amount+" . Kindly clear your balance on time without any due. \n - Thank you! \n SKY VISION KONGAD");
if(!TextUtils.isEmpty(s1)&&!TextUtils.isEmpty(s2))
{
if(checkPermission(Manifest.permission.SEND_SMS))
{
SmsManager smsManager= SmsManager.getDefault();
ArrayList<String> part = smsManager.divideMessage(s2);
smsManager.sendMultipartTextMessage(s1,null,part,null,null);
}
else {
Toast.makeText(UserDetailsActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(UserDetailsActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
private void reloadData() {
balance_text.setText(data1);
balance_edit.setText(data1);
LastPaidAmount.setText(data2);
LastPaidDate.setText(timeStamp);
paidAmount_edit.setText(data2);
paidDate_edit.setText(timeStamp);
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.user_details, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.payment_details:
Intent intent = new Intent(this,PaymentDetailsActivity.class);
intent.putExtra("ID",id);
startActivity(intent);
break;
case R.id.WriteOff:
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Write Off?");
builder.setMessage("Are you sure you want to Write off ?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
WriteOff();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
break;
case R.id.boxDetails:
Intent boxDetails = new Intent(this,BoxDetailsActivity.class);
boxDetails.putExtra("ID",id);
startActivity(boxDetails);
break;
}
return super.onOptionsItemSelected(item);
}
private void WriteOff() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy - hh:mm:ss");
timeStamp = simpleDateFormat.format(new Date()) ;
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH,Calendar.LONG, Locale.UK);
int year = Calendar.getInstance().get(Calendar.YEAR);
String due= balance_text.getText().toString().trim();
String paid = "Write Off";
balance_text.setText("0");
balance_edit.setText("0");
String Writeofbalance ="0";
mDatabase.writeOff(id, month , year , timeStamp , paid , due, Writeofbalance);
}
private boolean checkPermission(String sendSms) {
int checkpermission= ContextCompat.checkSelfPermission(this,sendSms);
return checkpermission== PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case SEND_SMS_PERMISSION_REQ:
if(grantResults.length>0 &&(grantResults[0]== PackageManager.PERMISSION_GRANTED))
{
btnRecharge.setEnabled(true);
}
break;
}
}
private void loadSpinnerData() {
SqliteDatabase db = new SqliteDatabase(getApplicationContext());
List<String> labels = db.getAllPlansSpinner();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,labels);
arrayAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
pkgname.setAdapter(arrayAdapter);
}
ArrayList<String> channel_id,channel_name,channel_ntMoney,channel_tMoney;
ChannelAdapter cAdapter;
public static Dialog dialog;
}
here is my ChannelAdapterActivity
ChannelAdapterActivity.Java
package com.ancorp.aplo.adapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ancorp.aplo.R;
import com.ancorp.aplo.activity.UserDetailsActivity;
import com.ancorp.aplo.model.Contacts;
import java.util.ArrayList;
public class ChannelAdapter extends RecyclerView.Adapter<ChannelAdapter.MyViewHolder> {
private Context context;
private Activity activity;
private ArrayList<Contacts> allChannels;
String id,name,money;
private ArrayList channel_id,channel_name,channel_ntMoney,channel_tMoney;
public ChannelAdapter(Activity activity, Context context, ArrayList<String> channel_id, ArrayList<String> channel_name, ArrayList<String> channel_ntMoney, ArrayList<String> channel_tMoney) {
this.context = context;
this.activity = activity;
this.channel_id = channel_id;
this.channel_name=channel_name;
this.channel_ntMoney= channel_ntMoney;
this.channel_tMoney= channel_tMoney;
}
public ChannelAdapter(Context context, ArrayList<Contacts> allChannel) {
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater .inflate(R.layout.channel_list,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
holder.channelName.setText(String.valueOf(channel_name.get(i)));
holder.channelNt.setText(String.valueOf(channel_ntMoney.get(i)));
holder.channelT.setText(String.valueOf(channel_tMoney.get(i)));
id = String.valueOf(channel_id.get(i));
name=String.valueOf(channel_name.get(i));
money = String.valueOf(channel_tMoney.get(i));
}
#Override
public int getItemCount() {
return channel_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView channelName,channelNt,channelT;
LinearLayout channelLayout;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
channelName = itemView.findViewById(R.id.channelName);
channelNt = itemView.findViewById(R.id.ntMoney);
channelT = itemView.findViewById(R.id.tMoney);
channelLayout = itemView.findViewById(R.id.channelMainLayout);
}
}
}
Somebody please help me I am Newbie to this.
This is another method of sending data from Adapter to Activity.
Follow these steps carefully:
Create an interface with a method
public interface InterfaceTax {
public void getTaxMoney(int amount);
}
the parameters of the method should contain the data you want to send back to the activity.
Create a variable for that interface in the Adapter and add the interface to the constructor of the Adapter.
private InterfaceTax interfaceT;
public ChannelAdapter(/* other parameters */, InterfaceTax interface) {
interfaceT = interface;
}
Then in onBindViewHolder (or wherever your data is) call the method of the interface and send the data
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int i) {
money = String.valueOf(channel_tMoney.get(i));
interface.getTaxMoney(money);
}
Then in your activity implement the interface and override the method to receive data
public class UserDetailsActivity extends AppCompatActivity implements InterfaceTax {}
#Override
public void getTaxMonney(int data) {
// receive data here
}
In your AddChannel method, replace this line
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney);
with this
ChannelAdapter cAdapter = new ChannelAdapter(UserDetailsActivity.this,this,channel_id,channel_name,channel_ntMoney,channel_tMoney, this);
This will automatically send the data from the adapter to the activity and you can receive it in the method overridden in the activity.

Change colour of an item view in recycler view after comparison with its textview data

I have a RecyclerView with 'n' number of ItemViews in it. These ItemViews contain Textviews with data with are updated through Firestore.
Now I need to compare one of the value0(getexpirydate) in the Textviews with another value1(Current date). Then if value1 > value0, then change the colour of that specific Itemview to RED. else GREEN.
ContractsAdapter
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import org.w3c.dom.Text;
import java.util.Calendar;
import java.util.List;
public class ContractsAdapter extends RecyclerView.Adapter<ContractsAdapter.ContractViewHolder>{
private Context mCtx;
private List<Contracts> contractsList;
private FirebaseFirestore db;
public ContractsAdapter(Context mCtx, List<Contracts> contractsList){
this.mCtx = mCtx;
this.contractsList = contractsList;
}
#NonNull
#Override
public ContractsAdapter.ContractViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ContractViewHolder(
LayoutInflater.from(mCtx).inflate(R.layout.contract_layout, parent, false)
);
}
#Override
public void onBindViewHolder(#NonNull ContractsAdapter.ContractViewHolder holder, int position) {
Contracts contract = contractsList.get(position);
holder.contractname.setText(contract.getStationorpackagename());
holder.contractorname.setText(contract.getContractorname());
holder.dateofcommencement.setText(contract.getDateofcommnew());
holder.dateofexpiry.setText(contract.getDateofexpiry());
holder.licensefee.setText(contract.getLicensefees());
holder.contracttenure.setText(contract.getContracttenure());
holder.datesixmonths.setText(contract.getDateexpirysixmonths());
holder.dateoffloating.setText(contract.getDateofnewfloatingtender());
holder.dateofopening.setText(contract.getDateofopeningtender());
holder.dateofaward.setText(contract.getDateofletterofawardee());
holder.dateofcommnew.setText(contract.getDateofcommencementofnew());
holder.reasonsfordelay.setText(contract.getReasonsfordelay());
holder.duedatelicensefee.setText(contract.getDuedatelicensefee());
/*int po = 2;
if(po == position){
holder.itemView.setBackgroundColor(Color.RED);
} else {
holder.itemView.setBackgroundColor(Color.GREEN);
}*/
}
#Override
public int getItemCount() { return contractsList.size(); }
class ContractViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView contractname, contractorname, dateofcommencement, dateofexpiry, licensefee, contracttenure, datesixmonths;
TextView dateoffloating, dateofopening, dateofaward, dateofcommnew, reasonsfordelay;
TextView textviewtenure, sixmonths, floatingtext, opening, award, commnew, duedatelicensefee;
public ContractViewHolder(#NonNull View itemView) {
super(itemView);
contractname = itemView.findViewById(R.id.contract_name);
contractorname = itemView.findViewById(R.id.contractor_name);
dateofcommencement = itemView.findViewById(R.id.date_of_commencement);
dateofexpiry = itemView.findViewById(R.id.date_of_expiry);
licensefee = itemView.findViewById(R.id.license_fee);
contracttenure = itemView.findViewById(R.id.contract_tenure);
datesixmonths = itemView.findViewById(R.id.date_six_months);
dateoffloating = itemView.findViewById(R.id.date_floating_new);
dateofopening = itemView.findViewById(R.id.date_of_opening);
dateofaward = itemView.findViewById(R.id.letter_of_award);
dateofcommnew = itemView.findViewById(R.id.date_of_commnew);
reasonsfordelay = itemView.findViewById(R.id.reasons_delay);
duedatelicensefee = itemView.findViewById(R.id.due_license_fee);
/// Text View for explanations
textviewtenure = itemView.findViewById(R.id.textView11);
sixmonths = itemView.findViewById(R.id.textView13);
floatingtext = itemView.findViewById(R.id.textView16);
opening = itemView.findViewById(R.id.textView18);
award = itemView.findViewById(R.id.textView20);
commnew = itemView.findViewById(R.id.textView22);
//// End
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
builder.setTitle("Choose an action");
final String[] action = {"Update/Modify Contract", "Delete Contract"};
builder.setItems(action, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (action[which].equals("Update/Modify Contract")) {
Contracts contract = contractsList.get(getAdapterPosition());
Intent intent = new Intent(mCtx, Update.class);
intent.putExtra("contract", contract);
mCtx.startActivity(intent);
}
else if (action[which].equals("Delete Contract")){
Contracts contract = contractsList.get(getAdapterPosition());
Intent intent = new Intent(mCtx, Delete.class);
intent.putExtra("contract", contract);
mCtx.startActivity(intent);
}
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return;
}
}
}
So was able to make it work by adding this before setText.
String date = new SimpleDateFormat("dd.MM.yyyy", Locale.getDefault()).format(new Date());
DateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
try {
Date date1 = (Date)formatter.parse(date);
Date d1 = new SimpleDateFormat("dd.MM.yyyy").parse(contract.getDateofexpiry());
if (d1.after(date1)){
holder.contractname.setTextColor(Color.GREEN);
}
} catch (ParseException e) {
e.printStackTrace();
}
#Override
public void onBindViewHolder(#NonNull ContractsAdapter.ContractViewHolder holder, int position) {
Contracts contract = contractsList.get(position);
if (contract.getCurrentDate() > contract.getDateofexpiry()) {
holder.dateofexpiry.setTextColor(Color.RED);
}
holder.dateofexpiry.setText(contract.getDateofexpiry());
}

getting selected radiobutton text as string

I have created two activity one for registration details and another one for showing the value user has entered. But when I tried to get the value of radiobutton from the radiogroup selected. It doesn't show any error but when I debug and run in my phone.
And clicked the signup button
It show app stopped working start again message
My MainActivity.java :
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button signUpButton,signInButton;
TextView userTimeJoining, dateOfBirth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signInButton = findViewById(R.id.signinbutton);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
signUpButton = findViewById(R.id.signupbutton);
signUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoRegAct = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(gotoRegAct);
}
});
}
}
My RegistrationActivity.java :
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class RegistrationActivity extends AppCompatActivity {
String courseList[] = {"Java","Python", "Android", "Kotlin"};
Button submitButton;
EditText nameOfUser, userGmail, userName, userPassword;
TextView userDateOfBirth, userTimeOfJoining;
Spinner mySpinnerForCourse;
RadioGroup genderSelected;
RadioButton selectedRadiobutton;
String setTime;
String setDate;
String setGender=" ";
int itemNoSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
submitButton = findViewById(R.id.submitButton);
nameOfUser = findViewById(R.id.nameofuser);
userGmail = findViewById(R.id.usergmail);
userName = findViewById(R.id.username);
userPassword = findViewById(R.id.userpassword);
userDateOfBirth = findViewById(R.id.userdateofbirth);
userTimeOfJoining = findViewById(R.id.usertimeofjoining);
mySpinnerForCourse = findViewById(R.id.usercourse);
genderSelected = findViewById(R.id.usergender);
//This is the code which is not working
int selectedRadioButtonId = genderSelected.getCheckedRadioButtonId();
selectedRadiobutton = (RadioButton) findViewById(selectedRadioButtonId);
setGender = selectedRadiobutton.getText().toString();
ArrayAdapter<String> arrayAdapterForCourse = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,courseList);
mySpinnerForCourse.setAdapter(arrayAdapterForCourse);
mySpinnerForCourse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
itemNoSelected = i;
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
userTimeOfJoining.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int hh = calendar.get(Calendar.HOUR);
int mm = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(RegistrationActivity.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int i, int i1) {
setTime = i+" : "+i1;
userTimeOfJoining.setText(setTime);
}
},
hh, mm, false);
timePickerDialog.show();
}
});
userDateOfBirth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int mm = calendar.get(Calendar.MONTH);
int yy = calendar.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(RegistrationActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
setDate = i2+" / "+i1+" / "+i;
userDateOfBirth.setText(setDate);
}
}, yy, mm, dd);
datePickerDialog.show();
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoShowInfo = new Intent(RegistrationActivity.this, ShowInfo.class);
Bundle bundleforenteredvalue = new Bundle();
bundleforenteredvalue.putString("enteredname",nameOfUser.getText().toString());
bundleforenteredvalue.putString("enteredgmail",userGmail.getText().toString());
bundleforenteredvalue.putString("enteredusername",userName.getText().toString());
bundleforenteredvalue.putString("enteredpassword",userPassword.getText().toString());
bundleforenteredvalue.putString("dateselected",setDate);
bundleforenteredvalue.putString("timeselected",setTime);
bundleforenteredvalue.putString("genderselected",setGender);
bundleforenteredvalue.putString("courseselected",courseList[itemNoSelected]);
gotoShowInfo.putExtras(bundleforenteredvalue);
startActivity(gotoShowInfo);
}
});
}
}
My ShowInfo.java :
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ShowInfo extends AppCompatActivity {
TextView nameOfUserEntered, usernameEntered, passwordEntered,gmailEntered, genderSelected, courseSelected, dateOFJoinSelected, timeOfJoinSelected;
Button signInButtonAgain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_info);
Bundle getValue = getIntent().getExtras();
String getnameentered = getValue.getString("enteredname");
String getenteredGmail = getValue.getString("enteredgmail");
String getenteredUsername = getValue.getString("enteredusername");
String getenteredPassword = getValue.getString("enteredpassword");
String getdateSelected = getValue.getString("dateselected");
String gettimeSelected = getValue.getString("timeselected");
String getgenderSelected = getValue.getString("genderselected");
String getcourseSelected = getValue.getString("courseselected");
nameOfUserEntered = findViewById(R.id.nameofuserentered);
usernameEntered = findViewById(R.id.usernameentered);
passwordEntered = findViewById(R.id.passwordentered);
gmailEntered = findViewById(R.id.gmailentered);
genderSelected = findViewById(R.id.genderselected);
courseSelected = findViewById(R.id.courseselected);
dateOFJoinSelected = findViewById(R.id.dateofjoinselected);
timeOfJoinSelected = findViewById(R.id.timeofjoinselected);
signInButtonAgain = findViewById(R.id.signinbuttonagain);
nameOfUserEntered.setText("Welcome "+ getnameentered);
usernameEntered.setText("Your username is "+getenteredUsername);
passwordEntered.setText("Your password is "+getenteredPassword);
gmailEntered.setText("Your gmail is "+getenteredGmail);
genderSelected.setText("Your gender is the "+getgenderSelected);
courseSelected.setText("You selected for the "+getcourseSelected+" Course");
dateOFJoinSelected.setText("your joinig date is "+getdateSelected);
timeOfJoinSelected.setText("Time of your duty is starts from "+gettimeSelected);
signInButtonAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent gotoMainmenu = new Intent(ShowInfo.this, MainActivity.class);
startActivity(gotoMainmenu);
}
});
}
}
In registration activity I've added a comment by only that code my app show the error message. If I remove the radiobutton code and the getString String. It works properly and then it doesn't show app stopped working message.
So why I'm not able to pass the value of the radiobutton string from one activity to another.
Try this may be your radiobutton id returns -1 if no values are selected in radio group.
int chk_gender = rg_gender.getCheckedRadioButtonId();
if (chk_gender != -1) {
Gender = ((RadioButton)findViewById(chk_gender)).getText().toString();
}
else
{
Gender = "";
}
EDITED
rg_gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId != -1) {
Gender = ((RadioButton)findViewById(checkedId)).getText().toString();
}
else
{
Gender = "";
}
}
});
In your xml layout ,did you checked TRUE any radio button ?
You should get the selected radio button value on click of submit button.It will update your setGender string with most recent value.
for your app crash , Please post your logcat error while app crash.

Create a TimePickerDialog using the FragmentDialog?

I want to create a TimePickerDialog using FragmentDialog and exchange data between my fragment and the TimePickerDialog . I already created a DatePickerDialog but I don't know how to create a TimePickerDialog . I want that when the user click the button in my fragment TimePickerDialog appear .
This is how I create The DatePickerDialog :
import java.util.Calendar; import java.util.Date; import
java.util.GregorianCalendar;
import android.app.Activity; import android.app.AlertDialog; import
android.app.Dialog; import android.content.DialogInterface; import
android.content.Intent; import android.os.Bundle; import
android.support.v4.app.DialogFragment; import android.view.View;
import android.widget.DatePicker; import
android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "criminalintent.DATE";
Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment()
.onActivityResult(getTargetRequestCode(), resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date)getArguments().getSerializable(EXTRA_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater()
.inflate(R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker)v.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month, int day) {
mDate = new GregorianCalendar(year, month, day).getTime();
// update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
sendResult(Activity.RESULT_OK);
}
})
.create();
} }
CrimeFragment
import java.util.Date; import java.util.UUID;
import android.app.Activity; import android.content.Intent; import
android.os.Bundle; import android.support.v4.app.Fragment; import
android.support.v4.app.FragmentManager; import android.text.Editable;
import android.text.TextWatcher; import android.view.LayoutInflater;
import android.view.View; import android.view.ViewGroup; import
android.webkit.WebView.FindListener; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener; import
android.widget.EditText;
public class CrimeFragment extends Fragment {
public static final String EXTRA_CRIME_ID = "criminalintent.CRIME_ID";
private static final String DIALOG_DATE = "date";
private static final int REQUEST_DATE = 0;
Crime mCrime;
EditText mTitleField;
Button mDateButton;
CheckBox mSolvedCheckBox;
Button mTime;
String time;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
public void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
public void updateTime() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before, int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count, int after) {
// this space intentionally left blank
}
public void afterTextChanged(Editable c) {
// this one too
}
});
mDateButton = (Button)v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTime = (Button) v.findViewById(R.id.crime_time);
mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
if (requestCode == REQUEST_DATE) {
Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
} }
Now I want to create a TimePickerDialog .
public class DialogFragmentTimePicker extends DialogFragment implements OnTimeSetListener {
public static final String ARG_HOUR = "hour";
public static final String ARG_MINUTE = "minute";
private OnTimeSetListener mListener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
int hour, minute;
if (getArguments() != null) {
hour = getArguments().getInt(ARG_HOUR);
minute = getArguments().getInt(ARG_MINUTE);
} else {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
}
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
public void setOnTimeSetListener(OnTimeSetListener listener) {
mListener = listener;
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
if (mListener != null) {
mListener.onTimeSet(view, hourOfDay, minute);
}
}
}

Categories