Handling clicks inside listview - android

I'm new in Android and need help with my ListView, which contains text view and image in every list item. I need handle clicks on list item and on icon (R.id.list_star) in list item separately. I tried several ways but it seems I can't do it by myself. I tried to put star.setOnItemClickListener in the beginning, near lvData.setOnItemClickListener - but in this case view isn't found, and add swith inside AdapterView.OnItemClickListener - doesn't work. My code handles only list item click but no icon clicks
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class ListViewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
ListView lvData;
DB db;
SimpleCursorAdapter scAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
db = new DB(this);
db.open();
String[] from = new String[]{DB.COLUMN_IMG, DB.COLUMN_TXT, DB.COLUMN_IMG2};
int[] to = new int[]{R.id.list_label, R.id.list_text, R.id.list_star};
scAdapter = new SimpleCursorAdapter(this, R.layout.list_item, null, from, to, 0);
lvData = (ListView) findViewById(R.id.list);
lvData.setAdapter(scAdapter);
getSupportLoaderManager().initLoader(0, null, this);
lvData.setOnItemClickListener(mOnListItemClickListener);
}
final Context context = this;
protected void onDestroy() {
super.onDestroy();
db.close();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle bndl) {
return new MyCursorLoader(this, db);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
scAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
static class MyCursorLoader extends CursorLoader {
DB db;
public MyCursorLoader(Context context, DB db) {
super(context);
this.db = db;
}
#Override
public Cursor loadInBackground() {
Cursor cursor = db.getAllData();
return cursor;
}
}
private AdapterView.OnItemClickListener mOnListItemClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Cursor cursor = (Cursor) scAdapter.getItem(position);
switch (v.getId()) {
case R.id.list_star:
Toast.makeText(getApplicationContext(), "star", Toast.LENGTH_SHORT).show();
case R.id.list_label:
Toast.makeText(getApplicationContext(), "label", Toast.LENGTH_SHORT).show();
}
ImageView star = (ImageView) findViewById(R.id.list_star);
star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Вы выбрали стихи Агнии Барто", Toast.LENGTH_SHORT).show();
}
});
Intent intent = new Intent(context, ViewPagerActivity.class);
String pos = Long.toString(position);
intent.putExtra("pos", pos);
startActivity(intent);
}
};
}

Related

setListAdapter() Gone Wrong

When I try to use setListAdapter to show my data this happens:
Cannot resolve method setListAdapter
This is my Activity:
package id.sch.smktelkom.www.crud;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class CollectionActivity extends AppCompatActivity implements
FetchCollectListener {
String[] daftar;
ListView listView;
protected Cursor cursor;
Button search;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
Button btn=(Button)findViewById(R.id.button2);
search = (Button) findViewById(R.id.cari);
initView();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inte = new Intent(CollectionActivity.this, MainActivity.class);
startActivity(inte);
}
});
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent c = new Intent(CollectionActivity.this, SearchV.class);
startActivity(c);
}
});
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(CollectionActivity.this, "", "Loading...");
String url = "http://192.168.4.5/SqliteSync/readC.php";
FetchCollection task = new FetchCollection(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
And this is my Adapter:
package id.sch.smktelkom.www.crud;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.List;
public class CollectAdapter extends ArrayAdapter<Collect> {
private List<Collect> items;
private Context mContext;
public CollectAdapter(Context context, List<Collect> items) {
super(context, R.layout.item_collect, items);
this.items = items;
mContext = context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.item_collect, null);
}
Collect app = items.get(position);
if(app != null) {
TextView id = (TextView) v.findViewById(R.id.txtpeminjam);
TextView name = (TextView) v.findViewById(R.id.txtpinjaman);
ImageButton btn = (ImageButton) v.findViewById(R.id.list_image);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent b = new Intent(mContext,LihatDataActivity.class);
mContext.startActivity(b);
}
});
if(id != null) id.setText(app.getNama());
if(name != null) name.setText(app.getPinjaman());
}
return v;
}
}
I don't know what's wrong with this and it's annoying me already.
I want to retrieve data from MySQL to my Android app and when I type setListAdapter suddenly it becomes red and shows some error.
Appreciate any help.
Instead of setListAdapter(adapter); call listView.setAdapter(adapter);
setListAdapter works for activities extending ListActivity
I see also that you should add in onCreate this:
ListView listView=(ListView)findViewById(R.id.listView);
if the name of the ListView is listView in xml
So after some advice from #AmitVikramSingh
I'm referencing my listview
public class CollectionActivity extends AppCompatActivity implements FetchCollectListener {
String[] daftar;
ListView listView;
protected Cursor cursor;
Button search;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection);
Button btn=(Button)findViewById(R.id.button2);
search = (Button) findViewById(R.id.cari);
listView = findViewById(R.id.list);
And I change this from
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
To this
#Override
public void onFetchComplete(List<Collect> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
CollectAdapter adapter = new CollectAdapter(this, data);
// set the adapter to list
listView.setAdapter(adapter);
}
Big thanks to all who help me solving this problem

.setOnItemClicklistener not works

I would like to send my data from one activity to other with help of intent and uri but the task doesnt get accomplished
my main activity code
package com.example.vidit.inventoryapp;
import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ListView;
import static android.R.attr.id;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
/** Identifier for the pet data loader */
private static final int ITEM_LOADER = 0;
/** Adapter for the ListView */
ItemCursorAdapter mCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,editor.class);
startActivity(intent);
}
});
ListView ItemListView = (ListView) findViewById(R.id.list);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
ItemListView.setEmptyView(emptyView);
// Setup an Adapter to create a list item for each row of pet data in the Cursor.
// There is no pet data yet (until the loader finishes) so pass in null for the Cursor.
mCursorAdapter = new ItemCursorAdapter(this, null);
ItemListView.setAdapter(mCursorAdapter);
// Setup the item click listener
ItemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Create new intent to go to {#link EditorActivity}
Intent intent = new Intent(MainActivity.this,editor.class);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
intent.setData(itemUri);
startActivity(intent);
}
});
// Kick off the loader
getLoaderManager().initLoader(ITEM_LOADER, null, this);
}
private void insertPet() {
// Create a ContentValues object where column names are the keys,
// and Toto's pet attributes are the values.
ContentValues values = new ContentValues();
values.put(ItemContract.ItemEntry.NAME, "Football");
values.put(ItemContract.ItemEntry.PRICE, 200);
values.put(ItemContract.ItemEntry.STATUS, ItemContract.ItemEntry.ACCEPTED);
values.put(ItemContract.ItemEntry.QUANTITY, 7);
// Insert a new row for Toto into the provider using the ContentResolver.
// Use the {#link PetEntry#CONTENT_URI} to indicate that we want to insert
// into the pets database table.
// Receive the new content URI that will allow us to access Toto's data in the future.
Uri newUri = getContentResolver().insert(ItemContract.ItemEntry.CONTENT_URI, values);
}
/**
* Helper method to delete all pets in the database.
*/
private void deleteAllPets() {
int rowsDeleted = getContentResolver().delete(ItemContract.ItemEntry.CONTENT_URI, null, null);
Log.v("CatalogActivity", rowsDeleted + " rows deleted from pet database");
}
#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_main, 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;
}
return super.onOptionsItemSelected(item);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
ItemContract.ItemEntry._ID,
ItemContract.ItemEntry.NAME,
ItemContract.ItemEntry.PRICE,
ItemContract.ItemEntry.QUANTITY,
};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
ItemContract.ItemEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mCursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
My adapter class:
package com.example.vidit.inventoryapp;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import static android.R.attr.id;
import static android.R.attr.order;
import static android.R.attr.value;
import static android.os.Build.VERSION_CODES.M;
public class ItemCursorAdapter extends CursorAdapter {
public ItemCursorAdapter(Context context, Cursor c) {
super(context, c, 0 /* flags */);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate a list item view using the layout specified in list_item.xml
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) view.findViewById(R.id.name);
TextView priceTextView = (TextView) view.findViewById(R.id.price);
final TextView quantityTextView = (TextView) view.findViewById(R.id.quantity);
Button sell=(Button) view.findViewById(R.id.sell);
Button order=(Button) view.findViewById(R.id.order);
Button detail =(Button) view.findViewById(R.id.detail);
// Find the columns of pet attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.NAME);
int priceColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.PRICE);
int quantityColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry.QUANTITY);
// Read the attributes from the Cursor for the current pet
String itemName = cursor.getString(nameColumnIndex);
String itemPrice = cursor.getString(priceColumnIndex);
final String itemQuantity=cursor.getString(quantityColumnIndex);
if (TextUtils.isEmpty(itemPrice)) {
itemPrice = "Not known yet";
}
if (TextUtils.isEmpty(itemQuantity)) {
itemPrice = "Not known yet";
}
final int qua=Integer.parseInt(itemQuantity);
nameTextView.setText(itemName);
priceTextView.setText(itemPrice);
quantityTextView.setText(itemQuantity);
sell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Integer.parseInt(itemQuantity)>0)
{
int x=Integer.parseInt(itemQuantity)-1;
quantityTextView.setText("" + x);
int idColumnIndex = cursor.getColumnIndex(ItemContract.ItemEntry._ID);
int id = cursor.getInt(idColumnIndex);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
ContentValues values = new ContentValues();
values.put(ItemContract.ItemEntry.QUANTITY, x);
context.getContentResolver().update(itemUri, values, null, null);
}
}
});
order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","abc#gmail.com", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
context.startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
});
/* view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context,editor.class);
Uri itemUri = ContentUris.withAppendedId(ItemContract.ItemEntry.CONTENT_URI, id);
intent.setData(itemUri);
context.startActivity(intent);
}
});*/
}
}
if I add intent code which i have commented in adapter class itnet happens succesfully but no data is passed from list view to the intent .
Thanks in advance.

How to do switch case statement to display ListView in Android

I newbie in this field.
my application have 6 buttons with different category. when i click on one of the button it will go to another page for displaying listView for particular category in my database.
my problem is, I don't know how do switch case for this method.
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
I want to include getCategoryHall, getCategoryFacilty,and getCategoryAdmin in this QSFacultyLocation.java. so that, i no need to create another activity merely to get getCategoryHall, getCategoryFacilty,and getCategoryAdmin (listView).Because it just using same coding.
below is my full code for:
QSFacultyLocation.java
package com.example.ukmlocationsearching;
import java.util.ArrayList;
import java.util.List;
import com.example.ukmlocationsearching.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class QSFacultyLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qs_faculty_location);
final Intent c = new Intent(QSFacultyLocation.this, QSLocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
/*SearchKategori searchKategori = new SearchKategori();
UkmLocation selectedKategori = searchKategori.getSelectedKategori();
List<UkmLocation> locationList = null;*/
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
//------------------------------------------------------------------
// Determine list POI with category
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
//------------------------------------------------------------------
// Closing db (if any)
// db.close();
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
QuickSearchMenu.java
package com.example.ukmlocationsearching;
import java.io.IOException;
import com.example.ukmlocationsearching.R;
import com.example.ukmlocationsearching.R.id;
import com.example.ukmlocationsearching.R.layout;
import com.example.ukmlocationsearching.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearchMenu extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//---------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search_menu);
View faculty = findViewById(R.id.button2);
faculty.setOnClickListener(this);
View researchInstitute = findViewById(R.id.button1);
researchInstitute.setOnClickListener(this);
View college = findViewById(R.id.button3);
college.setOnClickListener(this);
View admin = findViewById(R.id.button4);
admin.setOnClickListener(this);
View facility = findViewById(R.id.button5);
facility.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search_menu, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Intent b1 = new Intent(this, QSResearch.class);
startActivity(b1);
break;
case R.id.button2:
Intent b2 = new Intent(this,QSFacultyLocation.class);
startActivity(b2);
break;
/*case R.id.button3:
Intent b3 = new Intent(this,QuickSearchCollege.class);
startActivity(b3);
break;
case R.id.button4:
Intent b4 = new Intent(this,QuickSearchFaculty.class);
startActivity(b4);
break;
case R.id.button5:
Intent b5 = new Intent(this,QuickSearchCollege.class);
startActivity(b5);
break;*/
}
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
/*Log.d("Initiate", "Kategori Count: " + myDbHandler.getKategoriCount());
Log.d("Initiate", "KategoriPoi Count: " + myDbHandler.getKategoriPoiCount());*/
myDbHandler.close();
}
//------------------------------------------------------------------------------
}
please do help me solve this. thank you
First,pass a query or simply any key value such as department id or department name as an intent with each button click using
intentname.putExtra(keyname_used_to_retrieve_value,value_to_be_passed_to_next_activity);
case R.id.button1:
String query="select * from table_name where something='xyz'";
Intent b1 = new Intent(this, QSResearch.class);
b1.putExtra("myextrakey",query);
startActivity(b1);
Then, receive the intent in the onCreate method of list activity as follows,initialise database and call user defined mylist() and setuplist() functions
Intent i=getIntent();
String x=i.getStringExtra("myextrakey");//this assigns the query to string x
//open database here
mylist();//call myList function which i have defined in the following lines
setUpList();//call setUpList function which i have defined in the following lines
This is the myList function:
private void myList() {
myownlist= new ArrayList<String>();
Cursor myCursor = database.rawQuery(x,null);
myCursor.moveToFirst();
if(!myCursor.isAfterLast()) {
do {
//selects data in column 2 to be displayed on list
String listitem= myCursor.getString(2);
myownlist.add(listitem);
} while (myCursor.moveToNext());
}
myCursor.close();
}
This is the setUpList() function:
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myownlist));
ListView lv = getListView();
}

OnListItemClick in an activity

In my Android app I have a list of countries that I can add new entries to at any time when the app is running. This list is held in a database. I have tried several different ways of trying to implement an OnListItemClick but I cannot get it to work. Here is my class containing my list:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends Activity
{
private DBManager db;
Cursor cursor;
Button goEdit;
ListView listContent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.initial_activity);
listContent = (ListView)findViewById(R.id.list);
goEdit = (Button)findViewById(R.id.goedit);
//Open database
db = new DBManager(this);
db.openToRead();
cursor = db.queueAll();
String[] from = new String[]{DBManager.KEY_ID, DBManager.KEY_YEAR, DBManager.KEY_CONTENT, DBManager.KEY_DESC};
int[] to = new int[]{R.id.editcountry, R.id.yeartext, R.id.countrytext};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
//go to add/delete screen
goEdit = (Button)findViewById(R.id.goedit);
goEdit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Log.i("Test", "Now moving to the edit activity");
Intent intent = new Intent(MainActivity.this, EditList.class);
startActivity(intent);
}
});
}
//life cycles
protected void onPause()
{
super.onPause();
db.close();
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
finish();
}
}
Here is my class where I can choose to enter new countries into the list:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class EditList extends Activity
{
private DBManager db;
Cursor cursor;
EditText editCountry, editYear, editDesc;
Button add, delete, back;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editCountry = (EditText)findViewById(R.id.editcountry);
editYear = (EditText)findViewById(R.id.edityear);
editDesc = (EditText)findViewById(R.id.editdesc);
add = (Button)findViewById(R.id.add);
delete = (Button)findViewById(R.id.delete);
back = (Button)findViewById(R.id.backmain);
//Open database and fill it with content, then close it
db = new DBManager(this);
db.openToWrite();
cursor = db.queueAll();
add.setOnClickListener(buttonAddOnClickListener);
delete.setOnClickListener(buttonDeleteAllOnClickListener);
//handle switching back to main screen
Log.i("Test", "back to main");
back = (Button)findViewById(R.id.backmain);
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
db.close();
//can't use "finish()" because then the list won't refresh with the new data
Log.i("Test", "Going back to the main screen");
Intent intent = new Intent(EditList.this, MainActivity.class);
startActivity(intent);
}
});
}
//insert new country button
Button.OnClickListener buttonAddOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Added!", Toast.LENGTH_LONG).show();
int year = Integer.parseInt(editYear.getText().toString());
String country = editCountry.getText().toString();
String desc = editDesc.getText().toString();
db.insert(year, country, desc);
updateList();
//clear text fields after use
editYear.setText(null);
editCountry.setText(null);
editDesc.setText(null);
}
};
//delete all button
Button.OnClickListener buttonDeleteAllOnClickListener = new Button.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Your list has been deleted!", Toast.LENGTH_LONG).show();
db.deleteAll();
updateList();
}
};
private void updateList()
{
cursor.requery();
}
#Override
protected void onDestroy()
{
super.onDestroy();
db.close();
finish();
}
}
I have previously implemented an OnListItemClick in a class where the data was statically held in an array. That class also extended ListActivity, which this one doesn't.
The difference between ListActivity and a standard Activity is that the ListActivity handled the OnItemClickListener interface mapping for you, and just provided an extra callback method. Without ListActivity, you'll need to add that plumbing yourself; i.e.
public class MainActivity extends Activity implements AdapterView.OnItemClickListener
{
...
ListView listContent;
#Override
public void onCreate(Bundle savedInstanceState)
{
...
listContent.setOnItemClickListener(this);
...
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//Callback logic here for clicked items
}
...
}
In your MainActivity add
#Override
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
// a list item is click do whatever you want
}

Android Database Help ( How do I add a delete button )

I have been following a datababse tutorial of commonsware which is the LunchList example, however i would love to know how i can add a delete button, so that i could delete a lunch item once its been created.
I have searched around and found this answer but i'm just not sure how to implement it, please could someone show me how
Add a delete() method to the RestaurantHelper class and call it from
an options menu item on the DetailForm activity.
Thanks
Lucy
ResaurantHelper.java
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
class RestaurantHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="Lunchlist.db";
private static final int SCHEMA_VERSION=1;
public RestaurantHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// no-op, since will not be called until 2nd schema
// version exists
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY name",
null));
}
public void insert(String name, String address,
String type, String notes) {
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("address", address);
cv.put("type", type);
cv.put("notes", notes);
getWritableDatabase().insert("restaurants", "name", cv);
}
public String getName(Cursor c) {
return(c.getString(1));
}
public String getAddress(Cursor c) {
return(c.getString(2));
}
public String getType(Cursor c) {
return(c.getString(3));
}
public String getNotes(Cursor c) {
return(c.getString(4));
}
}
LunchList.java
package apt.tutorial;
import android.app.TabActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
public class LunchList extends TabActivity {
Cursor model=null;
RestaurantAdapter adapter=null;
EditText name=null;
EditText address=null;
EditText notes=null;
RadioGroup types=null;
RestaurantHelper helper=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helper=new RestaurantHelper(this);
name=(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.addr);
notes=(EditText)findViewById(R.id.notes);
types=(RadioGroup)findViewById(R.id.types);
address.setVisibility(View.GONE);
notes.setVisibility(View.GONE);
Button save=(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);
ListView list=(ListView)findViewById(R.id.restaurants);
model=helper.getAll();
startManagingCursor(model);
adapter=new RestaurantAdapter(model);
list.setAdapter(adapter);
TabHost.TabSpec spec=getTabHost().newTabSpec("tag1");
spec.setContent(R.id.restaurants);
spec.setIndicator("My Reasons", getResources()
.getDrawable(R.drawable.list));
getTabHost().addTab(spec);
spec=getTabHost().newTabSpec("tag2");
spec.setContent(R.id.details);
spec.setIndicator("Add Reason", getResources()
.getDrawable(R.drawable.restaurant));
getTabHost().addTab(spec);
getTabHost().setCurrentTab(0);
list.setOnItemClickListener(onListClick);
}
#Override
public void onDestroy() {
super.onDestroy();
helper.close();
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
String type=null;
switch (types.getCheckedRadioButtonId()) {
case R.id.sit_down:
type="sit_down";
break;
case R.id.take_out:
type="take_out";
break;
case R.id.delivery:
type="delivery";
break;
}
helper.insert(name.getText().toString(),
address.getText().toString(), type,
notes.getText().toString());
model.requery();
}
};
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id) {
model.moveToPosition(position);
name.setText(helper.getName(model));
address.setText(helper.getAddress(model));
notes.setText(helper.getNotes(model));
if (helper.getType(model).equals("sit_down")) {
types.check(R.id.sit_down);
}
else if (helper.getType(model).equals("take_out")) {
types.check(R.id.take_out);
}
else {
types.check(R.id.delivery);
}
getTabHost().setCurrentTab(1);
}
};
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor c) {
super(LunchList.this, c);
}
#Override
public void bindView(View row, Context ctxt,
Cursor c) {
RestaurantHolder holder=(RestaurantHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
RestaurantHolder holder=new RestaurantHolder(row);
row.setTag(holder);
return(row);
}
}
static class RestaurantHolder {
private TextView name=null;
private TextView address=null;
private ImageView icon=null;
RestaurantHolder(View row) {
name=(TextView)row.findViewById(R.id.title);
address=(TextView)row.findViewById(R.id.address);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Cursor c, RestaurantHelper helper) {
name.setText(helper.getName(c));
address.setText(helper.getAddress(c));
if (helper.getType(c).equals("sit_down")) {
icon.setImageResource(R.drawable.ball_red);
}
else if (helper.getType(c).equals("take_out")) {
icon.setImageResource(R.drawable.ball_yellow);
}
else {
icon.setImageResource(R.drawable.ball_green);
}
}
}
}
Add a new Button (btnDelete) to your layout-xml
mount it in your code using Button btnDel =(Button)findViewById(R.id.btnDelete);
Add a clickListener on it using:
btnDel.setOnClickListener)new OnClickListener()
{
#Override
public void onClick(View v)
{
//add SQL deletion code here
}
});
And final execute the SQL deletion statement in the onClickListener ;)
If you can check a matching ID, this could work
db.execSQL("DELETE FROM restaurants WHERE id = '+" idToDelete "+' ;");
I am fairly certain that you need to carry on with the tutorials. Having watched Commons_Ware (the book's author and extremely active member here) on the site I doubt he will leave you hanging. I am quite certain he teaches the complete CRUD model one step at a time.
As a side note, if you haven't purchased a subscription to his books, I highly recomend it. They are updated frequently to include the latest info.
Rather than using execSQL() for deletion, use following :
To delete entire table:
db.delete(DATABASE_TABLE, null, null);
To delete particular records in a table:
db.delete(DATABASE_TABLE, whereCondition, null);
for eg:
db.delete(restaurants, "id = '"+ IdToBeDeleted +"'", null);

Categories

Resources