Delete or hide a row in a list view - android

Hello everyone I have a problem in regards with the deletion or hiding of list in a list view something like .hide() in javascript . I know there are lots of answers here about it but it seems It didn't answer my problem. To explain clearly, below is some part of my code.
package sample.wew.wew;
import info.androidhive.sqlite.model.Message;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class QuestionsSent extends Fragment {
private static final String TAG = "Question";
private static List questions;
protected ListAdapter adapter;
ListView theList;
#SuppressWarnings("deprecation")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.questions_main_layout, container, false);
AskdDatabaseHelper msg_db = new AskdDatabaseHelper(getActivity());
Cursor cursor = msg_db.FetchQuestion("S");
String[] fromFieldNames = new String[] { "msg_from_user", "msg_message" };
int[] toViewIDs = new int[] { R.id.tvMessage, R.id.tvMessageSender };
adapter = new QuestionsCursorAdapter(getActivity(), // Context
R.layout.question_detail, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
theList = (ListView) view.findViewById(R.id.list);
theList.setAdapter(adapter);
theList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/*
Log.v(TAG, ": NAAY GI CLICK");
Intent intent = new Intent(getActivity(), Sent_details.class);
Cursor cursor = (Cursor) adapter.getItem(position);
Log.d("TAG", "" + adapter.getItem(position));
intent.putExtra("MESSAGE_ID", cursor.getString(cursor.getColumnIndex("msg_message")));
startActivity(intent);
*/
// HERE IS WHERE I WANT TO PUT MY CODE TO DELETE OR HIDE A LIST
}
});
if(adapter.isEmpty()){
view = inflater.inflate(R.layout.fragments_question_new, container, false);
((TextView)view.findViewById(R.id.textView)).setText("No Sent Questions");
}
return view;
}
}

Here you can do something like this it will ask you in the form of dialogue box to weather delete the record or not and after clicking yes it will delete the record. Hope this helps you ...
userList.setOnItemLongClickListener(new OnItemLongClickListener()
{
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,final int arg2, long arg3)
{
build = new AlertDialog.Builder(HomePage.this);
build.setTitle("Delete " + FirstName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), FirstName.get(arg2) + " " + LastName.get(arg2) + " is deleted.", 3000).show();
dataBase = mHelper.getWritableDatabase();
dataBase.delete(DatabaseActivity.TABLE_NAME, DatabaseActivity.KEY_ID + "=" + userId.get(arg2), null);
dataBase.close();
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}

put these lines in your onlistitemclick
int count = youradapter.getCount();
for (int i = count-1; i >= 0; i--)
{
adapter.remove(adapter.getItem(i).postion);
}
and add this line in belooo
adapter.notifyDataSetChanged();

Related

SQLite: get id from ListView

This is my first app and i'm having some problem whit ListView
How can I get the ID in the database after clicking on a Item?
I can't use position because the Id may not be continuous and even if it is in order sometimes does not return the correct Id any.
this is my code, Thank you for your help:
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", position);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
There are a lot of solution approaches.
For example, you can store of Id's if ArrayList before ListView initialization.
That is, execute "SELECT id FROM mytable"
Then store in arraylist and use while click method.
Example:
//in class declaration
private ArrayList<Long> ar_ids = new ArrayList<Long>;
//
String sql = "SELECT id FROM table";
Cursor cur = db.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
}
}
cur.close();
for click event:
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", ar_id.get(position));
//this is awsome!
startActivity(i);
}
and initialize this something like:
private void myfunc() {
String sql = "SELECT id FROM table";
Cursor cur = myDb.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
throw new NullPointerException();
}
}
cur.close();
}
private void populateListView(){
myfunc();
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
well instead of using the ArrayAdapter you can extend a BaseAdapter or ListAdapter or even the ArrayAdapter to make your custom adapter. First of all make a plain java class to map your database data including id to an object. Then make a custom BaseAdapter instead of using the ArrayAdapter. In your BaseAdapter class you have to override various methods including getItem and getItemId methods. Now you can return the whole mapped object from the getItem method and simply obtain the object of selected item of the ListView by using listView.getSelectedItem() method in the Activity or Fragment class. Once you get the object you can access the id easily.
You can find a good example and explanation of a custom adapter here
About mapping the database result to an object, you can get some concept here
Here, you can replace you code class with this one, I have added a cursorAdapter and attached it with your ListView, in adapter I have added a method for getting Id that I call from click listener to retrieve id from cursor, you will have to set column number for _ID in public void getId(int position) from MyCursorAdapter class below.
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
private MyCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
//retrieve id from cursor
int _id = adapter.getId(position)
i.putExtra("id", _id);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
adapter = new MyCursorAdapter(this, res, 0);
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setAdapter(adapter);
}
//adapter for list view
class MyCursorAdapter extends CursorAdapter {
Cursor cursor;
// Default constructor
public MyCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
this.cursor = cursor;
}
public void bindView(View view, Context context, Cursor cursor) {
String text = cursor.getString(1);
//make sure the TextView id is "#+id/text1" in da_item.xml
TextView tvText = (TextView) view.findViewById(R.id.text1);
tvText.setText(text);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflator inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
return Inflater.inflate(R.layout.da_item, parent, false);
}
public int getId(int position){
cursor.moveToPosition(position);
int colId = //set id column number here
int id = cursor.getLong(colId);
return id;
}
}
Since the code is untested, you might face a build issue in start, but it should give an idea of what's going on in code. feel free to ask any question if you face any problem in compilation

I get into trouble, how to keep each listview can open their own webview?

how can I make WebView can open the fragment listview? this is my code, and i got error code in :
lv.setOnItemClickListener(new OnItemClickListener() : The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView is not applicable for the arguments (new OnItemClickListener(){})
package info.androidhive.slidingmenu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.content.Intent;
import java.util.ArrayList;
import java.util.HashMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment(){}
protected ListView lv;
protected ListAdapter adapter;
public static final String MOVIE_DETAIL_KEY = "movie";
SimpleAdapter Adapter;
HashMap<String, String> map;
ArrayList<HashMap<String, String>> mylist;
String[] Pil;
String[] Ltn;
String[] Gbr;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_pulau, container,false);
ListView lv = (ListView) rootView.findViewById(R.id.lv);
Pil = new String[] {"Pulau Gusung", "Binatang Laut Khas"};
Ltn = new String[] {"Baca Selengkapnya...", "Baca Selengkapnya..."};
Gbr = new String[] {Integer.toString(R.drawable.ic_photos),
Integer.toString(R.drawable.ic_photos),
};
mylist = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < Pil.length; i++){
map = new HashMap<String, String>();
map.put("list", Pil[i]);
map.put("latin", Ltn[i]);
map.put("gbr", Gbr[i]);
mylist.add(map);
}
Adapter = new SimpleAdapter(getActivity(), mylist, R.layout.item_kepulauan,
new String[] {"list", "latin", "gbr"}, new int[] {R.id.tv_nama, R.id.tv_des, R.id.imV});
lv.setAdapter(Adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) lv
.getItemAtPosition(position);
if (position == 0) {
Intent myIntent = new Intent(getApplicationContext(),
Story.class);
startActivity(myIntent);
}else if (position == 1) {
Intent myIntent = new Intent(getApplicationContext(),
Story.class);
startActivity(myIntent);
}
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition + " ListItem : "
+ itemValue, Toast.LENGTH_LONG).show();
}
});
return rootView;
}
}
The issue is because you're using a new instance of OnItemClickListener when it should be AdapterView.OnItemClickListener. You've imported AdapterView, but not the inner interface, and there is no standalone OnItemClickListener interface so the types do not line up.

how to use a custom button in a list to redirect the user to another activity

I've written a big code and I've used a list view within one of my task layouts :
I want to know how I can make a listener for each update button in this case in order to move to another activity , I know how to use more than one activity and moves between them But I want to know how to make a listener only .
The custom adapter code :
package com.example.task_9;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TempLyaout extends ArrayAdapter<String> {
Context context;
ArrayList<String> sa;
public TempLyaout(Context context , ArrayList<String> sa) {
super(context,R.layout.temp,sa);
this.context=context;
this.sa = sa;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater l = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView = l.inflate(R.layout.temp, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
Button update = (Button) rowView.findViewById(R.id.button1);
// myDb.open();
// Cursor cursor= myDb.getRowByName(sa.get(position));
// myDb.updateRowByName(cursor.getInt(DBAdapter.COL_ROWID), sa.get(position), cursor.getString(DBAdapter.COL_PASSWD), cursor.getInt(DBAdapter.COL_AGE), isAdmin);
// myDb.close();
textView.setText(sa.get(position));
return rowView;
}
}
This is the related class :
package com.example.task_9;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class UsersActivity extends Activity {
Intent redirect;
ListView list;
ArrayList<String> sa;
DBAdapter myDb;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.users);
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
openDB();
/*********************************************/
Cursor cursor = myDb.getAllRows();
cursor.moveToFirst();
ArrayList<String> ha = new ArrayList<String>();
while(cursor.moveToNext()) {
ha.add(cursor.getString(DBAdapter.COL_NAME));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ha);
list.setAdapter(new TempLyaout(UsersActivity.this,ha));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
} // end onStart method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
} // end openDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void closeDB() {
myDb.close();
} // end closeDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
}// end main class
In your getView
Button update = (Button) rowView.findViewById(R.id.button1);
update.setOnClickListener(mClickListener);
Then
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ListActivtiy.this,SecondActivity.class);
startActivity(intent);
}
};
Also use a viewholder for smooth scrolling and performance
http://developer.android.com/training/improving-layouts/smooth-scrolling.html

onclick sqlite item

The app works fine up to //***************** in ListViewActivity.java. After this point I want to be able to click on an item and modify that item. I have tried numerous examples to no avail. My first goal is to be able to toast the item clicked.
package bipsnm.android;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListViewActivity extends Activity{
public void onCreate(Bundle savedInstanceState, String[] outputData, String[]
ListView1){
super.onCreate(savedInstanceState);
Toast.makeText(this, "list/textview", Toast.LENGTH_LONG).show();
final String KEY_ROWID = "_id";
final String KEY_ITEMTYPE = "itemType";
final String KEY_QUANTITY = "quantity";
setContentView(R.layout.sqlview);
// TextView content = (TextView) findViewById(R.id.outputData);
ListView content = (ListView) findViewById(R.id.listView1);
DatabaseControl control = new DatabaseControl(this);
String result = "ItemType\t Quantity \n";
try {
control.open();
result = result + "" + control.fetchItemIdByQty();
control.close();
}catch (SQLiteException e) {
e.printStackTrace();
}
content.setFilterText(result);
//***************************************************************************
setListAdapter(new ArrayAdapter<String>(this, R.layout.sqlview,ListView1));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent,View view,int position,long id){
Toast.makeText(getApplicationContext(),((TextView)view).getText(),Toast.LENGTH_LONG).show();
}
});
}
private ListView getListView() {
// TODO Auto-generated method stub
return getListView();
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
};
// binding array to ListAdapter
setListAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_expandable_list_item_1,result));
selection = (TextView)findViewById(R.id.selection);
// listening to single list item on click
protected void onListItemClick(ListView l,View v, int position, long id){
super.onListItemClick(l, v, position, id);
// selected item
String product = result[position];
Intent ii = new Intent(getApplicationContext(),Desire.class);
// sending data to new activity
ii.putExtra("product", product);
startActivity(ii);
};

Program never seems to get to the onclick listen

Hi below is some code ive been playing with but when i debug it never gets to the onitemclicklisten routine can anyone help?
package sanderson.swords.mobilesales;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class OrderProductSearch extends Activity {
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> item = new HashMap<String,String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.orderproducts);
}
catch (Exception e) {
//
String shaw="";
shaw = e.getMessage();
}
//Create view of the list where content will be stored
final ListView listContent = (ListView)findViewById(R.id.orderproductlistview);
//Set for fast scrolling
listContent.setFastScrollEnabled(true);
//Create instance of the database
final DbAdapter db = new DbAdapter(this);
//Open the Database and read from it
db.openToRead();
//Routine to call all product sub groups from the database
final Cursor cursor = db.getAllSubGroupProduct();
//Manages the cursor
startManagingCursor(cursor);
int i=0;
cursor.moveToFirst();
while (cursor.getPosition() < cursor.getCount()) {
item.put("ProdName",cursor.getString(2));
item.put("ProdSize", cursor.getString(3));
item.put("ProdPack",cursor.getString(4));
item.put("OrdQty","0");
//list.add(item);
list.add(i, item);
item = new HashMap<String,String>();
cursor.moveToNext();
i = i + 1;
}
String[] from = new String[] {"ProdName", "ProdSize", "ProdPack", "OrdQty"};
int[] to = new int[] { R.id.productlinerow, R.id.productlinerow2, R.id.productlinerow3, R.id.productlinerow4};
SimpleAdapter notes = new SimpleAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to);
listContent.setAdapter(notes);
//Close the database
db.close();
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String neil = "test";
neil = neil + "test";
}
});
}
}
An easier way to verify the click listener is to add some logcat prints in it, e.g.
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "Click!");
}
});
If you set a breakpoint at
listContent.setOnItemClickListener(new OnItemClickListener() {
it may not break when you click.
Try setting a breakpoint at
String neil = "test";
and debugging.

Categories

Resources