I have MainActivity, which holds fragment. One of my fragments (Participants) checks if there's anything in database. If no, shows fragment(EmptyParticipantsList) with message to add data. If yes, it shows fragment with TabHost with 2 tabs, one of them holds fragment (ParticipantsList) with ListView with database entries. There's a FAB button to add more records. How can I refresh ListView after adding another record? I'm not sure since TabHost is not working with FragmentManager which I'm using in app.
//TODO refresh ListView is the place where I need to put my code.
EDIT 6.5.2017
I modify the code and add 'myCursorAdapter.notifyDataSetChanged();' after adding/editting items in SQLite but List still not refresh it self. Any help?
Participants.java
myDB = new DBAdapter(getActivity());
myDB.open();
Class S;
if (myDB.isEmptyParticipants()) {
S = EmptyParticipantsList.class;
} else {
S = ParticipantsList.class;
}
myDB.close();
mTabHost = (FragmentTabHost) root.findViewById(R.id.tabHost);
mTabHost.setup(getContext(), getChildFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("List of participants"),
S, bundle1);
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Event information"),
EventInfo.class, bundle1);
ParticipantsList.java
public class ParticipantsList extends DialogFragment {
DBAdapter myDB;
ListView participantList;
long id_eventu;
EditText participantName;
EditText participantSurname;
SimpleCursorAdapter myCursorAdapter;
public ParticipantsList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View root = inflater.inflate(R.layout.fragment_participants_list, container, false);
myDB = new DBAdapter(getContext());
participantList = (ListView) root.findViewById(R.id.list_participants);
myDB.open();
FloatingActionButton fab1 = (FloatingActionButton) root.findViewById(R.id.fab_participant);
Bundle bundle = getArguments();
if (bundle != null) {
id_eventu = bundle.getLong("key");
}
myDB.open();
Cursor cursor = myDB.getAllRowsParticipant(id_eventu);
String[] fromParticipantNames = new String[] {DBAdapter.PARTICIPANTS_NAME, DBAdapter.PARTICIPANTS_SURNAME};
int[] toViewIDs = new int[] {R.id.name_of_participant, R.id.surname_of_participant};
myCursorAdapter = new SimpleCursorAdapter(getActivity(),R.layout.row_participant, cursor, fromParticipantNames, toViewIDs,0 );
participantList.setAdapter(myCursorAdapter);
myCursorAdapter.notifyDataSetChanged();
myDB.close();
registerForContextMenu(participantList);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder addParticipantDialog = new AlertDialog.Builder(getContext());
addParticipantDialog.setTitle("Add new Participant");
final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
addParticipantDialog.setView(viewInflated);
participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
addParticipantDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//TODO zde se načtou data z polí a uloží do databáze
String name = participantName.getText().toString();
String surname = participantSurname.getText().toString();
myDB.open();
myDB.insertRowParticipant(name,surname, id_eventu);
Toast.makeText(getActivity(),"Participant added", Toast.LENGTH_LONG).show();
myDB.close();
myCursorAdapter.notifyDataSetChanged();
}
});
addParticipantDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
addParticipantDialog.show();
}
});
return root;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.event_popup, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final long id = info.id;
switch(item.getItemId()) {
case R.id.edit_event_popup:
final android.app.AlertDialog.Builder addEventDialog = new android.app.AlertDialog.Builder(getContext());
addEventDialog.setTitle("Edit participant");
final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_participant, (ViewGroup) getView(), false);
addEventDialog.setView(viewInflated);
participantName = (EditText) viewInflated.findViewById(R.id.add_participant_name);
participantSurname = (EditText) viewInflated.findViewById(R.id.add_participant_surname);
myDB.open();
Cursor c = myDB.db.rawQuery("SELECT * FROM participants WHERE _id=="+id, null);
c.close();
c.moveToFirst();
String name_par = c.getString(c.getColumnIndex("name"));
String surname_par = c.getString(c.getColumnIndex("surname"));
participantName.setText(name_par); //tady se musí načíst data z db
participantSurname.setText(surname_par);
addEventDialog.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//TODO zde se načtou data z polí a uloží do databáze
String str = participantName.getText().toString();
String str1 = participantSurname.getText().toString();
ContentValues cv = new ContentValues();
cv.put("name",str);
cv.put("surname",str1);
myDB.db.update("participants", cv, "_id="+id, null);
Toast.makeText(getActivity(),"participant changed", Toast.LENGTH_LONG).show();
myDB.close();
myCursorAdapter.notifyDataSetChanged();
//TODO refresh listview
}
});
addEventDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
addEventDialog.show();
return true;
case R.id.delete_event_popup:
myDB.open();
myDB.deleteRowParticipant(id);
Toast.makeText(getActivity(),"participant deleted", Toast.LENGTH_LONG).show();
myCursorAdapter.notifyDataSetChanged();
//TODO když je to poslední záznam, tak nahodit empty frag
return true;
default:
return super.onContextItemSelected(item);
}
}
}
You should call notifyDataSetChanged after setAdapter
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.
participantList.setAdapter(myCursorAdapter);
myCursorAdapter.notifyDataSetChanged(); // this
myDB.close();
Related
I would like to display an alertDialog when there is no data stored in my database.However what i have tried seems not to achieve the desired goal as the alert dialog is not called when the database is empty.
Here is how i check for the existance of tables in my database:
public boolean checkForTables() {
boolean hasTables = false;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*)FROM" + CONTACTS_TABLE_NAME, null);
if (cursor != null && cursor.getCount() > 0) {
hasTables = true;
cursor.close();
}
return hasTables;
}
And in my activity onCreate:
if (myDb.checkForTables()) {
showTable();
btn.setVisibility(View.VISIBLE);
} else {
showAlert();
btn.setVisibility(View.GONE);
}
Where method showTable()
private void showTable() {
ArrayList<String> array_list = myDb.getAllContacts();
ArrayAdapter arrayAdapter;
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
And method showAlert()
public void showAlert() {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.empty_basket, (ViewGroup) findViewById(R.id.root));
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setView(layout);
adb.setCancelable(false);
adb.setPositiveButton("Add items to basket", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(MyBasket.this, MainActivity.class);
startActivity(i);
}
});
adb.show();
}
My Activity full code:
public class MyBasket extends ActionBarActivity {
private ListView obj;
DBHelper myDb;
int numRows;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_basket);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myDb = new DBHelper(this);
Button btn = (Button) findViewById(R.id.checkout);
if (myDb.checkForTables()) {
showTable();
btn.setVisibility(View.VISIBLE);
} else {
showAlert();
btn.setVisibility(View.GONE);
}
TextView txt = (TextView) findViewById(R.id.numRows);
myDb.numberOfRows();
txt.setText(Integer.toString(numRows));
Button basketButton = (Button) findViewById(R.id.checkout);
basketButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyBasket.this);
alertDialog.setCancelable(false);
alertDialog.setMessage("Done with shopping?");
alertDialog.setPositiveButton("Proceed to checkout", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MyBasket.this, CheckOut.class);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
});
}
public void showAlert() {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.empty_basket, (ViewGroup) findViewById(R.id.root));
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setView(layout);
adb.setCancelable(false);
adb.setPositiveButton("Add items to basket", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(MyBasket.this, MainActivity.class);
startActivity(i);
}
});
adb.show();
}
private void showTable() {
ArrayList<String> array_list = myDb.getAllContacts();
ArrayAdapter arrayAdapter;
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
}
#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_my_basket, 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;
}
if (id == R.id.action_delete) {
myDb.deleteContact();
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MyBasket.this, MyBasket.class);
startActivity(intent);
return true;
}
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
Any help will be appreciated.Thanks in advance.
The thing is that you are selecting the count not the rows so you will have one row every time showing you the count even that is zero.
public boolean checkForTables() {
boolean hasRows = false;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_COMMENTS, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if(count > 0)
hasRows = true;
db.close();
return hasRows;
}
There is another issue in your code after solving the one that not showing your Dialog you will get an IllegalStateException becuase of this ;)
View layout = inflater.inflate(R.layout.empty_basket, (ViewGroup) findViewById(R.id.root));
You should pass null as the parent view because its going in the dialog layout
.
View layout = inflater.inflate(R.layout.empty_basket, null);
'SELECT COUNT(*)...` will return a cursor and a value. Rather than looking at the size of the cursor's result set, you will need to check the returned value to determine whether the table is empty:
public boolean checkForTables() {
boolean hasTables = false;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*)FROM" + CONTACTS_TABLE_NAME, null);
if (cursor != null) {
if( cursor.moveToFirst() ) {
if( cursor.getInt(0) > 0 ) {
hasTables = true;
}
cursor.close();
}
return hasTables;
}
i hope you guys can help me. it`s drivin me crazy find the solution...
i already read some question that similar with my problems, but none solved mine.
here`s the problems
1 have 2 activity...
first --> i have activity that contain a view pager which hold 3 tab fragment.
in this first activity i extends with fragmentActivity
and here the code
public class A_BonRokok_Add_Main_Paged extends FragmentActivity {
private static final String[] CONTENT = new String[] { "Header", "Item", "Info"};
MainActivity main = new MainActivity();
FragmentManager manager;
FragmentTransaction transaction;
Dialog alert;
LayoutInflater li;
LinearLayout someLayout;
Button btnSave_dialog;
Button btnCancel_dialog;
public EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l_bon_rokok_add_main_paged);
FragmentPagerAdapter adapter = new MyAdapter(getSupportFragmentManager());
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
getActionBar().setDisplayHomeAsUpEnabled(true);
pager.setOffscreenPageLimit(3);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_print) {
Toast.makeText(this, "print", Toast.LENGTH_SHORT).show();
}
else if (item.getItemId() == R.id.edit_save) {
Toast.makeText(this, "Save", Toast.LENGTH_SHORT).show();
}
else{
createDialogConfirm();
}
return false;
}
#Override
public boolean onTouchEvent(MotionEvent event){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
public void onBackPressed(){
createDialogConfirm();
}
public void createDialogConfirm(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert.show();
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt(ChildFragmentPaged.POSITION_KEY, position);
return ChildFragmentPaged.newInstance(args);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
}
public static A_BonRokok_Add_Main_Paged newInstance() {
return new A_BonRokok_Add_Main_Paged();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.save_print, menu);
return super.onCreateOptionsMenu(menu);
}
}
the first activity manage the tab fragment using class which extends fragment...
here the code
public class ChildFragmentPaged extends Fragment {
public static final String POSITION_KEY = "FragmentPositionKey";
private int position;
View root;
static EditText txtDate, txtGudang;
static RadioGroup btnGroupGudang;
static RadioButton btnGudang1, btnGudang2;
static Button btnNewItem, btnNewItem_Cancel;
private database mySQLiteAdapter;
private A_BonRokok_Item_View view = new A_BonRokok_Item_View();
public ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
AdapterView<?> tempAdt;
int tempPos;
public EditText search;
public ArrayList<bonRokokPagedEntity> list;
public ListViewAdapter adapter;
private databasePaged databasePaged;
public static ChildFragmentPaged newInstance(Bundle args) {
ChildFragmentPaged fragment = new ChildFragmentPaged();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
position = getArguments().getInt(POSITION_KEY);
if(position == 0){
root = inflater.inflate(R.layout.t_bon_rokok_header_paged, container,false);
}if (position == 1) {
root = inflater.inflate(R.layout.t_bon_rokok_item_paged, container, false);
settingTabItem();
} else if (position == 2)
root = inflater.inflate(R.layout.t_bon_rokok_info_paged, container, false);
return root;
}
public void settingTabItem() {
listContent = (ListView) root.findViewById(R.id.vl_tab_paged);
btnNewItem = (Button) root.findViewById(R.id.btnNewItem_paged);
search = (EditText)root.findViewById(R.id.search_paged);
try{
databasePaged = new databasePaged(getActivity());
databasePaged.createDataBase();
}catch(IOException ioe){
throw new Error("Unable to craete database");
}
try{
databasePaged.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
btnNewItem.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(),A_BonRokok_Item_New_Paged.class);
startActivity(intent);
getActivity().finish();
}
});
list = databasePaged.Getvalue();
adapter = new ListViewAdapter(getActivity(), list);
listContent.setAdapter(adapter);
}
private void updateList() {
cursor.requery();
}
public void createMenu(){
final Cursor cursor = (Cursor) tempAdt.getItemAtPosition(tempPos);
final String header = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.d_global_edit_delete,null, false);
ListView lv = (ListView)contentView.findViewById(R.id.d_globalEditDelete_lvEditDelete);
TextView txtHeader = (TextView)contentView.findViewById(R.id.d_globalEditDelete_lblHeader);
Button btnCancel = (Button)contentView.findViewById(R.id.d_globalEditDelete_btnCancel);
txtHeader.setText(header);
ArrayList<String> tempData = new ArrayList<String>();
tempData.add("Edit");
tempData.add("Delete");
int layoutID = android.R.layout.simple_list_item_1;
ArrayAdapter tempAdapter = new ArrayAdapter<String>(getActivity(), layoutID, tempData);
lv.setAdapter(tempAdapter);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(contentView);
final AlertDialog alert = builder.create();
alert.show();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
if (position == 0){ //Edit Data
passStringValue();
updateList();
Intent intent = new Intent(getActivity(),A_BonRokok_Item_View.class);
intent.putExtra("status", true);
startActivity(intent);
getActivity().finish();
}
else if (position == 1){ //Delete Data
final int item_id = cursor.getInt(cursor.getColumnIndex(database.KEY_ID));
mySQLiteAdapter.delete_byID(item_id);
updateList();
alert.cancel();
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
}
public void passStringValue(){
final String nama_Rokok = cursor.getString(cursor.getColumnIndex(database.SKDROKOK));
final String kode_Rokok = "102030";
final String pita_Cukai = cursor.getString(cursor.getColumnIndex(database.SPITACUKAI));
final String jumlah = cursor.getString(cursor.getColumnIndex(database.SJUMLAH));
view.Detail(nama_Rokok, kode_Rokok, pita_Cukai, jumlah);
}
}
and the second --> i have activity that contain an edittext.
here the code
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(contentView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
return false;
}
});
// txtSelop.setOnFocusChangeListener(focusSelopChange);
// txtBungkus.setOnFocusChangeListener(focusBungkusChange);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.edit_save) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
} else {
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main_Paged.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save_print, menu);
MenuItem item = menu.findItem(R.id.edit_print);
item.setVisible(false);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
OnClickListener searchClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
createDialogSearch();
}
};
OnItemClickListener itemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> hm = (HashMap<String, String>)arg0.getAdapter().getItem(position);
autoCompleteBonRokok.setText(hm.get("kdRokok"));
txtNamaRokok.setText(hm.get("namaRokok"));
}
};
public void onBackPressed(){
if(txtNamaRokok.getText().length()==0){
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
else
createDialogConfirm();
}
Button.OnClickListener dialogYes = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getBaseContext(),A_BonRokok_Add_Main.class);
startActivity(intent);
finish();
}
};
Button.OnClickListener dialogNo = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
};
OnFocusChangeListener focusBalChange = new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean isFocused) {
if(!isFocused){
if(txtBal.length()==0)
bal = 0;
else
bal = Integer.parseInt(txtBal.getText().toString());
splitValue();
}
}
};
public void saveToDatabase() {
}
private void updateList() {
cursor.requery();
}
public void createDialogSearch(){
li = LayoutInflater.from(this);
someLayout = (LinearLayout)li.inflate(R.layout.d_bon_rokok_search_new_item, null);
DialogDummyAutoComplete[] modelItemsDialog;
final ListView lvDialog = (ListView)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_lvSearch);
modelItemsDialog = new DialogDummyAutoComplete[3];
modelItemsDialog [0] = new DialogDummyAutoComplete("1051200", "Supra need 12");
modelItemsDialog [1] = new DialogDummyAutoComplete("1051600", "Supra need 16");
modelItemsDialog [2] = new DialogDummyAutoComplete("1001200", "NY");
DialogAutoCompleteSearchRokok dialogAdapter = new DialogAutoCompleteSearchRokok(this, modelItemsDialog);
lvDialog.setAdapter(dialogAdapter);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.getWindow().getAttributes().height = LayoutParams.WRAP_CONTENT;
alert.show();
btnCancel = (Button)someLayout.findViewById(R.id.d_bonRokokSearchNewItem_btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
alert.cancel();
}
});
lvDialog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
String selectedKdRokok = ((TextView)arg1.findViewById(R.id.kdRokok_dialog)).getText().toString();
String selectedNamaRokok = ((TextView)arg1.findViewById(R.id.namaRokok_dialog)).getText().toString();
autoCompleteBonRokok.setText(selectedKdRokok);
txtNamaRokok.setText(selectedNamaRokok);
alert.cancel();
}
});
}
public void splitValue(){
if (txtJumlah.length()==0)
txtJumlah.setText("0,000");
separated = txtJumlah.getText().toString().split(",");
first = separated[0];
second = separated[1];
first = Integer.toString(bal);
txtJumlah.setText(first + "," + second);
txtJumlah.clearFocus();
}
public void createDialogConfirm(){
LayoutInflater li = LayoutInflater.from(this);
LinearLayout someLayout = (LinearLayout) li.inflate(R.layout.d_global_confirm_transaksi, null);
Button btnSave_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnSave);
Button btnCancel_dialog = (Button) someLayout.findViewById(R.id.d_globalConfirmTrans_btnCancel);
btnSave_dialog.setOnClickListener(dialogYes);
btnCancel_dialog.setOnClickListener(dialogNo);
alert = new Dialog(this);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(someLayout);
alert.getWindow().getAttributes().width = LayoutParams.FILL_PARENT;
alert.show();
}
}
My question is
how can i pass a value from second activity (contain edittext) to fragment in view pager, because everytime i try to insert using many way, java lang null pointer always become my nightmare...
please help me... thx you so much
Intent.putExtra("YourValueKey", datatobepassed);
on the other activity
Bundle extras = getIntent().getExtras();
if ( extras != null ){
extras.get("YourValueKey")
}
I'm new in Android. I have the same problem as described here...I am trying to manage a simple list in an Android application. The contents of the list are maintained in a SQLite database. When the user selects and holds on a specific row, a context menu appears with a "Open/Delete" option. When they select "Delete", the row is deleted from the database, but the view does not refresh. When I back out of the application and get back in, the appropriate row has been removed. So, I know the row is deleted, it's just the ListView that doesn't refresh. The same with adding new item to the database. I searched solution, but not yet find. Appreciate any help.
Activity class:
public class ProjectsActivity extends Activity {
private RMProject rmProject = null;
private RMProjectDBHelper projectDBHelper = null;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rmProject = new RMProject();
projectDBHelper = new RMProjectDBHelper(this);
final ListView lv = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<>(this, R.layout.list_item, getProjectNames());
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProjectsActivity.this);
builder.setTitle("What to do with project?");
builder.setPositiveButton("Open", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ProjectsActivity.this, OpenProjectActivity.class);
//todo: send project information as parameter
startActivity(intent);
}
});
//**!!!Here I delete project item from database!!!**
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selected = ((TextView) view.findViewById(R.id.list_textView)).getText().toString();
int projId = projectDBHelper.findIdByName(selected);
projectDBHelper.deleteProject(projId);
Toast toast=Toast.makeText(getApplicationContext(), "Project "+selected+" deleted", Toast.LENGTH_SHORT);
toast.show();
//**call getProjectNames and notifydataSetChanged**
getProjectNames();
adapter.notifyDataSetChanged();
}
});
builder.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_item) {
final Dialog dialog = new Dialog(ProjectsActivity.this);
dialog.setContentView(R.layout.add_proj);
dialog.setTitle("Введите название проекта:");
dialog.setCancelable(false);
Button okBtn = (Button) dialog.findViewById(R.id.btn_create_proj);
Button cancelBtn = (Button) dialog.findViewById(R.id.btn_cancel_proj);
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editProjName = (EditText) dialog.findViewById(R.id.edit_proj_name);
String projName = editProjName.getText().toString();
if (rmProject == null) {
rmProject = new RMProject();
}
rmProject.setName(projName);
if (projectDBHelper == null) {
projectDBHelper = new RMProjectDBHelper(ProjectsActivity.this);
}
projectDBHelper.addProject(rmProject);
dialog.dismiss();
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
private String[] getProjectNames() {
LinkedList<RMProject> projects = (LinkedList<RMProject>) projectDBHelper.getAllProjects();
String[] names = new String[projects.size()];
int i = 0;
for (RMProject p : projects) {
names[i++] = p.getName();
}
return names;
}
}
Fragment with custom DbHelper class:
public class RMProjectDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "RM_DB";
private static final String TABLE_PROJECT = "PROJECT";
private static final String[] COLUMNS = {"id_project", "project_name"};
private static final int DB_VERSION = 1;
public RMProjectDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
//.....some code...
public void deleteProject(int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PROJECT, "id_project = ?", new String[]{String.valueOf(id)});
db.close();
Log.d("deleteProject with id: ", Integer.toString(id));
}
public int findIdByName(String name){
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT PROJECT.id_project FROM PROJECT WHERE PROJECT.project_name = '"+name+"'";
Cursor cursor = db.rawQuery(selectQuery,null);
int id=-1;
while (cursor.moveToNext()){
id = cursor.getInt(cursor.getColumnIndex("id_project"));
Log.i("LOGGING:"," FIND ID BY NAME: ID="+id);
}
return id;
}
on delete action fetch the data once again and then again call adapter.notifyDataSetChanged it will work
Im setting up a main activity with a ListView object, however, the ListView will not respond to touch, onItemClick and onContextItemSelected are not reachable, i have set up setOnItemClickListener and registerForContextMenu, and i dont see my error, here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemClickListener {
long selectedMovieId;
DbHandler dbhandler;
Movie selectedMovie;
MovieAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_setting = (Button) findViewById(R.id.page_main_setting);
Button btn_add = (Button) findViewById(R.id.page_main_add);
ListView lv = (ListView) findViewById(R.id.list);
btn_add.setOnClickListener(this);
btn_setting.setOnClickListener(this);
lv.setOnItemClickListener(this);
dbhandler = new DbHandler(this);
registerForContextMenu(lv);
Cursor c = dbhandler.queryAll();
startManagingCursor(c);
adapter = new MovieAdapter(this, c);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_options, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.main_options_exit:
finish();
return true;
case R.id.main_option_delete_all:
dbhandler.deleteAll();
refresh();
return true;
}
return false;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.d("context menu", "clicked");
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
selectedMovieId = info.id;
switch (item.getItemId()) {
case R.id.main_context_edit:
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_CONTEXT, selectedMovie+"");
startActivity(intent);
return true;
case R.id.main_context_delete:
dbhandler.deleteMovie(selectedMovieId);
refresh();
return true;
}
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.page_main_setting:
openOptionsMenu();
break;
case R.id.page_main_add:
DialogInterface.OnClickListener listenerInternet = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),
InternetEditActivity.class);
startActivity(intent);
}
};
DialogInterface.OnClickListener listenerManual = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),AddEditActivity.class);
intent.putExtra(DbConstants.MANUAL, DbConstants.MANUAL);
startActivity(intent);
}
};
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Please choose an adding method")
.setCancelable(false).setNegativeButton("Cancel", null)
.setNeutralButton("via internet", listenerInternet)
.setPositiveButton("Manual", listenerManual).create();
dialog.show();
break;
}
}
class MovieAdapter extends CursorAdapter /*implements OnTouchListener*/ {
public MovieAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// inflate the view:
return getLayoutInflater().inflate(R.layout.main_list_layout,
parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// bind the data
// get the data from the cursor
String subject = cursor.getString(cursor.getColumnIndex(DbConstants.DB_SUBJECT));
String body = cursor.getString(cursor.getColumnIndex(DbConstants.DB_BODY));
String internal_location = cursor.getString(cursor.getColumnIndex(DbConstants.DB_INTERNAL_LOCATION));
int year = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_YEAR));
int status = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_STATUS));
int rating = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_RATING));
TextView subjectText = (TextView) view.findViewById(R.id.list_main_subject);
TextView bodyText = (TextView) view.findViewById(R.id.list_main_body);
TextView yearText = (TextView) view.findViewById(R.id.list_main_year);
TextView statusText = (TextView) view.findViewById(R.id.list_main_status);
ImageView image = (ImageView) view.findViewById(R.id.list_main_imgae);
//RatingBar ratingBar = (RatingBar) view.findViewById(R.id.list_main_ratingBar1);
//ratingBar.setOnTouchListener(this);
subjectText.setText(subject);
bodyText.setText(body);
yearText.setText(String.valueOf(year));
//ratingBar.setRating(rating);
Log.d("status in main", status+"");
Log.d("rating in main", rating+"");
if (status==0){
statusText.setText("watched");
} else if (status==1){
statusText.setText("Not watched");
}
Log.d("ternal loction", internal_location+"!");
if (internal_location!=null){
File imgFile = new File(internal_location);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
}
}
}
/*#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}*/
} //Movie Adapter close
public void refresh(){
Cursor newCursor = dbhandler.queryAll();
Cursor oldCursor = adapter.getCursor();
adapter.changeCursor(newCursor);
startManagingCursor(newCursor);
stopManagingCursor(oldCursor);
oldCursor.close();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long id) {
Log.d("list menu", "clicked");
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_LISTVIEW, id);
startActivity(intent);
}
} //Main Activity close
it has to be somthing to do with the layout of the list, a simple list inserted next to it worked
OnItemClick event is now intercepted by RatingBar.
Add onTouchEvent listener to your RatingBar and return false to say to system that RatingBar does not handle this events.
#Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(MotionEvent event)
return false;
}
Edit: above answer is for subclassing RatingBar.
But you already have onTouchEvent just return false instead of true.
The problem was that there was a Scroll view object in the layout of the adapter, remove it and the problem will be fixed
I'm using the following code to show data from sqlite in listView
public class AndroidSQLite extends Activity {
ListView listContent;
private SQLiteAdapter mySQLiteAdapter;
Button addZekr;
EditText zekrTxtEditor;
String[] items;
boolean[] itemsChecked ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_sqlite);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.deleteAll();
mySQLiteAdapter.insert(getResources().getString(R.string.zekr1));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr2));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr3));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr4));
mySQLiteAdapter.insert(getResources().getString(R.string.zekr5));
// Open the same SQLite database and read all it's content.
mySQLiteAdapter = new SQLiteAdapter(this);
setDataInList();
Button addZekr = (Button) findViewById(R.id.addZekrBtn);
addZekr.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
zekrTxtEditor = (EditText)findViewById(R.id.zekr_text);
String newZekr = zekrTxtEditor.getText().toString();
System.out.println("newZekr: "+newZekr);
mySQLiteAdapter.openToWrite();
mySQLiteAdapter.insert(newZekr);
setDataInList();
}
});
mySQLiteAdapter.close();
listContent.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parentView, View childView,
int position, long id) {
// TODO Auto-generated method stub
String itemPostion = listContent.getItemAtPosition(position).toString();
System.out.println("in Long Press itemPostion: "+itemPostion);
return false;
}
});
listContent.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView, View childView,
int position, long id) {
// TODO Auto-generated method stub
String itemPostion = listContent.getItemAtPosition(position).toString();
System.out.println("in Normal Press itemPostion: "+itemPostion);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Dialog with simple text");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < items.length; i++) {
if (itemsChecked[i]) {
Toast.makeText(getBaseContext(), items[i] + " checked!", Toast.LENGTH_LONG).show();
}
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_LONG).show();
}
});
builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(), items[which] + (isChecked ? "checked!" : "unchecked!"), Toast.LENGTH_SHORT).show();
}
});
builder.create();
builder.show();
}
break;
}
return true;
}
public void setDataInList(){
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
items = new String[]{SQLiteAdapter.KEY_CONTENT};
int[] to = new int[]{R.id.text};
String myContent = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT)).toString().trim();
// long id = cursor.getLong(cursor.getColumnIndex(SQLiteAdapter.KEY_ID));
System.out.println("itemssss: "+myContent);
itemsChecked = new boolean[items.length];
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.row, cursor, items, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
}
}
what I want to to is to get the data of KEY_CONTENT column and put them in an array to show them in the AlertDialog
So I putted this line
String myContent = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT)).toString().trim();
but it gives me this Exception:
CursorIndexOutOfBoundsException: Index -1 requested, with a size of 5
any help?
The exception mean that the cursor is positioned before the first row, as it is the case when it is created. You should move it to the first row using moveToFirst()
for example :
if (moveToFirst()) {
String myContent = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT)).toString().trim();
...
} else {
// no data
}
Alternatively you may use moveToNext(), in a loop for example.