I'm trying to get into a listview items have different action when pressed, this action depends on a variable "state", but the problem is that all the items are in the same action, here the code:
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
// Storing JSON item in a Variable
String codigo = c.getString(TAG_CODIGO);
String asignatura = c.getString(TAG_NOMBRE);
int estado = c.getInt("estado");
final int maxhoras = c.getInt("maxhoras");
final String idprogramacion = c.getString("programacionid");
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CODIGO, codigo);
map.put(TAG_NOMBRE, asignatura);
jsonlist.add(map);
list=(ListView)findViewById(R.id.lvclases);
ListAdapter adapter = new SimpleAdapter(Bienvenida.this, jsonlist,
R.layout.listview,
new String[] { TAG_CODIGO,TAG_NOMBRE, }, new int[] {
R.id.codigo, R.id.nombre,
});
list.setAdapter(adapter);
if(estado == 1) {
Log.e("estado", ""+estado);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", idprogramacion);
i.putExtra("maxhoras", maxhoras);
startActivity(i);
/*Toast toast1 = Toast.makeText(getApplicationContext(), "Correcto: el usuario existe", Toast.LENGTH_SHORT);
toast1.show();*/
//Toast.makeText(Bienvenida.this, "You Clicked at " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
}
});
}else{
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + jsonlist.get(+position).get("asignatura"), Toast.LENGTH_SHORT).show();
}
});
}
}
I am working on android studio, I appreciate the help
Acually, this is not an answer to your question. But after watching your code it seems that you are not implementing ListView in a correct way.
A simple way to work with ListView goes through following abstract steps:
Make your Collection Ready -> Prepare the Adapter from the collection -> Set this adapter to ListView
In your case, assuming you are calling web services for getting data and your web services is responding with JSON array.
Now, make a POJO(plain old Java object) class like:
public class MyListItem{
private String codigo;
private String asignatura;
private int estado;
private int maxhoras;
private String idprogramacion;
public MyListItem(String codigo, String asignatura, int estado, int maxhoras, String idprogramacion){
this.codigo = codigo;
this.asignatura = asignatura;
this.estado = estado;
this.maxhoras = maxhoras;
this.idprogramacion = idprogramacion;
}
// you can write getter setter methods for this
public int get_estado(){
return estado;
}
public String get_idprogramacion(){
return idprogramacion;
}
public int get_maxhoras(){
return maxhoras;
}
public String get_asignatura(){
return asignatura;
}
}
Now, prepare list like:
ArrayList<MyListItem> mArrayList = new ArrayList<>();
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
mArrayList.Add(
new MyListItem(
c.getString(TAG_CODIGO),
c.getString(TAG_NOMBRE),
c.getInt("estado"),
c.getInt("maxhoras"),
c.getString("programacionid")
)
);
}
Now, you are ready with list, just pass it to your custom adapter. If you are not aware of preparing Custom Adapter, check this link.
Once you are ready with making custom adapter, pass the list to this adapter like:
MyCustomAdapter adapter = new MyCustomAdapter(context, mArrayList);
Note: Above line strictly depends constructor of your custom adapter, say, MyCustomAdapter
After that, you are ready with your adapter, set it to your ListView, like:
list.setAdapter(adapter);
Now, here you set the OnItemClickListener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
MyListItem item = (MyListItem)parent.getItem(position);
if(item.get_estado() == 1)
{
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", item.get_idprogramacion());
i.putExtra("maxhoras", item.get_maxhoras());
startActivity(i);
}
else{
Toast.makeText(Bienvenida.this, "la clase aún no ha comenzado " + item.get_asignatura(), Toast.LENGTH_SHORT).show();
}
}
});
Hope you get what you are trying to achieve..
This should help you out.
Instead of having two different onClickListeners(), try using only one and move your if-else block inside of the onItemClick() method
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(estado == 1) {
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", idprogramacion);
i.putExtra("maxhoras", maxhoras);
startActivity(i);
} else {
// Do something else
}
}
});
Problem is estado variable, it's global varible, so When you use listview.setOnItemClickListener(...) that mean all the item in listview will be the same action with your above code.
Solution is you should create your own custom adapter and then implement OnItemClickListener in your adapter, base on different states to set different actions for item . Also you can setOnClickListener in getView() in Adapter and base on state also.
Please refer as below :
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int estado = -1;
// you should do something like this
/* ********** */
YourItem item = ((YourItemsData)data).get(position);
estado = item.getState();
/* ********** */
if(estado == 1) {
Intent i = new Intent(Bienvenida.this, registroAsistencia.class);
i.putExtra("programacion", idprogramacion);
i.putExtra("maxhoras", maxhoras);
startActivity(i);
} else {
// Do something else
}
}
});
Related
I have a spinner which populates data after an API call. I need to add an item that says "select one" as a first item in spinner. This item should not be able to be selected. I tried several ways online, but not able to implement it in my code since the array is filled after the api call and couldn't figure out a correct way to add "select one" item to that array.. Could anyone tell me how to do this in my code?
public void TEMPLATE_PARSE(JSONArray array) {
TemplateArrayList = new ArrayList<>();
TemplateNames = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) {
JSONObject json = null;
try {
json = array.getJSONObject(i);
ModelTemplate GetTemplateDataModel = new ModelTemplate();
GetTemplateDataModel.setTemplateID(json.getInt("TemplateID"));
GetTemplateDataModel.setTemplateText(json.getString("TemplateText"));
TemplateArrayList.add(GetTemplateDataModel);
TemplateNames.add(TemplateArrayList.get(i).getTemplateText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
} // Close for loop here
if (array.length() != 0) {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, simple_spinner_item, TemplateNames);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinTemplate.setAdapter(spinnerArrayAdapter);
spinTemplate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.i("ssssmIsSpinnerFirstCall",mIsSpinnerFirstCall.toString());
if(!mIsSpinnerFirstCall) {
selectedTemplateID = TemplateArrayList.get(position).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position).getTemplateText();
editText.setText(selectedTemplateText);
saveInSp("selectedTemplateID", String.valueOf(selectedTemplateID));
templateSelected = true;
}
mIsSpinnerFirstCall = false;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
First add Select One at position 0 to TemplateNames and then create adapter and set it to Spinner
TemplateNames.add(0, "Select One");
And then inside onItemSelected, check selected position and do whatever you want.
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position == 0)
// Skip or show validation message if you want
else {
// Do your actual task here
...
selectedTemplateID = TemplateArrayList.get(position - 1).getTemplateID();
String selectedTemplateText = TemplateArrayList.get(position - 1).getTemplateText();
...
}
}
I have this private method to render a spinner in a fragment:
private void renderSpinner() {
List<String> spinnerArray = new ArrayList<String>();
for (int i = 0; i<mPromotionList.size(); i++) {
ModelPromotion modelPromotion = (ModelPromotion) mPromotionList.get(i);
String name_promotion = modelPromotion.getName();
int id_promotion = modelPromotion.getIdPromotion();
spinnerArray.add(name_promotion);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(mBaseApp, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerPromotion.setAdapter(adapter);
mSpinnerPromotion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String name_promotion_selected = parent.getItemAtPosition(pos).toString();
//TODO REMOVE
Log.d(LOGTAG, "Il nome della promo selezionata è " + name_promotion_selected);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
As you can see, I have "ready" the id_promotion (It's the real value that I need)... And I know that I'm not adding (for now) at the List.
How I can get it, inside the onItemSelected?
Thank you very much
You can use the position of the selected item and use that to get the ID from the original list.
((ModelPromotion) mPromotionList.get(pos)).getIdPromotion()
Another option is to create a custom ArrayAdapter subclass that will accept ModelPromotion instead of String and override getItemId to return the idPromotion
An example about custom ArrayAdapter on Github.
the code bellow was working so fine with me but now i don't know what's wrong with it!! whenever i click to an item it put the value of the last item to the intent! any idea?
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>();
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
//int doctorid=Integer.parseInt(id.replaceAll("[\\D]",""));
addAvailableAppoint(fromT, toT, date);
}
updateListView();
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("items", "fromt " + fromT + "tot: " + toT);
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
intent.putExtra("Doctor's name", DoctorName);
intent.putExtra("Doctor's infos", DoctorInfos);
intent.putExtra("fromT", fromT);
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
// split new function for update listview
private void updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
1) You don't need to set the click listener for each new item in your list.
Just set it once, outside the for-loop.
2) Try to use a Model class for your adapter that contains all the data:
fromT , toT and date. Because as i see, your AvailabilityList contains only fromT.
3) As mentioned in #CommonsWare answer, in onItemClick try to find the appropriate object using position or id in parameters.
eg:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AvailabilityList item = (AvailabilityList)parent.getItem(position);
//Then from your item you can get the data: fromT , toT and date
}
whenever i click to an item it put the value of the last item to the intent!
You are ignoring all of the parameters to onItemClick(). If you are expecting your data to vary, you need to find the appropriate data in your collection, via position or id.
this is the script :
public class LecturAct extends ListActivity {
private static final String AR_ID = "id_lec";
private static final String AR_LC = "lec_nm";
private static final String AR_CLS = "class";
private static final String EXTRA_DATA = "idr";
JSONArray lec = null;
ArrayList<HashMap<String, String>> lec_list = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_lec);
Intent quiz = getIntent();
String id = quiz.getStringExtra(EXTRA_DATA);
String link_url = "http://xxxx/xxxx.php?id="+id;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.gtJson(link_url);
try {
lec = json.getJSONArray("lec");
for(int i = 0; i < lec.length(); i++){
JSONObject ar =lec.getJSONObject(i);
String lectid = ar.getString(AR_ID);
String lecname = ar.getString(AR_LC);
String class = ar.getString(AR_CLS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, lectid);
map.put(AR_LC, lecname);
map.put(AR_CLS, class);
lec_list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
ive tried to make a clickable item on my listview, this is the script:
public void adapter_listview() {
ListAdapter adapter = new SimpleAdapter(this, lec_list,
R.layout.list_item,
new String[] { AR_ID, AR_CLS, AR_LC}, new int[] {
R.id.title, R.id.content, R.id.code});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cd = ((TextView) view.findViewById(R.id.code)).getText().toString();
Intent in = new Intent(LecturAct.this, Quis.class);
in.putExtra(AR_ID, cd);
startActivity(in);
}
});
}
but when i click an item, it keep take me to the wrong direction, always take me to the last item. if the items on the list are
physic
biology
sport
social
math
then when i click biology or whatever i choose, it will always lead me to the "math" page. so what should i do? am i using a wrong adapter? please help me, give me solution to make this right :(
This answer is like Amin's but with few differences. Sample code:
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String mlecture p = (String) l.getItemAtPosition(position);
...
in.putExtra(AR_ID, lecture);
startActivity(in);
}
Notes:
Get the ListView parameter (l), and get the row/item position to begin with.
You cannot use view.findViewById method since ListView (l) already has the UI object.
Use the override onListItemClick since ListActivity is used.
Just override protected void onListItemClick (ListView l, View v, int position, long id) in LecturAct for example
protected void onListItemClick (ListView l, View v, int position, long id) {
String cd = getListAdapter().getItem(position);
Intent in = new Intent(LecturAct.this, Quis.class);
in.putExtra(AR_ID, cd);
startActivity(in);
}
I reviewed your code more closely. I suspect the data is not arranged correctly.
Change FROM:
new String[] { AR_ID, AR_CLS, AR_LC},
new int[] { R.id.title, R.id.content, R.id.code});
TO:
new String[] { AR_ID, AR_CLS, AR_LC},
new int[] { R.id.code, R.id.title, R.id.content });
I switched R.id.code. I think this is compatible with in.putExtra(AR_ID, cd). There is no good way for me to make sure since I don't know Quiz.class.
My example like yours.Just change your object casting.Or String.
catalogListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj=(Object)((String) parent.getAdapter().getItem(position));
String ss=obj.toString();
Intent i = new Intent(getActivity(), PdfReader.class);
i.putExtra("catalogPdfUrl", "" +ss;
getActivity().startActivity(i);
}
});
I am having an issue with using a listview that when I click it nothing is happening. I would like for it when I click the listview item to make a toast so I know it is being clicked. I have been trying/researching for a while and nothing. Would anybody mind taking a look to see if I am missing something I just am overlooking? Many thanks in advance!
Here is my class:
public class MyCar extends Activity {
/**
* Called when the activity is first created.
*/
public ListView mylistView;
String carInfo;
private ArrayAdapter<String> mylistAdapter;
ArrayList<String> arrayListCar = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mycar);
mylistView = (ListView) findViewById(R.id.listView);
arrayListCar = new ArrayList<String>();
//Just had to remove setting this adapter 2 times. Took out line below to fix.
mylistView.setAdapter(mylistAdapter);
mylistView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView) view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
carInfo = trySomethin();
fillList();
}
public void fillList() {
String make = "";
String model = "";
String[] pieces = carInfo.split("\"");
make = pieces[3];
model = pieces[7];
ArrayList<String> carList = new ArrayList<String>();
carList.add(make + " " + model);
// Create ArrayAdapter using the car list.
mylistAdapter = new ArrayAdapter<String>(MyCar.this, android.R.layout.simple_list_item_single_choice, carList);
mylistView.setAdapter(mylistAdapter);
mylistAdapter.notifyDataSetChanged();
}
}
if you have any elements on listview item change this for them
android:focusable="false"
and if you are changing any elements visibility on runtime you have to handle focus programatically each time you change its visibility.
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});