List Items not working - java

I made a simple list which calls other activities when a ListItem is clicked, but it is not working for me. When I click, nothing shows up. WHat is wrong ? Here is the code:
String classes[]={"StartingPoint","Splash", "ex1","ex2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese = classes[position];
try
{
Class ourclass = Class.forName("com.alfred.splashscreenwithsound." + cheese);
Intent myintent = new Intent(this,ourclass);
startActivity(myintent);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}

I think you haven't implemented OnItemClickListener
Try the below code
//Declare your listView here
yourlistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent callActivity = new Intent(CurrentActivity.this,NextActivity.class);
startActivity(callActivity);
}
});
}
Hope it helps

Related

How to spend a remote image of a listview to another layout , to just click on that item ? ... In Android Studio

I made a listview of my server that sends images to a smartphone and the code I have works up there, the result is this :
Now I want to do that when you click on an item in the list, see the complete image in another layout and only get this by using intents.
I do not understand how to pass parameters in the onItemClick method. Please if someone tells me the solution.
The code is this :
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ProgressDialog progressDialog;
ArrayList asuntos=new ArrayList();
ArrayList imagen=new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
listView=(ListView) findViewById(R.id.list);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
lista o=new lista();
o.obtenerAvisos();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Visor.class);
startActivity(intent);
}
});
}
public class lista {
public void obtenerAvisos() {
asuntos.clear();
imagen.clear();
String tag_string_req = "req_data";
progressDialog.setMessage("Conectando...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppURLs.URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
asuntos.add(jsonArray.getJSONObject(i).getString("asunto"));
imagen.add(jsonArray.getJSONObject(i).getString("publicacion"));
}
listView.setAdapter(new ImagenAdaptador(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "data");
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
public class ImagenAdaptador extends BaseAdapter {
Context ctx;
LayoutInflater layoutInflater;
SmartImageView smartImageView;
TextView tvasunto;
public ImagenAdaptador(Context applicationContext) {
this.ctx=applicationContext;
layoutInflater=(LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return imagen.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup viewGroup=(ViewGroup) layoutInflater.inflate(R.layout.activity_main_items,null);
smartImageView=(SmartImageView)viewGroup.findViewById(R.id.imagen1);
tvasunto=(TextView) viewGroup.findViewById(R.id.tvAsunto);
String urlfinal="http://192.168.43.45/xxxx/xxxxx/"+imagen.get(position).toString();
Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
smartImageView.setImageUrl(urlfinal, rect);
tvasunto.setText(asuntos.get(position).toString());
return viewGroup;
}
}
}
Note: Use these libraries:
com.mcxiaoke.volley:library:1.0.19
and
com.github.snowdream.android:smartimageview:0.0.2
In this case you don't need to , you already have access to "imagen arrayList" :
public static final string ARG_IMAGE_URL = "URL";
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Visor.class);
intent.putExtras(ARG_IMAGE_URL, imagen.get(position))
startActivity(intent);
}
});
But you will have to think of a strategy to avoid reloading the image from the network that would be a waste of resources.
Okay thanks so are the lines . Although this method had to move to the getView ImagenAdaptador class method :
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup viewGroup=(ViewGroup) layoutInflater.inflate(R.layout.activity_main_items,null);
smartImageView=(SmartImageView)viewGroup.findViewById(R.id.imagen1);
tvasunto=(TextView) viewGroup.findViewById(R.id.tvAsunto);
final String urlfinal="http://192.168.43.45/InfoTec/publicaciones/"+imagen.get(position).toString();
Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
smartImageView.setImageUrl(urlfinal, rect);
tvasunto.setText(asuntos.get(position).toString());
**listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Visor.class);
intent.putExtra("arg", urlfinal);
startActivity(intent);
}
});**
return viewGroup;
}
For taking the ArrayList where they were not sent anything, the image variable is processed in this method of ImagenAdaptador class. Everything seemed fine only now visualize the last picture but click on any of the others, always sends the photo of Heineken. What happens now?

Navigating back to FragmentPagerAdapter the listFragment is empty

I don't see the ListFrangment on FragmentPageAdapter after reload the fragment.
I have a sliding menu with 3 options, when I click a one options, the fragment change for FragmentPageAdapter and load the ListFragment in a tab.
The problem starts When I click again in the same option... the fragment change but the loaded fragment is empty, any list...
Does anyone know that can happen?
the code is:
is a code exemple..
The code on call a FragmentPageAdapter...
public class MyListaCompra extends Fragment {
View gv;
private static final String[] CONTENT = new String[] {"Pendientes","Realizadas" };
public static Intent newInstance(Activity activity,int pos) {
Intent intent = new Intent(activity, MyListaCompra.class);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("Truiton FragmentList", "CREO LA VISTA");
gv = inflater.inflate(R.layout.inicio,container, false);
gv.setBackgroundResource(android.R.color.white);
FragmentPagerAdapter adapter = new GoogleMusicAdapter(getActivity().getSupportFragmentManager());
ViewPager pager = (ViewPager) gv.findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) gv.findViewById(R.id.indicator);
indicator.setViewPager(pager);
return gv;
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Log.i("Truiton FragmentList", "ESTOY EN PAUSE");
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.i("Truiton FragmentList", "ESTOY EN RESUME");
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Log.i("Truiton FragmentList", "VistaDestruida!");
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
getActivity().getMenuInflater().inflate(R.menu.menu, menu);
}
class GoogleMusicAdapter extends FragmentPagerAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FragmentListaPendiente.init(position);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override
public int getCount() {
return CONTENT.length;
}
}
}
The code on inflate a FragmentPageAdapter with ListFragment
public class FragmentListaPendiente extends ListFragment{
int fragNum;
private Bundle savedState = null;
String arr[] = { "dates","exemple","1" };
public static FragmentListaPendiente init(int val) {
FragmentListaPendiente truitonList = new FragmentListaPendiente();
// Supply val input as an argument.
Bundle args = new Bundle();
args.putInt("val", val);
truitonList.setArguments(args);
return truitonList;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
fragNum = getArguments() != null ? getArguments().getInt("val") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.list,null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, arr));
this.getListView().setTextFilterEnabled(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("Truiton FragmentList", "Item clicked: " + id);
}
}
Thanks
I investigate for this question and I solve the problem....
the problem is:
FragmentPagerAdapter adapter = new GoogleMusicAdapter(getActivity().getSupportFragmentManager());
For solve this problem:
FragmentPagerAdapter adapter = new GoogleMusicAdapter(getChildFragmentManager());
information source:
FragmentPagerAdapter inside Fragment
Navigating back to FragmentPagerAdapter -> fragments are empty
Thanks =)

setOnClickListener on child elements in ListView?

I am trying to attach an OnClickListener on the child elements in a custom list view.The class that I am using extends ListActivity. In my custom list view I have two text views and a button. I need to attach an OnClickListener on each of them. The following is my code.
final ListView listview = getListView();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
callBut= (Button)listview.getChildAt(position);
callBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Call Phone","");
}
});
}
But when I click on the child element Nothing is shown on the log.
You can atach a OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
change
callBut= (Button)listview.getChildAt(position);
to
callBut= (Button)findViewById(R.id.yourCallButton);

Set onItemClick to Custom adapter ListView

When I had problems trying to fix the position of my listView items to the desired intent when filtered, and got info I could override the problem using a custom adapter, I have done that but I do not know how to assign the clicks to each items, please check below code:
public class IndexPageActivity extends Activity {
ListView listView;
EditText editTextB;
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener((OnItemClickListener) this);
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements OnItemClickListener{
ArrayList<SingleRow> pagelist;
Context context;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<SingleRow>();
Resources res = c.getResources();
String [] pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(new SingleRow(pagedatas[i]));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public Object getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return row;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
// TODO Auto-generated method stub
}
}
I will appreciate any help given. Thank Yhu!
EDIT
Will this work?
if (index == 0) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page1.html");
startActivity(i);
} else if (index == 1) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page2.html");
startActivity(i);
Edited ALL
I just got what you need, I added a filter to your baseAdapter and then on text change within the editText You filter the listView and then you go to the activity needed.
here is the full code but you need to bare in mind that I have changed the following:
I changed the pageList to ArrayList instead of
There is a bug in filtering that when I erase what I wrote in the EditText it doesnt update the ListView, you need to figure out why.
I changed the returned value of the function getItem(int i) from Object to String
Within the onItemClick you have to search for the name instead of the position.
here is the code:
public class IndexPageActivity extends Activity implements OnItemClickListener{
ListView listView;
EditText editTextB;
PagesAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
adapter1 = new PagesAdapter(this);
listView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
listView.setOnItemClickListener(this);
editTextB.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
IndexPageActivity.this.adapter1.getFilter().filter(cs.toString());
adapter1.notifyDataSetChanged();
}
#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
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Intent i;
String name = adapter1.getItem(position);
Log.d("id", name);
if (name.equals("Item1"))
{
i = new Intent(this, anActivity.class);
startActivity(i);
}
else if (name.equals("Item2"))
{
i = new Intent(this, anActivity2.class);
startActivity(i);
}
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements Filterable{
ArrayList<String> pagelist;
List<String> arrayList;
Context context;
String [] pagedatas;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<String>();
Resources res = c.getResources();
pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(pagedatas[i]);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public String getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
String temp=pagelist.get(i);
pagetitle.setText(temp);
return row;
}
public class filter_here extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ){
Result.values = pagelist;
Result.count = pagelist.size();
return Result;
}
ArrayList<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString;
for(int i = 0; i<pagelist.size(); i++){
filterableString = pagelist.get(i);
if(filterableString.toLowerCase().contains(filterString)){
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
pagelist = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return new filter_here();
}
}
Two different ways for it:
1) If you want to use something like this at onCreate of your activity;
listView.setOnItemClickListener((OnItemClickListener) this);
You should implement OnItemClickListener to your activity:
IndexPageActivity extends Activity implements OnItemClickListener
and implement its onItemClick method at your activity. (also remove OnItemClickListener interface from your custom adapter)
2) You can simply use below without implementing OnItemClickListener to any class:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: handle row clicks here
}
I suggest 2nd option. That is easier.
Edit: This not relevant to your problem but you should reuse your views/rows at listView. Change your getView method to:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.single_row, parent, false);
} else {
view = convertView;
}
TextView pagetitle = (TextView) view.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return view;
}
Set your setOnItemClickListenerlike this:
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Your code here
//int position is the index of the list item you clicked
//use it to manipulate the item for each click
}
});
}

Spinner with on Click Listener

I am using spinner that shows error when i am trying to extract the item id of the selected spinner item.
My Code goes here:
public void dispspi()
{
spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter <String> adap= new ArrayAdapter(this, android.R.layout.simple_spinner_item, level);
spinner.setAdapter(adap);
spinner.setOnItemClickListener(new OnItemClickListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
int item = spinner.getSelectedItemPosition();
p=item;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
}
How to get the item id of the spinner? Any help is appreciated..Thanks in advance
IIRC, you should be using a selected listener, not click:
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
Then you can add the override tag to your selected method.
private String selecteditem;
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
selecteditem = adapter.getItemAtPosition(i).toString();
//or this can be also right: selecteditem = level[i];
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
}
});
spinner3.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int postion, long arg3) {
// TODO Auto-generated method stub
String SpinerValue3 = parent.getItemAtPosition(postion).toString();
Toast.makeText(getBaseContext(),
"You have selected 222 : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Yes you can use some OnItemSelectedListener for work with selected item. But sometimes we would like to handle exactly click for spinner. For example hide keyboard or send some analytics etc. In this case we should use TouchListener because OnClickListener doesn't work properly with Spinner and you can get error. So I suggest to use TouchListener like:
someSpinner.setOnTouchListener { _, event -> onTouchSomeSpinner(event)}
fun onTouchSomeSpinner(event: MotionEvent): Boolean {
if(event.action == MotionEvent.ACTION_UP) {
view.hideKeyBoard()
...
}
return false
}
you should have this in the listener(OnItemSelectedListener)
public void onNothingSelected(AdapterView<?> arg0) {
}
It might works without it but put it to be consistent
but there might be other errors also, can you provide the error log ?

Categories