May be this question many times.
i am getting some data from server and showing in listview . every thing working fine but i am getting problem to show image in list view.
Here is my example code
public class MainActivity extends ListActivity {
private static String url = null;
private static final String book_name = "b_name";
private static final String book_detail = "b_publisher";
private static final String book_image = "b_image";
ProgressDialog progressDialog;
ListView lv;
String cus_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
url = getResources().getString(R.string.url);
/*----Receiving data from Splash Activity-----*/
Bundle b = getIntent().getExtras();
cus_id = b.getString("custom_id");
new ProgressTask(MainActivity.this).execute();
}
class ProgressTask extends AsyncTask<String, Integer, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Processing...");
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(final Boolean success) {
progressDialog.dismiss();
}
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
setBookImageUrl(b_image);
setBookName(b_name);
setBookDetail(b_detail);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
public String getBookImageUrl() {
return book_image;
}
public CharSequence getBookName() {
return book_name;
}
public CharSequence getBookDetail() {
return book_detail;
}
public void setBookImageUrl(String imgeUrl) {
book_image = imgeUrl;
}
public void setBookName(String b_name) {
book_name = b_name;
}
public void setBookDetail(String b_detail) {
book_detail = b_detail;
}
}
BookListAdapter class:
public class BookListAdapter extends ArrayAdapter<MainActivity> {
private ArrayList<MainActivity> bookModels;
private Context context;
public BookListAdapter(Context context, int resource,
ArrayList<MainActivity> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_list_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView.findViewById(R.id.icon);
viewHolder.bookName = (TextView) rowView.findViewById(R.id.b_name);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.b_detail);
rowView.setTag(viewHolder);
}
final MainActivity bookModel = bookModels.get(position);
ViewHolder holder = (ViewHolder) rowView.getTag();
Picasso.with(context).load(bookModel.getBookImageUrl())
.into(holder.bookIcon);
holder.bookName.setText(bookModel.getBookName());
holder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
i can show book name and book detail in listview finely but image is not showing ..
i am getting value for book_image is http:\/\/X.X.X.X\/admin\/book_images\/232513pic9.png how to show in listview from that path..
I think you will need to implement your own adapter and use some library to display the image from URL.
My recommendation is Picasso
This is an example to implement your own adapter
BookListAdapter.java
public class BookListAdapter extends ArrayAdapter<BookModel> {
private ArrayList<BookModel> bookModels;
private Context context;
public BookListAdapter(Context context, int resource, ArrayList<BookModel> bookModels) {
super(context, resource, bookModels);
this.bookModels = bookModels;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.book_child_list, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.bookIcon = (ImageView) rowView
.findViewById(R.id.bookIcon);
viewHolder.bookName = (TextView) rowView
.findViewById(R.id.bookName);
viewHolder.bookDetail = (TextView) rowView
.findViewById(R.id.bookDetail);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) rowView.getTag();
}
final BookModel bookModel = bookModels.get(position);
Picasso.with(context).load(bookModel.getBookImageUrl()).into(viewHolder.bookIcon);
viewHolder.bookName.setText(bookModel.getBookName());
viewHolder.bookDetail.setText(bookModel.getBookDetail());
return rowView;
}
#Override
public int getCount() {
return bookModels.size();
}
static class ViewHolder {
public ImageView bookIcon;
public TextView bookName;
public TextView bookDetail;
}
}
BookModel.java
public class BookModel {
private String bookName;
private String bookDetail;
private String bookImageUrl;
public BookModel() {
bookName = "";
bookDetail = "";
bookImageUrl = "";
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDetail() {
return bookDetail;
}
public void setBookDetail(String bookDetail) {
this.bookDetail = bookDetail;
}
public String getBookImageUrl() {
return bookImageUrl;
}
public void setBookImageUrl(String bookImageUrl) {
this.icons = bookImageUrl;
}
}
Where BookModel class is a class where you can wrap your data (book name, book detail, book image) and pass it as a list to the adapter.
for example :
protected Boolean doInBackground(final String... args) {
url = url + "?custom_iid=" + cus_id;
Log.d("Passing Url", url);
CustomListAdapter jParser = new CustomListAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
ArrayList<BookModel> bookModelList = new ArrayList<BookModel>();
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
BookModel bookModel = new BookModel();
JSONObject c = json.getJSONObject(i);
String b_image = c.getString("b_image");
String b_name = c.getString("b_name");
String b_detail = c.getString("b_publisher");
Log.d("detail", "" + b_image);
bookModel.setBookName(b_name);
bookModel.setBookDetail(b_detail);
bookModel.setBookImageUrl(b_image);
bookModelList.add(bookModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if(bookModelList.size()>0) {
BookListAdapter bookListAdapter = new BookListAdapter(MainActivity.this, R.id.yourlistview, bookModelList );
}
return null;
}
I hope my answer can help you!
lv.setAdapter(adapter);
use AQuery lib.
and just write this code in your custom adapter:
AQuery aQuery = new AQuery(context);
aQuery.id(your image id).image(your url,true,true);
Related
actually I Have a custom listview which contains a countdown timer and the countdown timer is created by a handler, now the list loads fine and everything seems to be correct but when I start to scroll the countdown timer becomes shaky and unstable the values seems to overlap each other means the lastrow values are printed in the first row and things like that, the values are up and down and it does not work properly, here the API sends a long value which is passed to handler and the handler converts that to a countdown timer, so where does the problem lies , whenever I refresh the list it becomes all fine, but as I start scrolling the same problem comes again.. here is my code
public class fixtures extends Fragment {
private ListView fixtureListView;
String Balance,userEmail;
SwipeRefreshLayout mSwipeRefreshLayout;
private static final String FORMAT = "%02d:%02d:%02d";
List<ListView_fixture_conveyer> fixture_conveyerList;
ListView_fixture_conveyer fixtureList;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fixtures, viewGroup, false);
fixtureListView = view.findViewById(R.id.fixture_list);
mSwipeRefreshLayout = view.findViewById(R.id.swipeToRefresh);
User user = SharedPrefManager.getInstance(getActivity()).getUser();
userEmail= user.getEmail();
new JSONTask().execute("http://www.judgement6.com/judgement_files/fixture_json.php");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(Objects.requireNonNull(getActivity()))
.defaultDisplayImageOptions(options)
.build();
com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
fixture_conveyerList.clear();
new JSONTask().execute("http://www.judgement6.com/judgement_files/fixture_json.php");
mSwipeRefreshLayout.setRefreshing(false);
}
});
return view;
}
#SuppressLint("StaticFieldLeak")
public class JSONTask extends AsyncTask<String, String, List<ListView_fixture_conveyer>> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(getActivity(), "loading,please wait...", null, true, true);
}
#Override
protected List<ListView_fixture_conveyer> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("list");
fixture_conveyerList = new ArrayList<ListView_fixture_conveyer>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Log.e("fixtureObject",finalObject.toString());
fixtureList = new ListView_fixture_conveyer();
fixtureList.setTournament(finalObject.getString("tournament"));
fixtureList.setTeam1_photo(finalObject.getString("team1_photo"));
fixtureList.setTeam2_photo(finalObject.getString("team2_photo"));
fixtureList.setTeam1_name(finalObject.getString("team1_name"));
fixtureList.setTeam2_name(finalObject.getString("team2_name"));
fixtureList.setTime(finalObject.getString("Time"));
fixture_conveyerList.add(fixtureList);
}
return fixture_conveyerList;
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<ListView_fixture_conveyer> result) {
super.onPostExecute(result);
if (result !=null) {
loading.dismiss();
ListAdapter adapter = new ListAdapter(getActivity(), R.layout.custom_list_fixture, result);
fixtureListView.setAdapter(adapter);
}
else
{
Toast.makeText(getActivity(), "No Internet Connection!", Toast.LENGTH_LONG).show();
loading.dismiss();
}
}
}
public class ListAdapter extends ArrayAdapter {
private List<ListView_fixture_conveyer> fixture_conveyerList;
private int resource;
private LayoutInflater inflater;
ListAdapter(Context context, int resource, List<ListView_fixture_conveyer> objects) {
super(context, resource, objects);
fixture_conveyerList = objects;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
final TextView team1_name,team2_name;
final TextView tournament,time;
ImageView team1_photo,team2_photo;
team1_photo = convertView.findViewById(R.id.team1);
team2_photo = convertView.findViewById(R.id.team2);
team1_name = convertView.findViewById(R.id.team1_name);
team2_name = convertView.findViewById(R.id.team2_name);
tournament= convertView.findViewById(R.id.tournament);
time= convertView.findViewById(R.id.timecounter);
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam1_photo(), team1_photo);
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam2_photo(), team2_photo);
team1_name.setText(fixture_conveyerList.get(position).getTeam1_name());
team2_name.setText(fixture_conveyerList.get(position).getTeam2_name());
tournament.setText(fixture_conveyerList.get(position).getTournament());
time.setText(fixture_conveyerList.get(position).getTime());
Log.e("mytimer",fixture_conveyerList.get(position).getTime());
if (!("false").equals(fixture_conveyerList.get(position).getTime())){
Log.e("inside_mytimer",fixture_conveyerList.get(position).getTime());
long newValue=Long.parseLong(fixture_conveyerList.get(position).getTime());
new CountDownTimer(newValue, 1000) {
#SuppressLint({"DefaultLocale", "SetTextI18n"})
public void onTick(long millisUntilFinished) {
time.setText("" + String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
public void onFinish() {
time.setText("Fixture closed");
}
}.start();
}
else{
time.setText("Fixture closed");
}
return convertView;
}
}
}
Here is my model class code
public class ListView_fixture_conveyer {
private String tournament;
private String team1_photo;
private String team2_photo;
private String team1_name;
private String team2_name;
private String time;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getTeam1_name() {
return team1_name;
}
public void setTeam1_name(String team1_name) {
this.team1_name = team1_name;
}
public String getTeam2_name() {
return team2_name;
}
public void setTeam2_name(String team2_name) {
this.team2_name = team2_name;
}
public String getTournament() {
return tournament;
}
public void setTournament(String tournament) {
this.tournament = tournament;
}
public String getTeam1_photo() {
return team1_photo;
}
public void setTeam1_photo(String team1_photo) {
this.team1_photo = team1_photo;
}
public String getTeam2_photo() {
return team2_photo;
}
public void setTeam2_photo(String team2_photo) {
this.team2_photo = team2_photo;
}
}
Edit (Tested)
---> For Timer issue , you need to take time variable in your class and update variable with Handler use it with reload data. Like,
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
for (int i = 0, dataLength = fixture_conveyerList.size(); i < dataLength; i++) {
ListView_fixture_conveyer item = fixture_conveyerList.get(i);
item.timeRemaining -= 1000;
}
adapter.notifyDataSetChanged();
timerHandler.postDelayed(this, 1000); //run every Second
}
};
List Adapter Class
public class ListAdapter extends ArrayAdapter {
private List<ListView_fixture_conveyer> fixture_conveyerList;
private int resource;
private LayoutInflater inflater;
ViewHolder holder;
ListAdapter(Context context, int resource, List<ListView_fixture_conveyer> objects) {
super(context, resource, objects);
fixture_conveyerList = objects;
this.resource = resource;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
timerHandler.postDelayed(timerRunnable, 50); //start unique timer
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
holder = new ViewHolder();
holder.team1_photo = convertView.findViewById(R.id.team1);
holder.team2_photo = convertView.findViewById(R.id.team2);
holder.team1_name = convertView.findViewById(R.id.team1_name);
holder.team2_name = convertView.findViewById(R.id.team2_name);
holder.tournament = convertView.findViewById(R.id.tournament);
holder.time = convertView.findViewById(R.id.timecounter);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam1_photo(), holder.team1_photo);
ImageLoader.getInstance().displayImage(fixture_conveyerList.get(position).getTeam2_photo(), holder.team2_photo);
holder.team1_name.setText(fixture_conveyerList.get(position).getTeam1_name());
holder.team2_name.setText(fixture_conveyerList.get(position).getTeam2_name());
holder.tournament.setText(fixture_conveyerList.get(position).getTournament());
holder.time.setText(fixture_conveyerList.get(position).timeRemaining);
Log.e("mytimer", fixture_conveyerList.get(position).getTime());
if (!("false").equals(fixture_conveyerList.get(position).getTime())) {
Log.e("inside_mytimer", fixture_conveyerList.get(position).getTime());
long newValue = fixture_conveyerList.get(position).timeRemaining;
if (newValue > 0) {
holder.time.setText(String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(newValue),
TimeUnit.MILLISECONDS.toMinutes(newValue) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(newValue)),
TimeUnit.MILLISECONDS.toSeconds(newValue) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(newValue))));
} else {
holder.time.setText("Fixture closed");
}
} else {
holder.time.setText("Fixture closed");
}
return convertView;
}
}
I'm implementing a listview on android that contains an imageview and I'm experiencing a problem:
When a row does not have an image it is repeating an image of the previous item.
Here's my adapter:
public class NewsAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<News> newsList;
public NewsAdapter(List<News> newsList, Context context) {
this.newsList = newsList;
this.context = context;
inflater = LayoutInflater.from(context);
}
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater row = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = row.inflate(R.layout.image_new_row, null);
viewHolder = new ViewHolder();
viewHolder.mTitle = convertView.findViewById(R.id.txtNewsTitle);
viewHolder.mImage = convertView.findViewById(R.id.imageNews);
viewHolder.mDescription = convertView.findViewById(R.id.txtDescription);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
News news = newsList.get(position);
viewHolder.mTitle.setText(news.getTitle());
viewHolder.mDescription.setText(news.getDescription());
if (news.getImageUrl() != null){
ImageLoader.getInstance().displayImage(news.getImageUrl(), viewHolder.mImage);
}
else{
viewHolder.mImage.setImageResource(R.drawable.loading);
}
return convertView;
}
my viewHolder:
static class ViewHolder {
private TextView mTitle;
private TextView mDescription;
private ImageView mImage;
}
my activity:
public class NewsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final String ITEM = "item";
private static final String TITLE = "title";
private static final String LINK = "link";
private static final String DESCRIPTION = "description";
private static final String MEDIA = "media:content";
private static final String IMAGE_URL = "url";
private Feed feed;
private ListView newsListView;
private ArrayList<News> newsList;
private NewsAdapter mAdapter;
private ImageLoaderConfiguration imageLoaderConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
newsListView = (ListView) findViewById(R.id.newsList);
this.feed = (Feed) getIntent().getSerializableExtra(Constants.EXTRA_CLICKED_FEED);
configListView();
}
private void configListView() {
File cacheDir = StorageUtils.getCacheDirectory(this);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.loading)
.showImageOnLoading(R.drawable.loading)
.showImageOnFail(R.drawable.loading).cacheInMemory(true).cacheOnDisk(true).build();
imageLoaderConfiguration = new ImageLoaderConfiguration.Builder(this)
.defaultDisplayImageOptions(defaultOptions).build();
ImageLoader.getInstance().init(imageLoaderConfiguration);
newsList = new ArrayList<News>();
mAdapter = new NewsAdapter(newsList, this);
newsListView.setAdapter(mAdapter);
newsListView.setOnItemClickListener(this);
new RssAsyncTask().execute(
feed.getUrl());
}
private List<News> readXML(InputStream is) {
List<News> newsList =
new ArrayList<News>();
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
factory.newDocumentBuilder();
Document xmlDocument = builder.parse(is);
NodeList posts =
xmlDocument.getElementsByTagName(ITEM);
String title = null, description = null,
link = null, image = null;
for (int i = 0; i < posts.getLength(); i++) {
Node post = posts.item(i);
// Cada nó ITEM tem os filhos:
// TITLE, DESCRIPTION e LINK
NodeList postInfo = post.getChildNodes();
for (int j = 0; j < postInfo.getLength(); j++) {
Node info = postInfo.item(j);
if (TITLE.equals(info.getNodeName())) {
title = info.getTextContent();
} else if (LINK.equals(
info.getNodeName())) {
link = info.getTextContent();
} else if (DESCRIPTION.equals(
info.getNodeName())) {
description = extractText(info.getTextContent()).trim();
} else if (MEDIA.equals(
info.getNodeName())) {
image = ((Element) info).getAttribute(IMAGE_URL);
}
}
newsList.add(
new News(title, description, link, image));
}
} catch (Throwable e) {
e.printStackTrace();
}
return newsList;
}
class RssAsyncTask extends
AsyncTask<String, Void, List<News>> {
ProgressDialog dialog;
...
#Override
protected void onPostExecute(List<News> result) {
super.onPostExecute(result);
dialog.dismiss();
newsList.addAll(result);
mAdapter.notifyDataSetChanged();
}
}
}
obs: I'm using universal image load api:
https://github.com/nostra13/Android-Universal-Image-Loader
put your variable initialization into for loop as shown below so that it re initializes variables to null every time..
for (int i = 0; i < posts.getLength(); i++) {
String title = null, description = null,
link = null, image = null;
Node post = posts.item(i);
// Cada nó ITEM tem os filhos:
// TITLE, DESCRIPTION e LINK
NodeList postInfo = post.getChildNodes();
for (int j = 0; j < postInfo.getLength(); j++) {
Node info = postInfo.item(j);
if (TITLE.equals(info.getNodeName())) {
title = info.getTextContent();
} else if (LINK.equals(
info.getNodeName())) {
link = info.getTextContent();
} else if (DESCRIPTION.equals(
info.getNodeName())) {
description = extractText(info.getTextContent()).trim();
} else if (MEDIA.equals(
info.getNodeName())) {
image = ((Element) info).getAttribute(IMAGE_URL);
}
}
newsList.add(
new News(title, description, link, image));
}
Of course it does... You are reusing the previous item's layouts. that's what the below statement means.
viewHolder = (ViewHolder) convertView.getTag();
If you're not initializing it in the getView method it'll show the same contents as the previous item.
From your code - it may happens when image failed to download.
You can use:
viewHolder.mImage.setImageResource(R.drawable.loading);
if (news.getImageUrl() != null){
ImageLoader.getInstance().displayImage(news.getImageUrl(), viewHolder.mImage);
}
Or
You may use below code:
ImageLoader.getInstance().displayImage(imageUri, imageView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
...
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
...
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
...
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
...
}
}
});
android ListActivity how to make Custom Adapter getter setter using ,call json Volley library populate data ListActivity ? could not populate data with Json how to implement ,Please Help me
my code
ItemFragment Class
public class ItemFragment extends ListActivity {
RequestParse requestParse;
MySharedPreferences prefs;
String UsrId;
Context context;
ArrayList<BizForumArticleInfo> list = new ArrayList<>();
private List<BizForumArticleInfo> CountryCodeNumber = new ArrayList<>();
MobileArrayAdapter adapter;
LinearLayoutManager mLayoutManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
requestParse = new RequestParse();
prefs = MySharedPreferences.getInstance(this, SESSION);
UsrId = prefs.getString("UsrID", "");
context = getApplicationContext();
setListAdapter(new MobileArrayAdapter(this,0, list));
getJson(60);
}
public void getJson(final int limit){
requestParse.postJson(ConfigApi.postArticleBiz(), new RequestParse.VolleyCallBackPost() {
#Override
public void onSuccess(String result) {
list = parseResponse(result);
}
#Override
public void onRequestError(String errorMessage) {
}
#Override
public Map OnParam(Map<String, String> params) {
params.put("sessionid", UsrId);
params.put("offset", "0");
params.put("limit", String.valueOf(limit));
params.put("viewtype", "all");
params.put("access_token","e3774d357aa7d4bd14e9763b5459ee9cf7ebe36161c142551836ee510d98814a:b349b76b334a94b2");
return params;
}
});
}
public static ArrayList<BizForumArticleInfo> parseResponse(String response) {
ArrayList<BizForumArticleInfo> bizList = new ArrayList<>();
try {
JSONObject json = new JSONObject(response);
JSONArray data = json.getJSONArray(DATA);
for (int i = 0; i < data.length(); i++) {
BizForumArticleInfo ls = new BizForumArticleInfo();
JSONObject item = data.getJSONObject(i);
String ArticleTitle = item.getString("ArticleTitle");
String Article = item.getString("Article");
M.i("===================",ArticleTitle);//working
ls.setArticleTitle(ArticleTitle);
ls.setArticleArticle(Article);
bizList.add(ls);
}
} catch (JSONException e) {
e.printStackTrace();
}
return bizList;
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("selectedValue", selectedValue);
setResult(RESULT_OK, intent);
finish();
//startActivity(new Intent(v.getContext(), MainActivity.class));
}
}
Adapter Class
public class MobileArrayAdapter extends ArrayAdapter<BizForumArticleInfo> {
private Activity activity;
private ArrayList<BizForumArticleInfo> lPerson;
private static LayoutInflater inflater = null;
public MobileArrayAdapter (Activity activity, int textViewResourceId,ArrayList<BizForumArticleInfo> _lPerson) {
super(activity, textViewResourceId, _lPerson);
try {
this.activity = activity;
this.lPerson = _lPerson;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
}
}
public int getCount() {
return lPerson.size();
}
public BizForumArticleInfo getItem(BizForumArticleInfo position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView display_name;
public TextView display_number;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.list_mobile, null);
holder = new ViewHolder();
holder.display_name = (TextView) vi.findViewById(R.id.label);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.display_name.setText(lPerson.get(position).getArticleTitle());
} catch (Exception e) {
}
return vi;
}
}
I am currently modifying an android app that I need to add a listview to an existing fragment. As I am new to android, I am just imitating the code from the apps. I created a new arrayadapter, a new class of data and made some modifies to the existing fragment class. The problem is I cannot see my list in the app. Below are my codes.
Adapter
public class RecordArrayAdapter extends ArrayAdapter<CheckInRecord.CheckInRec> {
private int resourceId;
private Context context;
private List<CheckInRecord.CheckInRec> checkInRec;
public RecordArrayAdapter(Context context, int resourceId, List<CheckInRecord.CheckInRec> checkInRec)
{
super(context, resourceId, checkInRec);
this.resourceId = resourceId;
this.context = context;
this.checkInRec = checkInRec;
}
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(resourceId, parent, false);
}
TextView textViewName = (TextView) convertView.findViewById(R.id.tv_name);
TextView textViewCheckInDate = (TextView) convertView.findViewById(R.id.tv_checkindate);
TextView textViewPoints = (TextView) convertView.findViewById(R.id.tv_points);
ImageView imageViewIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
CheckInRecord.CheckInRec checkInrec = checkInRec.get(position);
textViewName.setText(checkInrec.providerName);
textViewCheckInDate.setText(checkInrec.checkInDate);
textViewPoints.setText(checkInrec.providerPoints);
ImageLoader.getInstance().displayImage(checkInrec.providerIcon, imageViewIcon, Utility.displayImageOptions);
return convertView;
}
public int getIsPrize(int position) {return (this.checkInRec.get(position).isPrize);}
}
Data type
public class CheckInRecord {
public int userPoints;
public String userName;
public String gender;
public String birthDate;
public String location;
public String userIcon;
public List<CheckInRec> checkInRecList = new ArrayList<CheckInRec>();
public void addCheckInRec(String providerName, String providerLocation, String providerIcon,
String checkInDate, int providerPoints, int isPrize){
CheckInRec checkInRec = new CheckInRec();
checkInRec.providerName = providerName;
checkInRec.providerLocation = providerLocation;
checkInRec.providerIcon = providerIcon;
checkInRec.checkInDate = checkInDate;
checkInRec.providerPoints = providerPoints;
checkInRec.isPrize = isPrize;
checkInRecList.add(checkInRec);
}
public List<String> recImages(){
List<String> resultList = new ArrayList<String>();
if (this.checkInRecList == null){
return resultList;
}
for (CheckInRec rec : this.checkInRecList){
resultList.add(rec.providerIcon);
}
return resultList;
}
public class CheckInRec{
public String providerName;
public String providerLocation;
public String providerIcon;
public String checkInDate;
public int providerPoints;
public int isPrize;
}
}
Fragment
public class MeFragment extends Fragment implements ApiRequestDelegate {
private TextView textViewName;
private TextView textViewPoints;
private ProgressDialog progressDialog;
private RecordArrayAdapter recordArrayAdapter;
private List<CheckInRecord.CheckInRec> checkInRec = new ArrayList<CheckInRecord.CheckInRec>();
public MeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppDataManager.getInstance().setAllowCheckIn(true);
progressDialog = ProgressDialog.show(getActivity(), "", "");
ApiManager.getInstance().checkInHistories(AppDataManager.getInstance().getUserToken(), AppDataManager.getInstance().getUserPhone(),
Utility.getPictureSize(), this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_me, container, false);
textViewName = (TextView) view.findViewById(R.id.tv_name);
textViewPoints = (TextView) view.findViewById(R.id.tv_points);
ListView listViewCheckInRec = (ListView) view.findViewById(R.id.lv_histories);
recordArrayAdapter = new RecordArrayAdapter(this.getActivity().getApplicationContext(), R.layout.row_record, checkInRec);
listViewCheckInRec.setAdapter(recordArrayAdapter);
return view;
}
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (menuVisible) {
refreshName();
}
}
public void refreshName() {
progressDialog = ProgressDialog.show(getActivity(), "", "");
AppDataManager dataManager = AppDataManager.getInstance();
ApiManager.getInstance().checkInHistories(dataManager.getUserToken(), dataManager.getUserPhone(), Utility.getPictureSize(), this);
}
#Override
public void apiCompleted(ApiResult apiResult, HttpRequest httpRequest) {
if (progressDialog!=null){
progressDialog.dismiss();
}
if (!apiResult.success){
ApiManager.handleMessageForReason(apiResult.failReason, getActivity());
return;
}
CheckInRecord checkInRecord = (CheckInRecord) apiResult.valueObject;
if (checkInRecord != null){
textViewName.setText(checkInRecord.userName);
textViewPoints.setText(String.format("积分%d分", checkInRecord.userPoints));
// this.checkInRec.clear();
// this.checkInRec.addAll(checkInRecord.checkInRecList);
//
// recordArrayAdapter.notifyDataSetChanged();
}
}
}
The problem is I cannot see my list in the app.
That is because checkInRec does now have any elements inside of it.
I can really tell that it is empty because you commented this out:
// this.checkInRec.clear(); //clear the old data from the list
// this.checkInRec.addAll(checkInRecord.checkInRecList); //add all the data inside the checkInRecord.checkInRecList
//
// recordArrayAdapter.notifyDataSetChanged(); //refreshing the ListView to display the new data
now what are those doing is that clearing the old list array and adding the new set of data from checkInRecord.checkInRecList and refreshing the ListView so those new data are implemented/shown in your ListView.
I'm using onScroll onclicklistner to update listview in my listFragment.
public class WishboardFragment extends ListFragment implements OnScrollListener{
private ProgressBar progressBar2;
private TextView finished;
private Context context = null;
private ListAdapter wishAdapter = null;
private final String TAG = "wishboard";
private final String cachedName = "wishboard";
JSONObject jsonObject = null;
JSONArray jsonArray = null;
private Menu optionsMenu;
private Integer pageStart = 1;
private Integer pageEnd = 15;
private Boolean isDownloading = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.context = getActivity();
return inflater.inflate(R.layout.activity_dashboard,container,false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
String url = getWishboardUrl();
sendRequest(url);
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
wishAdapter = new WishRowAdaptor(getActivity(),this.getWishboardCached());
setListAdapter(wishAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
this.optionsMenu = menu;
inflater.inflate(R.menu.dashboard, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
getListView().setOnScrollListener(this);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.btn_refresh:
Common.setRefreshActionButtonState(true,optionsMenu);
String url = getWishboardUrl();
sendRequest(url);
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendRequest(String url) {
new SendRequest().execute(url);
}
private class SendRequest extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... requestURL) {
String data = "";
HttpURLConnection httpUrlConnection = null;
try {
URL url = new URL(requestURL[0]);
URLConnection connection = url.openConnection();
connection.setUseCaches(true);
Object response = connection.getContent();
Log.i(TAG, "Requesting http "+requestURL[0]);
if (response instanceof Bitmap) {
}
InputStream in = new BufferedInputStream(
connection.getInputStream());
data = Common.readStream(in);
} catch (MalformedURLException exception) {
Log.e(TAG, "MalformedURLException");
} catch (IOException exception) {
Log.e(TAG, "IOException");
} finally {
if (null != httpUrlConnection)
httpUrlConnection.disconnect();
}
return data;
}
protected void onPostExecute(String jsonString) {
jsonObject = Common.getObjectFromJsonString(jsonString,3);
ArrayList<HashMap<String, String>> wishList = Common.parseJson(jsonObject);
if (pageEnd > Constants.limit) {
wishAdapter = new WishRowAdaptor(getActivity(),wishList);
}else{
Common.cacheResponse(context,cachedName,jsonString);
wishAdapter = new WishRowAdaptor(getActivity(),wishList);
setListAdapter(wishAdapter);
Common.setRefreshActionButtonState(false, optionsMenu);
}
isDownloading = false;
}
}
private ArrayList<HashMap<String, String>> getWishboardCached() {
String jsonString = Common.getCachedResponse(context,cachedName);
try {
jsonObject = Common.getObjectFromJsonString(jsonString,3);
ArrayList<HashMap<String, String>> wishList = Common.parseJson(jsonObject);
return wishList;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (view.getAdapter() != null
&& ((firstVisibleItem + visibleItemCount) >= totalItemCount)
&& isDownloading == false) {
pageStart = pageEnd + 1;
pageEnd = pageStart + (Constants.limit -1);
String url = getUrl();
sendRequest(url);
isDownloading = true;
}
}
}
In the above code If use setListAdapter(wishAdapter); in onPostExecute() after user has reached end of list. Listview gets updated but all the preveious entries goes away.
Here is my custom adapter
public class WishRowAdaptor extends BaseAdapter {
public WishRowAdaptor(Context context,
ArrayList<HashMap<String, String>> arrayList) {
// TODO Auto-generated constructor stub
this.mData = arrayList;
this.context = context;
this.listAq = new AQuery(context);
// mKeys = mData.keySet().toArray(new String[arrayList.size()]);
}
/* private view holder class */
private class ViewHolder {
ImageView imageView;
TextView txtWishName;
ImageButton btn_touchwood;
ImageButton btn_addwish;
TextView tvGesture;
TextView tvNotes;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final HashMap<String, String> rowItem = (HashMap<String, String>) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_wish, null);
holder = new ViewHolder();
holder.txtWishName = (TextView) convertView
.findViewById(R.id.tvwishname);
holder.imageView = (ImageView) convertView
.findViewById(R.id.ivWishImage);
holder.btn_touchwood = (ImageButton) convertView
.findViewById(R.id.btn_touchwood);
holder.btn_addwish = (ImageButton) convertView
.findViewById(R.id.btn_addwish);
holder.tvGesture = (TextView) convertView
.findViewById(R.id.tvGestures);
holder.tvNotes = (TextView) convertView
.findViewById(R.id.tvNotesText);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
return convertView;
}
}
How do update listview so that it should push new changes to list instead replacing all the content.
you are changing the adapter of the list adapter after each websevice call. just call notifyDataSetChanged after changing the items of your array list. Also dont replace the items of the array list. add the new to your arraylist.