So what i m trying to do is get a String value on click of an item.
But through this code when i click on the item i get the position of the converter class or something like that,which i dont understand.
"MainActivity$Converter#30e6eb1" in the toast. I just want the subject part to Appear in the Toast.
#Override
protected void onPostExecute(String result) {
JSONObject jsonObject;
JSONArray jsonArray;
CustomAdapter customAdapter;
ListView listview;
listview = (ListView) findViewById(R.id.xlistview);
customAdapter = new CustomAdapter(getApplicationContext(), R.layout.row_layout);
listview.setAdapter(customAdapter);
//Log.d("json_raw_home",result);
if (result != null) { //Log.d("post execute",result);
try {
jsonObject = new JSONObject(result);
jsonArray = jsonObject.getJSONArray("data");
int count = 0;
String subject, description;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
subject = JO.getString("subject");
description = JO.getString("description");
Converter converter = new Converter(subject, description);
customAdapter.add(converter);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),item, Toast.LENGTH_LONG).show();}
});
}
}
public class CustomAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row==null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder=new ContactHolder();
contactHolder.tv_subject=(TextView)row.findViewById(R.id.xsubject_tv);
contactHolder.tv_description=(TextView)row.findViewById(R.id.xdescription_tv);
row.setTag(contactHolder);
}
else
{
contactHolder=(ContactHolder)row.getTag();
}
Converter converter = (Converter) this.getItem(position);
contactHolder.tv_subject.setText(converter.getSubject());
contactHolder.tv_description.setText(converter.getDescription());
return row;
}
public class ContactHolder{
TextView tv_subject,tv_description;
}
}
public class Converter {
private String subject,description;
public Converter(String subject, String description) {
this.setSubject(subject);
this.setDescription(description);
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
Change
String item = String.valueOf(parent.getItemAtPosition(position));
to
String item = ((Converter)parent.getAdapter().getItem(position)).getSubject()
You pass Converter objects to CustomAdapter to list them. So if you call getItem you have to concat Object to Converter. So;
change
String item = String.valueOf(parent.getItemAtPosition(position));
to
String item = ((Converter)parent.getAdapter().getItem(position)).getSubject();
so final code:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = ((Converter)parent.getAdapter().getItem(position)).getSubject();
Toast.makeText(getApplicationContext(),item, Toast.LENGTH_LONG).show();}
});
parent.getItemAtPosition(position); return the object of at position whatever you return from getItem(position).
Converter item = (Converter )parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),item.getSubject(), Toast.LENGTH_LONG).show();
Related
I want to display status and wilayah details from tbl_pegawai table.. If i select an item (name) from the spinner, i want to display the corresponding data (status and wilayah) matches with that item from the database.
Here is my android MainActivity.class file..
Spinner spinnernama, spinnerstatus, spinnerwilayah;
EditText inputstatus, inputwilayah;
Adapterspinner adapter;
List<String> valueId = new ArrayList<String>();
List<String> valueNama = new ArrayList<String>();
List<ModelSpinner> listspinner = new ArrayList<ModelSpinner>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cobaspinner);
spinnernama = findViewById(R.id.spin1);
spinnerstatus = findViewById(R.id.spin2);
spinnerwilayah = findViewById(R.id.spin3);
inputstatus = findViewById(R.id.input1);
inputwilayah = findViewById(R.id.input2);
spinnernama.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
inputstatus.setText(listspinner.get(position).getStatus());
inputwilayah.setText(listspinner.get(position).getWilayah());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
adapter = new Adapterspinner(cobaspinner.this, listspinner);
spinnernama.setAdapter(adapter);
callData();
}
private void callData() {
AndroidNetworking.get("http://192.168.43.20:8080/mopp/getDataPegawai.php")
.setTag("Get Data")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
try {
Boolean status = response.getBoolean("status");
if(status){
JSONArray jsonArray = response.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ModelSpinner item =new ModelSpinner();
item.setId(jsonObject.getString("id"));
item.setNama(jsonObject.getString("nama"));
item.setStatus(jsonObject.getString("status"));
item.setWilayah(jsonObject.getString("wilayah"));
listspinner.add(item);
}
}
} catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onError(ANError anError) {
}
});
}
}
here is my spinneradapter...
private Activity activity;
private LayoutInflater inflater;
private List<ModelSpinner> item;
public Adapterspinner(Activity activity, List<ModelSpinner> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.activity_cobaspinner, null);
EditText status = (EditText) convertView.findViewById(R.id.input1);
EditText wilayah = (EditText) convertView.findViewById(R.id.input1);
ModelSpinner data;
data = item.get(position);
status.setText(data.getStatus());
wilayah.setText(data.getWilayah());
return convertView;
Here output when I running and select data from spinner no data display on spinner
First here is my json.
[{"MemberId":"MI001","MemberName":"Member 1"},
{"MemberId":"MI002","MemberName":"Member 2"},
{"MemberId":"MI003","MemberName":"Member 3"}]
here how i put my json to my adapter
#Override
public void onResponse(JSONArray response) {
try {
Model_member m_member = new Model_member();
List<String> list = new ArrayList<String>();
for(int i = 0; i < response.length(); i++){
m_member.setMember_id(response.getJSONObject(i).getString("MemberId"));
m_member.setMember_name(response.getJSONObject(i).getString("MemberName"));
Log.d("ASDF", response.getJSONObject(i).getString("MemberName"));
memberList.add(m_member);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
and here is my adapter.
public class Adapter_member extends ArrayAdapter{
private ArrayList<Model_member> mData;
public Adapter_member(Context context, ArrayList<Model_member> m_member) {
super(context, 0, m_member);
this.mData = m_member;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.single_member_layout, parent, false);
}
Model_member m_member = getItem(position);
TextView memberName = convertView.findViewById(R.id.membername);
memberName.setText(m_member.getMember_name());
return convertView;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Model_member getItem(int position) {
return mData.get(position);
}
}
and here is my pojo
public class Model_member {
String member_id,member_name;
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public String getMember_name() {
return member_name;
}
public void setMember_name(String member_name) {
this.member_name = member_name;
}
#Override
public String toString() {
return getMember_name().toString();
}
}
So my problem is when i enter MI00 there result is like this
i only see MI003. the data is looping, i mean all of the result are MI003.
How can i make this working properly ? Did i miss something ?
Just clear your previous List before inserting new items.
#Override
public void onResponse(JSONArray response) {
if (memberList == null) memberList = new ArrayList<>();
memberList.clear();
Reason
Because you have attached memberList to your adapter, when each time
response come, then you don't clear previous List, and add new items
again.
That is what I could find in your code.
I'm trying to do a task where selecting school branch, List of students details has to get print in Listview, But i'm not getting after selecting a spinner how to get those in Listview
MainActivity.java
public class MainActivity extends AppCompatActivity implements OnItemSelectedListener{
Spinner branchSpinner,organisationSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
branchSpinner = (Spinner)findViewById(R.id.branchId);
organisationSpinner = (Spinner)findViewById(R.id.organisationId);
organisationSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String spinnerOne = String.valueOf(organisationSpinner.getSelectedItem());
Toast.makeText(this,spinnerOne,Toast.LENGTH_LONG).show();
if(spinnerOne.contentEquals(" Delhi public School"))
{
List<String> list = new ArrayList<>();
list.add("Hyderabad");
list.add("Delhi");
list.add("kolkata");
list.add("Chennai");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
arrayAdapter.notifyDataSetChanged();
branchSpinner.setAdapter(arrayAdapter);
}
if (spinnerOne.contentEquals("chaitanya"))
{
List<String> list =new ArrayList<>();
list.add("Hyderabad");
list.add("Bengaluru");
list.add("Dharwad");
list.add("Ameerpet");
list.add("Mumbai");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
arrayAdapter.notifyDataSetChanged();
branchSpinner.setAdapter(arrayAdapter);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
StudentData.java
public class StudentData {
private long id;
private long RollNo;
private long date;
private long age;
private String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getRollNo() {
return RollNo;
}
public void setRollNo(long RollNo) {
this.RollNo = RollNo;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
}
StudentDetailsAdapter.java
public class StudentDetailsAdapter extends BaseAdapter {
private LayoutInflater mLayoutInflater;
private List schedule;
private Context context;
public StudentDetailsAdapter(Context context,List data)
{
schedule = data;
mLayoutInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View updateView;
ViewHolder viewHolder;
if(view == null)
{
updateView = mLayoutInflater.inflate(R.layout.list_items,null);
viewHolder = new ViewHolder();
viewHolder.mName = (TextView) updateView.findViewById(R.id.name);
viewHolder.mRollNo = (TextView) updateView.findViewById(R.id.nricId);
viewHolder.mDob = (TextView) updateView.findViewById(R.id.dobId);
viewHolder.mAge = (TextView) updateView.findViewById(R.id.ageID);
updateView.setTag(viewHolder);
} else {
updateView = view;
viewHolder = (ViewHolder)updateView.getTag();
}
final StudentData item = (StudentData) getItem(position);
viewHolder.mName.setText(item.getName());
viewHolder.mRollNo.setText((int) item.getRollNo());
viewHolder.mDob.setText((int) item.getDate());
viewHolder.mAge.setText((int) item.getAge());
return updateView;
}
static class ViewHolder
{
TextView mName;
TextView mRollNo;
TextView mDob;
TextView mAge;
}
}
Expecting Result in this format Image
you need add listview and inttilize it than set adpater to listview not in spinner.
you need add listview and inttilize it than set adpater to listview not in spinner.
Spinner spinner;
String path[] = {"Laptops","DesktopPC","Tablets","Add-Ons","Gaming"};
ArrayList<String> list = new ArrayList<String>();
String Laptops[] = {"Dell","Hp","Apple"};
ListView lstView;
ArrayAdapter<String> adapter,listadapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstView = (ListView) findViewById(R.id.listView1);
for(int i=0;i<Laptops.length;i++)
{
list.add(Laptops[i]);
}
adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,path);
listadapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item,list);
lstView.setAdapter(listadapter);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String s = spinner.getItemAtPosition(arg2).toString();
list.add(s);
listadapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
What I'm trying to do is fetch images from database and show them in listView. for this i am using one adapter and list elements class but it is not showing any image but one string value that passed from main activity to elements class actually address of the image in which it is stored in database. Like this
Please don't make it duplicate
http://howdysend.com/Howdy/uploads/6.png ... actually that is the address of the image in database and 6 is the id of the image. Here is my code
Main activity
listEvents.setAdapter((ListAdapter) adapterNewsFeed);
adapterNewsFeed = new AdapterNewsFeed(getActivity(), R.layout.custom_events_list_in_newsfeed);
listEvents.setAdapter((ListAdapter) adapterNewsFeed);
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String EventTitle, EventDate, FriendName,friend_id,image;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
friend_id=JO.getString("friend_id");
EventTitle = JO.getString("address");
EventDate = JO.getString("DOB");
FriendName = JO.getString("name");
image=("http://howdysend.com/Howdy/uploads/" + friend_id + ".png");
EventsElements eventsElements = new EventsElements(image,EventTitle, EventDate, FriendName);
adapterNewsFeed.add(eventsElements);
listEvents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
EventsElements eventsElements =(EventsElements) adapterNewsFeed.getItem(position);
Intent i = new Intent(getActivity(), SendGreetings.class);
i.putExtra("user_id", eventsElements.getFriendName());
startActivity(i);
}
});
Elements Class
public class EventsElements {
private String EventTitle, EventDate,FriendName;
public String image;
public EventsElements(String EventTitle,String EventDate,String FriendName, String image){
this.setEventTitle(EventTitle);
this.setEventDate(EventDate);
this.setFriendName(FriendName);
this.setImage(image);
}
public String getEventTitle(){
return EventTitle;
}
public void setEventTitle(String EventTitle) {
this.EventTitle = EventTitle;
}
public String getEventDate() {
return EventDate;
}
public void setEventDate(String EventDate) {
this.EventDate = EventDate;
}
public String getFriendName() {
return FriendName;
}
public void setFriendName(String FriendName) {
this.FriendName = FriendName;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
And AdapterNewsFeed
public class AdapterNewsFeed extends ArrayAdapter {
List list=new ArrayList();
public AdapterNewsFeed(Context context, int resource) {
super(context,resource);
}
#Override
public int getCount() {
return list.size();
}
public void add(EventsElements object) {
super.add(object);
list.add(object);
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
view=convertView;
ElementsHolder elemetsHolder;
if (view==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.custom_events_list_in_newsfeed,parent,false);
elemetsHolder=new ElementsHolder();
elemetsHolder.EventTitle=(TextView) view.findViewById(R.id.EventTitle);
elemetsHolder.EventDate=(TextView) view.findViewById(R.id.EventDate);
elemetsHolder.FriendName=(TextView) view.findViewById(R.id.FriendName);
elemetsHolder.imageView=(ImageView)view.findViewById(R.id.FriendsUserImage);
view.setTag(elemetsHolder);
}
else
{
elemetsHolder=(ElementsHolder) view.getTag();
}
EventsElements eventsElements=(EventsElements)this.getItem(position);
elemetsHolder.EventTitle.setText(eventsElements.getEventTitle());
elemetsHolder.EventDate.setText(eventsElements.getEventDate());
elemetsHolder.FriendName.setText(eventsElements.getFriendName());
Picasso.with(getContext()).load(Uri.parse(eventsElements.getImage())).fit().into(elemetsHolder.imageView);
return view;
}
static class ElementsHolder
{
TextView EventTitle,EventDate,FriendName;
ImageView imageView;
String user_id;
}
}
Your image is from Url so basically you don't need Uri.parse(eventsElements.getImage(). Instead just set your url like this
Picasso.with(getContext()).load(eventsElements.getImage()).fit().into(elemetsHolder.imageView);
For more info check https://guides.codepath.com/android/Displaying-Images-with-the-Picasso-Library
Hope this helps!!
I am trying to implement a listview with a custom adapter. The problem is that it crashes whenever a onItemClickListener event is triggered.
java.lang.ClassCastException: imp.translator.diana.lang.CardItemData
cannot be cast to java.lang.String
at imp.translator.diana.lang.Speak$1.onItemClick(Speak.java:41)
at android.widget.AdapterView.performItemClick
This is my class:
final ListView list = (ListView) findViewById(R.id.list_view);
list.addHeaderView(new View(this));
list.addFooterView(new View(this));
BaseInflaterAdapter<CardItemData> adapter = new BaseInflaterAdapter<CardItemData>(new CardInflater());
CardItemData data = new CardItemData("Translate");
adapter.addItem(data, false);
CardItemData data2 = new CardItemData("Voice to Text");
adapter.addItem(data2, false);
CardItemData data3 = new CardItemData("Record");
adapter.addItem(data3, false);
CardItemData data4 = new CardItemData("Info");
adapter.addItem(data4, false);
list.setAdapter(adapter);
list.setClickable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView myAdapter, View myView, int position, long mylng) {
String selectedFromList = (String) (myAdapter.getItemAtPosition(position));
}
});
and my adapter:
public class BaseInflaterAdapter<T> extends BaseAdapter
{
private List<T> m_items = new ArrayList<T>();
private IAdapterViewInflater<T> m_viewInflater;
public BaseInflaterAdapter(IAdapterViewInflater<T> viewInflater)
{
m_viewInflater = viewInflater;
}
public BaseInflaterAdapter(List<T> items, IAdapterViewInflater<T> viewInflater)
{
m_items.addAll(items);
m_viewInflater = viewInflater;
}
public void setViewInflater(IAdapterViewInflater<T> viewInflater, boolean notifyChange)
{
m_viewInflater = viewInflater;
if (notifyChange)
notifyDataSetChanged();
}
public void addItem(T item, boolean notifyChange)
{
m_items.add(item);
if (notifyChange)
notifyDataSetChanged();
}
public void addItems(List<T> items, boolean notifyChange)
{
m_items.addAll(items);
if (notifyChange)
notifyDataSetChanged();
}
public void clear(boolean notifyChange)
{
m_items.clear();
if (notifyChange)
notifyDataSetChanged();
}
#Override
public int getCount()
{
return m_items.size();
}
#Override
public Object getItem(int pos)
{
return getTItem(pos);
}
public T getTItem(int pos)
{
return m_items.get(pos);
}
#Override
public long getItemId(int pos)
{
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent)
{
return m_viewInflater != null ? m_viewInflater.inflate(this, pos, convertView, parent) : null;
}
}
and the CardItemData:
public class CardItemData
{
private String m_text1;
public CardItemData(String text1)
{
m_text1 = text1;
}
public String getText1()
{
return m_text1;
}
}
Any idea what might be wrong here?
java.lang.ClassCastException: imp.translator.diana.lang.CardItemData
cannot be cast to java.lang.String
the above exception was due to
String selectedFromList = (String) (myAdapter.getItemAtPosition(position)); here you are try to convert CardItemData into String
try this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView myAdapter, View myView, int position, long mylng) {
CardItemData selectedFromList = (CardItemData) (myAdapter.getItemAtPosition(position));
String pos = selectedFromList.getText1();
}
});
Any idea what might be wrong here?
your getItem is returning T which is, in your case, an instance of CardItemData, but here:
String selectedFromList = (String) (myAdapter.getItemAtPosition(position));
you are casting it to String. You probably want to cast it to CardItemData. Btw, Java supports covariant return types, so you should be able to use
#Override
public T getItem(int pos) {
return m_items.get(pos);
}
Its a typecast issue, you are type casting " CardItemData " to " String "
String selectedFromList = (String) (myAdapter.getItemAtPosition(position));
use "getItem" method to get clicked " CardItemData " item.
Check the link given below
Android Docs link