MainFragment:
public class MainFragment extends Fragment {
RecyclerView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
// URL Address
String url = "http:";
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String x = "/aaa/bbb/omer/000";
String []tokens = x.split("/aaa/bbb/");
for (String t: tokens)
Toast.makeText(getActivity(), t, Toast.LENGTH_SHORT).show();
View view =inflater.inflate(R.layout.fragment_main, container, false);
listview = (RecyclerView) view.findViewById(R.id.listview);
listview.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
listview.setLayoutManager(llm);
new JsoupListView().execute();
return view;
}
// Title AsyncTask
private class JsoupListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Diziler Yükleniyor");
// Set progressdialog message
mProgressDialog.setMessage("Yükleniyor...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Connect to the Website URL
Document doc = Jsoup.connect(url).get();
// Identify Table Class "worldpopulation"
for (Element table : doc.select("div[class=col-sm-12 col-xs-12 pad0 middle]")) {
// Identify all the table row's(tr)
for (Element row : table.select("div[class=col-sm-12 col-xs-12 pad0 streamingBoxWrap mNewsItem]:gt(0)")) {
HashMap<String, String> map = new HashMap<String, String>();
// Identify all the table cell's(td)
Elements tds = row.select("a");
// Identify all img src's
Elements imgSrc = row.select("img[src]");
// Get only src from img src
String imgSrcStr = imgSrc.attr("src");
Elements aSrc = row.select("a[href]:gt(1)");
String aSrcStr = aSrc.attr("href");
// Retrive Jsoup Elements
// Get the first td
map.put("rank", aSrcStr);
// Get the second td
map.put("country", tds.get(1).text());
// Get the third td
map.put("population", tds.get(2).text());
// Get the image src links
map.put("flag", imgSrcStr);
// Set all extracted Jsoup Elements into the array
arraylist.add(map);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
listview.setAdapter(adapter);
listview.setItemAnimator(new DefaultItemAnimator());
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ListViewAdapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
final TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.singleitemview, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainFragment.RANK));
country.setText(resultp.get(MainFragment.COUNTRY));
population.setText(resultp.get(MainFragment.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainFragment.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
DiziFragment myFragment3 = new DiziFragment();
Bundle bundle = new Bundle();
bundle.putString("gun",resultp.get(MainFragment.POPULATION));
bundle.putString("flag",resultp.get(MainFragment.FLAG));
myFragment3.setArguments(bundle);
android.support.v4.app.FragmentTransaction fragmentTransaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,myFragment3);
fragmentTransaction.commit();
}
});
return itemView;
}
}
Gradle build
I want to list items with recyclerview. Help me Please.
Turkish:kodda listview ile liteliyordu ben ise recyclerview ile listelemek istiyorum.
edit my code
adapter:
public class SimpleRecyclerAdapter extends RecyclerView.Adapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public SimpleRecyclerAdapter(Context context,ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int position) {
final TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.singleitemview, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainFragment.RANK));
country.setText(resultp.get(MainFragment.COUNTRY));
population.setText(resultp.get(MainFragment.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainFragment.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
DiziFragment myFragment3 = new DiziFragment();
Bundle bundle = new Bundle();
bundle.putString("gun",resultp.get(MainFragment.POPULATION));
bundle.putString("flag",resultp.get(MainFragment.FLAG));
myFragment3.setArguments(bundle);
android.support.v4.app.FragmentTransaction fragmentTransaction = ((FragmentActivity)context).getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,myFragment3);
fragmentTransaction.commit();
}
});
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
return itemView; is eroor
If you are using recycler view then your adapter should also extends recycler view instead of Base Adapter. For eg.
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> {
private List<FeedItem> feedItemList;
private Context mContext;
public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) {
this.feedItemList = feedItemList;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
FeedItem feedItem = feedItemList.get(i);
//Download image using picasso library
Picasso.with(mContext).load(feedItem.getThumbnail())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
//Setting text view title
customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle()));
}
#Override
public int getItemCount() {
return (null != feedItemList ? feedItemList.size() : 0);
}
}
Related
In each row, I have a button and a textView. When the Button is clicked, It successfully sets the textView to a new value in that row. However, When I call ParseQuery() in GetView(); and try to do object.put("objectName", num) The only value that is populated to my Parse-Server is the last row. My SetTag(); and GetTag(); and ViewHolder class is correct When I click the button, I believe android studio is unsure of which row's TextView to populate so it just automatically populates the last row's TextView.
Custom ListView Adapter Class
public class CustomFeedListViewAdapter extends BaseAdapter {
String likesString;
int position;
private Context mContext;
private ArrayList<HashMap<String, String>> feed;
private static LayoutInflater inflater = null;
ParseObject parseObFeed;
public CustomFeedListViewAdapter(Context context, ArrayList<HashMap<String, String>> data) {
super();
this.mContext = context;
this.feed = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return feed.size();
}
#Override
public Object getItem(int i) {
return feed.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
position = i;
final ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.feed_list_row, viewGroup, false);
holder = new ViewHolder();
holder.feedProfilePic = (ImageView) view.findViewById(R.id.feedProfilePic);
holder.feedUsername = (TextView) view.findViewById(R.id.feedUsernameId);
holder.feedNumOfLikes = (TextView) view.findViewById(R.id.feedNumofLikes);
holder.feedUpVoteButton = (Button) view.findViewById(R.id.feedUpVoteButton);
view.setTag(holder);
HashMap<String, String> mFeed = new HashMap<>();
mFeed = feed.get(i);
holder.feedNumOfLikes.setText(mFeed.get("likes"));
likesString = mFeed.get("likes");
holder.mLikes = Integer.valueOf(likesString);
position = i;
}
else{
position = i;
holder = (ViewHolder) view.getTag();
}
holder.feedUpVoteButton.setTag(position);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("FeedItem");
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
for (final ParseObject object : objects) {
holder.feedUpVoteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject[] mParseObject = new ParseObject[feed.size()];
int pos = (Integer) v.getTag();
mParseObject[pos] = object;
holder.likes[pos] = holder.mLikes;
mParseObject[pos].put("likes", holder.likes[pos]);
mParseObject[pos].saveInBackground();
holder.feedNumOfLikes.setText(String.valueOf(holder.likes[pos]
));
}
});
}
}
}
});
return view;
}
class ViewHolder {
ImageView feedProfilePic;
TextView feedUsername;
TextView feedNumOfLikes;
TextView feedFeedItem;
TextView feedDate;
TextView feedNumofReplies;
Button feedUpVoteButton;
Button feedDownVoteButton;
Button feedCommentButton;
ListView feedListView;
int likes[] = new int[feed.size()];
int mLikes;
}
}
I have a custom listview with checkbox. It's working fine. When I click on any item its value store to arraylist and when I again click value is removed from array list. It's working but when I click on checkbox its value not store to the arraylist. I want to use checkbox setOnCheckedChangeListener to handle checkbox but issue is this I have only one adapter and I want to use this adapter for more than on activity. Please tell me can I use setOnCheckedChangeListener in activity. If I can than how to can I get position and textview and checkbox in activity please tell me with some code or edit my code thanks in adavnce.
Here is my adapter
public class Listadapter extends BaseAdapter {
CheckBox checkBox;
boolean index[];
boolean[] itemChecked;
ResolveInfo entry;
String[] itempkg;
private Context mContext;
private List<ResolveInfo> mListAppInfo;
private PackageManager mPackManager;
private ArrayList<Boolean> checkList = new ArrayList<Boolean>();
public Listadapter(Context applicationContext, List<ResolveInfo> installedApplication, PackageManager packageManager)
{
//super(applicationContext,textViewResourceId,installedApplication);
super();
this.mContext = applicationContext;
this.mListAppInfo = installedApplication;
index = new boolean[installedApplication.size()];
this.mPackManager = packageManager;
for (int i = 0; i < installedApplication.size(); i++) {
checkList.add(false);
itemChecked = new boolean[installedApplication.size()];
itempkg = new String[installedApplication.size()];
}
}
#Override
public int getCount()
{
return mListAppInfo.size();
//return ((null != mListAppInfo) ? mListAppInfo.size() : 0);
}
#Override
public Object getItem(int position)
{
// index = new boolean[mListAppInfo.size()];
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// get the selected entry
final ViewHolder holder;
// LayoutInflater inflater = (LayoutInflater) mContext.getLayoutInflater();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
// reference to convertView
holder.tvAppName = (TextView) convertView
.findViewById(R.id.textView1);
holder.tvPkgName = (TextView) convertView
.findViewById(R.id.textView);
holder.checkBox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
holder.ivAppIcon = (ImageView) convertView
.findViewById(R.id.imageView);
convertView.setTag(holder);
// holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
entry = mListAppInfo.get(position);
holder.ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
holder.tvAppName.setText(entry.loadLabel(mPackManager));
holder.tvPkgName.setText(entry.activityInfo.packageName);
holder.checkBox.setChecked(false);
if (itemChecked[position])
holder.checkBox.setChecked(true);
else
holder.checkBox.setChecked(false);
holder.checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.checkBox.isChecked()) {
itemChecked[position] = true;
} else {
itemChecked[position] = false;
}
}
});
return convertView;
}
private class ViewHolder
{
ImageView ivAppIcon;
TextView tvAppName;
TextView tvPkgName;
CheckBox checkBox;
}
}
this is activity code.
public class Profile5Activity extends Activity implements AdapterView.OnItemClickListener {
ListView apps5;
PackageManager packageManager5;
static ArrayList<String> checkedValue5;
Button bt5;
ResolveInfo pi5 = new ResolveInfo();
Context context = this;
CheckBox cb5;
Listadapter Adapter5 = null;
boolean[] itemChecked5;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile5);
itemChecked5 = new boolean[AllApps.getInstalledApplication(this).size()];
checkedValue5 = new ArrayList<String>();
}
apps5 = (ListView) findViewById(R.id.list5);
apps5.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
packageManager5 = getPackageManager();
List<String> list = new ArrayList<String>();
Adapter5 = new Listadapter(this, AllApps.getInstalledApplication(this), packageManager5);
apps5.setAdapter(Adapter5);
apps5.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, final int position, long arg3)
{
// TODO Auto-generated method stub
cb5 = (CheckBox) v.findViewById(R.id.checkBox1);
final TextView tv5 = (TextView) v.findViewById(R.id.textView);
final TextView tvv5 = (TextView) v.findViewById(R.id.textView1);
pi5 = (ResolveInfo) arg0.getItemAtPosition(position);
cb5.performClick();
if (cb5.isChecked()) {
checkedValue5.add(tv5.getText().toString());
itemChecked5[position] = true;
Toast.makeText(context, "all :" +checkedValue5, Toast.LENGTH_SHORT).show();
} else if (!cb5.isChecked()) {
checkedValue5.remove(tv5.getText().toString());
Toast.makeText(context, "all :" +checkedValue5, Toast.LENGTH_SHORT).show();
}
}
This is what i have tried, but my ListView doesn't get filled. I use a custom adapter because i wan't to change the background color of the items that't got a boolean value = true. I am using Android Studio.
Hope someone can help.
i'm new to android.
public class ShoppingListActivity extends ActionBarActivity {
private TextView header;
private ListView listView;
private CustomArrayAdapter arrayAdapter;
private ShoppingList shoppingList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
header = (TextView)findViewById(R.id.textView2);
//get reference to ListView
listView = (ListView)findViewById(R.id.shoppingListItemsView);
shoppingList = (ShoppingList) getIntent().getSerializableExtra(Globals.CHOSENLISTKEY);
arrayAdapter = new CustomArrayAdapter(this, R.layout.custom_list_view, shoppingList.getItemList());
listView.setAdapter(arrayAdapter);
header.setText(shoppingList.toString());
Button btnShop = (Button) findViewById(R.id.btnShop);
btnShop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ShoppingListActivity.this, SelectStoreActivity.class);
startActivity(intent);
}
});
}
public void setData() {
for(int i = 0; i < shoppingList.getItemList().size(); i++) {
arrayAdapter.add(shoppingList.getItemList().get(i));
}
}
}
public class CustomArrayAdapter extends ArrayAdapter<Entry> {
private int resource;
private ArrayList<Entry> list;
public CustomArrayAdapter(Context context, int resource, ArrayList<Entry> list) {
super(context, resource);
this.resource = resource;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parentGroup) {
View view = convertView;
Entry entry = list.get((position));
if(view == null) {
LayoutInflater layoutInflater = ((Activity) getContext()).getLayoutInflater();
view = layoutInflater.inflate(resource, parentGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.customName);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
return view;
}
}
To show data in ListView rows call setText method of TextView which is return from getView method:
TextView textView = (TextView) view.findViewById(R.id.customName);
// get Text from entry and pass it to setText method
String strTextViewData=entry.getItem()...;
textView.setText(strTextViewData);
if(entry.getItem().isBought()) {
textView.setBackgroundColor(Color.BLUE);
}
I am trying to design a menu like this:
It almost works, however there is a problem. The menu works fine at start, but after scrolling down and up again, the items are gone and downloaded again and it takes a little time. Is there a way to set a number of elements to create at start and keep them from disappearing?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
Possibly you can implement lazy loading with some sort of caching of images or whatever you are downloading...
You say the images are donwloaded, i assume that the images are coming from internet. Implement a custom cache for http download or download and store the images in one place before you use
i have problem with listview... i'm trying to add OnClickListener but in still doesn't work. I want to display another activity after click. Can somebody help me? I know that there are many of example, but it's doesn't work for my appl or i don't know how to use it in my example...
This is my LocationAdapter class:
public class LocationAdapter extends ArrayAdapter<LocationModel> {
int resource;
String response;
Context context;
private LayoutInflater mInflater;
public LocationAdapter(Context context, int resource, List<LocationModel> objects) {
super(context, resource, objects);
this.resource = resource;
mInflater = LayoutInflater.from(context);
}
static class ViewHolder {
TextView titleGameName;
TextView distanceGame;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
//Get the current location object
LocationModel lm = (LocationModel) getItem(position);
//Inflate the view
if(convertView==null)
{
convertView = mInflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.titleGameName = (TextView) convertView
.findViewById(R.id.it_location_title);
holder.distanceGame = (TextView) convertView
.findViewById(R.id.it_location_distance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.titleGameName.setText(lm.getGameName());
holder.distanceGame.setText(lm.getGameDistance()+" km");
return convertView;
}
}
This is my mainListView class:
public class SelectGameActivity extends Activity {
LocationManager lm;
GeoPoint userLocation;
ArrayList<LocationModel> locationArray = null;
LocationAdapter locationAdapter;
LocationList list;
ListView lv;
TextView loadingText;
TextView sprawdz;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectgame);
lv = (ListView) findViewById(R.id.list_nearme);
locationArray = new ArrayList<LocationModel>();
locationAdapter = new LocationAdapter(SelectGameActivity.this, R.layout.item, locationArray);
lv.setTextFilterEnabled(true);
lv.setAdapter(locationAdapter);
lv.setItemsCanFocus(true);
String serverName = getResources().getString(R.string.serverAdress);
ApplicationController AC = (ApplicationController)getApplicationContext();
String idPlayer = AC.getIdPlayer();
int latitude = AC.getCurrentPositionLat();
int longitude = AC.getCurrentPositionLon();
int maxDistance = 99999999;
try {
new LocationSync().execute("myserverName");
} catch(Exception e) {}
}
//this is connection with json
private class LocationSync extends AsyncTask<String, Integer, LocationList> {
protected LocationList doInBackground(String... urls) {
LocationList list = null;
int count = urls.length;
for (int i = 0; i < count; i++) {
try {
// ntar diganti service
RestClient client = new RestClient(urls[i]);
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String json = client.getResponse();
list = new Gson().fromJson(json, LocationList.class);
//
} catch(Exception e) {}
}
return list;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(LocationList loclist) {
for(LocationModel lm : loclist.getLocations())
{
locationArray.add(lm);
}
locationAdapter.notifyDataSetChanged();
}
}
EDIT:: I have second problem... i want to get id from item (items are downloading from json url) This is my list:
I want to get for example: ID:159 for first item and send it to nextActivity.
I have also the controllerClass.java where i'm setting and getting selectedIdGame:
public String getIdGameSelected() {
return idGame;
}
public void setIdGameSelected(String idGame) {
this.idGame = idGame;
}
Is it good idea? Thanks for help.
Ok, it's done. i used:
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
String idGame = (String) ((TextView) v.findViewById(R.id.idGameSelected)).getText();
Thanks, Michal.
You could define an onItemClick on your adapter instance (i.e. in mainListView.java, just after lv.setAdapter):
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View
v, int position, long id) {
Intent i = new Intent(v.getContext(), NextActivity.class);
startActivity(i);
}
});
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Intent i = new Intent(view.getContext(), NextActivity.class);
startActivity(i);
}
});
I don't know why this wouldn't work, put it after the try{}catch{} block.