Deleting data from SQLite using listview by clicking Delete Button - android

Okay, so my supervisor wants me to do this:
The third screen should be accessible via the "View All" button. It should show all the records that were added. Then beside each name, there should be a Delete button for removing the record from the SQLite database.
Please refer to this link to see what I'm talking about since I'm not good in expressing myself in English.
I've already made a way to show all the data that are saved in the database, but I really have no idea on how to automatically put an Delete button beside the data and delete it by clicking it.
Here's my code: (If there are more simple codes that you can suggest, then I'll be more glad.)
public class CheckData extends ListActivity implements OnClickListener {
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] name : names2) {
stg = name[1];
stg1[x]=stg;
x++;
//ONCLICK
View homeonviewall = findViewById(R.id.homeonviewall);
homeonviewall.setOnClickListener(this);
View newdataonviewall = findViewById(R.id.newdataonviewall);
newdataonviewall.setOnClickListener(this);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.homeonviewall:
Intent a = new Intent(this, Dbsample.class);
startActivity(a);
break;
case R.id.newdataonviewall:
Intent b = new Intent(this, SaveData.class);
startActivity(b);
break;
}
}
}

1) Make a layout to display the name and the Delete button. Pass the layout to your adapter, where you currently use android.R.layout.simple_list_item_1, for example
new ArrayAdapter<String>(this, R.layout.row_layout_delete, stg1);
2) Extend your Adapter and override getView() to add an OnClickListener to your button. Inside onClick() simply delete the current row.
I recommend using a CursorAdapter, like SimpleCursorAdapter, they are specifically designed to link database information to a ListView.
This answer covers an extra topic, but I provide details on how to extend an Adapter and implement an OnClickListener: How to attach multiple touch actions to a single list item?, the "quick and dirty" answer should help you. You should also watch the Google I/O presentation Turbo-Charge Your UI to get the most from your Adapters.

Related

combining 2 activities together

ok so I'm making an app where I use an edit text to write anything and when I press a button it adds whatever I wrote in the edit to a listView, and it works, but I want the List to be in a different activity than the button and edit text, so I moved it without changing the code.can anyone figure this out,
BTW all the variables are public.
public class MainActivity extends AppCompatActivity {
public ArrayList<String> arrayList2;
public ArrayAdapter<String> adapter,adapter2;
public EditText editText,editText2;
public ArrayList<String> itemList,itemList2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] items = {};
itemList = new ArrayList<String>(Arrays.asList(items));
adapter = new ArrayAdapter<String>(this, R.layout.activity_list_layout,R.id.txtItem,itemList);
ListView listV = (ListView)findViewById(R.id.list_layout);
listV.setAdapter(adapter);
editText = (EditText)findViewById(R.id.thingadd);
Button btAdd = (Button)findViewById(R.id.add);
String[] age = {};
arrayList2 = new ArrayList<String>(Arrays.asList(age));
itemList2 = new ArrayList<String>(Arrays.asList(age));
adapter2 = new ArrayAdapter<String>(this, R.layout.activity_list__layout2,R.id.txtage,itemList2);
ListView listV2 = (ListView)findViewById(R.id.Age);
listV2.setAdapter(adapter2);
editText2 = (EditText)findViewById(R.id.agetxt);
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newItem=editText.getText().toString();
String newItem2=editText2.getText().toString();
itemList.add(newItem);
itemList2.add(newItem2);
adapter.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
});
}
}
You can use SQLite Database for that, where you would be saving data in database from one activity and reading it and displaying it in listview from another.
You have 2 options to do so.
You can use any database service. Store the values and display them in the next activity. But this needs Internet service to be enabled in the phone.
You can use intent. Convert those input to string type and pass them to next activity and display them using ids. This type do not require Internet service. To know more about this, Visit this link

ListView item gets destroyed while moving to other activity

My first activity contains a listview with textviews in each cell and uses a custom adapter. So if you click on any of the items, it will open up a form activity containing textfields. The user can fill up the details and once they press the save form button the details appear on the listview. Now I am trying to add items to the list dynamically. I have created a button which when clicked adds a new instance item so that more users can register the same way. I have been able to implement these functions. However, my problem now is when i click on the newly added item and go to the form activity and click save, i am not able to see the newly added entry after i come back to the listview activity.All I see is the first entry alone. So i am guessing it gets destroyed as soon as i leave the activity. How to ensure all newly added items are not destroyed when i keep moving between these two activities.
Here is my code of the ListView Activity:
public class FormTableActivity extends Activity {
private PassengerListAdapter adapter;
Button add_passenger;
String mrzdata,ic_data,name_data;
SharedPreferences nPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final_display_listview);
nPref = PreferenceManager.getDefaultSharedPreferences(this);
mrzdata = nPref.getString("MRZ", "");
name_data = nPref.getString("resultData", "");
ic_data = nPref.getString("icdata", "");
final ListView lv1 = (ListView) findViewById(R.id.custom_list);
adapter = new PassengerListAdapter(this);
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
add_passenger = (Button) findViewById(R.id.add_user);
add_passenger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// mrzdata = "";
// name_data = "";
// ic_data = "";
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
}
});
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent intent = new Intent(v.getContext(), FirstActivity.class);
startActivity(intent);
}
});
}
The easiest way to pass data between Intent is
Intent intent = new Intent(getBaseContext(), your_list_view_activity.class);
intent.putExtra("String_Key", data1);
//data1 could be an array of string where you have hold the values previously
startActivity(intent);
now on your list_view_activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String [] value = extras.getString("String_Key");
}
This way you won't get any exception but you get to populate your listView if there is data.
Another way to get data is via SharedPreference but I won't recommend it as it increases the size of the app.
You have to save these newly added items somewhere , e.g. to a SQLite database and retrieve them on create to populate the listview
You can see here if You want, the code is commented ,
here I have a listview with custom adapter with two items
the feed's name and it's url
i add URL and name using a text input dialog (with two edit text), save to DB, and retrieve them on create to populate the listview
https://github.com/enricocid/iven-feed-reader/blob/master-as/project/app/src/main/java/com/iven/lfflfeedreader/mainact/ListActivity.java

ListView items sort/reorder and saving changes?

I have a ListView and I can reorder items, but every time I exit from the app and start it again the order goes back to default. I'd appreciate if someone can give me answer and maybe a little snippet of how I can do that.
Example: I have two items and two links. Google and Yahoo. I use drag and drop and ArrayList with that. Everything is fine except I don't know how to save the new order.
I don't know if there is some other way to reorder those items.
I use CWAC-TOUCHLIST to do this.
Here is how far I have got:
private static String[] items={"Google", "Yahoo"};
private static String[] links={"http://google.com", "http://yahoo.com"};
private IconicAdapter adapter=null;
private IconicAdapter1 adapter2=null;
ArrayList<String> array= new ArrayList<String>(Arrays.asList(items));
private ArrayList<String> array2=
new ArrayList<String>(Arrays.asList(links));
/** Called when the activity is first created. **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TouchListView tlv=(TouchListView)getListView();
adapter=new IconicAdapter();
adapter2=new IconicAdapter1();
setListAdapter(adapter);
setListAdapter(adapter2);
tlv.setOnItemClickListener(itemclick);
tlv.setDropListener(onDrop);
}
private TouchListView.DropListener onDrop =
new TouchListView.DropListener() {
#Override
public void drop(int from, int to) {
String item=(String) adapter.getItem(from);
adapter.remove(item);
adapter.insert(item, to);
String link=(String) adapter2.getItem(from);
adapter2.remove(link);
adapter2.insert(link, to);
}
};
private TouchListView.OnItemClickListener itemclick =
new TouchListView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int from, long id) {
String item = adapter.getItem(from);
Toast.makeText(getBaseContext(), "you pick: "+item,
Toast.LENGTH_SHORT).show();
String link = adapter2.getItem(from);
Intent showContent = new Intent(getApplicationContext(),
Web.class);
showContent.setData(Uri.parse(link));
startActivity(showContent);
}
};
Is there a smarter way to do it?
You have to save the lists with their order either to a file or a DB.
When the application starts you have to initialize the ListViews from the saved lists.
When you drag & drop an item, you have to save the changes.
The method you need to change :
Your drop method should, in addition to what it already does, store the changes in a file or a DB.
Instead of the arrays that you pass in the IconicAdapter and IconicAdapter2 constructors (array & array2), you should pass the saved arrays.
You can read in many places how to store data to a file or a SQLite DB. For example, you can find a good tutorial for SQLite here - http://www.vogella.com/articles/AndroidSQLite/article.html#android_requisites (only the first four sections are relevant, since you don't have to use a ContentProvider).
If you choose to use a DB, you can create a table that contains the following columns : item, link & order. In the drop method you'll have to update the order column of all the rows whose order is between from and to (or if the lists are not too big, you can simply update all the rows and set the order to be the index in the array that holds the list).
When you load the table from the DB you should order it by the order column.

Android app - how to display a list of items and make them clickable

I need to display a list of text items to the screen and make them clickable. So it would be something like a list of links on a web application.
How can I do that in an Android Activity screen?
It would be some random number of items that I have to pull from a db and display all as links.
Any idea how that can be done?
You should read the doc about ListActivity, ListView and follow the Hello ListView tutorial.
Yes you can do it. Create a DataExchange class to fetch it from Db..
Store the Strings in an Array.
Create a ArrayAdapter to display the array of Strings you got from the database.
for Example
public class AndroidListViewActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] numbers = {"one","two","three","four"}
// here you store the array of string you got from the database
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, numbers));
// refer the ArrayAdapter Document in developer.android.com
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String num = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("number", num);
startActivity(i);
}
});
}
}
The secondActivity to display the Particular item you have clicked should be
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("number");
// displaying selected product name
txtProduct.setText(product);
}
}
you have to create various layout files accordingly..
Hope this helps you :)
You should use a ListView. It's very simple, just create a ListActivity, put your items inside an Adapter and then set it as the Adapter of your ListActivity.
You can read more about ListViews here
There is also a new paradigm called ListFragment.
I have used ListViews before but prefer the fragments approach now - it's just very straight forward and quite flexible esp on tablets since the interation with another area on the screen when selecting an item is quite flexible and only requires very little code.
Just one example:
public class Select_FoodCategories_Fragment extends android.app.ListFragment {
private static final boolean DEBUG = true;
#Override
public void onCreate(Bundle savedInstanceState) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
HoldingActivity a = (HoldingActivity) getActivity();
//accessing a variable of the activity is easy
a.visibleListViewInFragment = getListView();
List<XYZ> listTodisplay = a.getListToDisplay();
MyAdapter adapter = new MyAdapter(
getActivity(), 0, listTodisplay);
setListAdapter(adapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (DEBUG)
Log.i(this.getClass().getSimpleName(), " ->"
+ Thread.currentThread().getStackTrace()[2].getMethodName());
XYZ item = (XYZ) getListAdapter()
.getItem(position);
}
}
More info here: http://developer.android.com/reference/android/app/ListFragment.html
By the way, I find it really worth it to get familiar with the new fragments concept - it just makes live much easier - esp on tablets!
ps I left the debug statements in on purpose - since it helps alto to understand the whole concept much faster in my experience

How to call different intents from each listview item in android?

I am working on android applications. In my project I need to create Listview. My layout i.e info.xml contains topbar with one image view, footer with other imageview. Also in the center of the layout I kept an imageview and on that I have created the Listview. Also I have created row.xml for the textview to display listitems. Now when I click on each listitem a new intent should be called...i.e when I click on 1st listitem page1 should open. Similarly if I click on 2nd listitem page2 should open and so on. So how could I do that. I am struggling for this since 3 days but didnt find any correct solution. Please hgelp me regarding this.
My Code:
public class Information extends Activity
{
private String[] Countries;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
Countries = getResources().getStringArray(R.array.countries);
ListView list = (ListView)findViewById(R.id.listnew);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, Countries);
list.setAdapter(adapter);
registerForContextMenu(list); }
}
All you have to add is
list.setOnItemClickListener(this);
Then you let your class implement the OnItemClickListener interface and create this method:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent firstIntent = new Intent(this, MyClass.class);
startActivity(firstIntentIntent);
break;
case 1:
Intent secondIntent = new Intent(this, MySecondClass.class);
startActivity(secondIntentIntent);
break;
[... etc ...]
}
}
In this case, if the first item is clicked, it will launch the MyClass Activity, if the second item is clicked, the MySecondClass Activity will be launched, etc.
Yes, it is a bit tedious but it is the best way.

Categories

Resources