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
Related
I have an activity and a fragment
In my activity i have button in my action bar ,on button click a dialog box is popup , in that i have a listview.
If i select any item from that list , that data goes to fragment , and based on that data from activity my fragment listview should be shown
e.g. if i select Technology , technology id =1 should pass in my query parameter and based on that my fragment listview should appear.
everytime i select different item from list my fragment listview should be updated.
But my problem is that i am not getting any data in fragment and my list is not getting updated
Mainactivity.java
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem actionViewItem = menu.findItem(R.id.miActionButton);
// Retrieve the action-view from menu
View v = MenuItemCompat.getActionView(actionViewItem);
// Find the button within action-view
Button b = (Button) v.findViewById(R.id.btnCustomAction);
// Handle button click here
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(CUSTOM_DIALOG_ID);
}
});
return super.onPrepareOptionsMenu(menu);
}
#Override
public Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(this);
dialog.setContentView(R.layout.dialoglayout);
dialog.setTitle("Select Category");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
dialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
}
});
// Prepare ListView in dialog
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listContent);
dialog_ListView.setAdapter(adapter);
dialog_ListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// i = (int) parent.getItemIdAtPosition(position);
category_name = (String) parent.getItemAtPosition(position);
Log.d("category name", category_name);
if(category_name.equals("a"))
{
cat_id=1;
}
if(category_name.equals("b"))
{
cat_id=2;
}
if(category_name.equals("c"))
{
cat_id=3;
}
if(category_name.equals("d"))
{
cat_id=4;
}
if(category_name.equals("e"))
{
cat_id=5;
}
if(category_name.equals("f"))
{
cat_id=6;
}
Log.d("id",""+cat_id);
dismissDialog(CUSTOM_DIALOG_ID);
}
});
break;
}
return dialog;
}
public int getMyData() {
return cat_id;
}
Fragment.java :
public String param;
public String url;
public int cat_id;
Mainactivity activity = (Mainactivity) getActivity();
int myDataFromActivity = activity.getMyData();
cat_id = myDataFromActivity;
Log.d("Category_id", "" + cat_id);
Map<String, String> map1 = new HashMap<String, String>();
param = "?cat_id=" + cat_id;
//URL is fake , original url is working fine.
url = "http://www.abbcd.com/xyz/webservices/data/getAllData.php"
+ param;
map1.put("url", url);
new MultiPartRequester(mainActivity, map1,
NetUtils.RequestCode.GET_ALL_DATA,
this).execute();
Updated Part :
#Override
public void updateFragmentList(int catId) {
// TODO Auto-generated method stub
param = "?cat_id=" + catId;
url = "http://www.abbcd.com/xyz/webservices/data/getAllData.php"+ param;
Map<String, String> map1 = new HashMap<String, String>();
map1.put("url", url);
new MultiPartRequester(mainActivity, map1,
NetUtils.GET_DATA, this)
.execute();
}
The good approach for communication between Activity and Fragment is Listeners. When you want to update fragment, use the listener and update the fragment. Create the interface in MainActivity
Listener
public interface FragmentListener {
void updateFragmentList(int catId);
}
Implement in Fragment as
public class MyFragment extends Fragment implements MainActivity.FragmentListener
then in onActivityCreated of Fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((MainActivity) getActivity()).setFragmentListener(this);
}
MainActivity
public void setFragmentListener(FragmentListener listener)
{
this.fragmentListener = listener;
}
public void sendDataToFragment(int catId) {
this.fragmentListener.updateFragmentList(catId);
}
Hope this helps.
UPDATE
Sending data to fragment using this.fragmentListener.updateFragmentList(catId);, create the method in Fragment as ``
public void updateFragmentList(int catId){
//Here update your listview with cat id
}
use static global variable in activity
public static int cat_id = 0;
access cat_id in fragment like below
Map<String, String> map1 = new HashMap<String, String>();
param = "?cat_id=" + activity.cat_id;
or do below changes in your getMyData method
public int getMyData() {
return cat_id;
}
EDITED:
another approach finally work, call your fragment method from activity ans pass cat_id in method. instead of ExampleFragment use your fragment name.
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.mymethod(cat_id);
i am a very very dumb newbie in Android Programming,
here i want to make a Cashflow note app in android studio.
In this case i want to create a table call Category_Table with 4 column called CategId, CategName, Note and Currency.
I have doing the tutorial from google and etc extacly. But till now i still have this problem.
When i want to insert some data into Category_Table, it says No Column named Currency in Android Studio report.
I dont know what to do, i have googling it but still cant solve this problem.
Please gimme an answer that i can understand as a newbie programmer.
Thanks.
NB. Here is my code:
Add_Category code :
public class AddCategory extends ActionBarActivity {
private static Button BtnIAdd;
private static Button BtnICancel;
EditText txtcategname, txtnote;
Spinner selectCurrency;
ArrayAdapter<CharSequence> adapterCurrency;
DatabaseHelper myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_category);
myDB = new DatabaseHelper(this);
txtcategname = (EditText)findViewById(R.id.editText);
txtnote = (EditText)findViewById(R.id.editText2);
BtnICancel = (Button)findViewById(R.id.btnCancel);
BtnIAdd = (Button)findViewById(R.id.btnAdd);
//spinner
selectCurrency = (Spinner) findViewById(R.id.spin_selectCurrency);
adapterCurrency = ArrayAdapter.createFromResource(this, R.array.CurrencyName,android.R.layout.simple_spinner_item );
adapterCurrency.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectCurrency.setAdapter(adapterCurrency);
selectCurrency.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemAtPosition(position)+" selected",Toast.LENGTH_LONG).show();
String currencyValue = String.valueOf(parent.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
addCategData();
}
#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_add_category, menu);
return true;
}
public void addCategData(){
BtnIAdd.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(AddCategory.this,"Clicked", Toast.LENGTH_LONG).show();
boolean isInserted = myDB.insertCategData(txtcategname.getText().toString(),
txtnote.getText().toString(), selectCurrency.getSelectedItem().toString());
if (isInserted == true)
Toast.makeText(AddCategory.this,"Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(AddCategory.this,"Not Inserted", Toast.LENGTH_LONG).show();
}
}
);
BtnICancel.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
);
}
#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);
}
}
And this one for DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String MyVillageSoftware = "MyVillageSoftware";
public static final String DATABASE_NAME = "Cashflow.db";
public static final String TABLE_Categ_NAME = "category_table";
public static final String COL1 = "CategId";
public static final String COL2 = "CategName";
public static final String COL3 = "Note";
public static final String COL4 = "Currency";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Drop Table" + TABLE_Categ_NAME);
/*db.execSQL("Create table " + TABLE_Categ_NAME +
"(CategID Integer PRIMARY KEY AUTOINCREMENT " +
"CategName Text" +
"Note Text" +
"Currency Text)");*/
}
public boolean insertCategData(String categname, String note, String currency){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, categname);
contentValues.put(COL3, note);
contentValues.put(COL4, currency);
long result = db.insert(TABLE_Categ_NAME, null, contentValues);
if (result == -1)
return true;
else
return false;
}
public ArrayList<String>getAllCategory(){
ArrayList<String> AllCategoryList = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String selectCateg="Select * FROM " +TABLE_Categ_NAME;
Cursor cursor = db.rawQuery(selectCateg, null);
if(cursor.getCount()>0){
while (cursor.moveToNext()){
String categname=cursor.getString(cursor.getColumnIndex(COL2));
AllCategoryList.add(COL2);
}return AllCategoryList;
}
return AllCategoryList;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " +TABLE_Categ_NAME);
onCreate(db);
thanks before... :)
1) Uninstall the App and Install again.
2) issue is "No Column named Currency in Android Studio report" this is because column currency might be added after table created. so for that you have to define Database Version(an integer value e.g. Ver=1) and change the version of DB whenever you do changes in database(increase that int value e.g. Ver=2) so it will call onUpgrade() and drop your tables and create it again. this will solve your problem.
EDIT: You have given that Database version 1 as default in super(context,dbName,cursorFactory,dbVersion)
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
//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
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..
}
hi all Am having listview which displays list of items from sqlite db. Using DialogBox am inserting data in DB. Insertion done successfully. But if i entered data on DialogBox and click ok button, the data inserted in db but the inserted data is not displaying in ListView.
ListView is not refreshing.... I hv used adapter.setNotifyOnChange(true);. But this wont take any effect on listview.
And I have got warning on logcat as
`09-16 15:01:10.215: INFO/dalvikvm(2066): Uncaught exception thrown by finalizer (will be discarded):
09-16 15:01:10.215: INFO/dalvikvm(2066): Ljava/lang/IllegalStateException;: Finalizing cursor android.database.sqlite.SQLiteCursor#44c4be28 on PAYMENT_TABLE that has not been deactivated or closed
09-16 15:01:10.215: INFO/dalvikvm(2066): at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:596)
09-16 15:01:10.215: INFO/dalvikvm(2066): at dalvik.system.NativeStart.run(Native Method)`
But i hv closed the cursor in OnDestory()
Here is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
String mTitleRaw = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_PAYMENT_TYPE));
al.add(mTitleRaw);
cursor.moveToNext();
}
adapterChanged();
}
#SuppressWarnings("unchecked")
private void adapterChanged() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, al);
adapter.setNotifyOnChange(true);
setListAdapter(adapter);
listContent = getListView();
listContent.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
//Object o = this.getListAdapter().getItem(position);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (mySQLiteAdapter != null) {
mySQLiteAdapter.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, MENU_ADD, 0, "Add New");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()) {
case MENU_ADD:
AlertMsg();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateList(){
cursor.requery();
}
public void AlertMsg() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Payment Type");
alert.setMessage("Add field");
final EditText mTxt = new EditText(this);
alert.setView(mTxt);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String mNewField = mTxt.getText().toString();
//Toast.makeText(getApplicationContext(), "Item " + mNewField + " Added", Toast.LENGTH_LONG).show();
mySQLiteAdapter.insert(mNewField);
updateList();
adapterChanged();
}
});
alert.show();
}
}
Are this efficient way....
Can anyone pls give some suggestions.....
Thanks......