my following codes show the data of sqlite in listview. now i want to write long click to delete row in listview and sqlite. please help me. how can i do that?
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
R.layout.cartformat,results));
getListView().setTextFilterEnabled(true); }
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " + title + ", Quantity: " + qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}}}
The best way would be to develop a custom adapter. But if you don't want, this should work :
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList(){
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
String currentString = results.get(position);
String resultRegexString = "Title\\: ([^,]+), Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(resultRegexString);
if(resultRegexMatcher){
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3));
database.delete("CART", whereClause, null);
}
}
results.remove(position);
displayResultList();
});
}
Related
I have two spinner in my application which populating list from sqlite and it is working fine. When I select State in first spinner then second spinner list populate depend on first spinner. Now what I want that when I select item in both spinner and then I press back and again launch the activity then the list of second spinner still there. I want to clear list of second spinner when I press back button and Populate list in second spinner when user select value in first spinner.
public void fillStateData() {
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst()) {
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
stateCodeId = cursor.getString(0);
}
cursor.close();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void fillDistrictData(String stateCodeId) {
try {
district_array = new ArrayList<String>();
district_array.clear();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '" + stateCodeId + "'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
fillTalukaData(districtCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
add this method to activity.Hope this will work .
#Override
public void onBackPressed() {
spnDistrict.getAdapter().clear();
spnDistrict.getAdapter().notifyDataSetChanged();
finish();
}
Try using
adapter.clear();
spinner.setAdapter(new ArrayAdapter<String>(YourActivity.this,android.R.layout.simple_dropdown_item_1line,adapter));
Use Onresume for clear the array list you want
#Override
public void onResume() {
Log.e("DEBUG", "onResume of LoginFragment");
state_array.clear();
district_array.clear();
super.onResume();
}
or in onCreate view After Inttilizing array clean both arrayList.
I am fetching some json data into an EventApp and I am trying to store in SQLite database some of the events. I am showing the events in another activity, not the main one and whenever I go back from that activity to the main one and the I go back to the activity with the listview, the data gets duplicated every time. SO if I click to go to that activity 10 time, my data gets 10 times in the listview and in the database as well. How can I fix this?
SQLiteDatabase db = getWritableDatabase();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//Add new row to the database
public void addEvent(Event ev){
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.TITLE, ev.getTitle());
contentValues.put(DatabaseHelper.START_DATE, ev.getStartTime());
contentValues.put(DatabaseHelper.END_DATE, ev.getEndTime());
contentValues.put(DatabaseHelper.IMAGE_URL, ev.getImageURL());
contentValues.put(DatabaseHelper.URL, ev.getUrl());
contentValues.put(DatabaseHelper.SUBTITLE, ev.getSubtitle());
contentValues.put(DatabaseHelper.DESCRIPTION, ev.getDescription());
db.insert(TABLE_NAME, null, contentValues);
//db.close();
}
//Delete event from database
public void deleteEvent(String eventTitle){
db.execSQL("DELETE FROM " + TABLE_NAME + "WHERE " + TITLE + "=\"" + eventTitle + "\";" );
}
public int deleteEvents() {
return db.delete(DatabaseHelper.TABLE_NAME, null, null);
}
//Print the database as string
public String databaseToString(){
String dbString="";
//points to a location in results
Cursor c = getEvents();
while (c.moveToNext()){
if(c.getString(c.getColumnIndex("Title")) != null){
dbString += c.getString(c.getColumnIndex("Title"));
dbString += "\n";
}
}
//db.close();
return dbString;
}
public Cursor getEvents(){
return db.query(TABLE_NAME, ALL_COLUMNS, null, null, null, null, null, null);
}
}
This is the activity where I show the data from the database
public class StoredEventsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stored_events);
ListView listView = (ListView) findViewById(R.id.lv_stored_events);
Intent intent = getIntent();
ArrayList<Event> events = new ArrayList<Event>();
events = (ArrayList<Event>) intent.getSerializableExtra("storedEvents");
EventAdapter adapter = new EventAdapter(this, R.layout.list_view_row, R.id.stored, events );
listView.setAdapter(adapter);
}
}
Here is the method that returns the stored events
public static ArrayList<Event> returnStoredEvents(){
long id = -1;
//getStoredEvents();
Cursor c = eventsDB.getEvents();
while (c.moveToNext()){
id = c.getInt(c.getColumnIndex(eventsDB.ID));
String title = c.getString(c.getColumnIndex(eventsDB.TITLE));
String start = c.getString(c.getColumnIndex(eventsDB.START_DATE));
String end = c.getString(c.getColumnIndex(eventsDB.END_DATE));
organizeEvents.add(new Event(title, start, end, true));
}
c.close();
Log.d("DATABASE", organizeEvents.toString());
return organizeEvents;
}
Here is where I actually add some of the events:
private void readEvents(String str){
Event ev = null;
try {
JSONObject geoJSON = new JSONObject(str);
JSONArray jsonEvents = geoJSON.getJSONArray("events");
for (int i = 0; i < jsonEvents.length(); i++) {
JSONObject event = jsonEvents.getJSONObject(i);
JSONArray timeJsonEvent = event.getJSONArray("datelist");
JSONObject time = timeJsonEvent.getJSONObject(0);
title = event.getString("title_english");
Date date = new Date(time.getLong("start"));
startDate = dateFormat.format(date);
date = new Date(time.getLong("end"));
endDate = dateFormat.format(date);
imageURL = event.getString("picture_name");
url = event.getString("url");
subtitle = event.getString("subtitle_english");
description = event.getString("description_english");
if (title.charAt(0) == 'T') {
ev = new Event(title, startDate, endDate, true);
eventsDB.addEvent(ev);
}else {
ev = new Event(title, startDate, endDate, false);
}
// Process a newly found event
final Event finalEv = ev;
handler.post(new Runnable() {
public void run() {
addNewEvent(finalEv);
}
});
}
}catch (Exception e) {
Log.d(null, e.getMessage());
}
}
And here is my main:
public class MainActivity extends AppCompatActivity{
DatabaseHelper eventsDB;
ListFragment listFragment;
SimpleCursorAdapter adapter;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eventsDB = new DatabaseHelper(this);
//storedEvents.addAll(EventsListFragment.returnStoredEvents());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Sort by name")){
Toast.makeText(this, "ITEM 2 CLICKED", Toast.LENGTH_LONG).show();
EventsListFragment.sort(-1);
}else if (item.getTitle().equals("Sort by date")) {
EventsListFragment.sort(1);
}else if (item.getTitle().equals("Stored events")){
showSavedEvents();
Toast.makeText(this, "ITEM 3 CLICKED", Toast.LENGTH_LONG).show();
}
return true;
}
public void showSavedEvents(){
intent = new Intent(this, StoredEventsActivity.class);
intent.putExtra("storedEvents", EventsListFragment.returnStoredEvents());
startActivity(intent);
}
}
Hy guys!
I've got a problem. My app should display all routes in a listview. But there is something wrong with the arrayadapter. If i try my arrayadapter like this:
ArrayAdapter<DefineRoute> adapter = new ArrayAdapter<DefineRoute>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
it works, but it only display the objectname of DefineRoute and i wanna display the output of the cursor.
Ithink i should try:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
But here comes the error: Cannot resolve constructor ArrayAdapter
Here is my Acticity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated constructor stub
super.onCreate(savedInstanceState);
setContentView(R.layout.planausgabelayout);
//Aufruf der TextViews
TextView txtStart = (TextView)findViewById(R.id.txtAusgabeStart);
TextView txtZiel = (TextView)findViewById(R.id.txtAusgabeZiel);
TextView txtZeit = (TextView)findViewById(R.id.txtAusgabeZeit);
intent = getIntent();
txtStart.setText(intent.getStringExtra("StartHaltestelle"));
txtZiel.setText(intent.getStringExtra("ZielHaltestelle"));
txtZeit.setText(intent.getStringExtra("Zeit"));
getRoute();
}
public void getRoute() {
lvList = (ListView)findViewById(R.id.lvList);
Verbindungen verbindungen = new Verbindungen(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
lvList.setAdapter(adapter);
}
Here is my Activity Define Route:
public class DefineRoute {
private String abfahrtszeit;
private String ankunftszeit;
private String dauer;
private String umstieg;
public DefineRoute(String abfahrtszeit, String ankunftszeit, String dauer, String umstieg)
{
this.abfahrtszeit = getAbfahrtszeit();
this.ankunftszeit = getAnkunftszeit();
this.dauer = getDauer();
this.umstieg = getUmstieg();
}
public String getAbfahrtszeit() {
return abfahrtszeit;
}
public String getAnkunftszeit() {
return ankunftszeit;
}
public String getDauer() {
return dauer;
}
public String getUmstieg() {
return umstieg;
}
}
Here is my Activity Verbindungen:
public class Verbindungen {
SQLiteDatabase db;
LinkedList<DefineRoute> route;
DefineRoute[] routeArray;
Context context;
DatabaseHelper myDbHelper = null;
public Verbindungen(Context context) {
route = new LinkedList<DefineRoute>();
this.context = context;
myDbHelper = new DatabaseHelper(context);
}
public DefineRoute[] getVerbindungen() {
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
db = myDbHelper.getReadableDatabase();
// Alle Daten der Datenbank abrufen mithilfe eines Cursors
Cursor cursor = db.rawQuery("SELECT strftime('%H:%M', f.abfahrt) AS Abfahrt," +
"strftime('%H:%M', f.ankunft) AS Ankunft," +
"strftime('%H:%M', strftime('%s',f.ankunft)- strftime('%s',f.abfahrt), 'unixepoch') AS Dauer," +
"r.name AS Route," +
"count(u.fahrt_id) AS Umstiege " +
"FROM scotty_fahrt f " +
"JOIN scotty_haltestelle start ON f.start_id = start.id " +
"JOIN scotty_haltestelle ziel ON f.ziel_id = ziel.id " +
"JOIN scotty_route r ON f.route_id = r.id " +
"LEFT OUTER JOIN scotty_umstiegsstelle u ON f.id = u.fahrt_id " +
"WHERE start.name = 'Linz/Donau Hbf (Busterminal)' " +
"AND ziel.name = 'Neufelden Busterminal (Schulzentrum)' " +
"GROUP BY u.fahrt_id",null);
cursor.moveToFirst();
int i=0;
while (cursor.moveToNext()){
//in this string we get the record for each row from the column "name"
i++;
}
routeArray = new DefineRoute[i];
cursor.moveToFirst();
int k =0;
while (cursor.moveToNext())
{
routeArray[k] = new DefineRoute(cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3));
k++;
}
//here we close the cursor because we do not longer need it
//}
cursor.close();
myDbHelper.close();
return routeArray;
}
please help me.
Now i am creating a ArrayAdapter class where i define my ouput in the listview with:
public class RouteAdapter extends ArrayAdapter<DefineRoute>{
Activity context;
DefineRoute[] defineroute;
public RouteAdapter(Activity context, DefineRoute[] defineroute){
super(context, R.layout.layoutausgabe, defineroute);
this.defineroute = defineroute;
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.layoutausgabe,null);
TextView txZeit = (TextView)row.findViewById(R.id.txZeit);
TextView txDauer = (TextView)row.findViewById(R.id.txDauer);
TextView txUmstieg = (TextView)row.findViewById(R.id.txUmstieg);
DefineRoute defineRoute = defineroute[position];
txZeit.setText(defineRoute.getAbfahrtszeit() + " - " + defineRoute.getAnkunftszeit());
txDauer.setText(defineRoute.getDauer());
txUmstieg.setText(defineRoute.getUmstieg());
return row;
}
}
How should i continue?
and what should my adapter look like?
Your ArrayAdapter<String> is type of String so pass String list to it's constructor instead of verbindungen.getVerbindungen() list of objects.
ArrarAdapter < T > is any type of class you can use
in your case ArrayAdapter so you need override toString method of DefineRoute class
in your case
#Override
public String toString() {
return ankunftszeit+" "+ankunftszeit;
//or what ever you want to displat
}
or there is other Solution is Create your Own adapter extending by BaseAdapter Class.
I have a listview which connect to an sqlite database. at first it shows my sqlite fields. but my problem is,I can't delete row by setOnLongClickDelete().
error:
The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(16908298, class android.widget.ListView) with Adapter(class android.widget.ArrayAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1510)
codes:
public class CartList extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(com.example.easyshopping.R.layout.cart);
openAndQueryDatabase();
displayResultList();
setOnLongClickDelete();
}
private void displayResultList() {
// setListAdapter(new ArrayAdapter<String>(this,R.layout.cartformat,results));
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.cartformat,results);
setListAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
Cursor c = database.rawQuery("SELECT title,qty,price FROM CART;", null);
if (c != null ) {
int totalPrice=0;
if (c.moveToFirst()) {
do {
String title = c.getString(c.getColumnIndex("title"));
int qty = c.getInt(c.getColumnIndex("qty"));
int price = c.getInt(c.getColumnIndex("price"));
int pricePerTitle=price*qty;
results.add("Title: " +title+ ",Quantity: "+qty+", Price: $"+pricePerTitle);
totalPrice=totalPrice+pricePerTitle;
}while (c.moveToNext());
}
TextView tTotalPrice=(TextView)findViewById(com.example.easyshopping.R.id.txttotalprice);
String total= Integer.toString(totalPrice);
tTotalPrice.setText(total);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
private void setOnLongClickDelete(){
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
try{ String currentString = results.get(position);
String resultRegexString = "Title\\:([^,]+),Quantity\\: ([^,]+), Price\\: \\$([\\W\\w]+)";
Pattern resultRegexPattern = Pattern.compile(resultRegexString);
Matcher resultRegexMatcher = resultRegexPattern.matcher(currentString);
if(resultRegexMatcher.find()){
String whereClause = "title=".concat(DatabaseUtils.sqlEscapeString(resultRegexMatcher.group(1))
.concat(" AND qty=").concat(resultRegexMatcher.group(2))
.concat(" AND price=").concat(resultRegexMatcher.group(3)));
SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
database.delete("CART", whereClause, null);
database.close();
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
results.remove(position);
}
return true;
} catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
return false;
}
}
} );
displayResultList();
}
}
following Toast works:
Toast.makeText(getApplicationContext(), "Row Delete", Toast.LENGTH_SHORT).show();
If you are able to successfully remove the data from the SQLite database then you simply make your listAdapter global and then adding the code
listAdapter.notifyDataSetChanged();
after
results.remove(position);
in your onItemLongClick. After this you can remove calling displayResultList(); in setOnLongClickDelete().
i have a problem in showing data coming from database sqlite, i looked for a solution
here i did found plenty but i couldn't make it work, the error i get is : Error occured:
java.lang.IllegalArgumentException: column '_id' does not exist !!
my code is :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
private ArrayList<String> arr;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
Button suivant = (Button)findViewById(R.id.com_quest);
suivant.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent l = new Intent(MainActivity.this,ActivityUn.class);
startActivity(l);
}
});
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
Log.i("MyApp", "Total users: " + cursor.getCount());
Toast.makeText(getApplicationContext(),
"Number of rows: " + cursor.getCount(), Toast.LENGTH_LONG)
.show();
String[] databaseColumnNames = new String[] { DBAdapter._id };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
list.setAdapter(myCursordapter);
} }
and in dbadapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id
}, null, null, null,
null, null);
}
All CursorAdapters require that the Cursor includes a column called _id. Your Cursor contains just one column called Num_du_Questionnaire.