How to set onClick for custom array adapter with extra data - android

I have a custom array adapter for a ListView. The goal is to have each list item have an individual picture, and that when the user clicks on the item they are taken to a web page. I have the image part working, and there are some stackoverflow answers for where to put the onItemClickListener. It seems it would go in the custom array adapter class But I can't figure out how to access the url from the list item.
Here is the code:
public class Animal
{
int image_resource_id;
String animal_type;
String wikipedia_url;
Animal(int image_resource_id, String animal_type, String wikipedia_url)
{
this.image_resource_id = image_resource_id;
this.animal_type = animal_type;
this.wikipedia_url = wikipedia_url;
}
}
class AnimalViewHolder
{
ImageView animal_image = null;
TextView animal_name = null;
String animal_url = "";
}
class CustomAnimalAdapter extends ArrayAdapter<Animal>
{
Context context;
int layoutResourceId;
Animal data[] = null;
public CustomAnimalAdapter(Context context, int layoutResourceId, Animal[] data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
AnimalViewHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new AnimalViewHolder();
holder.animal_image = (ImageView)row.findViewById(R.id.animal_image);
holder.animal_name = (TextView)row.findViewById(R.id.animal_name);
row.setTag(holder);
}
else
{
holder = (AnimalViewHolder)row.getTag();
}
Animal animal = data[position];
holder.animal_name.setText(animal.animal_type);
holder.animal_image.setImageResource(animal.image_resource_id);
return row;
}
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
Animal[] animal_list = {
new Animal(R.drawable.lion, "Lion", "http://en.wikipedia.org/wiki/Lion"),
new Animal(R.drawable.tiger, "Tiger", "http://en.wikipedia.org/wiki/Tiger"),
new Animal(R.drawable.bear, "Bear", "http://en.wikipedia.org/wiki/Bear"),
new Animal(R.drawable.monkey, "Monkey", "http://en.wikipedia.org/wiki/Monkey"),
new Animal(R.drawable.moose, "Moose", "http://en.wikipedia.org/wiki/Moose"),
new Animal(R.drawable.shark, "Shark", "http://en.wikipedia.org/wiki/Shark")
};
CustomAnimalAdapter adapter = new CustomAnimalAdapter(this,
R.layout.row_item, animal_list);
list_view_1 = (ListView)findViewById(R.id.listView1);
list_view_1.setAdapter(adapter);
}

update your adapter getview with
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(animal.wikipedia_url));
context.startActivity(browserIntent);
}
});

Related

Put two values in two separate fields Android

I need to be able to choose or pick an item from a list and after I choose it, the name of that item will go into one field and the corresponding weight to that item will go into another field.
I've been really stuck on this. I tired making a adapter but it wasn't working out and I'm just so lost, I don't know where to go with it.
I would really appreciate help.
If you need any code that I've done please say and I'll put it up straight away.
I don't have a database, I have a class of an array or numbers and Letter.
Thanks all!
Main.java
public void Chem() {
Chemical chemical_data[] = new Chemical[]
{
new Chemical("Acid", 125.33),
new Chemical("Blue", 145.3356),
};
ChemicalAdapter adapter = new ChemicalAdapter(this, R.layout.sollayout, chemical_data);
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
weightval = (EditText) findViewById(R.id.editText);
//ChemicalAdapter header = new ChemicalAdapter(this, R.layout.sollayout, null);
//weightval.addHeaderView(header);
chemname.setAdapter(adapter);
}
public void Chemname()
{
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
AutoCompleteTextView b = (AutoCompleteTextView) findViewById(R.id.editText4);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Chem();
}
});
}
Chemical.java
public class Chemical {
String chemicalValue;
double weight;
public Chemical(String chemicalValue, double weight) {
this.chemicalValue = chemicalValue;
this.weight = weight;
}
public String getChemicalValue() {
return chemicalValue;
}
public double getWeight() {
return weight;
}
}
ChemicalAdpater.java
public class ChemicalAdapter extends ArrayAdapter<Chemical> {
Context context;
int layoutResourceId;
Chemical data[] = null;
public ChemicalAdapter(Context context, int layoutResourceId, Chemical[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChemicalHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChemicalHolder();
holder.chemname = (AutoCompleteTextView)row.findViewById(R.id.editText4);
holder.weightval = (EditText)row.findViewById(R.id.editText);
row.setTag(holder);
}
else
{
holder = (ChemicalHolder)row.getTag();
}
Chemical chemical = data[position];
holder.weightval.setText(String.valueOf(chemical.weight));
holder.chemname.setText(chemical.chemicalValue);
return row;
}
static class ChemicalHolder
{
AutoCompleteTextView chemname;
EditText weightval;
}
}

The content of adapter has changed but listview did not receive a notification

I have research a lot on this but nothing satisfy me .Everyone give me the a solution put the adapter.notifyDataSetChanged() in runOnUiThread which i have already done bit didi not give me the solution.
My Code is below
public class FragmentActivity3 extends Fragment {
// Hashmap for ListView
ArrayList<Item> imageArry = new ArrayList<Item>();
CustomQuoteAdapter adapter;
String jsonstring;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView=inflater.inflate(R.layout.activity_fragment_activity1, container,false);
jsonstring=JsonClass.readData();
Log.d("JSon String ",jsonstring);
new GetQuotesInfo().execute();
adapter = new CustomQuoteAdapter(getActivity(), R.layout.list, imageArry);
ListView dataList = (ListView) rootView. findViewById(R.id.list);
dataList.setAdapter(adapter);
return rootView;
}
//Async Task to load data
class GetQuotesInfo extends AsyncTask<Void, Void, Void>
{
int count;
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
JSONArray jsonarr=new JSONArray(Globals.jsonText);
count=jsonarr.length();
for(int i=0;i<count;i++)
{
HashMap<String, String> quoteinfo = new HashMap<String, String>();
String author="";
Log.d("Json","Reading");
JSONObject jsonobj=jsonarr.getJSONObject(i);
String name=jsonobj.getString("name");
quoteinfo.put("name", name);
JSONArray jarr=jsonobj.getJSONArray("quotes");
String[] myarr=new String[jarr.length()];
String[] myarr1=new String[jarr.length()];
for(int j=0;j<jarr.length();j++)
{
JSONObject jobj=jarr.getJSONObject(j);
author=jobj.getString("author");
String text=jobj.getString("text");
Log.d("Author ",author);
Log.d("Text ",text);
myarr[j]=text;
myarr1[j]=author;
}
imageArry.add(new Item(name,myarr1, myarr));
}
}
catch(Exception ex)
{
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
getActivity().runOnUiThread(new Runnable(){
public void run() {
adapter.notifyDataSetChanged();
}
});
}
}
}
My Adapter class is below
public class CustomQuoteAdapter extends ArrayAdapter<Item> {
Context context;
int layoutResourceId;
LinearLayout linearMain;
ArrayList<Item> data = new ArrayList<Item>();
public CustomQuoteAdapter(Context context, int layoutResourceId,
ArrayList<Item> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = ((FragmentActivity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);
Item myImage = data.get(position);
TextView txtview=new TextView(context);
String heading=myImage.heading;
txtview.setText(heading);
txtview.setTextColor(Color.BLUE);
txtview.setTextSize(20);
linearMain.addView(txtview);
for (int j = 0; j < myImage.getName().length; j++) {
TextView label1 = new TextView(context);
label1.setText(myImage.author[j]);
linearMain.addView(label1);
TextView label2 = new TextView(context);
label2.setText(myImage.name[j]);
linearMain.addView(label2);
}
// ImageView image = new ImageView(context);
// int outImage = myImage.image;
// image.setImageResource(outImage);
// linearMain.addView(image);
}
return row;
}
}
Can anyone give me the solution to resolve my error
onPostExecute() is automatically called on the UI thread, so you don't need the runOnUIThread()
Have you checked to make sure the data in your list is actually changing? Also I didn't go through the logic of your entire adapter, but this line looks like there's a typo. I'm guessing your IDE would have caught it if that typo weren't also in your resources file too though
linearMain = (LinearLayout) row.findViewById(R.id.lineraMain);
Not sure if that typo R.id.lineraMain is causing you problems.

ListView showing only one item or last item

The title of this question is same but technical issue are different.
Hi i am trying to get data from SQLite but i am able to show only last item in listview. I tried different- different solution but not getting success.
Problem is not getting item from SQLite(I am able to fetch all item) but showing item using adapter in listview.
Here is my code.
ListActivity.java
db=new DBHelper(getBaseContext());
db.getWritableDatabase();
try {
final DBHelper m = new DBHelper(getBaseContext());
final List<GetSet> NotesWiseProfile = m.getBabyDetails();
for (final GetSet cn : NotesWiseProfile) {
counter++;
String babyName = cn.getBabyName();
String babyImage = cn.getBabyImage();
int babyId = cn.getBabyId();
BabyData baby_data[] = new BabyData[]
{
new BabyData(R.drawable.ic_launcher, babyName,babyId),
};
adapter = new MobileArrayAdapter(this,
R.layout.list_row, baby_data);
listView1.invalidateViews();
listView1.setAdapter(adapter);
}
}
catch (Exception e) {
}
BabyData.java
public class BabyData {
public int icon;
public String title;
public int babyid;
public BabyData(){
super();
}
public BabyData(int icon, String title,int babyId) {
super();
this.icon = icon;
this.title = title;
babyid = babyId;
}
}
MobileArrayAdapter.java
public class MobileArrayAdapter extends ArrayAdapter<BabyData>{
Context context;
int layoutResourceId;
BabyData data[] = null;
public MobileArrayAdapter(Context context, int layoutResourceId, BabyData[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
DataHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DataHolder ();
holder.imgIcon = (ImageView)row.findViewById(R.id.imvBabyFace);
holder.txtTitle = (TextView)row.findViewById(R.id.tvbabyNameList);
holder.txtBabyId = (TextView)row.findViewById(R.id.tvBabyId);
row.setTag(holder);
}
else
{
holder = (DataHolder )row.getTag();
}
BabyData weather = data[position];
holder.txtTitle.setText(weather.title);
holder.txtBabyId.setText(String.valueOf(weather.babyid));
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class DataHolder
{
ImageView imgIcon;
TextView txtTitle;
TextView txtBabyId;
}
}
I don't understand what's wrong in my code. Please give me any hint or reference.
Thanks in Advance.
Put the listview declarations out of the for loop, something like:
BabyData baby_data[] = new BabyData[NotesWiseProfile.size()];
for (final GetSet cn : NotesWiseProfile) {
String babyName = cn.getBabyName();
String babyImage = cn.getBabyImage();
int babyId = cn.getBabyId();
baby_data[counter] = new BabyData(R.drawable.ic_launcher, babyName,babyId);
counter++;
}
adapter = new MobileArrayAdapter(this,
R.layout.list_row, baby_data);
listView1.invalidateViews();
listView1.setAdapter(adapter);
I think you should use a field for storing you babies. Currrently, you are using a local Baby array for that. As far as I know, the ListView always gets its data from the array you passed to it (invalidating it causes the ListView to look up that data again.
To recap: Store your array as a field - if data changes, update the array and call notifyDatasetChanged() on your adapter, which will cause your ListView to reload the data.

NullPointer Exception when setting the adapter for a ListView

I am trying to set the data to an adapter through an AsyncTask. This has caused alot of grief - Most recently when trying to set the Array Adapter.
The following method is called onPostExecute();
private void setQueues(final JSONObject[] qInfo)
{
queues = new QueueItem[qInfo.length];
for(int i = 0; i < qInfo.length; i++)
{
queues[i] = new QueueItem();
//final int ii = i;
// Formatting the queue title
String name = qInfo[i].optString("name").replace("-", " ");
queues[i].label = name;
try {
if(qInfo[i].getString("active").contains("1"))
{
queues[i].value = true;
}
else
{
queues[i].value = false;
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
lv.setAdapter(new QueueAdapter(getActivity(),
R.layout.queues_items, queues));
This causes the following exception runtime : link here
EDIT : As requested, here is QueueAdapter :
public class QueueAdapter extends ArrayAdapter<QueueItem>{
Context context;
int layoutResourceId;
QueueItem data[] = null;
public QueueAdapter(Context context, int layoutResourceId, QueueItem[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
QueueHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new QueueHolder();
holder.queueswitch = (Switch)row.findViewById(R.id.queues_item_switch);
holder.txtLabel = (TextView)row.findViewById(R.id.queues_item_text);
row.setTag(holder);
}
else
{
holder = (QueueHolder)row.getTag();
}
QueueItem queue = data[position];
holder.txtLabel.setText(queue.label);
holder.queueswitch.setChecked(queue.value);
return row;
}
static class QueueHolder
{
Switch queueswitch;
TextView txtLabel;
}
}
lv.setAdapter(new QueueAdapter(getActivity(),
R.layout.queues_items, queues));
this snippet should be in try block.. Because If there is JSONException all elements in that array will be null...
I mean to say.. put for loop inside try block and not the oppt.. if you still want to loop when an Exception occurs.. Then Try using Collections instead of array..

Can't fill the listView?

I have a listview, and i start an intent to fill it. But the list shows up with a default image and no text. It is supposed to show up with different images and text.
I have two arrays, one is in string type and the other one is in drawable type... But my list doesn't show me none of these that i wanted...
My ListActivity:
public class fillLeftMenu extends ListActivity {
private View menu;
ImageView findLocation;
Spinner cityList;
ListView leftList;
String [] textIndex;
Drawable [] imageIndex;
ArrayList<LeftListItems> Left;
listAdapter lAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataTransfer dt = BonubonActivity.deneme;
menu = dt.getView();
findLocation = (ImageView) menu.findViewById(R.id.image_findLocation);
leftList = (ListView) menu.findViewById(R.id.list);
// add items to listView
Left = new ArrayList<LeftListItems>();
textIndex = new String[] {"Bugünün Fırsatları", "Son Dakika Bonusları", "Kadın", "Aile", "Çocuk", "Alışveriş", "Şehirden Kaçış", "Kışa Özel"};
imageIndex = new Drawable[] {leftList.getResources().getDrawable(R.drawable.kucukicon_01),leftList.getResources().getDrawable(R.drawable.kucukicon_02),leftList.getResources().getDrawable(R.drawable.kucukicon_03),leftList.getResources().getDrawable(R.drawable.kucukicon_04),leftList.getResources().getDrawable(R.drawable.kucukicon_05),leftList.getResources().getDrawable(R.drawable.kucukicon_06),leftList.getResources().getDrawable(R.drawable.kucukicon_07),leftList.getResources().getDrawable(R.drawable.kucukicon_08)};
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);
getIndex();
lAdapter.notifyDataSetChanged();
leftList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
finish();
}
private void getIndex() {
try{
LeftListItems item = new LeftListItems();
for(int i=0; i<textIndex.length; i++) {
item.setText(textIndex[i]);
item.setImage(imageIndex[i]);
Left.add(item);
lAdapter.add(Left.get(i));
}
}
catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
}
private class listAdapter extends ArrayAdapter<LeftListItems> {
private ArrayList<LeftListItems> items;
private Context ctx;
public listAdapter(Context ctx, int textViewResourceId, ArrayList<LeftListItems> items) {
super(ctx, textViewResourceId, items);
this.ctx = ctx;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
LeftListItems index = items.get(position);
if(index != null) {
TextView text = (TextView) v.findViewById(R.id.text);
ImageView img = (ImageView) v.findViewById(R.id.icon);
if(text != null)
text.setText(index.getText());
if(img != null)
img.setBackgroundDrawable(index.getImage());
}
return v;
}
}
}
Try calling getIndex() method before creating the adapter and setting it to the list. Like this:
getIndex();
//then create new adapter
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);

Categories

Resources