Set the imageView src based on the value selected in a Spinner - java

I've been trying to set an ImageView (Default empty) based on the value selected from a Spinner.
So in the mainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp_home = (Spinner) findViewById(R.id.spinner_home_team);
sp_away = (Spinner) findViewById(R.id.spinner_away_team);
sp_home.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (!sp_home.getSelectedItem().toString().equals("Seleziona Squadra")) {
setTeamLogo(sp_home.getSelectedItem().toString(), "home");
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp_away.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
if (!sp_away.getSelectedItem().toString().equals("Seleziona Squadra")) {
setTeamLogo(sp_away.getSelectedItem().toString(), "away");
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
The setOnItemSelectedListener method works perfectly the problem comes when I execute the code inside setTeamLogo.
private void setTeamLogo(String teamName, String home_or_away_team){
int resId = getResources().getIdentifier(teamName, "drawable", getPackageName());
Toast.makeText(getBaseContext(), resId,
Toast.LENGTH_LONG).show();
}
The exception that has been thrown is:
android.content.res.Resources$NotFoundException: String resource ID #0x0
Any idea why if I use the name of the image instead of the variable teamName everything works perfectly?

Use String.valueOf()
If you pass it an integer it will try to look for the corresponding string resource id - which it can't find, which is your error.
check out this post:-
android.content.res.Resources$NotFoundException: String resource ID #0x0

Related

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
}
});
}

onItemLongClick is undefined?

I'm trying to implement a long click in my listview item but it doesn't work and i get an error that says is undefined. Here's the code:
protected void setOnItemLongClickListener(ListView l, View v, int position, long id) {
super.onItemLongClick(l, v, position, id);// Error
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
Someone has an idea how solve the problem?Thanks
The reason for this is most likely that you don't implement the listener. Something like
public class ActivityName extends Activity implements OnItemLongClickListener{
Try changing
protected void setOnItemLongClickListener
to
protected boolean setOnItemLongClickListener{
// your code
return true;
You need to use the proper return type for the method which is boolean then return true so the listener knows it was a success.
Docs
try this listener for Listview :
istView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(arg0.getContext(), ((TextView)arg1).getText(), Toast.LENGTH_SHORT).show();
return false;
}
});
use this code
yourListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//YOUR_CODE_HERE
return false;
}
});
Please replace
public class MainActivity extends Activity implements OnItemLongClickListener
and add unimplemented method
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
return false;
}
by default you can do this by right clicking on OnItemLongClickListener select Quick fix
try to add this lines to your list adapter
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return false;
}
});
and the method is try to overwrite your method
#Override
public boolean onItemLongClick(
AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
return false;
}

List Items not working

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

how to make radio button disappear on item select from spinner

rb1=(RadioButton)findViewById(R.id.radioButton1);
rb2=(RadioButton)findViewById(R.id.radioButton2);
rb3=(RadioButton)findViewById(R.id.radioButton3);
rb4=(RadioButton)findViewById(R.id.radioButton4);
rb5=(RadioButton)findViewById(R.id.radioButton5);
spiner1=(Spinner)findViewById(R.id.spinner1);
spiner2=(Spinner)findViewById(R.id.spinner1);
spiner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
This is my code there are 5 value in my spiner if i select first one then rb1,rb2,rb3,rb5 shud display and rest disappear if i select 2,3,4,5 value from spinner then it hud display 1st,4,5 plz tell me how to write code for this i m new in android try to implement some apps. i need code where and how to apply logic for this.
There are some demos about spinner
Here is an example.
you can set dropdown styles in this method
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Based on your condition or logic you can show/hide buttons.
rb1.setVisibility(View.VISIBLE); // show
rb2.setVisibility(View.INVISIBLE); // Hide
You can do this :
spiner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adView, View view,int pos, long id) {
selectedoption = adapter.get(pos);
if(selectedoption == rb1)
{
rb1.setVisibility(View.INVISIBLE);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

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