Getting text from Textview in listview with custom adapter [duplicate] - java

This question already has answers here:
How to extract the text from the selected item on the listView
(14 answers)
Listview with Details
(4 answers)
Closed 7 years ago.
I have a Listview with 3 Textviews, and I want to retrieve the specific data from these textviews on the clicked Item. For now I'm trying to get the data from the first textview. The problem is, it doesn't matter if I click on Item 1, 2, 3 or etc because I'll always get the text from first Item on the listview. I think the problem is because I don't know how to specific which data I want, from which Item. This is my code:
estoque.java:
package com.example.asus.mingausfashionmoda;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class estoque extends ListActivity {
String qntES;
String pcES;
String pvES;
//list
protected List<ParseObject> mObject;
String variable = "camisa";
// declare class variables
private ArrayList<Item> m_parts = new ArrayList<Item>();
private Runnable viewParts;
private ItemAdapter m_adapter;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.estoque_main);
// instantiate our ItemAdapter class
m_adapter = new ItemAdapter(this, R.layout.list_item, m_parts);
setListAdapter(m_adapter);
// here we are defining our runnable thread.
viewParts = new Runnable(){
public void run(){
handler.sendEmptyMessage(0);
}
};
// here we call the thread we just defined - it is sent to the handler below.
Thread thread = new Thread(null, viewParts, "MagentoBackground");
thread.start();
}
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
// create some objects
// here is where you could also request data from a server
// and then create objects from that data.
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(variable);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> statuslist, ParseException e) {
if(e != null){
//data successfully retrieved
Toast.makeText(estoque.this, "Houve um erro inesperado, tente novamente mais tarde", Toast.LENGTH_LONG).show();
}else{
//something went wrong
mObject = statuslist;
for(int i = 0; i<mObject.size(); i++) {
ParseObject statusObject = mObject.get(i);
String username = statusObject.getString("user");
Number qntE = statusObject.getNumber("qnt");
qntES = String.valueOf(qntE);
Number pcE = statusObject.getNumber("precoC");
pcES = String.valueOf(pcE);
Number pvE = statusObject.getNumber("precoV");
pvES = String.valueOf(pvE);
m_parts.add(new Item(qntES, pvES, pcES));
m_adapter = new ItemAdapter(estoque.this, R.layout.list_item, m_parts);
setListAdapter(m_adapter);
}
}
}
});
final ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
TextView ttd = (TextView)findViewById(R.id.toptextdata);
System.out.println(ttd.getText().toString());
}
});
}
};
}
ItemAdapter.java:
package com.example.asus.mingausfashionmoda;
/**
* Created by ASUS on 21/12/2015.
*/
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ItemAdapter extends ArrayAdapter<Item> {
// declaring our ArrayList of items
private ArrayList<Item> objects;
/* here we must override the constructor for ArrayAdapter
* the only variable we care about now is ArrayList<Item> objects,
* because it is the list of objects we want to display.
*/
public ItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
/*
* we are overriding the getView method here - this is what defines how each
* list item will look.
*/
public View getView(int position, View convertView, ViewGroup parent){
// assign the view we are converting to a local variable
View v = convertView;
/** v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("CARALHO VC CRICOU" + objects);
}
}); */
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_item, null);
}
/*
* Recall that the variable position is sent in as an argument to this method.
* The variable simply refers to the position of the current object in the list. (The ArrayAdapter
* iterates through the list we sent it)
*
* Therefore, i refers to the current Item object.
*/
Item i = objects.get(position);
if (i != null) {
// This is how you obtain a reference to the TextViews.
// These TextViews are created in the XML files we defined.
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView ttd = (TextView) v.findViewById(R.id.toptextdata);
TextView mt = (TextView) v.findViewById(R.id.middletext);
TextView mtd = (TextView) v.findViewById(R.id.middletextdata);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView btd = (TextView) v.findViewById(R.id.desctext);
// check to see if each individual textview is null.
// if not, assign some text!
if (tt != null){
tt.setText("Quantidade: ");
}
if (ttd != null){
ttd.setText(i.getName());
}
if (mt != null){
mt.setText("Preco compra: ");
}
if (mtd != null){
mtd.setText("$" + i.getPrice());
}
if (bt != null){
bt.setText("Preco venda: ");
}
if (btd != null){
btd.setText(i.getDetails());
}
}
// the view must be returned to our activity
return v;
}
}
Item.java:
package com.example.asus.mingausfashionmoda;
import android.widget.TextView;
public class Item {
private String details;
private String name;
private String price;
public Item(){
}
public Item(String i, String d, String p){
this.details = d;
this.name = i;
this.price = p;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
estoque_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/btnSelecionarQuery"
android:text="ROUPA"
/>
<ListView
android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
/>
<TextView
android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No items to display."/>
</LinearLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<!-- Item Name -->
<TextView
android:id="#+id/toptext"
android:layout_width="wrap_content"
android:layout_height="26dip"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:singleLine="true"
android:ellipsize="marquee"
/>
<!-- Actual Item Name Data -->
<TextView
android:id="#+id/toptextdata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/toptext"
android:singleLine="true"
android:ellipsize="marquee"
/>
<!-- Price Tag -->
<TextView
android:id="#+id/middletext"
android:layout_width="wrap_content"
android:layout_height="26dip"
android:layout_alignParentLeft="true"
android:layout_below="#id/toptext"
android:textStyle="bold"
android:gravity="center_vertical"
/>
<!-- Actual Price Data -->
<TextView
android:id="#+id/middletextdata"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentRight="true"
android:layout_below="#id/toptext"
android:layout_toRightOf="#id/middletext"
android:gravity="center_vertical"
/>
<!-- Description Tag -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#id/middletext"
android:textStyle="bold"
android:id="#+id/bottomtext"
android:singleLine="false"
/>
<!-- This is the actual description -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_below="#id/bottomtext"
android:id="#+id/desctext"
android:singleLine="false"
/>
</RelativeLayout>
To make it easier for your understanding, this is where I get the clicked item from the listview and try to get it's first textview text(This is on estoque.java):
final ListView lv = (ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
TextView ttd = (TextView)findViewById(R.id.toptextdata);
System.out.println(ttd.getText().toString());
}
});
Thanks.

Want to access View from clicked row layout of ListView, use second parameter of onItemClick to call findViewById like:
TextView ttd = (TextView) myView.findViewById(R.id.toptextdata);

Make your textView final and instead of using listItemClickListner use onclickListener on each textview in the getView().

Related

Expandable Listview OnClickListeners

I am creating an app in android studios that requires the user to select a child item from an expandable listview on one activity and for it to be displayed on another activity. I'm new to java and android studios and still dont understand how to do this really. If anyone has any sample code or can help that would be great, thanks!
You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView.
Here there's a tutorial for using a ExpandableListView and it shows how to set a ClickListener for the elements.
And here there's the Android developer's documentation which shows how to create and open a new Activity from a button's click.
**You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView and create the xml file for child and parent.child will be Expandable TextView **
**layout file**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.elite_android.explistview1.MainActivity">
<RelativeLayout
android:id="#+id/main_number_picker_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp">
<NumberPicker
android:id="#+id/main_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Next" />
<TextView
android:id="#+id/main_txt_patient_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/main_number_picker"
android:text="Select number of patient"
android:textColor="#color/colorAccent"
android:layout_marginLeft="80dp"/>
</RelativeLayout>
<ExpandableListView
android:id="#+id/exp_Listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/main_number_picker_layout">
</ExpandableListView>
</RelativeLayout>
**Main Activity.java file**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.view.View.OnFocusChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
ExpandableListView expandableListView;
private MyAdapter mAdapter;
ExpandableListView expand;
NumberPicker numberPicker;
private List<String> headerItems;
private ArrayList childDetails;
private HashMap<String, List<String>> childList;
private Context ctx;
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the EditText
editText1 = (EditText) findViewById(R.id.child_item);
// //set the onFocusChange listener
// // editText1.setOnFocusChangeListener(editText1.getOnFocusChangeListener());
//
//// //get reference to EditText
//// editText2 = (EditText) findViewById(R.id.sequence);
//// // set the on focusChange listner
//// editText2.setOnFocusChangeListener(editText2.getOnFocusChangeListener());
//
// //Generate list View from ArrayList;
//
//
// EditText editText = (EditText) findViewById(R.id.child_item);
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
//
//
//// editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// // #Override
// // public void onFocusChange(View v, boolean hasFocus) {
// // //editText.setOnFocusChangeListener();
// // return;
// // }
// //});
//
String[] numbers = new String[10];
for (int count = 0; count < 10; count++)
numbers[count] = String.valueOf(count);
numberPicker = (NumberPicker) findViewById(R.id.main_number_picker);
numberPicker.setMaxValue(numbers.length);
numberPicker.setMinValue(1);
numberPicker.setDisplayedValues(numbers);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
generateListItems(newVal);
loadRecycleView();
}
});
}
private void generateListItems(int childCount) {
if (headerItems != null)
headerItems.clear();
else
headerItems = new ArrayList<>();
if (childList != null)
childList.clear();
else
childList = new HashMap();
if (childDetails == null) {
childDetails = new ArrayList();
childDetails.add("Name");
childDetails.add("Age");
childDetails.add("Gender");
}
// Put header items
for (int count = 0; count < childCount; count++) {
headerItems.add(" Parent " + count);
childList.put(headerItems.get(count), childDetails);
}
}
private void loadRecycleView() {
if (expandableListView == null) {
expandableListView = (ExpandableListView) findViewById(R.id.exp_Listview);
mAdapter = new MyAdapter(this, headerItems, childList);
expandableListView.setAdapter(mAdapter);
} else {
expandableListView.invalidate();
mAdapter.setHeaderData(headerItems);
mAdapter.setListData(childList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
**Adapter class.java**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnFocusChangeListener;
/**
* Created by ELITE-ANDROID on 28-02-2017.
*/
// this is provides all needs methods implementing an Expandable List VIew
public class MyAdapter extends BaseExpandableListAdapter {
// We need some Variables here so therer are some Variables here
private List<String> header_titles; // This is for Representing the HeadLine(Array list)
private HashMap<String, List<String>> child_titles; // defin the HashMap for the child item how to Represent the Parent Handing so Hash Map, need some Variables
private Context ctx;
private NumberPicker numberPicker;
EditText editText;
View view;
private static LayoutInflater inflater = null;
//for initalized for all Variables we need some Constructor
public MyAdapter(Context context, List<String> header_titles, HashMap<String, List<String>> child_titles) {
super();
this.ctx = context;
this.child_titles = child_titles;
this.header_titles = header_titles;
}
public void refreshHeader_titles(List<String> events) {
this.header_titles.clear();
this.header_titles.addAll(header_titles);
notifyDataSetChanged();
}
;
#Override
// From this Override method How to Return how many elements are the Group count like parent
public int getGroupCount() {
return header_titles.size();
}
#Override
//here the number of child items are in each heading. There are three Heading - PAtien Name ,Age, Gender
public int getChildrenCount(int groupPosition) {
// Log.d("xxx", )
return child_titles.get(header_titles.get(groupPosition)).size(); //how to Return the size of HashMap
}
#Override
public Object getGroup(int groupPosition) {
return header_titles.get(groupPosition);
}
#Override
// here how to retuen child items on the particular headings and Positions.
public Object getChild(int groupPosition, int childPosition) {
return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
}
#Override
//return the groupo position
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
// Here return the Group View
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// ListViewHolder viewHolder;
// if (view == null) {
// viewHolder = new ListViewHolder();
// LayoutInflater inflater = context.getLayoutInflater();
// view = inflater.inflate(R.layout.listitems, null, true);
// viewHolder.itmName = (TextView) view.findViewById(R.id.Item_name);
// viewHolder.itmPrice = (EditText) view.findViewById(R.id.Item_price);
// view.setTag(viewHolder);
// } else {
// viewHolder = (ListViewHolder) view.getTag();
//// loadSavedValues();
// }
// Here how to get the Heading Title here Decalered String Variables, now how to get title of heading from getGroup methods so simple call Backed Methods.
String title = (String) this.getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.prent, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.heading_item);
textView.setText(title); // for Heading bold style ,title
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String title = (String) this.getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child, null);
}
String cellData = child_titles.get(header_titles.get(groupPosition)).get(childPosition);
EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Log.d("xxxx", "Has focus " + hasFocus);
if (!hasFocus) {
// int itemIndex = View.getId();
// String enteredName = ((EditText)v).getText().toString();
// selttems.put(itemIndex, enteredName);
} else {
}
return;
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setListData(HashMap<String, List<String>> lData) {
child_titles = lData;
}
public void setHeaderData(List<String> hData) {
header_titles = hData;
}
}
**child.Xml file**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ffff">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/child_item"
android:textSize="25dp"
android:textStyle="bold"
android:gravity="center_vertical"
android:layout_marginLeft="10dp"/>
<!--<EditText-->
<!--android:id="#+id/sequence"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_alignParentLeft="true"-->
<!--android:layout_alignParentTop="true"-->
<!--android:paddingLeft="35sp"-->
<!--android:layout_marginRight="10dp"-->
<!--android:textAppearance="?android:attr/textAppearanceMedium" />-->
</LinearLayout>
<!--This Layout File Represent the Child Items.
This Field Represent the Child Item IN the List VIew -->
**parent.Xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="vertical">
<TextView
android:id="#+id/heading_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:textColor="#color/colorAccent"
android:textSize="25dp" />
</LinearLayout>
<!--This Layout file for Heading -Lines.-->

Swipe ListItem + Pull-To-Refresh effect + Click event + Vertical scroll

I need a listview with vertical scroll, allowing a Pull-To-Refresh effect, and each cell must allow a Swipe (to show the button below). Furthermore, the whole ListView is contained in a three tabs activity. It's very similar to Gmail app for Android, which in inbox allows vertical scrolling, swipe to Archive conversation, and click to read the email.
The general activity contains tabs (SlidingTabLayout built with an HorizontalScrollView, SlidingTabStrip, and a ViewPager), extracted from developer.android.com.
Each tab contains a fragment with a FrameLayout, and a 47degree SwipeListView, inside. They're attached here.
We have disabled the horizontal movement of tabs (they work just clicking the header
I attach the layout of the cell and the java class which handles everything, too.
I implemented 47deg SwipeList library (https://github.com/47deg/android-swipelistview).
The errors I'm facing are: On one hand, the cell with swipe is not receiving the main click, and when I do swipe, the button bellow is shown but the click is not received correctly. And if we enable pull-to-refresh, the swipe stops working well.
layout_list_item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:orientation="vertical"
android:id="#+id/back"
android:tag="back"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#color/gold">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btFavorite"
android:background="#drawable/abc_btn_rating_star_off_mtrl_alpha"
android:layout_alignParentLeft="false"
android:adjustViewBounds="true"
android:contentDescription="Favorite"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp" />
</RelativeLayout>
<LinearLayout
android:id="#+id/front"
android:tag="front"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffffff"
android:layout_marginLeft="5dp">
<include android:id="#+id/layout_list_item_image" layout="#layout/layout_list_item_image"
android:layout_width="70dp"
android:layout_height = "70dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<include android:id="#+id/layout_list_item_content" layout="#layout/layout_list_item_content"
android:layout_width="184dp"
android:layout_toRightOf="#id/layout_list_item_image"
android:layout_height="70dp"
android:layout_centerHorizontal="true"
/>
<include android:id="#+id/layout_list_item_status"
layout="#layout/layout_list_item_status"
android:layout_width="match_parent"
android:layout_height = "wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"/>
</LinearLayout>
</FrameLayout >
layout_fragment_pager_contact_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:clickable="false">
<com.fortysevendeg.swipelistview.SwipeListView
xmlns:swipe="http://schemas.android.com/apk/res-auto"
android:id="#android:id/list"
android:listSelector="#00000000"
android:layout_width="match_parent"
android:layout_height="match_parent"
swipe:swipeFrontView="#+id/front"
swipe:swipeBackView="#+id/back"
swipe:swipeActionRight="reveal"
swipe:swipeMode="right"
swipe:swipeCloseAllItemsWhenMoveList="true"
swipe:swipeOpenOnLongPress="false"
swipe:swipeAnimationTime="350"
swipe:swipeOffsetLeft="280dp"
swipe:swipeOffsetRight="280dp"
/>
<!-- View to show if the list is emtpy -->
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="No items."
android:clickable="false"/>
</FrameLayout>
</LinearLayout>
ContactListFragment.java
package com.davduran.myapp.contacts.view;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.fortysevendeg.swipelistview.SwipeListView;
import com.davduran.myapp.R;
import com.davduran.myapp.contacts.connection.ContactController;
import com.davduran.myapp.contacts.detail.ContactDetailMainActivity;
import com.davduran.myapp.util.Constants;
import com.davduran.myapp.util.Utils;
import com.davduran.myapp.view.tab.SlidingTabLayout;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import io.realm.Realm;
import model.Contact;
import model.FavouriteContact;
import model.RecentContact;
/**
* A fragment representing a list of Items.
* <p/>
* <p/>
* Activities containing this fragment MUST implement the {#link OnFragmentInteractionListener}
* interface.
*/
public class ContactListFragment extends ListFragment {
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
private Realm realm;
private ContactController mContactController;
private ArrayList<Contact> contactList;
private ArrayList<FavouriteContact> favouriteContactList;
private ArrayList<RecentContact> recentContactList;
protected Handler handler = new Handler();
private ContactListViewArrayAdapter adapter;
private SwipeListView swipeListView;
private ListView listView;
private Parcelable state;
private TextView emptyText;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private int mIndex;
private String mParam2;
private OnFragmentInteractionListener mListener;
// TODO: Rename and change types of parameters
public static ContactListFragment newInstance(int index, String param2) {
ContactListFragment fragment = new ContactListFragment();
Bundle args = new Bundle();
args.putInt(ARG_PARAM1, index);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.layout_fragment_pager_contact_list, container, false);
listView = (ListView) v.findViewById(android.R.id.list);
emptyText = (TextView) v.findViewById(android.R.id.empty);
return v;
}
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ContactListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getInstance(getActivity());
mContactController = new ContactController(getActivity(),realm);
if (getArguments() != null) {
mIndex = getArguments().getInt(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
setListAdapterTabs();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i(Constants.TAG, "ContactListFragment.onListItemClick: Listclicking");
if (mListener != null) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
//mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).getId());
Intent in = new Intent(getActivity(), ContactDetailMainActivity.class);
if(mIndex == Constants.CONTACTS_ALL) {
in.putExtra(Constants.CONTACT_ID,contactList.get(position).getId() );
startActivity(in);
} else if (mIndex == Constants.CONTACTS_RECENT) {
try {
String action = recentContactList.get(position).getAction();
if (action.compareTo("call") == 0) {
String strPhones = recentContactList.get(position).getPhones();
if (strPhones != null) {
JSONArray jPhones = new JSONArray(strPhones);
String phone = (String)((JSONObject) jPhones.get(0)).get("phone");
Utils.launchCall(phone, getActivity());
}
}
else if (action.compareTo("sms") == 0) {
String strPhones = recentContactList.get(position).getPhones();
if (strPhones != null) {
JSONArray jPhones = new JSONArray(strPhones);
String phone = (String)((JSONObject) jPhones.get(0)).get("phone");
Utils.launchSms(phone, getActivity());
}
}
else if (action.compareTo("email") == 0) {
String strEmails = recentContactList.get(position).getEmails();
if (strEmails != null) {
JSONArray jPhones = new JSONArray(strEmails);
String email = (String)((JSONObject) jPhones.get(0)).get("email");
Utils.launchEmail(email, getActivity());
}
}
} catch (Exception ex) {
Log.e(Constants.TAG, "ContactListFragment.onListItemClick: ", ex);
}
} else if (mIndex == Constants.CONTACTS_FAVOURITE) { {
in.putExtra(Constants.CONTACT_ID,favouriteContactList.get(position).getId() );
startActivity(in);
}}
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
#Override
public void onDestroyView() {
super.onDestroyView();
realm.close();
}
public void setListAdapterTabs(){
Log.i(Constants.TAG, "ContactListFragment.setListAdapterTabs: index " + mIndex);
if(mIndex == Constants.CONTACTS_FAVOURITE) {
favouriteContactList = mContactController.getAllFavouriteContacts();
if (favouriteContactList!=null) {
setListAdapter(new ContactFavouriteListViewArrayAdapter(getActivity().getApplicationContext(),
favouriteContactList));
}
}else if(mIndex == Constants.CONTACTS_RECENT){
if (emptyText!=null)
emptyText.setText("");
recentContactList = mContactController.getAllRecentContacts();
if (recentContactList!=null) {
setListAdapter(new RecentListViewArrayAdapter(getActivity().getApplicationContext(), recentContactList));
}
}else if(mIndex == Constants.CONTACTS_ALL){
if (emptyText!=null)
emptyText.setText("");
contactList = mContactController.getAllContacts();
adapter = new ContactListViewArrayAdapter(getActivity().getApplicationContext(), contactList);
if (contactList!=null) {
if (listView!=null)
state = listView.onSaveInstanceState();
if (adapter != null){
setListAdapter(adapter);
if (state!=null)
listView.onRestoreInstanceState(state);
} else {
adapter = new ContactListViewArrayAdapter(getActivity().getApplicationContext(), contactList);
setListAdapter(adapter);
if (state!=null)
listView.onRestoreInstanceState(state);
}
}
}
}
}

Android: How to set the ImageView src in a list dynamically

I'm new to android, i have a news website
and i'm developing an android app, the main activity catches a JSON node from this link and displays all the articles in a ListView,
each item in the list has an image, title and a teaser of this particular article.
now i have written a java code for the title and the description and everything is working perfectly, but i want to display the images too and i don't know how to do that.
Here's my MainActivity.java:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
//Create a progress dialog instance
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://www.ana.fm/api/main/";
// JSON Node names
private static final String TAG_ARTICLES = "articles";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_TEASER = "teaser";
private static final String TAG_COVER_PHOTO = "cover_photo";
// contacts JSONArray
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String article_id = ((TextView) view.findViewById(R.id.article_id))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID, article_id);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All Contacts
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
title = Html.fromHtml(title).toString();
String teaser = c.getString(TAG_TEASER);
teaser = Html.fromHtml(teaser).toString();
String cover_photo = "http://www.ana.fm/med_photos/articles/";
cover_photo = cover_photo.concat(c.getString(TAG_COVER_PHOTO));
// tmp hashmap for single contact
HashMap<String, String> article = new HashMap<String, String>();
// adding each child node to HashMap key => value
article.put(TAG_ID, id);
article.put(TAG_TITLE, title);
article.put(TAG_TEASER, teaser);
article.put(TAG_COVER_PHOTO, cover_photo);
// adding contact to contact list
contactList.add(article);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
new GetContacts().execute();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_ID, TAG_TITLE, TAG_TEASER, TAG_COVER_PHOTO}, new int[] { R.id.article_id, R.id.title,
R.id.teaser, R.id.cover_photo});
setListAdapter(adapter);
}
}
}
And here's the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#color/white">
<!-- Main ListView
Always give id value as list(#android:id/list)
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp"
/>
</LinearLayout>
And here's the list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:layout_marginBottom="20dp"
android:background="#color/light_grey">
<!-- Cover photo -->
<ImageView
android:id="#+id/cover_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
<!-- ID Label -->
<TextView
android:id="#+id/article_id"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#43bd00"
android:textSize="16sp"
android:textStyle="bold" />
<!-- Title Label -->
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dip"
android:paddingTop="6dip"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
<!-- Teaser label -->
<TextView
android:id="#+id/teaser"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/medium_grey" />
</LinearLayout>
Anyone can help ?
So here is how to implement a custom adapter.
For this example we have a person object containing properties for name, surname and imageUrl (the web location for the image)
The following is the Person Class Object:
public class Person {
String name;
String surname;
String imageUrl;
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
Now we create an xml layout which will populate our listview with data. Nothing fancy here just a layout containing a textview for name, another for surname and an imageview for our image. The file in this case is called person_cell.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/person_cell_txtName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/person_cell_txtSurname" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/person_cell_imageview" />
</LinearLayout>
So til now we have a class for our person object, and an xml layout ready for use. Now we build our Custom Adapter. Create a class named MyAdapter which extends ArrayAdapter of type Person. Note that we need to pass the context to the adapter since we will be using Picasso to load the image.
public class MyAdapter extends ArrayAdapter<Person> {
Context context;
List<Person>myList;
public MyAdapter(Context context, int resource, List<Person> objects) {
super(context, resource, objects);
this.context = context;
this.myList = objects;
}
#Override
public int getCount() {
if(myList != null)
return myList.size();
return 0;
}
#Override
public Person getItem(int position) {
if(myList != null)
return myList.get(position);
return null;
}
#Override
public long getItemId(int position) {
if(myList != null)
return myList.get(position).hashCode();
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
//If the listview does not have an xml layout ready set the layout
if (convertView == null){
//we need a new holder to hold the structure of the cell
holder = new Holder();
//get the XML inflation service
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//Inflate our xml cell to the convertView
convertView = inflater.inflate(R.layout.person_cell, null);
//Get xml components into our holder class
holder.txtName = (TextView)convertView.findViewById(R.id.person_cell_txtName);
holder.txtSurname = (TextView)convertView.findViewById(R.id.person_cell_txtSurname);
holder.imageView = (ImageView)convertView.findViewById(R.id.person_cell_imageview);
//Attach our holder class to this particular cell
convertView.setTag(holder);
}else{
//The listview cell is not empty and contains already components loaded, get the tagged holder
holder = (Holder)convertView.getTag();
}
//Fill our cell with data
//get our person object from the list we passed to the adapter
Person person = getItem(position);
//Fill our view components with data
holder.txtName.setText(person.getName());
holder.txtSurname.setText(person.getSurname());
Picasso.with(context).load(person.getImageUrl()).fit().into(holder.imageView);
return convertView;
}
/**
* This holder must replicate the components in the person_cell.xml
* We have a textview for the name and the surname and an imageview for the picture
*/
private class Holder{
TextView txtName;
TextView txtSurname;
ImageView imageView;
}
}
Then in our Activity we can simply populate our List of person objects and create an instance of our adapter and set it as the listview main adapter.
ListView myListView = new ListView(getApplicationContext());
List<Person> personList = new ArrayList<>();
Person person = new Person();
person.setName("John");
person.setSurname("Doe");
person.setImageUrl("https://lh3.googleusercontent.com/-Sa9kdnhuE5E/AAAAAAAAAAI/AAAAAAAAABs/ILmJ8_sk9aY/photo.jpg");
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.person_cell, personList);
myListView.setAdapter(adapter);
This is basically the story behind a custom adapter.
Based on your JSON,all you have is the image file name. ie:
{
.
.
.
"cover_photo":"2018061675.jpg"
}
You will first need an API to deliver the InputStream from your image.
after that you have 3 options:
Volley
Its a very simple to use(but very powerful) library which takes care of maintaining your resource pool and memory when you.
This video is an introduction to volley.Please watch it if you have prior android experience or I would suggest watching to merely understand how it affects your normal methods.
making an image request is mentioned in the android tutorial for volley
OkHttp
It requires more working and is lightweight for overall http request use.
the image request can be obtained as file as detailed here
Picasso
Simple library meant solely for image request purposes
Do it manually
Use an input stream and fetch and build your image manually
This is is a good example or that.

How can a click Listener in a custom ListAdapter modify the lists data?

I'm trying to make a relatively simple filesystem browser that displays directories and lets you select them. I have a list fragment which uses a custom adapter to display the directories as a list. I have created a clickListener for each entry in the list. I need to get it so that when a list entry is clicked, the entire list view refreshes. As this click listener is defined within my adapter though, how can it signal up the stack somehow to the list fragment, in order to tell it to refresh the data that the adapter uses. Help much appreciated.
Here is my code:
PickerFragment.java:
package com.grid.picker;
import android.content.Intent;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import android.os.Environment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import static android.content.Intent.getIntent;
public class PickerFragment extends ListFragment
{
private String currentFilesystemPath = ""; // This path does not include the root path
private int numberOfFolders = 0;
private List<Folder> folders = new ArrayList<Folder>();
public PickerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
private void tempPopulate()
{
folders.add(new Folder("TestFolder", "/test/path"));
}
private void populateFolders()
{
// Create a new File at the current path
File currentFolder = new File(Environment.getExternalStorageDirectory().getPath()+currentFilesystemPath);
Utility.debugOutput("populateFolders() currentFolder: " +currentFolder);
// Lets get the list of folders
String[] directories = currentFolder.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
// Build up the list of folders with folder objects
for(int i=0; i<directories.length;i++)
{
//Utility.debugOutput("Folder:" +directories[i].toString());
folders.add(new Folder(directories[i].toString(), currentFolder.getPath()+directories[i].toString()));
}
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Temporary folder population
//tempPopulate();
populateFolders();
/*
// Set an adapter for this list fragment to use
setListAdapter(new ArrayAdapter<Folder>(getActivity(),
android.R.layout.simple_list_item_activated_1, folders));
*/
// We want to use our custom adapter. We pass in this activity, the layout to use, and an array of folders
// We give it a new Folder object just so it knows what type of objects are in the array...??
FolderAdapter adapter = new FolderAdapter(this.getActivity(), R.layout.listview_item_row, folders.toArray(new Folder[0]));
// Use our custom adapter for the list
setListAdapter(adapter);
}
}
FolderAdapter.java:
package com.grid.picker;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FolderAdapter extends ArrayAdapter<Folder>
{
Folder[] folders = null;
Context context;
int layoutResourceId;
// Constructor
// Param 1: Reference of the activity
// Param 2: The resource id of the layout file we want to use for displaying each ListView item
public FolderAdapter(Context context, int layoutResourceId, Folder[] data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.folders = data;
}
// This is a function that the click listener can call to start the list update process
public void updateList(String name)
{
Utility.debugOutput("updateList() rx: " +name);
this.notifyDataSetChanged();
}
// Presumably getView is called for every row in the list ?
// position is the index of the list item in the list
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// Create a new view to play with
View row = convertView;
final int rowID = position;
FolderHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
// Inflate (parse) the layout XML
row = inflater.inflate(layoutResourceId, parent, false);
//Instantiate a new static object for folder icons (static for speed (caching)
holder = new FolderHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
// Set clickListener
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Utility.debugOutput("Row ID clicked: " +rowID);
Utility.debugOutput("Folder array:" +folders[rowID].folderName);
updateList(folders[rowID].folderName);
//Toast.makeText(context,"you clicked item: "+rowID, Toast.LENGTH_LONG.show();
//code you want to execute on click of list item...
}
});
}
else
{
holder = (FolderHolder)row.getTag();
}
Folder folder = folders[position];
holder.txtTitle.setText(folder.folderName);
holder.txtTitle.setText(folder.folderName);
holder.imgIcon.setImageResource(folder.icon);
/*
// Add click listener to the view
View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
Utility.debugOutput("Something clicked???!");
// This call requires API level 15 minimum...
v.callOnClick();
}
}; */
//row.setOnClickListener(clickListener);
return row;
}
// This class will be used as a cache for the folder images
static class FolderHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
Folder.java:
package com.grid.picker;
public class Folder
{
// Each instance of this class will be an entry in the folder list
public String folderName;
public String fullPath;
public boolean hasChildren = false; // False by default
public static final int icon = R.drawable.folder;
// Constructor
public Folder(String newName, String newFullPath)
{
folderName = newName;
fullPath = newFullPath;
}
}
listview_item_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<ImageView android:id="#+id/imgIcon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="15dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
<TextView android:id="#+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
Eventually I am going to need to put a checkbox on each folder displayed in the list, but for now I need to get it so the folders shown in the list can be clicked on to refresh the display and update the list. Many thanks.
use this on your click listener
// Set clickListener
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Utility.debugOutput("Row ID clicked: " +rowID);
Utility.debugOutput("Folder array:" +folders[rowID].folderName);
notifyDataSetInvalidated();
}
});

Populating a ListView with Objects from Parse.com Android

I'm trying to fill a ListView with objects from my database at Parse.com, but I'm am having trouble because the ListView does not accept objects directly. I've tried making an array of strings by looping through my objects and casting them as strings but that failed. I have also tried to call a .toString on the objects but no luck either.
My plan is to loop through all of the parse objects and then add them to the ListView. That ListView will then be used to allow the user to search through all of the objects from Parse.com. The objects from Parse.com should replace the listview_array[] data....ex replace "BudWeiser", "Dubra" etc....
The loop I did create to retrieve the Objects names, prices, size did work, but I could not place it into the listView since I believe it was an object.
Here's my code
package com.alpha.dealtap;
import java.lang.reflect.Array;
import java.util.List;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class Search_Page extends Activity {
private ListView lv;
private EditText et;
public String listview_array[] = { "BudWeiser", "Dubra", "Corona",
"Jack Daniels", "Smirnoff", "Keystone Light", "Natural Ice" };
private ArrayList<String> array_sort = new ArrayList<String>();
public ArrayList<Object> _arrayList = new ArrayList<Object>();
int textlength = 0;
ParseObject dealsObject;
int n = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_page);
Parse.initialize(this, "vUz23Z6zdIL1jbxbVWeLpsSdu1ClTu3YiG30zTWY",
"4BTyoq1QQKows8qVJV7lvU3ZokSRrLFyOCPzffwJ");
// Using this Parsequery...I can grab/locate the objects from the Parse
// list...Here I grabbed the objects that have Burnettes and the price
// of it
// Eventually I may need to set a limit on how many results I will get
// from the for loop....So far I think it is limited to 100 by default
ParseQuery query = new ParseQuery("Deals");
// query.whereEqualTo("Brand", "Burnettes");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
Log.d("Brand", "Retrieved " + objects.size() + " Brands");
for (ParseObject dealsObject : objects) {
// use dealsObject.get('columnName') to access the
// properties of the Deals object
Object brands = dealsObject.get("Brand").toString();
_arrayList.add(brands);
listview_array = _arrayList;
//Having trouble putting strings into an array list....Have to cast as ArrayList and then it causes error!
Log.d("Size", (String) dealsObject.get("Size"));
Log.d("Price", (String) dealsObject.get("Price"));
Log.d("Brand", (String) dealsObject.get("Brand"));
n++;
}
} else {
Log.d("Brand", "Error: " + e.getMessage());
}
}
});
Button store = (Button) findViewById(R.id.b1);
Button deal = (Button) findViewById(R.id.b2);
lv = (ListView) findViewById(R.id.ListView01);
et = (EditText) findViewById(R.id.search_box);
lv.setAdapter(new ArrayAdapter<Object>(this,
android.R.layout.simple_list_item_1, listview_array));
et.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength = et.getText().length();
array_sort.clear();
for (int i = 0; i < listview_array.length; i++) {
if (textlength <= listview_array[i].length()) {
if (et.getText()
.toString()
.equalsIgnoreCase(
(String) listview_array[i].subSequence(
0, textlength))) {
array_sort.add(listview_array[i]);
}
}
}
lv.setAdapter(new ArrayAdapter<String>(Search_Page.this,
android.R.layout.simple_list_item_1, array_sort));
}
});
store.setOnClickListener(new View.OnClickListener() {
// When you use OnClickListener...you need the onClick method inside
// of it
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.alpha.dealtap.STOREPAGE"));
}
});
deal.setOnClickListener(new View.OnClickListener() {
// When you use OnClickListener...you need the onClick method inside
// of it
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.alpha.dealtap.DEALPAGE"));
}
});
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// Cheese equals the position for which item that is clicked...so it
// depends on which item that is clicked
String cheese = "TAPDEAL";
try {
Class ourClass = Class.forName("com.alpha.dealtap." + cheese);
Intent ourIntent = new Intent(Search_Page.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
}
you can use BaseAdapter class for custom listview. here is the code for that.
List<ParseObject> parse = new ArrayList<ParseObject>();
public class CustomChannelListAdapter extends BaseAdapter {
private Context context;
public CustomChannelListAdapter(Context context) {
super();
this.context = context;
}
#Override
public int getCount() {
if (parse != null) {
return parse.size();
}
return 0;
}
#Override
public Channel getItem(int position) {
// TODO Auto-generated method stub
return parse.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
TextView tittle = null;
TextView desc = null;
TextView nowPlaying = null;
if (view == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
view = inflater.inflate(R.layout.video_listrow, parent, false);
} else {
view = convertView;
}
tittle = (TextView) view.findViewById(R.id.title);
desc = (TextView) view.findViewById(R.id.Descp);
nowPlaying = (TextView) view.findViewById(R.id.NowplayingId);
if (parse!= null) {
if (parse.get(position).getName() != null) {
tittle.setText(parse.get(position).getName()
.toString());
} else {
tittle.setText("----------------------");
}
if (parse.get(position).getDesc() != null) {
desc.setText(parse.get(position).getDesc()
.toString());
} else {
desc.setText("------------------------");
}
}
return view;
}
}
video_listrow.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="400dp"
android:layout_height="75dp"
android:background="#drawable/videolist_selector"
android:orientation="horizontal"
android:paddingLeft="5dp"
android:paddingRight="5dp" >
<!-- Title Of Song -->
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:textColor="#color/orange"
android:textSize="18dip"
android:textStyle="bold"
android:typeface="sans"
android:ellipsize="marquee"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="5dip"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="Tittle Not Found " />
<!-- Artist Name -->
<TextView
android:id="#+id/Descp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail"
android:paddingTop="5dp"
android:textColor="#color/white"
android:textSize="12dip"
android:textStyle="bold"
android:typeface="sans"
android:ellipsize="marquee"
android:freezesText="true"
android:marqueeRepeatLimit="marquee_forever"
android:paddingLeft="5dip"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="Description Not Found"
/>
<!-- Rightend Duration -->
<!--
<TextView
android:id="#+id/duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#id/title"
android:gravity="right"
android:text="5:45"
android:layout_marginRight="5dip"
android:textSize="10dip"
android:textColor="#10bcc9"
android:textStyle="bold"/>
-->
<!-- Rightend Arrow -->
<!--
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
-->
<TextView
android:id="#+id/NowplayingId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="5dp"
android:layout_marginRight="4dp"
android:text="Now playing..."
android:textColor="#color/red"
android:textSize="12dp" />
</RelativeLayout>
In your activity code
ListView videoList = (ListView) findviewByid(_);
CustomChannelListAdapter channelAdapter = new CustomChannelListAdapter(PlasmaView.this);
videoList.setAdapter(channelAdapter);

Categories

Resources