Can anyone help me with code, I am developing an android application and need some help. On a screen called results I need to show the headings of the records in a sqlite database in a view, the heading must be clicked and open a new window to show the full record, A long click must allow the user to delete the record.
This is what I got so far:
import java.util.ArrayList;
public class Main extends Activity {
ListView txtMainList;
// EditText nameTxt,posTxt;
Button saveBtn,retrieveBtn,btnBegin;
ArrayList<String >accidents=new ArrayList<String>();
EditText index;
ArrayAdapter<String> Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
index=(EditText)findViewById(R.id.txtRegistrationNo);
btnBegin = (Button) findViewById(R.id.btnBegin);
txtMainList = (ListView) findViewById(R.id.txtMainList);
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, accidents);
final DBHelper newDb=new DBHelper(this);
accidents.clear();
Cursor c=newDb.getYVAllData();
while (c.moveToNext())
{
accidents.add("Accident Number : "+c.getString(0));
}
txtMainList.setAdapter(Adapter);
newDb.close();
txtMainList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View agr1, int index, long id) {
Toast.makeText(getApplicationContext(), accidents.get(index), Toast.LENGTH_SHORT).show();
}
});
}
If you are using listview you can use longClickListener.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
//Delete record
return true;
}
});
and add android:longClickable="true" to your listview item layout.
Onclick:
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//Show full record in pop up
}
});
Related
I am having trouble with my programming project. I am creating a shopping application and all I need is deleting the selected data from listview and mysqlite database with a click of a button. I also created a query on my sqlite where it will delete primary key autoincrement integer.
Here is my class:
public class CartPage extends AppCompatActivity {
DatabaseHelper myDB;
public Button button_delete;
public Button button_home;
public TextView textView_totalAmount;
public TextView textView_PK;
public ListView listView_datas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_page);
myDB = new DatabaseHelper(this);
listView_datas = (ListView) findViewById(R.id.listView_ShoppingData);
button_delete = (Button) findViewById(R.id.button_deleteData);
button_home = (Button) findViewById(R.id.button_HomePage);
textView_totalAmount = (TextView) findViewById(R.id.textView_DisplayTotalAmount);
int total = myDB.addPrice();
textView_totalAmount.setText("$" + Integer.toString(total));
final ArrayList<String> list_cart = new ArrayList<>();
final Cursor data = myDB.getPrice_cart();
if (data.getCount() == 0) {
Toast.makeText(CartPage.this, "The Database is empty..", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
list_cart.add(data.getString(1) + "\n" +
data.getString(2) + "\n");
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice, list_cart);
listView_datas.setAdapter(listAdapter);
}
}
button_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goHome = new Intent(CartPage.this, FirstPage.class);
startActivity(goHome);
}
});
}
}
Here is my database helper query for deleting the data by primary key
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(table_Cart,"number = ?" , new String[] {number} );
}
For this scenario I was thinking on using but I am not sure how to do it.
listView_datas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
I also saw where when you hold the selected item it would get deleted. I don't mind that as long as it deletes the data.
Thank you!
I would suggest you implement a long click listener in your ListView and on long click on the item in your list, it will show an option to delete the corresponding item in your list. Here's a sample code that can help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View view, final int position, long arg3) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(RecipeList.this);
alertDialog.setTitle("Delete");
alertDialog.setMessage(yourList.get(position));
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteSelectedItem(yourList.get(position))
}
});
alertDialog.show();
return true;
}
});
And yes, you need to call notifyDataSetChanged() in your deleteSelectedItem() function to see the effect of the delete in your list.
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(table_Cart,"number = ?" , new String[] {number} );
// Update your list here
// Remove the deleted item from the list that you have passed to the adapter. Then call notifyDataSetChanged
updateYourListCart();
myAdapter.notifyDataSetChanged();
}
I wanted to display selected item in the textView when selected from dropdown list of spinner I implemented AdapterView.OnItemSelectedListener but when I'm selecting item its always null/empty here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new CustomAdapter(MainActivity.this, Languages));
btn.setOnClickListener(this);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
item = (String)parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
SO answer source: https://stackoverflow.com/a/49301966/5461982
I know this is an older question now but if anyone else comes across it be sure to check that your custom implementation of the Adapter you're setting for your Spinner overrides the getItem method:
#Override
public Object getItem(int position) {
return spinnerItems.get(position);
}
By default, you're required to override this method when implementing a custom BaseAdapter but the default return type is null. Be sure to modify the return type to return spinnerItems.get(position).
Hope this helps, I spent around 30 mins trying to work this out originally!
Try this,
String selected_item = spinner.getSelectedItem().toString();
Just retrieve value from String Array:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String item = Languages[position];
Toast.makeText(MainActivity.this, item, Toast.LENGTH_SHORT).show();
}
try this
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
sSelectedItem = arr_spiner.get(spinner.getSelectedItemPosition())
.getName();
txtSpinnerValue.setText(sSelectedItem);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
https://stackoverflow.com/questions/45159011/spinner-item-is-not-visible-data-is-coming-from-server-android/45161202#45161202
Try This
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new CustomAdapter(MainActivity.this, Languages));
btn.setOnClickListener(this);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
//item = (String)parent.getItemAtPosition(position);
item = (String) spinner.getSelectedItem().toString(); //Here is the Change
Toast.makeText(MainActivity.this, item.toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
The change here is
From
item = (String)parent.getItemAtPosition(position);
TO
item = (String) spinner.getSelectedItem().toString();
I have tried reading the documentation on it and I understand that I need to use removeValue() to accomplish this, I just don't know how to get the position of the click. I am pulling the list down from firebase and trying to use an OnItemClick() to say anytime something in the listview is clicked, it will be deleted. I feel like this is super simple and I'm just missing something.
public class DeleteChoiceListFragment extends Fragment {
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mRestReference = mRootRef.child("restaurants");
List<String> listofrest = new ArrayList<String>();
ListView restaurantListView;
ListAdapter restaurantListAdapter;
public DeleteChoiceListFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.restaurant_selection_list_frag,container,false);
restaurantListView = (ListView) view.findViewById(R.id.restaurantListView);
restaurantListAdapter = new FirebaseListAdapter<Restaurants>(getActivity(),Restaurants.class,R.layout.individual_restaurant_name_nocheckbox,mRestReference) {
#Override
protected void populateView(View v, Restaurants model, final int position) {
TextView restName = (TextView) v.findViewById(R.id.restname);
restName.setText(model.getName());
listofrest.add(position,model.getName());
}
};
restaurantListView.setAdapter(restaurantListAdapter);
restaurantListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
return view;
}
}
Going on 36 hours of no sleep now so my brain is 100% dead. I can provide more detail if necessary
Implement your setOnItemClickListener like this
restaurantListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Firebase itemtoRemove = restaurantListAdapter.getRef(i);
itemtoRemove.removeValue();
}
});
add your gradle
compile 'com.google.firebase:firebase-core:9.0.1'
compile 'com.google.firebase:firebase-database:9.0.1'
I have implemented an activity with a simple ListView. In the java file, I have implemented OnItemClickListener() to respond to ListView item clicked.
public class MainActivity extends Activity
{
private String value;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
value = "Hello World";
final ListView listview = (ListView)findViewById(R.id.listview);
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ListValues);
listview.setAdapter(aa);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
{
// Get Item Clicked
String ItemSelected = (String)listview.getItemAtPosition(position);
// Access "value" containing "Hello World"
}
}
}
I need to access member variable value of my MainActivity class in onItemClick(). Kindly tell me how to do it.
Simply use:
MainActivity.this.value;
Or, even simpler, just as if it was a member of the OnClickListener:
value
Will also work.
you declared it globally so you can use it directly
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
{
//Get Item Clicked
String ItemSelected = (String)listview.getItemAtPosition(position);
Toast.makeText(getApplicationContext,value,Toast.LENGTH).show();
^
here
}
I have a listview which I want to edit from a dialog box. I've read from googling that I need to notifyDataSetChanged() on the listview, however when I try to do this I get an error:
The method notifyDataSetChanged(View) is undefined for the type ListView
My listview is set originally at the top of my code with just a:
ListView listView;
It's then set in a routine on the onload
public void loadItems(){
//Removed - just getting the data
int rowCount;
rowCount = mCategory.size();
listView = (ListView) findViewById(R.id.lvItems);
int[] colors = {0, 0xFFFF0000, 0};
listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
listView.setDividerHeight(1);
listView.setAdapter(new CustomAdapter());
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
loadPopup(mDescription.get(position).toString(), mCountList.get(position).toString(), mTemplatecode.get(position).toString());
}
});
//Removed - Tidying up
}
The dialog box that is loaded on the onlick has a simple interface, a minus button, a plus button, a text box and a go button. The number in the textbox is changed which does a db call. When the dialog box closes I want it to refresh the listview behind to reflect the new change. I.e. basically re-run the loadItems() routine again.
This is what happens when you click the go button on the dialog. I'm obviously putting the notifyDataSetChanged in the wrong place as it wont even run.
btnGo.setOnClickListener( new View.OnClickListener(){
#Override
public void onClick(View v) {
addAsset(v, AssetDesc, txt.getText().toString(), templateCode);
listView.notifyDataSetChanged();
loadItems();
dialog.dismiss();
}
});
Custom adapter:
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
return mDescription.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
LayoutInflater inf=getLayoutInflater();
View v=inf.inflate(R.layout.noncriticalasset, arg2,false);
TextView tv=(TextView)v.findViewById(R.id.txtOption);
TextView tvCount=(TextView)v.findViewById(R.id.txtCount);
tv.setText(mDescription.get(arg0).toString());
tvCount.setText(mCountList.get(arg0).toString());
return v;
}
}
You need to call notifyDataSetChanged on the adapter, not the ListView itself.