I tried uploading an image using JSON. I create a link to image in JSON. Many times I tried to fix my problem, but with no success.
Is there a mistake in my use of DownloadImageTask in My adapter Adapter ?
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
newsList = new ArrayList<News>();
//this is i take json image
new NewsAsynkTask().execute();
}
public class NewsAsynkTask extends AsyncTask<String , Void, String> {
protected String doInBackground(String... params) {
//code
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
//this i run adapter
NewsAdapter adapter = new NewsAdapter(getApplicationContext(), R.layout.list_row, newsList);
list.setAdapter(adapter);
}
}
My adapter Adapter
public class NewsAdapter extends ArrayAdapter<News> {
ArrayList<News> ArrayListNews;
int Resourse;
Context context;
LayoutInflater vi;
public NewsAdapter(Context context, int resource, ArrayList<News> objects) {
super(context, resource, objects);
ArrayListNews = objects;
Resourse = resource;
this.context = context;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = vi.inflate(Resourse, null);
holder = new ViewHolder();
holder.imageview = (ImageView) convertView.findViewById(R.id.imagenews);
holder.nameNews = (TextView) convertView.findViewById(R.id.namenews);
holder.dayNews = (TextView) convertView.findViewById(R.id.daynews);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
new DownloadImageTask(holder.imageview).execute(ArrayListNews.get(position).getImageNews());
holder.nameNews.setText(ArrayListNews.get(position).getNameNews());
holder.dayNews.setText(ArrayListNews.get(position).getDayNews());
return convertView;
}
static class ViewHolder {
public ImageView imageview;
public TextView nameNews;
public TextView dayNews;
}
//this is i try load image. I using wrong somthing, please help me
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
ImageLoader imgLoader;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected Bitmap doInBackground(String... urls) {
final String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
Handler handler = new Handler(context.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
//this is class on this [link][1]. I try use simple, it work. But here dont work
imgLoader = new ImageLoader(context);
imgLoader.DisplayImage(urldisplay, bmImage);
}
});
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Related
Iv tried some on the solutions in stack overflow, but was not able to work it out for my case.
I want to get the Bitmap data from onPostExecute or bmp from doInBackground and set it to ImageView imageurl using imageurl.setImageBitmap() in the getView() method
public class BooksAdapter extends ArrayAdapter<Books> {
public BooksAdapter(Activity context, ArrayList<Books> word) {
super(context, 0, word);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
// Get the {#link AndroidFlavor} object located at this position in the list
Books currentbook = getItem(position);
TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
String booktitle = currentbook.getBookName();
bookView.setText(booktitle);
TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
String authorname = currentbook.getAuthorName();
authorView.setText(authorname);
ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
String imagelink = currentbook.getImageLink();
ImageAsyncTask task = new ImageAsyncTask();
task.execute(imagelink);
// imageurl.setImageBitmap();
return listItemView;
}
private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
URL url = null;
Bitmap bmp = null;
try {
url = new URL(urls[0]);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
}
return bmp;
}
#Override
protected void onPostExecute(Bitmap data) {
}
}
}
Just pass your ImageView to AsyncTask via constructor and then set image in onPostExecute like this:
ImageAsyncTask task = new ImageAsyncTask(myImageView);
private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView img;
ImageAsyncTask(Imageview img){
this.img = img;
}
...
protected void onPostExecute(Bitmap data) {
this.img.setImageBitmap(data);
}
Hello I have a list and i try to do settext from it, example I knew that TextView.setText(List<String>object) like TextView.setText(array[index]) but it is not working.I tried with get also.Is it the right way to implement custom Adapter:
firtsly I should settext List and then I will add images and so on.
Below is my code :
public class GetName extends Fragment {
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
//ArrayAdapter<String> adapter;
CustomList adapter;
public GetName()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Parse.initialize(getActivity(), "user", "pass");
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
View view=inflater.inflate(R.layout.getnewlay,container, false);
new GetData().execute();
return view;
}
private class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Parse.com Simple ListView Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
ParseQuery query = new ParseQuery("Name");
query.orderByDescending("_created_at");
try {
ob = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
listview = (ListView)getView().findViewById(R.id.listviewget);
adapter = new CustomList(getActivity(), ob);
/*ArrayAdapter<String>(getActivity(),
R.layout.listview_item);*/
// Retrieve object "name" from Parse.com database
for (ParseObject country : ob) {
adapter.add((String) country.get("name"));
}
listview.setAdapter(adapter);
}
}
}
Adapter class:
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] descr;
private final Integer[] imageId;
private final Integer[] imagId;*/
private List<ParseObject> ob;
public CustomList(Activity context, List<ParseObject> ob) {
super(context, R.layout.list_single);
this.ob = ob;
this.context = context;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.lname);
>for(ParseObject i : ob) txtTitle.setText((CharSequence) i);
> txtTitle.setText( ob.get(position));
return rowView;
}
}
use this
TextView.setText(String.valueOf(array[index]));
Your object should be string. For example,
TextView.setText("Your Text");
only work.
So try like,
TextView.setText(array[index].toString())
or
TextView.setText(String.valueOf(array[index]))
I hope this will help you.
textView.setText(array[index].toString());
Or simply
textView.setText(array[index]+"");
You need to change this from
txtTitle.setText(ob.get(position));
to
txtTitle.setText(ob.get(position).get("name"));
Simply you can do this:
TextView.setText(String.valueOf(array[index]));
I'm a beginner .
I tried to implement listview in a fragment which data is parsed from json, I'm running in to error
Error is.
Error:(119, 22) error: no suitable constructor found for ProgressDialog(My_Actor)
constructor ProgressDialog.ProgressDialog(Context,int) is not applicable
(actual and formal argument lists differ in length)
constructor ProgressDialog.ProgressDialog(Context) is not applicable
(actual argument My_Actor cannot be converted to Context by method invocation conversion)
Up to my level I don't find anything error here. Please help me out.
MainActivity.java
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment newFragment = null;
switch (position){
case 0:
newFragment = new My_Actors();
break;
case 1:
newFragment = new My_Editors();
break;
}
if(newFragment!=null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, newFragment)
.commit();
}
}
My_Actors.java
public class My_Actors extends Fragment{
ArrayList<Actors> actorsList;
ActorAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
View v = inflater.inflate(R.layout.deal_featured, container,false);
ListView listview = (ListView)v.findViewById(R.id.listView1);
adapter = new ActorAdapter(getActivity().getBaseContext(), R.layout.listview_layout, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity().getBaseContext(), actorsList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
return v;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Deal_featured.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
actor.setDescription(object.getString("description"));
actor.setDob(object.getString("dob"));
actor.setCountry(object.getString("country"));
actor.setHeight(object.getString("height"));
actor.setSpouse(object.getString("spouse"));
actor.setChildren(object.getString("children"));
actor.setImage(object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getBaseContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
ActorAdapter.java
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Error:(119, 22) error: no suitable constructor found for
ProgressDialog(My_Actor) constructor
ProgressDialog.ProgressDialog(Context,int) is not applicable (actual
and formal argument lists differ in length) constructor
ProgressDialog.ProgressDialog(Context) is not applicable (actual
argument My_Actor cannot be converted to Context by method invocation
conversion)
It is clearly says that you have to pass a context and Deal_featured.this is not a context. So instead of
dialog = new ProgressDialog(Deal_featured.this);
You have to use
dialog = new ProgressDialog(getActivity());
getActivity() return the context of this fragment's parent Activity.
I have a Task which extends Androids AsyncTask in order to get data from my Database in the cloud. I am doing this as to avoid NetworkingOnMainThread exception (I know you can set up StrictMode but in my opionion it's more of a hack than a solution).
I get no errors whatsoever. I have checked values in debugging and everything gets fetched correctly from my database. I have a Venue where I set my name, description, image etc... and the ArrayList<Venue> which I use for my adapter gets instantiated properly.
The problem is - the ListView doesn't render.
Here is my custom adapter code
public class EventListArrayAdapter extends ArrayAdapter<String> {
Context context;
ArrayList<Venue> values;
public EventListArrayAdapter(Context context, ArrayList<Venue> values) {
super(context, R.layout.single_event_list_item);
this.context = context;
this.values = values;
}
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if(v==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.single_event_list_item, null);
}
Venue currEvent = values.get(position);
if(currEvent!=null){
TextView singleItemTitle = (TextView) v.findViewById(R.id.singleItemTitle);
TextView singleItemLocation = (TextView) v.findViewById(R.id.singleItemLocation);
TextView singleItemDate = (TextView) v.findViewById(R.id.singleItemDate);
ImageView singleItemImage = (ImageView) v.findViewById(R.id.singleItemImage);
singleItemTitle.setText(currEvent.getName());
singleItemDate.setText(currEvent.getDate());
singleItemLocation.setText(currEvent.getLocation());
singleItemImage.setImageBitmap(currEvent.getVenueImage());
}
return v;
}
}
And here is my AsyncTask code
private class FillContentTask extends AsyncTask<String, Void, Void> {
ArrayList<Venue> venues;
Context activity;
ProgressDialog dialog;
public FillContentTask(Context context) {
this.activity = context;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(activity);
dialog.setTitle("Loading...");
dialog.show();
}
#Override
protected Void doInBackground(String... params) {
this.venues = Venue.getAll();
for (Venue currentVenue : this.venues) {
try {
InputStream in = new java.net.URL(currentVenue.getImageURL()).openStream();
currentVenue.setVenueImage(BitmapFactory.decodeStream(in));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView list = (ListView) findViewById(R.id.eventList);
EventListArrayAdapter adapter = new EventListArrayAdapter(activity, this.venues);
list.setAdapter(adapter);
dialog.hide();
}
}
And as I already said. To the best of my knowledge, the AsnycTask does it's job properly since all ArrayList<Venue> values get filled properly
Override the getCount method in your EventListArrayAdapter
#Override
public int getCount()
{
return values.size();
}
OR
change the super call in EventListArrayAdapter constructor from
super(context, R.layout.single_event_list_item);
to
super(context, R.layout.single_event_list_item,values);
and also you will need to change extends ArrayAdapter<String> to extends ArrayAdapter<Venue>
For some reason my custom adapter is only allowing me to have 1 image visible in the list view at any time, I am not sure why this is happening. There should be a image within each list item but only the last list item has its image set, so I assume I am re-using a value somewhere that I should not be. The rest of the list items are being set properly.
public class CustomAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> itemList;
private ViewHolder holder;
private Context context;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<Item> list) {
super(context, textViewResourceId, list);
this.itemList = new ArrayList<Item>();
this.itemList.addAll(list);
this.context = context;
}
private class ViewHolder {
ImageView img;
TextView name;
CheckBox access;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_grid, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.access = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.img = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(holder);
}
else { holder = (ViewHolder) convertView.getTag(); }
Item it = itemList.get(position);
new UrlLookup().execute(it.getUrl());
holder.name.setText(it.getName());
holder.access.setChecked(it.isSelected());
return convertView;
}
//Create an image from the url passed in from the server and display it on the image view
private class UrlLookup extends AsyncTask<String, Integer, String>{
Bitmap bmp;
#Override
protected String doInBackground(String... params){
try {
URL u = new URL(params[0]);
bmp = BitmapFactory.decodeStream(u.openConnection().getInputStream());
} catch (Exception e) { e.printStackTrace(); }
return "Done!";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
holder.img.setImageBitmap(bmp);
}
}
}
You're forgetting the fact that your holder changes every time a view is visible. So it's normal only the last item has an image.
AsyncTask will take considerably longer to finish than your getView method.
You should pass your ImageView to your AsyncTask:
new UrlLookup().execute(it.getUrl(), holder.img);
To call the AsyncTask
private class UrlLookup extends AsyncTask<Object, Integer, String>{
Bitmap bmp;
ImageView view;
#Override
protected String doInBackground(Object... params){
view = (ImageView) params[1];
try {
URL u = new URL((String)params[0]);
bmp = BitmapFactory.decodeStream(u.openConnection().getInputStream());
} catch (Exception e) { e.printStackTrace(); }
return "Done!";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
view.setImageBitmap(bmp);
}
}
Now you will have a reference of the ImageView of every row in every AsyncTask.
I would like to point out to you that Koush has a splendid project for doing just what you want:
UrlImageViewHelper