Cannot be referenced from static context Android - android

I'm a beginner on Android, i'm creating a movie application where the user can browse the movies and search for top rated or most popular ones.
i'm using DetailsFragment to display movie details, also i'm using an expandable list view to display movie's trailers and reviews
my problem is that i get an error on this line
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
that says: this cannot be referenced from static context and i can't solve it by using getActivity() or DetailsFragment.this
Sorry if I'm being extremely incompetent but I searched and I couldn't understand how to fix it. Thanks.
here is DetailsFragment.java
package com.example.android.movies;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.android.movies.R.id.favoriteButton;
import static com.example.android.movies.R.id.iv_poster;
/**
* A placeholder fragment containing a simple view.
*/
public class DetailsFragment extends Fragment{
static Long id;
String title, overview, poster, date;
String vote;
ImageView posterIV;
TextView titleTV, dateTV, overviewTV, voteTV;
static Context mContext;
static ExpandableListAdapter listAdapter;
static ExpandableListView expListView;
static List<String> listDataHeader;
static HashMap<String, List<Trailers>> listDataChild;
static ArrayList<Trailers> arrTrailers;
static ArrayList<Trailers> arrReviews;
ToggleButton favorite;
private MoviesDB db;
Trailers t;
public static DetailsFragment newInstance() {
return new DetailsFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
// get the listview
expListView = (ExpandableListView) rootView.findViewById(R.id.lvExp);
// receiving intent
Intent gIntent = getActivity().getIntent();
Movies movie = null;
if (gIntent != null && gIntent.hasExtra("movie")) {
movie = gIntent.getParcelableExtra("movie");
id = movie.getMposter_id();
title = movie.getMtitle();
titleTV = (TextView) rootView.findViewById(R.id.tv_title);
titleTV.setText(title);
date=movie.getMdate();
dateTV = (TextView) rootView.findViewById(R.id.tv_date);
dateTV.setText(date);
vote=String.valueOf(movie.getMvote());
voteTV= (TextView) rootView.findViewById(R.id.tv_vote);
voteTV.setText(vote);
overview=movie.getMoverview();
overviewTV = (TextView) rootView.findViewById(R.id.tv_overview);
overviewTV.setText(overview);
poster = movie.getMposter_path();
posterIV = (ImageView) rootView.findViewById(iv_poster);
Picasso.with(getActivity())
.load("http://image.tmdb.org/t/p/w185".concat(poster)).into(posterIV);
favorite= (ToggleButton) rootView.findViewById(favoriteButton);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
db.insert(id,title,poster,date, Double.parseDouble(vote),overview,t.getContent1());
}
});
return rootView;
}
private static void settingAdapter() {
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
/*
* Preparing the list data
*/
private static void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<Trailers>>();
// Adding child data
listDataHeader.add("Reviews");
listDataHeader.add("Trailers");
listDataChild.put(listDataHeader.get(0), arrReviews); // Header, Child data
listDataChild.put(listDataHeader.get(1), arrTrailers);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext=getActivity();
new TrailersFetcher(getActivity(), id).execute();
}
public static void updateTrailers(ArrayList<Trailers> trailers){
arrTrailers = new ArrayList<>();
for (int i = 0; i <trailers.size() ; i++) {
arrTrailers.add(trailers.get(i));
}
new ReviewsFetcher(mContext, id).execute();
}
public static void updateReviews(ArrayList<Trailers> reviews){
arrReviews = new ArrayList<>();
for (int i = 0; i <reviews.size() ; i++) {
arrReviews.add(reviews.get(i));
}
settingAdapter();
}
}

Simlple OOP rule - Non-static variables/members/objects cannot be referenced in static context (methods, classes etc).
Why?
Static references does not require initialization to call, so there may be cases (mostly) that normal (non-static) members/objects are not initialized and a call is made to that (static) method. This will always throw NullPointerException (for reference types).
So its checked at compile time that non-static reference is not made in static context.
Solution..
either make a static object of ExpandableList, or
remove static from private static void settingAdapter().

I think you don't need so many static declarations.
modifier 'static' is only allowed in constant variable declarations.
Non-static variable this cannot be referenced from a static context.
private static void settingAdapter() {
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
Just remove 'static':
From Methods:
settingAdapter
prepareListData
updateTrailers
updateReviews
From Variables:
Context mContext
ExpandableListAdapter listAdapter
ExpandableListView expListView
List listDataHeader
HashMap> listDataChild
ArrayList arrTrailers
ArrayList arrReviews

Related

Dynamically adding data to listView which does not overwrite the previous data and permanently saving it

In the following program, When I click on Add button in the options menu a dialog is opened wherein the user enters the data which is then shown in the ListView.
There are a number of problems with his code.
1) age.setText in the Custom Adapter causes the app to crash.Commenting out the age.settext line, it works well for the other two TextViews.
2) When i add data in the list using the dialog the second time, the list gets overwritten and no updation is done.
I want the list to be automatically updated when new data is entered rather than over writing it.
3) The data vanishes away when i restart the app. I want the data to be saved permanently.
Code for Custom Adapter is:
package com.example.sakshi.dialogsandmenus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<Data> list;
private LayoutInflater mLayoutInflator;
public CustomAdapter(Context context, ArrayList list){
this.context=context;
this.list=list;
mLayoutInflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
dob.setText(list.get(position).getDate());
return convertView;
}
}
Code for Main Activity is:
package com.example.sakshi.dialogsandmenus;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.R.id.list;
import static com.example.sakshi.dialogsandmenus.R.id.date;
public class MainActivity extends AppCompatActivity{
ListView listview;
ArrayList<Data> arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView)findViewById(R.id.list_item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==R.id.add){
filldialog();
}
return super.onOptionsItemSelected(item);
}
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
arrayList = new ArrayList<>();
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
//customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
}
}
1) you have to convert the value of age to String before setText
//age.setText(list.get(position).getAge());
age.setText(Integer.toString(list.get(position).getAge()));
2) Every time new Arraylist initilaization
intarrayList = new ArrayList<>();
ArrayList arrayList = new ArrayList<>();
public void filldialog(){
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setCanceledOnTouchOutside(false);
dialog.setContentView(R.layout.dialog_layout);
dialog.show();
Button add = (Button)dialog.findViewById(R.id.additem);
final EditText getnamedata = (EditText)dialog.findViewById(R.id.name);
final EditText getagedata = (EditText)dialog.findViewById(R.id.age);
final DatePicker datePicker = (DatePicker)dialog.findViewById(date);
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getname = getnamedata.getText().toString();
int getage = Integer.parseInt(getagedata.getText().toString());
int mm,y,d;
mm=datePicker.getMonth();
y=datePicker.getYear();
d=datePicker.getDayOfMonth();
String getdate = d+"/"+mm+"/"+y;
Data data = new Data();
data.setName(getname);
data.setAge(getage);
data.setDate(getdate);
arrayList.add(data);
customAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
enter code here
3) Use Sqlite or anyStorage Option for data saving
You are setting int value directly to setText of ageTextView. You need to convert int to String before you setting a text to TextView.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mLayoutInflator.inflate(R.layout.row,null);
TextView name = (TextView)convertView.findViewById(R.id.name);
TextView age = (TextView)convertView.findViewById(R.id.agedata);
TextView dob = (TextView)convertView.findViewById(R.id.dob);
name.setText(list.get(position).getName());
//age.setText(list.get(position).getAge());
age.setText(String.valueOf(list.get(position).getAge())); // use this it will work
dob.setText(list.get(position).getDate());
return convertView;
}
}
Move these lines outside the onClickListener
arrayList = new ArrayList<>();
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,arrayList);
listview.setAdapter(customAdapter);
Because whenever you are clicking the button arraylist is initializing again.

Only returns an index of -1 when there is a match

I am trying to get an index of a item in an array that is selectable in a list view. The only issue is that when i click on the item, it only returns the index of -1 which means that it doesnt match when in fact there should be a match. Thanks in advanced!
package com.goldleaf.branden.goldleafcomics;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.kosalgeek.android.json.JsonConverter;
import com.kosalgeek.genasync12.*;
import java.io.FileInputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GlimpseListFragment extends ListFragment {
List<String> glimpse = new ArrayList<String>();
List<String> titles = new ArrayList<String>();
List<UniverseListing> universalListings = new ArrayList<UniverseListing>();
public GlimpseListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_glimpse_list, container, false);
return rootView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String url = "http://goldleafcomics.com/application/UniverseGlimpse.JSON";
PostResponseAsyncTask task = new PostResponseAsyncTask(getActivity(), new AsyncResponse() {
#Override
public void processFinish(String s) {
universalListings = new JsonConverter<UniverseListing>().toArrayList(s, UniverseListing.class);
Toast.makeText(getActivity(), "Application Data Refreshed", Toast.LENGTH_LONG).show();
ArrayList<String> glimpse = new ArrayList<String>();
for(UniverseListing value: universalListings){
glimpse.add(value.universeGlimpse);
}
ArrayList<String> titles = new ArrayList<String>();
for(UniverseListing value: universalListings){
titles.add(value.universeId);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, titles);
setListAdapter(adapter);
}
});
task.execute(url);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String value = (String)getListAdapter().getItem(position);
int index = this.titles.indexOf(value);
String value2 = Integer.toString(index);
Toast.makeText(getActivity(), value2, Toast.LENGTH_LONG).show();
}
}
you define glimpse two times, could you try to make those changes,
List<String> glimpse;
and inside onCreate initialize it
glimpse = new ArrayList<>();
and do the same for titles and universalListings.
Try using these two sections of code. You are shadowing the member variables with local variables of the same name.
public class GlimpseListFragment extends ListFragment {
List<String> glimpse;
List<String> titles;
List<UniverseListing> universalListings;
Later...
glimpse = new ArrayList<String>();
for(UniverseListing value: universalListings){
glimpse.add(value.universeGlimpse);
}
titles = new ArrayList<String>();
for(UniverseListing value: universalListings){
titles.add(value.universeId);
}
You don't need to initialize Arraylists with the class. You should typically lazily initialize them (in other words, when you need to)

In android using OnClickListner for expandable listview

I am new to android please help me out for this problem.
In expandable list view clicking on each child list new activity should open.
here is my code
package com.example.index;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
public class IndexMainActivity extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index_main);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Part 1");
listDataHeader.add("Part 2");
listDataHeader.add("Part 3");
// Adding child data
List<String> parta = new ArrayList<String>();
parta.add("Sweet Hour Of Prayer");
parta.add("Prayer and Royal Family");
parta.add("The Holy Bible-King James Version");
parta.add("William shakespeare - Scriptres about prayer");
List<String> partb = new ArrayList<String>();
partb.add("Samuel Rutherford/scriptures-Thankfulness");
List<String> partc = new ArrayList<String>();
partc.add("Matthew Henry/Scriptures on - Faith");
partc.add("John Wesley/Scriptures on - Freedom");
partc.add("Charles Simeon/Scriptures on -Protection");
partc.add("Christmas Evans/Scriptures on - Guidance");
listDataChild.put(listDataHeader.get(0), parta); // Header, Child data
listDataChild.put(listDataHeader.get(1), partb);
listDataChild.put(listDataHeader.get(2), partc);
}
}
there are three list i.e part a , part b and part c now by clicking on part a i will get four child list by clicking on first child list i.e Sweet Hour of prayer new activity should open.
Try Below Code:
public class MyActivity extends Activity implements ExpandableListView.OnChildClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
{
Toast.makeText(getApplicationContext(), "Go to Activity :: "+childPosition, Toast.LENGTH_LONG).show();
return true;
}
}
There is a onChildClickListener for ExpandableListView. Check this code:
yourListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// Open activity using intent...
return false;
}
});
Hope it helps!

load a few json elements at a time by scrollview

I have a ListFragment that contains a list of items. I would like to load say 9 items at a time and when i scroll and reach the bottom of the listview i want to load another 9 items in background.
I make 2 request to my web server:
1) to get all the item id's of the items, by a searh() method
2) to get all the item details of a specific item though its id, by getId(id) method
The version i have implemented gets all the ids and then loads all the items at once in the doInBackground method of AsyncTask and it works. and it takes very long (i dont want a button because its really ugly).
I'd like to introduce this thing about the onScrollListener so that when i first open my app, in background i get all the ids, and then i get the first 9 items and show them. then when i scroll to the end i want to load the next 9 items. How do i do this?
I have read a few posts but it not clear to me, especially due to the fact that i have 2 functions that need to be run in background, 1 function needs to be run once while the other many times and i need to keep track of which id's i getting.
I would also if possible like to add the function that if i pull the ListView a little then it should update my view.
Here is my code:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.adapter.ListViewAdapter;
import com.prjma.lovertech.util.MVPFunctions;
public class CompraFragment extends ListFragment {
public ListView listView;
public ListViewAdapter adapter;
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private DownloadTask mDownloadTask = null;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.fragment_compra, false);
View rootView = inflater.inflate(R.layout.fragment_compra, container, false);
// now you must initialize your list view
listView = (ListView) rootView.findViewById(android.R.id.list);
mDownloadTask = new DownloadTask();
mDownloadTask.execute((Void) null);
return rootView;
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog progressDialog;
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
//Here i get all the id's
ArrayList<Long> ids = MVPFunctions.getMioSingolo().search();
//for each id get all its details and put it in a map
items = new ArrayList<HashMap<String, Object>>();
for(int i=0; i < ids.size(); i++){
items.add(MVPFunctions.getMioSingolo().getItem(ids.get(i)));
}
return true;
}
#Override
protected void onPreExecute(){
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(getActivity(), "", "Downloading Content...");
}
#Override
protected void onPostExecute(final Boolean success) {
mDownloadTask = null;
// dismiss the dialog after getting all products
progressDialog.dismiss();
//showProgress(false);
if (items.get(0).get("status error")!= null){
Toast.makeText(getActivity(), "status error = " + items.get(0).get("status error"), Toast.LENGTH_LONG).show();
Log.i("status error put toast", (String) items.get(0).get("status error"));
//fai qualcosa, tipo torna indietro, ecc
}
// updating UI from Background Thread
ListViewAdapter adapter = new ListViewAdapter(getActivity(),R.layout.listview_item_row, items, icon);
// updating listview
listView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
mDownloadTask = null;
//showProgress(false);
}
}
}
Adapter class:
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.prjma.lovertech.R;
import com.prjma.lovertech.activity.DettagliActivity;
import com.prjma.lovertech.model.Item;
public class ListViewAdapter extends ArrayAdapter<String> {
private static LayoutInflater inflater = null;
public Context context;
public int layoutResourceId;
public ArrayList<HashMap<String, Object>> items;
public Bitmap icon;
//public ImageLoader imageLoader;
public ListViewAdapter(Context context, int listviewItemRow, ArrayList<HashMap<String, Object>> items, Bitmap icon) {
// TODO Auto-generated constructor stub
super(context, listviewItemRow);
this.items = items;
this.context = context;
this.icon = icon;
}
public int getCount() {
return items.size();
}
public Item getItem(Item position) {
return position;
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder viewHolder = new ViewHolder();
if (row == null) {
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listview_item_row, null);
viewHolder.ic_thumbnail = (ImageView)row.findViewById(R.id.ic_thumbnail);
viewHolder.scadenza = (TextView)row.findViewById(R.id.tvScadenza);
viewHolder.prezzo = (TextView)row.findViewById(R.id.tvPrezzo);
viewHolder.followers = (TextView)row.findViewById(R.id.tvFollowers);
viewHolder.hProgressBar = (ProgressBar)row.findViewById(R.id.hProgressBar);
row.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)row.getTag();
}
HashMap<String, Object> item = items.get(position);
viewHolder.ic_thumbnail.setImageBitmap((Bitmap) item.get("pic1m"));
viewHolder.scadenza.setText((CharSequence) item.get("scadenza"));
viewHolder.prezzo.setText((CharSequence) item.get("prezzo"));
viewHolder.followers.setText((CharSequence) item.get("followers"));
viewHolder.hProgressBar.setProgress((Integer) item.get("coefficient"));
//row.onListItemClick(new OnItemClickListener1());
row.setOnClickListener(new OnItemClickListener(position));
return row;
}
private class OnItemClickListener implements OnClickListener {
private int mPosition;
private OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.i("onListItemClickList", "Item clicked: " + mPosition);
Toast.makeText(context, "Message " + Integer.toString(mPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DettagliActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("id", mPosition);
intent.putExtras(bundle);
context.startActivity(intent);
}
}
static class ViewHolder {
public TextView prezzo;
public TextView scadenza;
public TextView followers;
public ImageView ic_thumbnail;
public ProgressBar hProgressBar;
}
}
In your adapter, check how close the user is from the bottom of the data set. When they get to the end, call a method that fetches more items from the network. I normally use a "REFRESH_THRESHOLD" integer to prefetch items before they're needed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Item current = getItem(position);
//Pre-fetch
if(getCount() - position <= REFRESH_THRESHOLD){
//If there are more items to fetch, and a network request isn't already underway
if(is_loading == false && has_remaining_items == true){
getItemsFromNetwork();
}
}

Set onChildItemClickListner for ExpadableListView?

So, I was wondering if there is any method to set Up onclickListner for Expandable List view..
I know that it is possible when you haven't implement Child data with "HashMap".
here is My code. I tired all possible onclick listeners for hashmap method. but no success yet.
enter code here
package com.prashant.dfs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ExpandableListView;
public class Chapter_1_full extends Activity {
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> ListDataHeader;
HashMap<String,List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_1_full);
//get the listView(expand)
expListView = (ExpandableListView) findViewById(R.id.ch1_expand);
//prepareDataList
prepareListData();
listAdapter=new ExpandableListAdapter(this, ListDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
}
private void prepareListData() {
ListDataHeader = new ArrayList<String>();
listDataChild=new HashMap<String, List<String>>();
//Adding child Data
ListDataHeader.add("1.1 Introductin");
ListDataHeader.add("1.2 DataType");
ListDataHeader.add("1.3 ADT");
List<String> Intro = new ArrayList<String>();
Intro.add("WHAT is DFS");
Intro.add("Algorithem");
Intro.add("Flowchart");
List<String> datatype = new ArrayList<String>();
datatype.add("WHAT is DFS");
datatype.add("Algorithem");
datatype.add("Flowchart");
List<String> ADT = new ArrayList<String>();
ADT.add("WHAT is DFS");
ADT.add("Algorithem");
ADT.add("Flowchart");
listDataChild.put(ListDataHeader.get(0),Intro);
listDataChild.put(ListDataHeader.get(1),datatype);
listDataChild.put(ListDataHeader.get(2),ADT);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.chapter_1_full, menu);
return true;
}
}
Well, assuming your adapter is correctly implementing its methods...
expandableListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(final ExpandableListView parent, final View view, final int groupPosition, final int childPosition,
final long identifier) {
final Object childObj = parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
if (childObj != null) {
// Do your magic
}
return true;
}
});

Categories

Resources