Android Search ListView - java

i am using the ListView method to search in a custom listview. I have made an image and textview as elements to search. However, the edittext in which i used as the search bar cant properly filter my items but when tested using only text it works. Is there a way that my codes could be corrected? it doesn't show any errors. The Image Shown shows that when i try to filter T it doesn't show temasek ;instead it shows only the first two elements.
MainActivity.java:
public class MainActivity extends Activity {
String[] schools = { "Elias Park Primary",
"Anderson Secondary",
"Temasek JC",
"Republic Poly",
"Nanyang Poly" ,
"Meridian JC",
"Temasek Poly",
"Ngee Ann Poly",
"Anglican High"
};
Integer[] imageId = {
R.drawable.eliaspark_pri,
R.drawable.anderson_sec,
R.drawable.temasek_jc,
R.drawable.republic_poly,
R.drawable.nyp,
R.drawable.mjc,
R.drawable.tp,
R.drawable.ngee_ann,
R.drawable.anglican_high
};
ListView list;
custom adapter1;
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.list);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter1 = new custom(MainActivity.this, schools, imageId);
list.setAdapter(adapter1);
inputSearch.addTextChangedListener(new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
Log.i("Char Sqequence", ""+s);
MainActivity.this.adapter1.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
Custom Listview :
public class custom extends ArrayAdapter<String>{
private final Activity context ;
private final String[] schools ;
private final Integer[] imageId;
public custom(Activity context, String[] schools, Integer[] imageId){
super(context, R.layout.list1,schools);
this.context = context;
this.schools = schools;
this.imageId = imageId;
}
public View getView(int position, View view, ViewGroup parent){
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list1,null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(schools[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}}
XML Listview :
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
Custom ListView :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="match_parent"
/>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="match_parent"
/>

Related

How to use SearchView with Custom ArrayAdapter and ListView with sub items

I added SearchView to ActionBar to search items in ListView. I created my own ListView. But when I debug the app and search something, nothing shown. Which part did I do a mistake? Can someone help me?
ListView XML Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtKodu"
android:layout_width="257dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="26dp"
android:layout_marginTop="11dp"
android:text="Kodu"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtAciklama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/txtKodu"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="48dp"
android:layout_marginBottom="5dp"
android:text="Açıklama"
android:textSize="16sp" />
</RelativeLayout>
Here is my Custom List Adapter class
public class ListAdapter extends ArrayAdapter implements Filterable {
ListClass [] kayitliste;
int resource;
public ListAdapter(Context context, int resource, ListClass[] kayitliste) {
super(context, resource, kayitliste);
this.resource = resource;
this.kayitliste = kayitliste;
}
public ListClass[] getKayitliste() {
return kayitliste;
}
public void setKayitliste(ListClass[] kayitliste) {
this.kayitliste = kayitliste;
}
public int getResource() {
return resource;
}
public void setResource(int resource) {
this.resource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View satir;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
satir = inflater.inflate(resource , null);
TextView kodu , aciklama;
kodu = (TextView) satir.findViewById(R.id.txtKodu);
aciklama = (TextView) satir.findViewById(R.id.txtAciklama);
ListClass list = kayitliste[position];
kodu.setText(list.getKodu());
aciklama.setText(list.getAciklama());
return satir;
}
Here is my onCreate method and implementation
ListView lv;
ListAdapter adapter;
ListClass[] kayitlar;
public void InitData(){
kayitlar = new ListClass[]{
new ListClass("1" , "Example Record1"),
new ListClass("2" , "Example Record2"),
new ListClass("3" , "Example Record3"),
new ListClass("4" , "Example Record4"),
new ListClass("5" , "Example Record5"),
};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_servis_fisi);
lv = (ListView) findViewById(R.id.lvGrid);
InitData();
adapter = new ListAdapter(this , R.layout.customlist , kayitlar);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ServisFisi.this , KayitDetay.class);
startActivity(intent);
}
});
}
And here is my code in Activity.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search , menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView) item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}

Button in ListView not clickable

I want to click on a button inside an item of a ListView and it should have the same effect from clicking the whole item. But when I click button nothing happens, when I click image its all Okey. How to fix it?
I tried setting on the button:
android:focusable="true"
android:clickable="true"
I also experimented with android:descendantFocusability.
None of my tries made the buttons clickable.
my_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:descendantFocusability="blocksDescendants"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_toLeftOf="#+id/imageArrow"
android:layout_toStartOf="#+id/imageArrow"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageArrow"
android:layout_alignTop="#+id/button"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#drawable/r_arr" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
ListView listView = (ListView)findViewById(R.id.listView);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
MyCustomAdapter adapter = new MyCustomAdapter(this, values);
setListAdapter(adapter);
}
#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
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_SHORT).show();
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] names;
static class ViewHolder {
public TextView myButton;
public ImageView image;
}
public MyCustomAdapter(Activity context, String[] names) {
super(context, R.layout.my_item, names);
this.context = context;
this.names = names;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.my_item, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.myButton = (Button)rowView.findViewById(R.id.button);
viewHolder.image = (ImageView) rowView.findViewById(R.id.imageArrow);
viewHolder.myButton.setFocusable(false);
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
String s = names[position];
String abs=Integer.toString(position + 1);
holder.myButton.setText(s+ " number " + abs);
holder.image.setImageResource(R.drawable.r_arr);
return rowView;
}
}
Please write onclicklistener on your button.
You just have to configure onClick method something like this:
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//your code goes here
}
});
Put button click listener in your getView
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.my_item, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.myButton = (Button) rowView.findViewById(R.id.button);
viewHolder.image = (ImageView) rowView.findViewById(R.id.imageArrow);
viewHolder.myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Button click functionalty here
});
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
String s = names[position];
String abs=Integer.toString(position + 1);
holder.myButton.setText(s+ " number " + abs);
holder.image.setImageResource(R.drawable.r_arr);
return rowView;
}
}
To make your both listview item and button clickable, do this.
make ListView focusable android:focusable="true"
Button not focusable in your custom listview item android:focusable="false"
Method 1:
First replace button code in xml as below
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:focusable="false"
android:onClick="onClick"
android:focusableInTouchMode="false"
android:layout_toLeftOf="#+id/imageArrow"
android:layout_toStartOf="#+id/imageArrow"
/>
Then go to your activity and write code as below
public void onClick(View v)
{
super.onClick(v);
if (v.getId() == R.id.button)
{
//your code goes here
}
}
or You can add below peace of code in you oncreate
Method 2 :
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
It is not recommended to have two click listeners for a same row item in listview.
You can have in a Listview Custom Adapter. You can customize this according to your requirement.
or
You can have in your Activity / Fragment listview onclicklistener. This cannot be customized and when you click the whole row is selected.

ListView with custom ArrayAdapter setOnItemClickListener doesn't fire

I can't figure out why setOnItemClickListener doesn't work. I have ListView with custom ListItem layout,- and i'd like to start other activity when user click on row.
I saw lots of topic with this problem, but nothing helped.
Screen:
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/notes_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/addNote">
</ListView>
<TextView
android:id="#+id/empty_list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/empty_notes"
android:visibility="gone"
android:gravity="center"
android:layout_above="#+id/addNote"
/>
<Button
android:id="#+id/addNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/add_note"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- Note text-->
<TextView
android:id="#+id/noteText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold" />
<!-- Note createdAt -->
<TextView
android:id="#+id/noteCreatedAt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/noteText"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip" />
<!-- Note complete -->
<Button
android:id="#+id/btnCompleteNote"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Complete" />
</RelativeLayout>
RNoteAdapter.java:
public class RNoteAdapter extends ArrayAdapter<RNote> {
private Context context;
private int resource;
RNote[] data;
private RNoteRepository noteRepository;
public RNoteAdapter(Context context, int resource, RNote[] data) {
super(context, resource, data);
this.context = context;
this.resource = resource;
this.data = data;
this.noteRepository = new RNoteRepository(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RNoteHolder holder = null;
if(row == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(resource, parent, false);
holder = new RNoteHolder();
holder.noteText = (TextView)row.findViewById(R.id.noteText);
holder.noteCreatedAt = (TextView)row.findViewById(R.id.noteCreatedAt);
holder.btnCompleteNote = (Button)row.findViewById(R.id.btnCompleteNote);
row.setTag(holder);
} else {
holder = (RNoteHolder)row.getTag();
}
final RNote note = data[position];
if(note.IsCompleted) {
holder.noteText.setPaintFlags(holder.noteText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
holder.noteText.setText(note.Text);
DateFormat df = new SimpleDateFormat("dd.MM.yyyy в HH:mm");
holder.noteCreatedAt.setText(df.format(note.CreatedAtUtc));
holder.btnCompleteNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
note.IsCompleted = true;
noteRepository.save(note);
RNoteAdapter.this.notifyDataSetChanged();
}
});
return row;
}
static class RNoteHolder {
TextView noteText;
TextView noteCreatedAt;
Button btnCompleteNote;
}
}
MainActivity.java
public class MainActivity extends ActionBarActivity {
private RNoteRepository _noteRepository = new RNoteRepository(this);
private Button addButton;
private ListView notesList;
RNoteAdapter adapter;
private void init() {
notesList = (ListView)findViewById(R.id.notes_list);
addButton = (Button)findViewById(R.id.addNote);
notesList.setEmptyView(findViewById(R.id.empty_list_item));
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showEditNoteActivity(0);
}
});
notesList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showEditNoteActivity(id);
}
});
}
private void updateData() {
List<RNote> list = _noteRepository.getAll();
RNote[] array = list.toArray(new RNote[list.size()]);
adapter = new RNoteAdapter(this, R.layout.list_row, array);
notesList.setAdapter(adapter);
}
private void showEditNoteActivity(long noteId) {
Intent intent = new Intent(getApplicationContext(), EditNoteActivity.class);
intent.putExtra("noteId", noteId);
startActivityForResult(intent, 1);
}
private void showDialog(String text) {
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
String msg = data.getStringExtra("response");
showDialog(msg);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
#Override
protected void onResume() {
super.onResume();
updateData();
}
#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);
}
}
add
android:descendantFocusability="blocksDescendants"
to your ListView's row root.
The implementation of getItemId of ArrayAdapter returns position and not the id of your RNote, so you probably want to override it to make it return the correct information
set android:focusable="false"
android:focusableInTouchMode="false" to all the clickable views (like button or editText) in your listView item

Android app crashing on startup [duplicate]

This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have just started android app development..and while opening the following app it says "Unfortunately your app has crashed". Can anyone point out the error in this code.
fragmentmain.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffbb"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="85dp"
android:text="Info of Departments and Student Bodies"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="190dp" >
</ListView>
</LinearLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//adding items to list view
final ListView listview = (ListView) findViewById(R.id.listView);
String values[] = new String[]{"Departments" , "Student_bodies"};
final ArrayList<String> list = new ArrayList<String>();
for (int i=0 ; i < values.length; ++i){
list.add(values[i]);
}
ArrayAdapter<String> ap = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,values);
listview.setAdapter(ap);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (((TextView)arg1).getText().toString() == "Departments"){
startActivity(new Intent(MainActivity.this,Departments.class));
}
if (((TextView)arg1).getText().toString() == "Student_bodies"){
startActivity(new Intent(MainActivity.this,Student_bodies.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
it is just simple implementation of list view and implementing onClick() on its elements to go to different Activity.thankful if anyone points out mistakes.
Your layout file named FragmentMain but You using activity_main as parameter of setContentView() method. Try to change to setContentView(R.layout.FragmentMain);
Please remove code from onCreate() and added in onCreateView(), as you are using fragment.
And your listview is also define in fragment_main.xml ,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final ListView listview = (ListView) rootView.findViewById(R.id.listView);
String values[] = new String[]{"Departments" , "Student_bodies"};
final ArrayList<String> list = new ArrayList<String>();
for (int i=0 ; i < values.length; ++i){
list.add(values[i]);
}
ArrayAdapter<String> ap = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,values);
listview.setAdapter(ap);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (((TextView)arg1).getText().toString() == "Departments"){
startActivity(new Intent(MainActivity.this,Departments.class));
}
if (((TextView)arg1).getText().toString() == "Student_bodies"){
startActivity(new Intent(MainActivity.this,Student_bodies.class));
}
}
});
return rootView;
}

Cannot Reach Breakpoint / Intent Will Not Launch

I'm attempting to launch an intent in my Home.java:
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
It should be initiated by:
package com.idg.omv.ui;
import com.idg.omv.domain.Video;
public interface VideoClickListener {
public void onVideoClicked(Video video);
}
which is initiated by listView.setOnVideoClickListener(this); in my Home.java
However I cannot seem to reach onVideoClicked when setting a breakpoint in Home.java and I'm unsure why.
FULL SOURCE:
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
// A reference to our list that will hold the video details
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
public static final String API_KEY = "AIzaSyC0Te2pyooXzuyLaE6_SsFlITKCwjj55fI";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
private ViewPager mPager;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
String TAG = "DEBUG THIS";
String PLAYLIST = "idconex";
Activity activity;
int imageArray[];
String[] stringArray;
private OnPageChangeListener mPageChangeListener;
ImagePagerAdapter adapter = new ImagePagerAdapter();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ActionBar actionBar = getActionBar();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
// get list items from strings.xml
drawerListViewItems = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerListView = (ListView) findViewById(R.id.left_drawer);
// Set the adapter for the list view
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
//mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
listView = (VideosListView) findViewById(R.id.videosListView);
// Here we are adding this activity as a listener for when any row in
// the List is 'clicked'
// The activity will be sent back the video that has been pressed to do
// whatever it wants with
// in this case we will retrieve the URL of the video and fire off an
// intent to view it
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, PLAYLIST).execute();
}
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
// This is the interface method that is called when a video in the listview
// is clicked!
// The interface is a contract between this activity and the listview
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns
// true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter(Activity act, int[] mImages,
String[] stringArra) {
imageArray = mImages;
activity = act;
stringArray = stringArra;
}
// this is your constructor
public ImagePagerAdapter() {
super();
// setOnPageChangeListener(mPageChangeListener);
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn };
private String[] stringArray = new String[] { "vevo",
"TheMozARTGROUP‎", "TimMcGrawVEVO‎", "TiestoVEVO‎",
"EminemVEVO‎" };
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Home.this;
ImageView imageView = new ImageView(context);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private final ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(final int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
mCurrentTabPosition = position;
}
};
protected void onTabChanged(final PagerAdapter adapter,
final int oldPosition, final int newPosition) {
// Calc if swipe was left to right, or right to left
if (oldPosition > newPosition) {
// left to right
} else {
// right to left
View vg = findViewById(R.layout.home);
vg.invalidate();
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
int oldPos = viewPager.getCurrentItem();
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
if (position > oldPos) {
// Moving to the right
} else if (position < oldPos) {
// Moving to the Left
View vg = findViewById(R.layout.home);
vg.invalidate();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
VideoListView.java
public class VideosListView extends ListView implements android.widget.AdapterView.OnItemClickListener {
private List<Video> videos;
private VideoClickListener videoClickListener;
public VideosListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VideosListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VideosListView(Context context) {
super(context);
}
public void setVideos(List<Video> videos){
this.videos = videos;
VideosAdapter adapter = new VideosAdapter(getContext(), videos);
setAdapter(adapter);
// When the videos are set we also set an item click listener to the list
// this will callback to our custom list whenever an item it pressed
// it will tell us what position in the list is pressed
setOnItemClickListener(this);
}
// Calling this method sets a listener to the list
// Whatever class is passed in will be notified when the list is pressed
// (The class that is passed in just has to 'implement VideoClickListener'
// meaning is has the methods available we want to call)
public void setOnVideoClickListener(VideoClickListener l) {
videoClickListener = l;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
}
// When we receive a notification that a list item was pressed
// we check to see if a video listener has been set
// if it has we can then tell the listener 'hey a video has just been clicked' also passing the video
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
if(videoClickListener != null){
videoClickListener.onVideoClicked(videos.get(position));
}
}
}
My Source:
https://www.dropbox.com/s/irab3x18nhj4twt/idg.zip
Working Example:
http://blog.blundell-apps.com/click-item-in-a-listview-to-show-youtube-video/
If the List has clickable elements like ImageViewand Button, when you click on the list it is consumed by the ImageView and Button and your onitemClickListener is never called.
To make it work add android:clickable="false", android:focusable="false" and
android:focusableInTouchMode="false" to each of those Buttons and ImageViews in custom adapter view.
list_item_user_video.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.idg.omv.ui.widget.UrlImageView
android:id="#+id/userVideoThumbImageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/black"
android:contentDescription="YouTube video thumbnail"
android:gravity="center"
android:scaleType="fitCenter"
android:src="#drawable/ic_launcher"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
<View android:layout_width="match_parent"
android:layout_height="2dp"
android:visibility="invisible"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/userVideoTitleTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft = "5dip"
android:textSize="16sp"
android:text="Video Title Not Found"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/userVideouploaderTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="13sp"
android:paddingLeft = "5dip"
android:layout_below="#id/userVideoTitleTextView"
android:textColor="#android:color/black" />
<Button
android:id="#+id/fav_up_btn1"
android:layout_width="27dp"
android:layout_height="27dp"
android:layout_alignParentRight="true"
android:background="#drawable/fav_up_btn1"
android:gravity="right"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"/>
</RelativeLayout>
<View android:layout_width="match_parent"
android:layout_height="11dp"
android:visibility="invisible"/>
</LinearLayout>
Checkout this article for more info
List view doesn't respond to click

Categories

Resources