Click an item from database displayed in listview - java

package at.thesis.ticmip;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Mainadminvdictionary extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String ddct = Databaseadapter.dtbldctnry;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_vdictionary);
SQLiteDatabase db= openOrCreateDatabase(Databaseadapter.DATABASE_NAME,MODE_PRIVATE, null);
try {
Cursor c= db.rawQuery("select * from Ddictionary", null);
//Looping through all rows
if (c != null ) {
if (c.moveToFirst()) {
do {
String dss = c.getString(c.getColumnIndex("disease"));
results.add(dss);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
db.close();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
}
i have my code here that will show the data and display in listview my problem now is how can i click an item by its id? I tried using protected void onListItemClick(ListView l, View v, int position, long id) {} but its not working

Try this :
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});

this work for me
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) getListAdapter().getItem(position);
if (position == 0) {
Toast.makeText(Mainadminvdictionary.this, item + " selected", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Mainadminvdictionary.this, Mainuserstop10.class); startActivity(intent);
}
}
});

Related

How to refresh or update a fragment after deleting from the database

I am new to android development, and i'm trying to build a simple hymn book,
I'm using bottom navigation, i use fragments on each tab to display numbers and titles of each hymn.
In my favourite fragments i have a list of favourite songs displayed using recycler view fetch from the database.
I use on long click listener to delete songs from the favorite table in the database, but any time i delete a
song my favorite fragment doesn't get refreshed or undated with current items. Please, how can I refresh or update
my favourite fragment anytime i delete a song. thank you!
'''Favourite Adapter''
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.ViewHolder> {
private Context favContext;
private ArrayList<String> favNumbers = new ArrayList<>();
private ArrayList<String> favTitles = new ArrayList<>();
public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles) {
this.favContext = favContext;
this.favNumbers = favNumbers;
this.favTitles = favTitles;
}
#Override
public FavouriteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favourite_list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final FavouriteAdapter.ViewHolder holder, final int position) {
holder.textViewFavNum.setText(favNumbers.get(position));
holder.textViewFavTitle.setText(favTitles.get(position));
final String hymn_no = favNumbers.get(position);
holder.itemView.setTag(favNumbers.get(position));
holder.favParentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i;
i = new Intent(view.getContext(), Songs.class);
i.putExtra("numId", favNumbers.get(position));
i.putExtra("titleName", favTitles.get(position));
favContext.startActivity(i);
}
});
holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete from favorites?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
try{
SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);
favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");
Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
#Override
public int getItemCount() {
return favNumbers.size();
}
#Override
public long getItemId(int position){
return position;
}
#Override
public int getItemViewType(int position){
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewFavNum;
public TextView textViewFavTitle;
RelativeLayout favParentLayout;
public ViewHolder(View itemView) {
super(itemView);
textViewFavNum = (TextView) itemView.findViewById(R.id.textViewFavNum);
textViewFavTitle = (TextView) itemView.findViewById(R.id.textViewFavTitle);
favParentLayout = (RelativeLayout) itemView.findViewById(R.id.favParentLayout);
}
}
}
'''favourite fragment'''
import android.app.FragmentManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.logging.Handler;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {#link Fragment} subclass.
*/
public class Favourites extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<String> favSongNumbers = new ArrayList<>();
private ArrayList<String> favSongTitles = new ArrayList<>();
private TextView favMessage;
public Favourites() {
// Required empty public constructor
}
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(view == null) {
view = inflater.inflate(R.layout.fragment_favourites, container, false);
favMessage = (TextView) view.findViewById(R.id.favMessage);
recyclerView = (RecyclerView) view.findViewById(R.id.favRecyclerView);
// adapter.setHasStableIds(true);
Toast.makeText(this.getActivity(), "Long press to delete hymns from favorites", Toast.LENGTH_LONG).show();
initFavSongs();
}
return view;
}
private void initFavSongs(){
try{
favMessage.setText("");
SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);
Cursor c = favHymns.rawQuery("SELECT hymnNum, hymnTitle FROM favorites", null);
int hymnNumIndex = c.getColumnIndex("hymnNum");
int hymnTitleIndex = c.getColumnIndex("hymnTitle");
if(c.moveToFirst()) {
while (c != null) {
favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
favSongTitles.add(" " + c.getString(hymnTitleIndex));
c.moveToNext();
}
}else{
favMessage.setText("Oops!No favorite songs added yet.");
}
}catch (Exception e){
e.printStackTrace();
}
initRecyclerView();
}
private void initRecyclerView(){
adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
}
}
Pass a listener to the adapter and invoke it at the time of item delete from database. Then update your list and as well as your adapter.Like this way:
First create a listener:
public interface UpdateListener {
void onValueChangedListener();
}
Initialize the listener in Adapter class that comes from fragment.
private UpdateListener updateListener;
public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles,UpdateListener updateListener ) {
this.favContext = favContext;
this.favNumbers = favNumbers;
this.favTitles = favTitles;
this.updateListener=updateListener;
}
holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete from favorites?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
try{
SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);
favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");
Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
// when any item delete from database notify the fragment through this
// listener for updating your adapter
updateListener.onValueChangedListener();
}catch(Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
// this method is needed for updating your adapter
public void update(ArrayList<String> favNumbers, ArrayList<String> favTitles){
this.favNumbers = favNumbers;
this.favTitles = favTitles;
}
Implement the listener in your fragment and reinitialize your list.
public class Favourites extends Fragment implements UpdateListener {
private void initRecyclerView(){
// pass listener
adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles,this);
}
private void updateFavSongs(){
favSongNumbers.clear;
favSongTitles.clear;
try{
favMessage.setText("");
SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);
Cursor c = favHymns.rawQuery("SELECT hymnNum, hymnTitle FROM favorites", null);
int hymnNumIndex = c.getColumnIndex("hymnNum");
int hymnTitleIndex = c.getColumnIndex("hymnTitle");
if(c.moveToFirst()) {
while (c != null) {
favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
favSongTitles.add(" " + c.getString(hymnTitleIndex));
c.moveToNext();
}
}else{
favMessage.setText("Oops!No favorite songs added yet.");
}
}catch (Exception e){
e.printStackTrace();
}
adapter.update(favSongNumbers,favSongTitles);
adapter.notifyDataSetChanged()
}
#Override
public void onValueChangedListener(){
updateFavSongs();
}
}

CalendarFragment cannot be cast to android.support.v4.app.LoaderManager$LoaderCallbacks

java.lang.ClassCastException: com.amira.amira.amira.ChatCalendarProfile.Calendar.CalendarFragment cannot be cast to android.support.v4.app.LoaderManager$LoaderCallbacksat com.amira.amira.amira.ChatCalendarProfile.Calendar.CalendarFragment.onCreateView(CalendarFragment.java:63)
enter image description here
i want to load the description of alert in fragment
package com.amira.amira.amira.ChatCalendarProfile.Calendar;
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.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import com.amira.amira.amira.ChatCalendarProfile.Calendar.data.AlertContract;
import com.amira.amira.amira.R;
import static com.amira.amira.amira.ChatCalendarProfile.Calendar.data.AlertContract.*;
public class CalendarFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int ALERT_LOADER = 0;
AlertCursorAdapter mCursorAdapter;
public CalendarFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_calendar_fragment, container, false);
com.github.clans.fab.FloatingActionButton addAlert = rootView.findViewById(R.id.add_alert);
addAlert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), EditorActivity.class);
startActivity(intent);
}
});
ListView AlertListView = (ListView) rootView.findViewById(R.id.list);
View emptyView = rootView.findViewById(R.id.empty);
AlertListView.setEmptyView(emptyView);
mCursorAdapter = new AlertCursorAdapter(getActivity(), null);
AlertListView.setAdapter(mCursorAdapter);
AlertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(getActivity(), EditorActivity.class);
Uri currentAlertUri = ContentUris.withAppendedId(AlertEntry.CONTENT_URI, id);
intent.setData(currentAlertUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(ALERT_LOADER, null, this);
return rootView;
}
private void insertAlert() {
ContentValues values = new ContentValues();
values.put(AlertEntry.COLUMN_ALERT_TITLE, "Title");
values.put(AlertEntry.COLUMN_ALERT_LOCATION, "Terrier");
values.put(AlertEntry.COLUMN_ALERT_OCCASION_DATE, " ");
values.put(AlertEntry.COLUMN_ALERT_OCCASION_TIME, " ");
values.put(AlertEntry.COLUMN_ALERT_REMINDER_DATE, " ");
values.put(AlertEntry.COLUMN_ALERT_REMINDER_TIME, " ");
Uri newUri = getActivity().getContentResolver().insert(AlertEntry.CONTENT_URI, values);
}
private void deleteAllAlerts() {
int rowsDeleted = getActivity().getContentResolver().delete(AlertEntry.CONTENT_URI, null, null);
//Log.v("CatalogActivity", rowsDeleted + " rows deleted from pet database");
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
AlertEntry._ID,
AlertEntry.COLUMN_ALERT_TITLE,
AlertEntry.COLUMN_ALERT_LOCATION,
AlertEntry.COLUMN_ALERT_OCCASION_DATE,
AlertEntry.COLUMN_ALERT_OCCASION_TIME};
return new CursorLoader(getActivity(), // Parent activity context
AlertEntry.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 cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
Please init the loader in onActivityCreated(..) method in the fragment.. it will hopefully solve your issue
First override the method and the then initialize it there

Refresh a Loader when data is changed - android

I user LoaderManager and CursorLoader to load the data from my database using a ContentProvider.
Now, the initial load is fine. I have a ListView that display all the rows from the DB(only the names-String adapter).
Now, when I add/delete a row from the database, I want to refresh the ListView so it will display the recent changes.
Currently I just restart the loader with the method "restartLoader" whenever a change is commited but I want to ask if there is another way of doing this without restarting the loader.
Here is my activity class code:
package com.silverfix.phony.activities;
import java.util.ArrayList;
import com.silverfix.phony.R;
import com.silverfix.phony.contentprovider.PhonyContentProvider;
import com.silverfix.phony.database.RingtonesTable;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
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.provider.MediaStore;
import android.text.Editable;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class RingtonesActivity extends Activity implements LoaderCallbacks<Cursor>{
private final int PICK_RINGTONE_CODE = 1;
private final int CURSOR_LOADER_ID = 1;
private final int EDIT_ID = 1;
private final int DELETE_ID = 2;
private String[] ContextCommands;
private ArrayAdapter<String> adapter;
private ArrayList<String> ringtones;
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtones);
listview = (ListView) findViewById(R.id.list);
Button add = (Button) findViewById(R.id.add_ringtone);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_RINGTONE_CODE);
}
});
fillData();
}
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
super.onActivityResult(arg0, arg1, arg2);
switch (arg0) {
case 1: // PICK_RINGTONE_CODE
if (arg1 == RESULT_OK) {
Uri ringtoneURI = arg2.getData();
String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(ringtoneURI,
projection, null, null, null);
cursor.moveToFirst();
int column = cursor
.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
String displayName = cursor.getString(column);
addRingtone(ringtoneURI, displayName);
cursor.close();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ringtones, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fillData() {
getLoaderManager().initLoader(CURSOR_LOADER_ID, null, this);
ringtones = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ringtones);
ContextCommands = getResources().getStringArray(R.array.commands);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
editRingtone();
}
});
registerForContextMenu(listview);
listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(ContextCommands[info.position]);
String[] menuItems = getResources().getStringArray(R.array.commands);
menu.add(Menu.NONE, EDIT_ID, 0, menuItems[0]);
menu.add(Menu.NONE, DELETE_ID, 0, menuItems[1]);
}
}
});
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case EDIT_ID:
editRingtone();
return true;
case DELETE_ID:
String name = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
getContentResolver().delete(PhonyContentProvider.RINGTONES_URI, RingtonesTable.COLUMN_NAME
+ "='" + name + "'", null);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void editRingtone() {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_RINGTONE_CODE);
}
private void addRingtone(Uri uri, String name) {
String[] projection = { RingtonesTable.COLUMN_NAME };
Cursor cursor = getContentResolver().query(
PhonyContentProvider.RINGTONES_URI, projection,
RingtonesTable.COLUMN_NAME + "='"+name+"'", null, null);
if (cursor.getCount() == 0) {
ContentValues values = new ContentValues();
values.put(RingtonesTable.COLUMN_NAME, name);
values.put(RingtonesTable.COLUMN_URI, uri.toString());
getContentResolver().insert(PhonyContentProvider.RINGTONES_URI,
values);
getLoaderManager().restartLoader(CURSOR_LOADER_ID, null, this);
} else {
Toast.makeText(this, "You already picked that ringtone!",
Toast.LENGTH_LONG).show();
cursor.close();
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {RingtonesTable.COLUMN_ID, RingtonesTable.COLUMN_NAME, RingtonesTable.COLUMN_URI};
return new CursorLoader(this, PhonyContentProvider.RINGTONES_URI, projection, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
swapCursor(null);
}
private void swapCursor(Cursor cursor) {
if(cursor != null) {
cursor.moveToFirst();
ringtones.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int column = cursor.getColumnIndex(RingtonesTable.COLUMN_NAME);
ringtones.add(cursor.getString(column));
}
adapter.notifyDataSetChanged();
cursor.close();
return;
}
ringtones.clear();
adapter.notifyDataSetChanged();
}
}
Since you already have access to the loader, you may not expect that much of a change, but another way of implementing this is by having the cursor setting PhonyContentProvider.RINGTONES_URI as its notification uri and notifying the uri whenever the database data changes.
Relevant methods:
setNotificationUri
notifyChange

How to load an specific activity (multiple intent) on filter ListView- Item-Click?

There no error, but when i click a item of listview nothing happen. I have more than 10 items. and go to difference activities. Any idea? I'am beginner in eclipse also java.
Example:
1.Niat (ListView-OnItemClickListener) will go to NiatActivity.class
2.Lafaz (ListView-OnItemClickListener) will go to LafazActivity.class
Here my code. Thanks in advance.
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainTwoActivity extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_two);
// Listview Data
final String products[] = { "Niat",
"Lafaz", "Solat" };
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item,
R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
MainTwoActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// if(position == 1)
String openClass = adapter.getItem(position);
if (openClass.equals("Niat")) {
// code specific to first list item
Intent myIntent = new Intent(view.getContext(),
NiatActivity.class);
startActivity(myIntent);
}
else if (openClass.equals("Lafaz")) {
Intent myIntent1 = new Intent(view.getContext(),
LafazActivity.class);
startActivity(myIntent1);
}
}
});
}
}
Use Reflection is better but also u can use of Hashmap
Use OF HashMap
HashMap<String, Class>hashMap=new HashMap<String, Class>();
hashMap.put("Niat",NiatActivity.class);
hashMap.put("Lafaz",LafazActivity.class);
hashMap.put("Solat",SolatActivity.class);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String openClass = adapter.getItem(position);
Intent myIntent1 = new Intent(MainTwoActivity.this,
hashMap.get(openClass));
startActivity(myIntent1);
}
MaWhen starting a new activity you should use
Intent myIntent = new Intent(MainTwoActivity.this ,NiatActivity.class);
View getContext() doesnt carry the full context of your app. Read up here

how to make a clickable listview

Ok. I'm working on a project, I have already created the listview, but I want to click on it and go to another page e.g like when you click a button it goes to another page, exactly like that, this is my code so far:
import android.app.ListActivity;
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 listV extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter( new ArrayAdapter<String>(this, R.layout.listview,Food));
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(), Toast.LENGTH_SHORT).show();
}
});
}
static final String[] Food = new String[]{
"Physical Activity" , "Healthy Diet", "Childhood Obesity"
};
}
Any help would be appreciated.
I'm just a beginner so please try to explain in detail.
Looks like you're 95% of the way there. In your onItemClick method of the listener, you just have to start the new activity like you normally would. You can use the 3rd argument of the onItemClick to give you the position of the listview item that was click and use that to differentiate the activity you call OR pass it into a single activity:
#Override
public void onItemClick(AdapterView<?> arg0, View position, int arg2, long arg3) {
Intent i;
if( position == 1 ){
i = new Intent(listV.this, MyFirstActivity.class);
} else if (position == 2){
i = new Intent(listV.this, MySecondActivity.class);
} else if (position == 3) {
i = new Intent(listV.this, MyThirdActivity.class);
} else {
return;
}
startActivity(i);
}
I am a fairly new programmer myself and I am attempting to create the same thing. A ListView where the user is able to click each individual item in the list and each item will start its own activity. Please check out my code based on the help you gave earlier.
package com.tylerbmc.test;
import android.app.ListActivity;
import android.content.Intent;
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;
public class Main extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.abdominals)));
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i;
if (position == 1) {
i = new Intent(Main.this, Second.class);
startActivity(i);
}
else if (position == 2) {
i = new Intent(Main.this, Third.class);
startActivity(i);
}
}
});
}
}

Categories

Resources