Related
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!!
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.
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.
Since i started programing with java on android projects, i didn't have problems where it says: Non static field cannot be referenced from a static context.
This is my code:
package com.esmad.pdm.friendlymanager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import java.util.Calendar;
import android.media.Image;
import android.os.Build;
import android.support.annotation.IdRes;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
public class NewMatch extends AppCompatActivity {
ImageView questionMark;
RadioGroup radioGroup;
EditText gameEventNameTxt;
TextInputLayout textInputLayout;
TextView dateHourTxt;
public static boolean changedData = false;
public static boolean changedHour = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_match);
questionMark = (ImageView) findViewById(R.id.questionMark);
questionMark.setClickable(true);
gameEventNameTxt = (EditText)findViewById(R.id.gameEvent);
textInputLayout = (TextInputLayout)findViewById(R.id.textInputLayout);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
dateHourTxt = (TextView)findViewById(R.id.dateHour);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup group, #IdRes int checkedId) {
if (checkedId == R.id.event) {
textInputLayout.setHint("Event name");
}
else{
textInputLayout.setHint("Match name");
}
}
});
}
public void imageClick(View view) {
Log.d("builderH","im in the builder");
AlertDialog.Builder builder = new AlertDialog.Builder(NewMatch.this);
builder.setTitle("What is a event?");
builder.setMessage("You can create a Event and a game, a Event is a list of games that can be repeated without the need to create every week a new game!");
builder.setCancelable(false);
builder.setPositiveButton("I got it!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int 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 onTimeSet(TimePicker view, int hourOfDay, int minute) {
changedHour = true;
if(changedHour && changedData){
dateHourTxt
}
}
}
public void hourPicker(View view){
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
changedData = true;
}
}
public void datePicker(View view){
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}
as you guys can see above i changed some data to static at initialization, but in other activities i didn't need to do that, and the same error happens for my dateHourTxt inside my onTimeSet method :S
You guys know why this is happening?
You are referencing dateHourTxt from a completely separate class, one that does not contain dateHourTxt.
Your onTimeSet() method is in TimePickerFragment. That is a static class. While its lines physically are inside of NewMatch, it has no access to regular fields on NewMatch. TimePickerFragment could just as easily be a separate Java class, in its own file. In fact, until you gain a bit more experience with Java, I recommend you do just that, to help you better visualize the separation between classes.
If you want TimePickerFragment to work with NewMatch, you need to do so using typical techniques, such as using getActivity() in the fragment to get at the NewMatch instance, so you can call methods on it.
When you make nested class static, it no longer has access to the outer class non static fields. It can access only static fields. In you example solution is to use Fragment.getActivity method to access NewMatch. It should look as follows,
if(changedHour && changedData){
if (getActivity() != null && getActivity() instanceof NewMatch) {
((NewMatch)getActivity()).dateHourTxt = ...
}
}
These two classes send methods and variables back and forth to each other and my code says there's no errors, but the program won't open and I can't figure out why
Here's the first class, TopLevelActivity
package com.example.oife;
import android.media.Image;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.content.Intent;
import android.view.View;
import java.text.SimpleDateFormat;
public class TopLevelActivity extends Activity {
TextView mText = (TextView) findViewById(R.id.calendarView);
private ShareActionProvider shareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_oife);
long date = System.currentTimeMillis();
TextView displayDate = (TextView) findViewById(R.id.displayDate);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
String dateString = sdf.format(date);
displayDate.setText(dateString);
}
public void onPostClick (View view) {
Intent intent = new Intent(this, PostActivity.class);
startActivity(intent);
}
//call onHomeClick() method when the button is clicked
public void onHomeClick (View view){
Intent intent = new Intent(this,TopLevelActivity.class);
startActivity(intent);
}
//call onMoreClick() method when the button is clicked
public void onMoreClick(View view){
Intent intent = new Intent(this, MoreActivity.class);
startActivity(intent);
}
public TextView getMainText(){
return mText;
}
public void setMText(TextView t){
mText.setText(t.getText());
}
}
Here's the second class, PostActivity
This class is where most of the functions from the other one are accessed
package com.example.oife;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
import android.view.View;
public class PostActivity extends Activity {
private TextView pDisplayDate;
private Button pPickDate;
private int pYear;
private int pMonth;
private int pDay;
private TextView mainText;
static final int DATE_DIALOG_ID = 0;
private TextView name = (TextView) findViewById(R.id.name);
private TextView day;
TopLevelActivity top = new TopLevelActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
/** Capture our View elements */
pDisplayDate = (TextView) findViewById(R.id.displayDate);
pPickDate = (Button) findViewById(R.id.pickDate);
/** Listener for click event of the button */
pPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
/** Get the current date */
final Calendar cal = Calendar.getInstance();
pYear = cal.get(Calendar.YEAR);
pMonth = cal.get(Calendar.MONTH);
pDay = cal.get(Calendar.DAY_OF_MONTH);
/** Display the current date in the TextView */
// updateDisplay();
}
private void setMainText(){
TextView d = (TextView) findViewById(R.id.description);
mainText.setText(top.getMainText() + "/n/n" + name + "/n" + makeDay().getText() + "/n" + d.getText());
}
private TextView makeDay(){
TextView ToD;
RadioGroup t = (RadioGroup) findViewById(R.id.TOD);
int id = t.getCheckedRadioButtonId();
if(id == -1) {
ToD = null;
}
else{
ToD = (TextView) findViewById(id);
}
TextView wow;
RadioGroup g = (RadioGroup) findViewById(R.id.WoW);
id = g.getCheckedRadioButtonId();
if (id == -1){
//no item selected
}
else{
wow = (TextView) findViewById(id);
}
TextView d = (TextView) findViewById(R.id.displayDate);
String s = String.valueOf(d);
String j;
if (ToD.getText().equals("Morning")){
j = "9:00";
}
else if(ToD.getText().equals("Midday")){
j = "12:00";
}
else if (ToD.getText().equals("Evening")){
j = "5:00";
}
else {
j = "10:00";
}
TextView time = new TextView(this);
time.setText( j + " " + s);
return time;
}
private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear;
pDay = dayOfMonth;
updateDisplay();
displayToast();
}
};
private void updateDisplay() {
pDisplayDate.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(pMonth + 1).append("/")
.append(pDay).append("/")
.append(pYear).append(" "));
}
private void updateMainDisplay(){
setMainText();
top.setMText(mainText);
}
private void displayToast() {
Toast.makeText(this, new StringBuilder().append("Date choosen is ").append(pDisplayDate.getText()), Toast.LENGTH_SHORT).show();}
/** Create a new dialog for date picker */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
pDateSetListener,
pYear, pMonth, pDay);
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_post, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onCreateClick(View view){
Intent intent = new Intent(this, TopLevelActivity.class);
updateMainDisplay();
startActivity(intent);
}
}
call code like this after you call setContentView:
Activity 1:
TextView mText = (TextView) findViewById(R.id.calendarView);
Activity 2:
private TextView name = (TextView) findViewById(R.id.name);
you did that wrong in both Activitys. You call findViewById in the member section of your Activitys and at this point the Activity dont know anything about the layout file.
That must leads to a NullpointerException.