Firstly, this is my first question here, Thanks for any reply:)
I have a fragment extends SherlockListFragment that has a list of (events) saved in database, i want when i click on any item in the list , to get all event data and fill in another activity that has editText(s) ....
this is the frgment.java code
public class EventsFragment extends SherlockListFragment {
EditText _eventName_;
EditText next_activty_text;
List<String> presidents = new ArrayList<String>();
public DBAdapter db;
String buf = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_events, container, false);
_eventName_ = (EditText) v.findViewById(R.id.editText11);
next_activty_text = (EditText) v.findViewById(R.id.editText12);
// The most Important part in action bar menus :)
setHasOptionsMenu(true);
/*
//This is how to link a button in fragment by its .xml file :Ds
Button create_btn = (Button) v.findViewById(R.id.button1);
create_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
}
});*/
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
db = new DBAdapter(getActivity());
db.open();
int i = 1;
while(db.getEvent(i).isLast()){
Cursor c = db.getEvent(i);
presidents.add(c.getString(1));
i++;
}
db.close();
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, presidents));
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_events_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.add:
startActivity(new Intent("com.nazmy.CreateEventActivity"));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
//startActivity(new Intent("com.nazmy.CreateEventActivity"));
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
//populate(c.getString(1));
_eventName_.setText(c.getString(1));
db.close();
}
}
`
and this is the activity code
public class CreateEventActivity extends FragmentActivity {
EditText mEdit;
EditText mEdit2;
EditText mEditFromTime;
EditText mEditToTime;
int whichDateBtn;
int whichTimeBtn;
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
db.open();
Cursor c = db.getAllEvents();
if (c.moveToFirst())
{
do {
DisplayEvent(c);
} while (c.moveToNext());
}
db.close();
Button cancel_btn = (Button) findViewById(R.id.button4);
Button save_btn = (Button) findViewById(R.id.button1); //if clicked -> save in data-base
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.open();
EditText event_name = (EditText)findViewById(R.id.editText12);
EditText event_place = (EditText)findViewById(R.id.editText13);
EditText from_date = (EditText)findViewById(R.id.editText14);
EditText from_time = (EditText)findViewById(R.id.editText15);
EditText to_date = (EditText)findViewById(R.id.EditText16);
EditText to_time = (EditText)findViewById(R.id.EditText17);
CheckBox share = (CheckBox)findViewById(R.id.checkBox1);
CheckBox alarm = (CheckBox)findViewById(R.id.checkBox2);
long id2 = db.insertEvent(event_name.getText().toString(), event_place.getText().toString(),
from_date.getText().toString(), to_date.getText().toString(),
from_time.getText().toString(),
to_time.getText().toString(),
share.isChecked(),alarm.isChecked());
db.close();
event_name.setText("");
event_place.setText("");
from_date.setText("");
to_date.setText("");
from_time.setText("");
to_time.setText("");
if (share.isChecked()) {
share.setChecked(false);
}
if (alarm.isChecked()) {
alarm.setChecked(false);
}
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
cancel_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.nazmy.HomeActivity"));
}
});
}
//This method shows the dialog when Button is clicked
public void selectFromtDate(View view) {
DialogFragment mDialog = new SelectDateFragment();
mDialog.show(getFragmentManager(), "DatePicker");
whichDateBtn = 0;
}
public void selectToDate(View view) {
DialogFragment mDialog2 = new SelectDateFragment();
mDialog2.show(getFragmentManager(), "DatePicker");
whichDateBtn = 1;
}
//This method will update the EditText field with the following code.
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)findViewById(R.id.editText14); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEdit2 = (EditText)findViewById(R.id.EditText16);
if(whichDateBtn==0) {
mEdit.setText(month+"/"+day+"/"+year);
}
else if (whichDateBtn == 1) {
mEdit2.setText(month+"/"+day+"/"+year);
}
}
//This subclass includes method to display the datepicker fragment to the user.
//It also has the method to handle the event on setting the date.
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
//The onCreateDialog() method creates a calendar object.
//Using this object the current day, month and year that will be retrieved.
//This current instance will return to the activity to display the date picker with the current date by default.
//onDateSet() method calls the populateSetDate() with the selected date parameters.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
public void onDateSet(DatePicker view, int yy, int mm, int dd) {
populateSetDate(yy, mm+1, dd);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
// Time Pickers
////////////////////////////////////////////////////////////////////////////////////////////////////////
public void selectFromTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 0;
}
public void selectToTime(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "TimePicker");
whichTimeBtn = 1;
}
public void populateSetTime(int hour, int min) {
mEditFromTime = (EditText)findViewById(R.id.editText15); //brbt el editText (mEdit) be el text ely hayzhar fel text Field
mEditToTime = (EditText)findViewById(R.id.EditText17);
if(whichTimeBtn==0) {
mEditFromTime.setText(hour+":"+min);
}
else if (whichTimeBtn == 1) {
mEditToTime.setText(hour+":"+min);
}
}
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
#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) {
// Do something with the time chosen by the user
populateSetTime(hourOfDay, minute);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_create_event, menu);
return true;
}
public void DisplayEvent(Cursor c)
{
Toast.makeText(this,
"id : " + c.getString(0) + "\n" +
"Event Name: " + c.getString(1) + "\n" +
"Place : " + c.getString(2) + "\n" +
"From Date : " + c.getString(3)+ "\n" +
"From Time : " + c.getString(5)+ "\n" +
"To Date : " + c.getString(4)+ "\n" +
"To Time : " + c.getString(6),
Toast.LENGTH_LONG).show();
}
}
`
Thanks in advance :)
You have two choices. Either fetch the data from your database in EventsFragment.onListItemClick(), and pass that data to your second Activity as Intent extras. Or you can pass the id of the clicked item, and do the database operations in your second Activity. Either way you have to pass data using Intents
public class EventsFragment extends SherlockListFragment {
.
.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this, CreateEventActivity.class);
// OPTION 1: Fetch data here, and pass it with the intent
db = new DBAdapter(getActivity());
db.open();
Cursor c = db.getEvent(id+1);
intent.putExtra("id", c.getString(1));
intent.putExtra("event_name", c.getString(2));
// Do this for all your values.
db.close();
startActivity(intent);
// OPTION 2: Pass the id of the selected item, and fetch the data in second activity
intent.putExtra("selected_id", id+1);
startActivity(intent);
}
}
In CreateEventActivity you then have to get the extras you chose to pass with the Intent.
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
Intent intent = getIntent();
// If you chose option 1, you have to get all the extras you attached to the Intent.
long id = intent.getLongExtra("id", -1)
String eventName = intent.getStringExtra("event_name", "defValue");
// Fetch all the values here..
// If you chose option 2, you fetch the id and do the database operations to retrive
// the data
long id = intent.getLongExtra("selected_id", -1);
// DB stuff here..
}
Related
I need to open the add new tasks activity once the data is saved in the database inside a fragment. But when I call the intent function it'snot working and the app is getting closed unfortunately. I couldn't find what the error is exactly. But once I comment the Intent function the add button is working properly. Please solve this for me.
package com.example.prami.prami;
public class AddNewAssignmentFragment extends Fragment{
//code elements
View myView;
EditText txtAddAssignmentName;
Spinner ddTasksNo;
EditText txtStartDate;
EditText txtEndDate;
// DatePickerDialog datePickerDialog;
Button btnAddAssignmentToDB;
// Button btnGotoAddTasksPage;
SQLiteDatabase assignDB;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.add_new_assignment, container, false);
txtAddAssignmentName = (EditText) myView.findViewById(R.id.txtAssignName);
txtStartDate = (EditText)myView.findViewById(R.id.txtHandoverDate);
txtEndDate = (EditText)myView.findViewById(R.id.txtSubmissionDate);
btnAddAssignmentToDB = (Button) myView.findViewById(R.id.btnAddAssignment);
// btnGotoAddTasksPage = (Button)myView.findViewById(R.id.btnAddTask);
ddTasksNo=(Spinner)myView.findViewById(R.id.spNoOfTasks);
String taskNoArray[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; //Java Array
ArrayAdapter<String> adbTaskNo = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, taskNoArray);
adbTaskNo.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ddTasksNo.setAdapter(adbTaskNo);
txtStartDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment picker = new DatePickerDialogThemeStart();
picker.show(getFragmentManager(), "handoverdatePicker");
}
});
txtEndDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment picker = new DatePickerDialogThemeEnd();
picker.show(getFragmentManager(), "submissiondatePicker");
}
});
btnAddAssignmentToDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateDB();
AddAssignRecordToDB();
}
});
// btnGotoAddTasksPage.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// GoToAddTasksPage();
// }
// });
return myView;
}
public static class DatePickerDialogThemeStart extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int hyear = calendar.get(Calendar.YEAR);
int hmonth = calendar.get(Calendar.MONTH);
int hday = calendar.get(Calendar.DAY_OF_MONTH);
#SuppressWarnings("ResourceType")
DatePickerDialog stdatepickerdialog = new DatePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT,this,hday,hmonth,hyear);
stdatepickerdialog.setTitle("Select Handover Date");
calendar.add(Calendar.DATE,0);
stdatepickerdialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
return stdatepickerdialog;
}
public void onDateSet(DatePicker view, int styear, int stmonth, int stday) {
if (view.isShown()) {
EditText txtStDate = (EditText) getActivity().findViewById(R.id.txtHandoverDate);
String handoverdate = String.valueOf(styear) + "/" + String.valueOf(stmonth + 1) + "/" + String.valueOf(stday);
txtStDate.setText(String.format(handoverdate,getActivity()));
}
}
}
public static class DatePickerDialogThemeEnd extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int subyear = calendar.get(Calendar.YEAR);
int submonth = calendar.get(Calendar.MONTH);
int subday = calendar.get(Calendar.DAY_OF_MONTH);
#SuppressWarnings("ResourceType")
DatePickerDialog endatepickerdialog = new DatePickerDialog(getActivity(),
AlertDialog.THEME_HOLO_LIGHT,this,subday,submonth,subyear);
endatepickerdialog.setTitle("Select Submission Date");
calendar.add(Calendar.DATE,0);
endatepickerdialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
return endatepickerdialog;
}
public void onDateSet(DatePicker view, int endyear, int endmonth, int endday) {
if (view.isShown()) {
EditText txtEnDate = (EditText) getActivity().findViewById(R.id.txtSubmissionDate);
String submissiondate = String.valueOf(endyear) + "/" + String.valueOf(endmonth + 1) + "/" + String.valueOf(endday);
txtEnDate.setText(String.format(submissiondate,getActivity()));
}
}
}
public void CreateDB()
{
assignDB = getActivity().openOrCreateDatabase("timeFighter", Context.MODE_PRIVATE, null);
assignDB.execSQL("Create TABLE IF NOT EXISTS myAssignInfo(id INTEGER PRIMARY KEY, assignName VARCHAR(50), " +
"numOfTasks INTEGER, stDate VARCHAR(10), enDate VARCHAR(10))");
}
protected void AddAssignRecordToDB()
{
try {
String assignName = txtAddAssignmentName.getText().toString().trim();
if (assignName.matches("")) {
Toast.makeText(getActivity().getApplicationContext(),"You did not enter an assignment name", Toast.LENGTH_SHORT).show();
return;
}
int assignTaskNo = Integer.parseInt(ddTasksNo.getSelectedItem().toString().trim());
if(ddTasksNo == null && ddTasksNo.getSelectedItem() == null ) {
assignTaskNo = (Integer) ddTasksNo.getSelectedItem();
}
String assignStartDate = txtStartDate.getText().toString().trim();
if (assignStartDate.matches("")) {
Toast.makeText(getActivity().getApplicationContext(),"You did not enter a handover date", Toast.LENGTH_SHORT).show();
return;
}
String assignEndDate = txtEndDate.getText().toString().trim();
if (assignEndDate.matches("")) {
Toast.makeText(getActivity().getApplicationContext(),"You did not enter a submission date", Toast.LENGTH_SHORT).show();
return;
}
String query = "Insert into myAssignInfo (assignName, numOfTasks, stDate," +
" enDate) Values('"+ assignName +"', "+ assignTaskNo +", '"+ assignStartDate +"', '"+ assignEndDate +"')";
assignDB.execSQL(query); //executing query
Toast.makeText(getActivity().getApplicationContext(),"Assignment added successfully", Toast.LENGTH_SHORT).show();
GoToAddTasksPage();
}
catch (Exception ex)
{
Toast.makeText(getActivity().getApplicationContext(),ex.getMessage(), Toast.LENGTH_SHORT).show();
//("ex.printStackTrace")
}
}
protected void GoToAddTasksPage()
{
Intent goToTasks = new Intent(getActivity(), AddTasks.class);
startActivity(goToTasks);
}
}
i try using SQLite in Fragment. But always error. I know that my syntax isn't great and I should be saving from a Party object instead of straight from the fragment interface, but my focus is really on the the process. Any help would be super helpful! Here my code. I try using getActivity() but not work.
public class DataHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "biodatadiri.db";
private static final int DATABASE_VERSION = 1;
public DataHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "create table biodata(no integer primary key, nama text null, tgl text null, jk text null, alamat text null);";
Log.d("Data", "onCreate: " + sql);
db.execSQL(sql);
sql = "INSERT INTO biodata (no, nama, tgl, jk, alamat) VALUES ('1001', 'Fathur', '1994-02-03', 'Laki-laki','Jakarta');";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
And here is the interface screen:
public class UserFragment extends Fragment {
String[] daftar;
ListView ListView01;
Menu menu;
protected Cursor cursor;
DataHelper dbcenter;
public static UserFragment ma;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_fragment);
Button btn=(Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inte = new Intent(UserFragment.this, BuatBiodata.class);
startActivity(inte);
}
});
ma = this;
dbcenter = new DataHelper(this);
RefreshList();
}
public void RefreshList(){
SQLiteDatabase db = dbcenter.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM biodata",null);
daftar = new String[cursor.getCount()];
cursor.moveToFirst();
for (int cc=0; cc < cursor.getCount(); cc++){
cursor.moveToPosition(cc);
daftar[cc] = cursor.getString(1).toString();
}
ListView01 = (ListView)findViewById(R.id.listView1);
ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftar));
ListView01.setSelected(true);
ListView01.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
final String selection = daftar[arg2]; //.getItemAtPosition(arg2).toString();
final CharSequence[] dialogitem = {"Lihat Biodata", "Update Biodata", "Hapus Biodata"};
AlertDialog.Builder builder = new AlertDialog.Builder(UserFragment.this);
builder.setTitle("Pilihan");
builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0 :
Intent i = new Intent(getApplicationContext(), LihatBiodata.class);
i.putExtra("nama", selection);
startActivity(i);
break;
case 1 :
Intent in = new Intent(getApplicationContext(), UpdateBiodata.class);
in.putExtra("nama", selection);
startActivity(in);
break;
case 2 :
SQLiteDatabase db = dbcenter.getWritableDatabase();
db.execSQL("delete from biodata where nama = '"+selection+"'");
RefreshList();
break;
}
}
});
builder.create().show();
}});
((ArrayAdapter)ListView01.getAdapter()).notifyDataSetInvalidated();
}
#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_main, menu);
return true;
}
Here is error from Android Studio.
Error:(81, 25) error: method updateDisplay in class MainMenu cannot be applied to given types;
required: Fragment
found: UserFragment
reason: actual argument UserFragment cannot be converted to Fragment by method invocation conversion
I use case in MainMenu.java
case R.id.navigation_item_user:
updateDisplay(new UserFragment());
break;
Anyone? Thank you for your help :) Sorry for bad english
setContentView(R.layout.user_fragment); // this call should be made only activity.
In Fragments you need to override onCreateView method to setup view. In this return the view that you show it in fragment
Best explained here
fragments with transactions
usage
This is my menu occasion layout...I need to display this delete icon in some condition....
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="ringee.app.com.ringeeapp.Occasion">
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
<item
android:id="#+id/menu_cancel_event"
android:icon="#drawable/delete_icon"
android:title="Cancel event"
app:showAsAction="ifRoom"/>
</menu>
Is it possible to change the visibilty of this delete_icon here...Please help me to find out the code
This is my occasion activity code....here delete icon displayed while Adding event as well as Updating event..Here i need to visible delete icon only when the event is updated...I don't need to display that while Adding event....
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.menu=menu;
getMenuInflater().inflate(R.menu.menu_occasion, menu);
hide();
show();
return true;
}
public boolean show()
{
menu.findItem(R.id.menu_cancel_event).setVisible(true);
return true;
}
public boolean hide(){
menu.findItem(R.id.menu_cancel_event).setVisible(false);
return false;
}
// delete the selected event from event list added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_cancel_event:
//Setting the value for deleted event
eventMO.setIsDelete(1);
del();
//Triggering the Create event
doOnCLickAndOnOptionSelected();
return true;
}
return super.onOptionsItemSelected(item);
}
private void del() {
//Deleting the event from SQLLite
SQLiteDatabase db = dbHelper.getWritableDatabase();
final long Id = eventMO.getEventId();
db.delete("event", "Event_ID" + " = ?", new String[]{String.valueOf(Id)});
db.close();
}
// Common for delete event and save event(Create button click listener)
private void doOnCLickAndOnOptionSelected() {
//We need create button click listener for both delete as well as save the event.so we have this common method.we call this method from delete event and save event
prgDialog = new ProgressDialog(OccasionActivity.this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
UserMO userMO = dbHelper.getRingeeUserData(1);
eventMO.setText(custom_Text.getText().toString());
eventMO.setPlace(event_Place.getText().toString());
eventMO.setEndTime(end_Time);
eventMO.setStartTime(start_Time);
try {
//date and time format changed here
String eventDate = btn_Date.getText().toString();
DateFormat date = new SimpleDateFormat("dd-M-yyyy");
Date date1 = date.parse(eventDate);
DateFormat convertDate = new SimpleDateFormat(" yyyy-MM-dd hh:mm:ss");
eventDate = convertDate.format(date1);
eventMO.setEventDate(eventDate);
} catch (ParseException e) {
e.printStackTrace();
}
//eventMO.setEventDate(btn_Date.getText().toString());
eventMO.setRingeeUserId(userMO.getRingeeUserId());
//event update functionality added here
final Long hidden_Text2 = eventId2;
if ((eventMO.getText() != null) && (eventMO.getPlace() != null) && (eventMO.getEventDate() != null)) {
if (hidden_Text2 != null) {
eventMO.setEventId(hidden_Text2);
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.updateEvent(eventMO, context);
}
#Override
protected void onPostExecute(String arg0) {
prgDialog.dismiss();
Intent contactAct = new Intent(getApplicationContext(), UserDashBoardActivity.class);
// Clears History of Activity
contactAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contactAct);
}
}.execute(null, null, null);
Toast.makeText(getApplicationContext(), "Details updated successfully", Toast.LENGTH_LONG).show();
} else {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.addEvent(eventMO, context);
}
#Override
protected void onPostExecute(String eventId) {
prgDialog.dismiss();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("eventId", eventId);
editor.commit();
Intent contactAct = new Intent(getApplicationContext(), ContactActivity.class);
// Clears History of Activity
contactAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contactAct);
}
}.execute(null, null, null);
Toast.makeText(getApplicationContext(), "Details added successfully", Toast.LENGTH_LONG).show();
}
} else {
prgDialog.dismiss();
Toast.makeText(context, "Please check Event custom text or Event place or Event date field", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_occasion);
context = getApplicationContext();
seekBar_startTime = (SeekBar) findViewById(R.id.seekBar1);
seekBar_startTime.setProgress(0);
seekBar_startTime.setMax(1440); //minutes in 24 hours(24*60)
seekBar_startTime.setProgress(1);
textView_startTime = (TextView) findViewById(R.id.textView1);
seekBar_endTime = (SeekBar) findViewById(R.id.seekBar2);
seekBar_endTime.setProgress(0);
seekBar_endTime.setMax(1440); //minutes in 24 hours(24*60)
seekBar_endTime.setProgress(1);
textView_endTime = (TextView) findViewById(R.id.textView2);
btn_Date = (Button) findViewById(R.id.event_date_button);
event_Place = (TextView) findViewById(R.id.Enter_Place);
custom_Text = (TextView) findViewById(R.id.Custom_Text);
checkBox_onEventDay=(CheckBox) findViewById(R.id.cb_onEventDay);
checkBox_2DaysBefore=(CheckBox) findViewById(R.id.cb_2DaysBefore);
checkBox_aWeekBefore=(CheckBox) findViewById(R.id.cb_aWeekBefore);
btn_create_button = (Button) findViewById(R.id.create_button);
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
dbHelper = new DatabaseHelper(context);
btn_Date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "Occasion Date");
}
});
seekBar_startTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
int minutes;
int hours;
minutes =progressValue % 60;
hours = progressValue/60;
int Hours=hours;
String am_pm;
if (hours==24)
{
hours = hours-12;
am_pm="AM";
}
else if
(hours> 12)
{
hours= hours- 12;
am_pm = "PM";
}
else if (hours ==0) {
hours =hours+12;
am_pm = "AM";
}
else if (hours <12) {
am_pm = "AM";
}
else
{
am_pm="PM";
}
if(minutes < 10)
{
//It shows 12 hours format with AM/PM to user
start_Time = String.valueOf(" "+hours+":0"+minutes+am_pm);
textView_startTime.setText("Event Start Time :" + start_Time);
//It pass 24hours format to database
start_Time = String.valueOf(Hours+":0"+minutes);
}
else {
//It shows 12 hours format with AM/PM to user
start_Time = String.valueOf(" "+hours+":"+minutes+am_pm);
textView_startTime.setText("Event Start Time :" + start_Time);
//It pass 24hours format to database
start_Time = String.valueOf(Hours+":"+minutes);
}
}
});
seekBar_endTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue,boolean fromUser) {
int minutes;
int hours;
minutes = progressValue % 60;
hours = progressValue/60;
int Hours=hours;
String am_pm;
if (hours==24)
{
hours = hours-12;
am_pm="AM";
}
else if(hours> 12)
{
hours= hours- 12;
am_pm = "PM";
}
else if (hours ==0) {
hours =hours+12;
am_pm = "AM";
}
else if (hours <12) {
am_pm = "AM";
}
else
{
am_pm="PM";
}
if(minutes < 10)
{
//It shows 12 hours format with AM/PM to user
end_Time = String.valueOf(""+hours+":0"+minutes+am_pm);
textView_endTime.setText("Event Start Time :" + end_Time);
//It pass 24hours format to database
end_Time = String.valueOf(Hours+":0"+minutes);
}
else {
//It shows 12 hours format with AM/PM to user
end_Time = String.valueOf(""+hours+":"+minutes+am_pm);
textView_endTime.setText("Event Start Time :" + end_Time);
//It pass 24hours format to database
end_Time = String.valueOf(Hours+":"+minutes);
}
}
});
//eventid get from OccasionFragment here
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
Long eventId1 = bundle.getLong("EventID");
eventId2 = eventId1;
String eventName = bundle.getString("EventName");
custom_Text.setText(eventName);
String eventPlace = bundle.getString("EventPlace");
event_Place.setText(eventPlace);
String eventDate = bundle.getString("EventDate");
try {
//String eventDate = bundle.getString("EventDate");
//time string removed from date here
String result = eventDate.split(" ")[0];
DateFormat sourceDate = new SimpleDateFormat("yyyy-MM-dd");
// parse the date string into Date object
Date date = sourceDate.parse(result);
DateFormat convertDate = new SimpleDateFormat("dd-M-yyyy");
// format the date into another format
result = convertDate.format(date);
btn_Date.setText(result);
} catch (ParseException e) {
e.printStackTrace();
}
//Event Start Time and Event End Time string added before the time here
String eventStart = bundle.getString("EventStart");
textView_startTime.setText("Event Start Time :" + eventStart);
String eventEnd = bundle.getString("EventEnd");
textView_endTime.setText("Event End Time :" + eventEnd);
}
checkBox_onEventDay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(OccasionActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}}
});
checkBox_2DaysBefore.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(OccasionActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}}
});
checkBox_aWeekBefore.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(OccasionActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}}
});
btn_create_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doOnCLickAndOnOptionSelected();
}
});
}
#SuppressLint("ValidFragment")
public 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) {
Date = new StringBuilder().append(year).append("-").append(month + 1).append("-").append(day).append(" ").toString();
btn_Date.setText(new StringBuilder().append(day).append("-").append(month + 1).append("-").append(year).append(" ").toString());
}
}
}
Here i need to show the delete icon only when the details are updated.....i need to hide that icon while creating an event...creating an event code is in "protected void on Create"....Where i need to add this hide method...i tried this inside this create method but it shows an error...Please help me
Try below code,
public class MainActivity extends Activity {
Menu menu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_act_app_home_new, menu);
return true;
}
void show(){
menu.findItem(R.id.menu_cancel_event).setVisible(true);
}
void hide(){
menu.findItem(R.id.menu_cancel_event).setVisible(false);
}
}
Let me know if this works for you...
And marks it as an answer so it would be useful to others
Simply create your menu:
boolean eventUpdated = true/false;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_occasion, menu);
return true;
}
and set visibility according your condition:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(R.id.menu_cancel_event).setVisible(eventUpdated);
return true;
}
Call invalidateOptionsMenu() everytime condition changes to refresh menu.
A MenuItem is not a regular view that's part of your layout. Its something special, completely different. Your code returns null for item and that's causing the crash. What you need instead is to do:
MenuItem item = menu.findItem(R.id.addAction);
Then get a MenuItem pointing to such item, call setVisible() on it to adjust its visibility and then call
invalidateOptionsMenu()
on your activity so the ActionBar menu is adjusted accordingly.
//imports
public class MainActivity extends Activity implements OnCheckedChangeListener
{
int count=0,ints......;
TextView textviews...;
int itemCode,month;
ArrayList<String> Name = new ArrayList<String>();
AlertDialog alertDialog ;
SharedPreferences sp;
EditText EtItemCode;
Editor editor ;
RadioButton RbForItemCode,RbForItemName;
RadioGroup RgForItemVsName;
PopupWindow popupWindowItems;
String popUpItems[];
ProgressDialog pDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
//shared prefs
sp = this.getSharedPreferences("MySharedPrefsFile", Context.MODE_PRIVATE);
editor = sp.edit();
intForShardPref= sp.getInt("NEW_INSTALLATION",1); // getting Integer(1 is for no)
if(intForShardPref==1){
Intent intent = new Intent(this,Verify.class);
startActivityForResult(intent, 1);
}
else{
//do nothing
}
EtItemCode.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
ToCheckItemCodeOfEdittext = EtItemCode.getEditableText().toString();
DatabaseHandler db=new DatabaseHandler(MainActivity.this);
List<Item> Items = db.getAllItemWithSubString(ToCheckItemCodeOfEdittext,itemNumberOrNameSelectedInRadioButtonOptions);
if(EtItemCode.length()>2){
if(EtItemCode.length()>3||flagForPopUpWindow>EtItemCode.length())
popupWindowItems.dismiss();
Name.clear();
for (Item cn : Items) {
if(RbForItemCode.isChecked()==true){
Name.add(Integer.toString(cn.getItemNumber()));
}
else{
Name.add(cn.getName());
}
}
popUpItems = new String[Name.size()];
Name.toArray(popUpItems);
popupWindowItems = popupWindowItems();
***popupWindowItems.setFocusable(false);***
popupWindowItems.showAsDropDown(findViewById(R.id.et_item_code), -5, 0);
}
else{
if(flagForPopUpWindow==3&&EtItemCode.length()==2)
popupWindowItems.dismiss();
}
flagForPopUpWindow=EtItemCode.length();
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
}
private void init() {
// TODO Auto-generated method stub
//some code
}
public PopupWindow popupWindowItems() {
// initialize a pop up window type
PopupWindow popupWindow = new PopupWindow(this);
// the drop down list is a list view
ListView listViewItems = new ListView(this);
// set our adapter and pass our pop up window contents
ArrayAdapter<String> adapter=new ArrayAdapter<String>(
this, //context for activity
android.R.layout.simple_list_item_1, //layout used
Name){ //Items to be displayed
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// setting the ID and text for every items in the list
String item = getItem(position);
String text = item.toString();
// visual settings for the list item
TextView listItem = new TextView(MainActivity.this);
listItem.setText(text);
//listItem.setTag(id);
listItem.setTextSize(22);
listItem.setPadding(10, 10, 10, 10);
listItem.setTextColor(Color.WHITE);
return listItem;
}
};
listViewItems.setAdapter(adapter);
// set the item click listener
listViewItems.setOnItemClickListener(new ItemsDropdownOnItemClickListener());
// some other visual settings
//popupWindow.setFocusable(true);
popupWindow.setWidth(EtItemCode.getWidth());
//popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
Rect r = new Rect();
View rootview = this.getWindow().getDecorView(); // this = activity
rootview.getWindowVisibleDisplayFrame(r);
popupWindow.setHeight(r.height()-3*EtItemCode.getHeight());
// set the list view as pop up window content
popupWindow.setContentView(listViewItems);
return popupWindow;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater blowUp = getMenuInflater();
blowUp.inflate(R.menu.cool_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.phone_number:
Intent p = new Intent(MainActivity.this,PhoneNumber.class);
startActivity(p);
break;
case R.id.exit:
finish();
break;
}
return false;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//some code
}
class LoadDataBase extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("DataBase Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(MainActivity.this);
Log.d("Reading: ", "Reading all Items..");
List<Item> Items = db.getAllItem();
//some code
//DatabaseHandler db1 = new DatabaseHandler(this);
count= db.getItemCount();
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
public class ItemsDropdownOnItemClickListener implements OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "Item is: ", Toast.LENGTH_SHORT).show();
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EtItemCode.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
// dismiss the pop up
popupWindowItems.dismiss();
// get the text and set it as the button text
String selectedItemText = ((TextView) v).getText().toString();
Toast.makeText(MainActivity.this, "Item is: " + selectedItemText, Toast.LENGTH_SHORT).show();
DatabaseHandler db =new DatabaseHandler(MainActivity.this);
Item item= new Item();
if(RbForItemCode.isChecked()==true){
item = db.getItem(Integer.valueOf(selectedItemText));
}
else if(RbForItemName.isChecked()==true){
item = db.getItem(selectedItemText);
}
itemCode=item.getItemNumber();
}
}
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(RbForItemCode.isChecked()==true){
itemNumberOrNameSelectedInRadioButtonOptions="id";
//some code
}
}
else if(RbForItemName.isChecked()==true){
//some code
}
}
}
This code is working fine on my phone galaxy note 2(custom rom of note 4.. Android 4.4.4).By fine I mean I can type in edittext and popupwidow shows up after 3rd text(because of condition I have put) and I can select an option from the popupwindow. When I try to run the code on any other phone like galaxy grand then callback to ItemsDropdownOnItemClickListener is not registered and I can only scroll the popupwindow and keep on typing in edittext but cannot select any of the options in the popupwindow. If I set popupWindowItems.setFocusable(false) to true i.e popupWindowItems.setFocusable(true), and then as soon as I type 3rd letter in edittext,edittext looses focus and popwindow gains it. Now I can select anything.. But now I cannot continue to type in edittext.I have to manually select edittext and type.
Now I want that after tying 3rd word in edittext a popupwindow should appear(which currently is appearing) and edittext doesn't loose focus(so that i can continue typing).. Further if I select anything from popupwindow ,ItemsDropdownOnItemClickListener should be called which is currently being not called in other phones when popupWindowItems.setFocusable(false);
I am doing this to load data from sqlite database and show in popupwindow once the user types 3rd word. Any suggestion is recommended
Edit: Problem solved. Now using AutoComplete TextView
all
i have created listview dynamically.now i want to change the name of listview/listitems or i want to retrieve content below each row but the content is coming from dialogbox.is it possible to have data from dialogbox in listview?How to achieve this??can any one guide or give some sample code of the same?
Thanks in Advance--
public class Tdate extends Activity
{
private ListView lView;
private String lv_items[] = { "Birth_Date", "Anniversary_Date", "Joining_Date","Meeting_Date","Appraisal_Date","Anniversary_Date", "Joining_Date","Meeting_Date","Appraisal_Date"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.tdate);
Button customdate = (Button)findViewById(R.id.customdate);
lView = (ListView) findViewById(R.id.ListView01);
lView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, lv_items));
lView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
showDateTimeDialog();
}
});
}
private void showDateTimeDialog()
{
// Create the dialog
final Dialog mDateTimeDialog = new Dialog(this);
// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
// Check is system is set to use 24h time (this doesn't seem to work as expected though)
final String timeS = android.provider.Settings.System.getString(getContentResolver(), android.provider.Settings.System.TIME_12_24);
final boolean is24h = !(timeS == null || timeS.equals("12"));
// Update demo TextViews when the "OK" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.clearFocus();
((TextView) findViewById(R.id.Date)).setText(mDateTimePicker.get(Calendar.YEAR) + "/" + (mDateTimePicker.get(Calendar.MONTH)+1) + "/"
+ mDateTimePicker.get(Calendar.DAY_OF_MONTH));
if (mDateTimePicker.is24HourView()) {
((TextView) findViewById(R.id.Time)).setText(mDateTimePicker.get(Calendar.HOUR_OF_DAY) + ":" + mDateTimePicker.get(Calendar.MINUTE));
} else {
((TextView) findViewById(R.id.Time)).setText(mDateTimePicker.get(Calendar.HOUR) + ":" + mDateTimePicker.get(Calendar.MINUTE) + " "
+ (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));
}
mDateTimeDialog.dismiss();
}
});
// Cancel the dialog when the "Cancel" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
mDateTimeDialog.cancel();
}
});
// Reset Date and Time pickers when the "Reset" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
mDateTimePicker.reset();
}
});
// Setup TimePicker
mDateTimePicker.setIs24HourView(is24h);
// No title on the dialog window
mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the dialog content view
mDateTimeDialog.setContentView(mDateTimeDialogView);
// Display the dialog
mDateTimeDialog.show();
}
}