passing Intent from class which extends ListView - android

This is my class which is population items in a list view , things goins well , onItemClick method is executed when clicked on a listitem , but when i pass an intent from there , it is not passing the intent , plz help me out.
public class VideosListView extends ListView implements android.widget.AdapterView.OnItemClickListener {
private List<Video> videos;
private VideoClickListener videoClickListener;
MainActivity ma;
private Context mcontext;
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);
mcontext=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)
{
Intent intent = new Intent(mcontext,AnVideoView.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mcontext.startActivity(intent);
Log.i("VideoListView", "I am Clicked");
if(videoClickListener != null)
{
videoClickListener.onVideoClicked(videos.get(position));
Log.d("My Position ","position is" + position);
}
this is my classsnow from onItemClick() i want to pass to a activity class , how to do that thanx helping

Try This...
It will help you.
Activity activity;
public VideosListView(Activity activity) {
super(context);
this.activity=activity;
}
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id)
{
Intent intent = new Intent(activity,AnVideoView.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
Log.i("VideoListView", "I am Clicked");
if(videoClickListener != null)
{
videoClickListener.onVideoClicked(videos.get(position));
Log.d("My Position ","position is" + position);
}

in onItemClick((AdapterView adapter, View v, int position, long id)
i have created a contructor to the class extending BaseAdapter , and then from the there we can easily pass our intent... it is working for me , anyways thaks helping me a lot guys
we can pass the position in the contructor , and do whatever we want to do with the item selected.

Related

StartActivityForResoult on ListViewItem click Android

I have an activity lets call it Activity 1 and there we will have a ListView composed by Player objetcs. When you click on a ListView_item (on a Player) a new activity starts, lets call it Activity 2. What I want is:
Activity 1 sends to Activity 2 player's name and player's race. In Activity 2 the user could edit that (player's name and player's race) and when the user click on Confirm Ativity 2 sends to Activity 1 the player's name and player's race even I the user has not edited it (in that case it would send the previus that Activity 1 has sended to Activity 2).
The problem is that when I'm suposse to use startActivityForResult I'm into ListViewAdapter class and using context.start... startActivityForResult doesn't appears.
public class AdaptadorJugadores extends BaseAdapter implements ListAdapter {
private ArrayList<Jugador> list = new ArrayList<Jugador>();
private Context context;
public AdaptadorJugadores(ArrayList<Jugador> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_lista_jugadores, null);
}
//Handle TextView and display string from your list
TextView TextoNombreJugador = (TextView)view.findViewById(R.id.etNombreJugador);
TextoNombreJugador.setText(list.get(position).getNombre());
if (list.get(position).getGenero() == "Hombre"){
TextoNombreJugador.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_face_black_24dp, 0, 0, 0);
}else{
TextoNombreJugador.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_face_black_girl24dp, 0, 0, 0);
}
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.btEliminarJugador);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
/*addBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});*/
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(context, VistaJugador.class);
intent.putExtra("Nombre",(list.get(position).getNombre()));
intent.putExtra("Genero",(list.get(position)).getGenero());
// Start SingleItemView Class
}
});
return view;
}
}
You could use the ListView's setOnItemClickListener(AdapterView.OnItemClickListener listener) method and in there you could start the activity using startActivityForResult.
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the data to pass to the activity based on the position clicked
Intent intent = new Intent(...);
intent.setExtra(...);
startActivityForResult(...);
}
});
Alternatively, you could pass the Activity to your adapter and use that instead of a context, but the first solution is preferable.
I suggest you to pass the context from the Activity to the Adapter, then store it in a local variable. After that, you can just use it to startActivityForResult, but note that you have to implement the onActivityResultMethod. My suggestion is that you use an interface, then pass the ID of the selected item and call the startActivityForResult() in the Activity.

On Item Click Listener for List View extending ArrayAdapter

What I have tried:
public class EntryAdapter extends ArrayAdapter<Item> {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
// // // // NON-FUNCTIONING CODE BELOW
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getContext(), NewsItemActivity.class);
convertView.getContext().startActivity(intent);
}
};
}
The AdapterView.onItemClickListener doesnt yield any errors but doesnt seem to function whatsoever.
What is the proper way of setting this onClick Listener?
Note: I have to set it in this adapter class, not the main class for my own reasons.
You shuldn't implement a listener inside the getView() unless you what set a listener on a particular view inside your row layout.
You should instead use setOnItemClickListener() method on your ListView:
ListView lv = (ListView) findViewById(R.id.your_listview);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(context, NewsItemActivity.class);
context.startActivity(intent);
}
});
EDIT:
If, for each action inside the onclick, you need information that resides in your Objects (Item) then you can get it in this way:
Item item = (Item)listview.getAdapter().getItem(position);
from inside of onItemClick() method
You can use:
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Make what you want
}
});
Or depending on your item view, you can make the OnCLickListener on your global layout of the item or a specific item's layout
Try by this code :-
Spinner cb_tv;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> dataAdapter;
list.add(phone1);
list.add(name1);
dataAdapter = new ArrayAdapter<String>(Display_Tank.this,android.R.layout.simple_spinner_item, list);
cb_tv.setAdapter(dataAdapter);
cb_tv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Clicked",Toast.LENGTH_SHORT).show();
}
});
at the place of cb_tv Spinner You can use ListView
First of all, the best way to achieve this is to use your own ViewHolders in ListView.
This is an example of a custom ViewHolder
class MyViewHolder extends ViewHolder implements View.OnItemClickListener {
public MyViewHolder(View view) {
/* Implement your views here
* like this: mTextView = (TextView) view.findViewById(R.id.myId);
*/
view.setOnItemClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), NewsItemActivity.class);
convertView.getContext().startActivity(intent);
}
}
And on your getView method you create this ViewHolder and populate your Views with your data.
You can try this way... it is working in my case Change your context to
Activity activity = (Activity) context;
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity, NewsItemActivity.class);
activity.startActivity(intent);
}
});

Android onclick listener custom listview

With the following code I'm correctly receiving a dynamic list from mysql db and putting the elements in a listview.
public class MenuActivity extends ListActivity implements FetchDataListener {
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
initView();
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading..");
String url = "http://www.*********.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(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();
}
This is my array adapter:
public class ApplicationAdapter extends ArrayAdapter<Application>{
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.app_cat_list, items);
this.items = items;
}
#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.app_cat_list, null);
}
Application app = items.get(position);
if(app != null) {
TextView titleText = (TextView)v.findViewById(R.id.titleTxt);
if(titleText != null) titleText.setText(app.getTitle());
}
return v;
}
Now I want to click on single row and open another activity passing some values via intent extra.
Where should I implement click listener?
I'm pretty sure it should be inserted in the "getView" but how I pass the app.getTitle() via intent? I know how pass intent extra in general, tried but no click happens.
Any help would be appreciated, thanks
Now I want to click on single row and open another activity passing
some values via intent extra. Where should I implement click listener?
No need to add OnItemClickListener because extending ListActivity in MenuActivity so just override onListItemClick method for handing ListView row click:
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
// your code here...
}
how I pass the app.getTitle() via intent?
Get selected row TextView value in onListItemClick using view parameter:
TextView txtView=(TextView)v.findViewById(R.id.titleTxt);
String selectedText=txtView.getText().toString();
Use selectedText for sending value with Intent in Next Activity
Put this in your getView()
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent =new Intent(context, YourActivity.class);
context.startActivity(intent);
}
});
There can be multiple ways and following is one of them:
Set onItemClickListner on your listview in your activity and it will give you a callback i.e onListItemClick. But as you said you want the title their you have to set tag on the convertView in the getView method like covertView.setTag("itemTitle"); and in your onListItemClick get the tag from view and convert it to the title like this v.getTag().toString(); and set it any where you want.
follwoing is the full code:
#Override
public void onListItemClick(ListView l, View view, int position, long id) {
String title = view.getTag().toString();
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("title", title);
startActivity(intent);
// your code here... }
Please post if got stuck anywhere.

How to find whether if user clicked spinner in Android?

In my application I am creating spinner dynamically in code.I want to force user to click on Spinner and change its value/content. Otherwise user should not be able to go to next screen by clicking Next button.
How to do that in Android? Anybody has any idea?
Thanks in Advance.
Rohan
you can use this:
if (spin.getSelectedItemPosition() < 0) {//Do something}
this means user hasn't selected anything.
Let the Spinner's first value be something like "-please select-".
when the user clicks on the next button perform validation and check whether the value of the selectedItem in the spinner is "-please select-" and if yes, then display a toast and ask the the user to select something from the spinner.
you need code, let me know.
Use this code for checking the spinner item is selected or not.
both flags take at class level (Globally).
Boolean temp = false;
Boolean check = false;
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(temp){
check = true;
}
temp = true;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
check = false;
}
});
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(check){
//perform when user select spinner item
}else{
//put Dialog for alert please select spinner item
}
}
}
Call your Intent for the next Activity in the Click Listener of that spinner
Create one boolean global variable like..
boolean isSelect = false;
Now when user select value from spinner then make it isSelect = false. And when user click on NEXT button check condition for isSelect is true or false.
That's it.
You can get the selected item value by using the following method.
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (spinner.getSelectedItem().toString().equals("YourValue")) {
Intent yourIntent = new Intent(this,YourClassName.class);
startActivity(yourIntent);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
In my case I added an extra item on first position of the list
1."Select Something"
2."Go next"
3."Go Previous"
5....
6..
then in use
String item=spinnerObject.getSelectedItem ();
now check if("Select Something".equels(item)){
show some dialog to select anything from spinner
}else{
send it to next screen
}
I made a new Spinner class encapsulating the above mentioned principles. But even then you have to make sure to call the correct method and not setSelection
Same thing in a gist
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
/**
* Used this to differentiate between user selected and prorammatically selected
* Call {#link Spinner#programmaticallySetPosition} to use this feature.
* Created by vedant on 6/1/15.
*/
public class Spinner extends android.widget.Spinner implements AdapterView.OnItemSelectedListener {
OnItemSelectedListener mListener;
/**
* used to ascertain whether the user selected an item on spinner (and not programmatically)
*/
private boolean mUserActionOnSpinner = true;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mListener != null) {
mListener.onItemSelected(parent, view, position, id, mUserActionOnSpinner);
}
// reset variable, so that it will always be true unless tampered with
mUserActionOnSpinner = true;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
if (mListener != null)
mListener.onNothingSelected(parent);
}
public interface OnItemSelectedListener {
/**
* <p>Callback method to be invoked when an item in this view has been
* selected. This callback is invoked only when the newly selected
* position is different from the previously selected position or if
* there was no selected item.</p>
*
* Impelmenters can call getItemAtPosition(position) if they need to access the
* data associated with the selected item.
*
* #param parent The AdapterView where the selection happened
* #param view The view within the AdapterView that was clicked
* #param position The position of the view in the adapter
* #param id The row id of the item that is selected
*/
void onItemSelected(AdapterView<?> parent, View view, int position, long id, boolean userSelected);
/**
* Callback method to be invoked when the selection disappears from this
* view. The selection can disappear for instance when touch is activated
* or when the adapter becomes empty.
*
* #param parent The AdapterView that now contains no selected item.
*/
void onNothingSelected(AdapterView<?> parent);
}
public void programmaticallySetPosition(int pos, boolean animate) {
mUserActionOnSpinner = false;
setSelection(pos, animate);
}
public void setOnItemSelectedListener (OnItemSelectedListener listener) {
mListener = listener;
}
public Spinner(Context context) {
super(context);
super.setOnItemSelectedListener(this);
}
public Spinner(Context context, int mode) {
super(context, mode);
super.setOnItemSelectedListener(this);
}
public Spinner(Context context, AttributeSet attrs) {
super(context, attrs);
super.setOnItemSelectedListener(this);
}
public Spinner(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
super.setOnItemSelectedListener(this);
}
public Spinner(Context context, AttributeSet attrs, int defStyle, int mode) {
super(context, attrs, defStyle, mode);
super.setOnItemSelectedListener(this);
}
}

Moving Activity to another Activity when class extends ArrayAdapter

When I click the edit_remainder button I want to move my Activity to another Activity.
But where the class extends ArrayAdapter I don't understand how to move to another Activity.
Please help me with an example of the Intent class.
public class mylist extends ArrayAdapter<String> implements OnClickListener
{
private final Context context;
private final String[] values;
Button edit_remainder;
public mylist(Context context, String[] values) {
super(context, R.layout.some, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.buttonadd, parent, false);
edit_remeinder=(Button) rowView.findViewById(R.id.btnEdit);
edit_remeinder.setOnClickListener(this);
return rowView;
}
public void onClick(View v) {
Toast.makeText(getContext(), "hi", 1000).show();
// please enter moving code here
}
}
If I understand correctly, you wish to transfer control to another activity when the user taps on a list item. You will need to issue an intent.
Here's a tutorial: http://www.vogella.com/articles/AndroidIntent/article.html
launch an explicit intent here like:
Intent i=new Intent(context,anotheractivity.class);
startActivity(i);
here the context could be the application context.
Are you create your own adapter(mylist)?
If yes then pass the intent in your main class from you call the mylist adapter.
here I created for listview ,but you can try for your own application.
pass the intent in your main activity instead of your own adapter.
mainActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, month, number); //here ListViewAdapter is my own adapter
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this,"Title => "+month[position]+"=> n Description"+number[position], Toast.LENGTH_SHORT).show();
// here your intent code
}
}
please put this onclick method in your main activity and try again.
public void onClick(View v) {
Toast.makeText(getContext(), "hi", 1000).show();
// please enter moving code here
}

Categories

Resources