I follow this video try to get data from mongodb
get the JsonArray from mongodb , and use debug mode check the class JsonTest.java : ArrayList<JsonSongs> songlist; have 21 data in it , and all correct , and the listview has 21 row show up , but somehow the data did't show on the textview ,
I think the Class JsonTest.java : Ë‹ArrayList songlist;did pass the data to class JsonSongAdapter.java Ë‹ArrayList<JsonSongs> songlist; right?
please help , stuck here for hours
JsonTest.java
public class JsonTest extends Activity {
ListView list;
ArrayList<JsonSongs> songlist;
private TextView test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jsonmain);
list = (ListView)findViewById(R.id.JsonlistView);
songlist = new ArrayList<JsonSongs>();
new JsonTalk().execute("http://192.168.1.102:3000/songs");
}
class JsonTalk extends AsyncTask< String , String ,String>{
#Override
protected String 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));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
// JSONObject parentJsonObject = new JSONObject(finalJson);
JSONArray jsonArray = new JSONArray(finalJson);
JsonSongs jsonSongs = new JsonSongs();
for (int i = 0 ; i < jsonArray.length();i++){
JSONObject finaObject = jsonArray.getJSONObject(i);
jsonSongs.set_id(finaObject.getString("_id"));
jsonSongs.setDecade(finaObject.getString("decade"));
jsonSongs.setArtist(finaObject.getString("artist"));
jsonSongs.setSong(finaObject.getString("song"));
jsonSongs.setWeeksAtOne(finaObject.getInt("weeksAtOne"));
songlist.add(jsonSongs);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (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(String result) {
super.onPostExecute(result);
if(result == null){
JsonSonAdapter adapter = new JsonSonAdapter(getApplicationContext(),R.layout.jsonlayout,songlist);
list.setAdapter(adapter);
}else {
Toast.makeText(JsonTest.this,"NOP",Toast.LENGTH_LONG).show();
}
}
}
}
JsonSonAdapter
public class JsonSonAdapter extends ArrayAdapter<JsonSongs> {
ArrayList<JsonSongs> songList;
int Resource;
Context context;
LayoutInflater vi;
public JsonSonAdapter(Context context, int resource, ArrayList<JsonSongs> objects) {
super(context, resource, objects);
songList = objects;
Resource = 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(Resource,null);
holder = new ViewHolder();
holder.textJson_ID=(TextView)convertView.findViewById(R.id.textJson_ID);
holder.textJSONname=(TextView)convertView.findViewById(R.id.textJSONname);
holder.textJsonSong=(TextView)convertView.findViewById(R.id.textJsonSong);
holder.textJsonYear=(TextView)convertView.findViewById(R.id.textJsonYear);
holder.textJsonWeeks=(TextView)convertView.findViewById(R.id.textJsonWeeks);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
return convertView;
}
static class ViewHolder{
public TextView textJsonYear;
public TextView textJSONname;
public TextView textJsonSong;
public TextView textJsonWeeks;
public TextView textJson_ID;
}
}
JsonSongs
public class JsonSongs {
private String _id;
private String decade;
private String artist;
private String song;
private int weeksAtOne;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getDecade() {
return decade;
}
public void setDecade(String decade) {
this.decade = decade;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
public int getWeeksAtOne() {
return weeksAtOne;
}
public void setWeeksAtOne(int weeksAtOne) {
this.weeksAtOne = weeksAtOne;
}
}
but somehow the data did't show on the textview ,
You set it nowhere so no wonders. You need to call setText() on your EditTexts (in getView()) once you done with convertView to populate it with data.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.textJson_ID=(TextView)convertView.findViewById(R.id.textJson_ID);
...
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
// populate it with data
JsonSongs song = songs.get(position);
holder.textJson_ID.setText(song.getSomething());
...
return convertView;
}
PS: JsonSongs should rather be named JsonSong. And you got quite a mess in naming pattern.
Related
OnPost Execute method how can I pass image from one Fragment to other activity. Able to pass the image from drawable folder using Bundle. Loding product details from server and able to other information except Image to other Activity.
package sanjay.apackage.torcente.com.torcentemotors;
public class HomeFragment extends Fragment {
FragmentTransaction fragmentTransaction;
//private TextView tvData;
private ListView lvMovies;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
//Image loader
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()) //getApplicationContext()
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView)view.findViewById(R.id.lvMovies);
new JSONTask().execute("http://torcentemotors.com/app_001/productsInfoNew.php");
return view;
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel> > {
#Override
protected List<MovieModel> 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));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null ) {
buffer.append(line);
}
//return buffer.toString();
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for(int i = 0; i< parentArray.length() ;i++ ) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setProduct_name(finalObject.getString("product_name"));
movieModel.setProduct_price(finalObject.getInt("product_price"));
movieModel.setProduct_image(finalObject.getString("product_image"));
movieModel.setProduct_color(finalObject.getString("product_color"));
movieModel.setCover_image(finalObject.getString("cover_image"));
movieModel.setOriginal_price(finalObject.getInt("original_price"));
movieModel.setApp_desc(finalObject.getString("app_desc"));
//adding the final object to the list
movieModelList.add(movieModel);
}
//return finalBufferedData.toString();
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (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<MovieModel> result) {
super.onPostExecute(result);
final MovieAdapter adapter = new MovieAdapter( getActivity().getApplicationContext(), R.layout.rownew, result );
//// getApplicationContext() // getActivity is added by me
lvMovies.setAdapter(adapter);
//set data to list
lvMovies.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getActivity().getBaseContext(),parent.getItemIdAtPosition(position)+" is selected",Toast.LENGTH_LONG).show();
MovieModel movieModel = (MovieModel) adapter.getItem(position);
Intent intent = new Intent("sanjay.apackage.torcente.com.torcentemotors.product_details");
//intent.putExtra("product_image", movieModel.getProduct_image());
//sanjay //
intent.putExtra("id",position);
intent.putExtra("product_name",movieModel.getProduct_name());
intent.putExtra("product_price", movieModel.getProduct_price());
intent.putExtra("product_color", movieModel.getProduct_color());
intent.putExtra("original_price", movieModel.getOriginal_price());
intent.putExtra("app_desc", movieModel.getApp_desc());
Bundle bundle=new Bundle();
bundle.putInt("image",R.drawable.ban);
bundle.putInt("image2",R.drawable.fz25);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}
public class MovieAdapter extends ArrayAdapter{
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater ;
public MovieAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource ;
inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE); // context is added by me.
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
viewHolder holder = null;
if (convertView == null ) {
holder = new viewHolder();
convertView = inflater.inflate(resource, null);
holder.tvIcon = (ImageView)convertView.findViewById(R.id.tvIcon);
holder.tvcover = (ImageView)convertView.findViewById(R.id.tvcover);
holder.tvproduct_name = (TextView)convertView.findViewById((R.id.tvproduct_name));
holder.tvproduct_price = (TextView)convertView.findViewById((R.id.tvproduct_price));
holder.tvproduct_color = (TextView)convertView.findViewById((R.id.tvproduct_color));
holder.tvoriginal_price = (TextView)convertView.findViewById((R.id.tvoriginal_price));
holder.tvapp_desc = (TextView)convertView.findViewById((R.id.tvapp_desc));
convertView.setTag(holder);
} else{
holder = (viewHolder)convertView.getTag();
}
ImageLoader.getInstance().displayImage(movieModelList.get(position).getProduct_image(), holder.tvIcon);
ImageLoader.getInstance().displayImage(movieModelList.get(position).getCover_image(), holder.tvcover);
//holder.tvproduct_id.setText(" Product ID : " +movieModelList.get( position ).getProduct_id());
//holder.tvcategory_id.setText("Category ID : " +movieModelList.get(position).getCategory_id());
//holder.tvsub_category_id.setText("Sub Category ID : " +movieModelList.get(position).getSub_category_id());
holder.tvproduct_name.setText(movieModelList.get(position).getProduct_name());
//holder.tvproduct_code.setText(movieModelList.get(position).getProduct_code());
holder.tvproduct_price.setText("BookingPrice : "+movieModelList.get(position).getProduct_price());
holder.tvproduct_color.setText(movieModelList.get(position).getProduct_color());
holder.tvoriginal_price.setText("Price : "+movieModelList.get(position).getOriginal_price());
//holder.tvapp_desc.setText(movieModelList.get(position).getApp_desc());
return convertView;
}
class viewHolder{
private ImageView tvIcon ;
private ImageView tvcover ;
private TextView tvproduct_id;
private TextView tvcategory_id;
private TextView tvsub_category_id;
private TextView tvproduct_name;
private TextView tvproduct_code;
private TextView tvproduct_color;
private TextView tvproduct_price;
private TextView tvoriginal_price;
private TextView tvapp_desc;
}
}
}
I am developing app just like YOUTUBE. I am getting data from the server and showing it in listview. Because data is too big so i want to restrict list view to 5 items and then when I scroll down to the bottom of listview it should add 5 more item.
I am calling ASyncTask from fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(R.layout.tab_fragment_2, container, false);
listView = (ListView) view.findViewById(R.id.myList);
New.jsonAsyncTask.execute("my url select_video.php?");
}
Now I have separate JsonAsyncTask Class because I am calling it from 3 fragments just like above mentioned way..
public class JSONAsyncTask extends AsyncTask<String, String, List<SetDatails>> {
ListView listView1;
Context context1;
List<SetDatails> videoLiast1;
private static int tab_id;
public JSONAsyncTask(ListView listView, List<SetDatails> videoLiast,Context context,int id) {
this.listView1 = listView;
this.context1 = context;
this.videoLiast1 = videoLiast;
tab_id=id;
}
#Override
protected List<SetDatails> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader myReader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream myInputStream = connection.getInputStream();
myReader = new BufferedReader(new InputStreamReader(myInputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = myReader.readLine()) != null) {
buffer.append(line);
}
String Json_data = buffer.toString();
videoLiast1 = new ArrayList<>();
JSONObject parentObj = new JSONObject(Json_data);
JSONArray dataArray = parentObj.getJSONArray("data");
JSONObject tabObject = dataArray.getJSONObject(tab_id);
JSONArray videoArray = tabObject.getJSONArray("videos");
for (int i = 0; i < videoArray.length(); i++) {
int len=dataArray.length();
SetDatails setDatails = new SetDatails();
JSONObject arrayChild = videoArray.getJSONObject(i);
String vid_ID = arrayChild.getString("id");
setDatails.setVidID(vid_ID);
String movie_title = arrayChild.getString("name");
setDatails.setTitle(movie_title);
String movie_catagory = arrayChild.getString("category_name");
setDatails.setGenre(movie_catagory);
videoLiast1.add(setDatails);
}
return videoLiast1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Throwable throwable) {
throwable.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (myReader != null) {
myReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(List<SetDatails> videoList) {
super.onPostExecute(videoList);
if(videoList!=null) {
try {
MyListAdapter myListAdapter = new MyListAdapter(context1, videoList);
listView1.setAdapter(myListAdapter);
}catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
I have created an Array adapter to fill list view.
public class MyListAdapter extends ArrayAdapter<SetDatails>{
public static int count =5;
List<SetDatails> videoList;
MyListAdapter(Context context,List<SetDatails> object){
super(context,R.layout.tab2_bookchilds,object);
videoList = object;
}
/**
* {#inheritDoc}
*/
#Override
public int getCount() {
return super.getCount();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater=LayoutInflater.from(getContext());
View view = layoutInflater.inflate(R.layout.tab2_bookchilds, parent, false);
TextView title = (TextView)view.findViewById(R.id.txt_title);
title.setText(videoList.get(position).getTitle());
ImageView imgV_Thumbnail = (ImageView) view.findViewById(R.id.imgV_thumbnail);
Picasso.with(getContext())
.load(videoList.get(position).getThumbnail())
.error(R.drawable.icon_white)
.into(imgV_Thumbnail);
return view;
}
}
I have searched a lot and many people suggest getCount() method although I tried a lot to use this method but don't know how to do that.
Please guys help me because my app is ready to upload but I can't solve this one issue.
I am trying to fetch data using AsyncTask & displaying into a ListView. It never calls getView(), I checked getCount() return always 0.
MainActivityFragment.java
public class MainActivityFragment extends Fragment {
private final String LOG_TAG = MainActivityFragment.class.getSimpleName();
SourceAdapter adapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
adapter = new SourceAdapter(getActivity());
ListView listView = (ListView) rootView.findViewById(R.id.listView);
listView.setAdapter(adapter);
Log.d(LOG_TAG,"after list view set to adapter");
return rootView;
}
#Override
public void onStart() {
new FetchDataTask().execute();
super.onStart();
}
public class FetchDataTask extends AsyncTask<String, Void, SourceObject[]>{
private final String LOG_TAG = FetchDataTask.class.getSimpleName();
private SourceObject[] getSourceDataFromJson(String jsonStr)throws JSONException{
JSONArray jsonArray = new JSONArray(jsonStr);
SourceObject[] sourceObjects = new SourceObject[jsonArray.length()];
for (int i=0; i<jsonArray.length();i++){
sourceObjects[i] = new SourceObject(
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getJSONObject("author").getString("name"),
jsonArray.getJSONObject(i).getJSONObject("commit").getString("message")
);
}
return sourceObjects;
}
#Override
protected SourceObject[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String jsonStr = null;
try {
String baseUrl = "https://api.github.com/repos/rails/rails/commits";
URL url = new URL(baseUrl);
Log.d(LOG_TAG,"URL IS "+url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
jsonStr = buffer.toString();
Log.d(LOG_TAG,"JSON STRING "+jsonStr);
}catch (IOException e){
Log.e(LOG_TAG, "ERROR"+e);
return null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getSourceDataFromJson(jsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
SourceAdapter.java
public class SourceAdapter extends BaseAdapter {
private final String LOG_TAG = SourceAdapter.class.getSimpleName();
Context context;
ArrayList<SourceObject> objects = new ArrayList<SourceObject>();
public SourceAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
Log.d(LOG_TAG,"getCount called "+objects.size());
return objects.size();
}
#Override
public Object getItem(int position) {
Log.d(LOG_TAG,"getItem called");
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG,"get view method is called");
SourceObject sourceObject = (SourceObject) getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_source,parent,false);
}
TextView personName = (TextView) convertView.findViewById(R.id.person_name);
TextView commit = (TextView) convertView.findViewById(R.id.xxx);
TextView commitMessage = (TextView) convertView.findViewById(R.id.commit_message);
personName.setText(sourceObject.getPersonName());
commit.setText(sourceObject.getCommit());
commitMessage.setText(sourceObject.getCommitMessage());
return convertView;
}
}
Please help.
You are not setting data retrieved from AsyncTask to adapter.
Add this method to your adapter class:
public void setItems(SourceObject[] items) {
this.objects = new ArrayList<SourceObject>();
for(SourceObject item : items){
this.objects.add(item);
}
this.notifyDataSetChanged();
}
And change onPostExecute of AsyncTask to:
#Override
protected void onPostExecute(SourceObject[] strings) {
adapter.setItems(strings);
super.onPostExecute(strings);
}
i am working on this Android application which firstly downloads a .txt file from internet then populates the arraylist and in the end listview. The problem is that the Listview doesn't seem to populate despite that my file downloading and reading is everything ok since i have tested it with a TOAST.
Here is my code
Downloading File and Reading with AsyncTask
public class DownloadFile extends AsyncTask<String, Void, String> {
String filenamelist=TEST_FILE_NAME;
#Override
protected String doInBackground(String... params) {
//Here i download the file
} catch (Exception e) {
e.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
try {
InputStream instream = new FileInputStream(new File(getCacheDir(), filenamelist));
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader bReader = new BufferedReader(inputreader);
String key,value = null;
do{
key = bReader.readLine();
if(key != null)
value = bReader.readLine();
//channelname is the ArrayList
channelname.add(key);
channelmaps.put(key,value);
} while (key != null && value != null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Declaration of ArrayList
ArrayList<String> channelname = new ArrayList<String>();
Listview
final ListView listView = (ListView) findViewById(android.R.id.list);
channelname.removeAll(Collections.singleton(null));
ChannelAdapter cAdapter = new ChannelAdapter(this, channelname);
listView.setAdapter(cAdapter);
ChannelAdapter class
private class ChannelAdapter extends ArrayAdapter<String>
{
ArrayList<String> channelname;
public ChannelAdapter(Context context, ArrayList<String> channelname)
{
super (context, R.layout.activity_list_channels, channelname);
this.channelname = channelname;
}
public View getView(int position, View convertView, ViewGroup parent)
{
try
{
if(convertView==null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.mylistchannel,parent, false);
}
String name = getItem(position);
TextView txtview = (TextView) convertView.findViewById(R.id.Channelname);
txtview.setText(name);
return convertView;
}
catch(Exception e)
{
}
return null;
}
#Override
public int getCount()
{
return channelname.size();
}
#Override
public String getItem(int position)
{
return channelname.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
}
So what's the problem with my code? Why isn't the listview populated?
You should do
cAdapter.notifyDataSetChanged();
after the cycle in which you've read all the items from the file;
I would like to know if it is possible to load an image inside a ListView directly from the web, when the URL is stocked inside a json.
Edit : Solved, It is possible to use an AsyncTask
public class ParseImage extends AsyncTask<Object, String, Drawable> {
private ProgressBar pd;
private ImageView imv;
private int position;
public ParseImage(int position, ImageView imv, ProgressBar pd2) {
this.position = position;
this.imv = imv;
this.pd = pd2;
}
#Override
public Drawable doInBackground(Object... params) {
Drawable d = null;
try {
d = Drawable.createFromStream(
(InputStream) new URL(list.get(position).get("Cover"))
.getContent(), "src");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
public void onPostExecute(Drawable result) {
if (result != null && imv != null) {
pd.setVisibility(View.INVISIBLE);
imv.setImageDrawable(result);
}
}
}
}
You need to create your own custom Listview to show more than a String.Here is a piece of code you can refer:
MovieAdaptor.java:
public class MovieAdaptor extends ArrayAdapter<Movie> {
Context context;
int layoutResourceId;
ArrayList<Movie> movieArrayList = new ArrayList<Movie>();
public MovieAdaptor(Context context, int layoutResourceId, ArrayList<Movie> movies) {
super(context, layoutResourceId, movies);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.movieArrayList = movies;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ContactHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.thumbnail = (ImageView) row.findViewById(R.id.imageThumbnail);
holder.title = (TextView) row.findViewById(R.id.MovieTitle);
holder.synopsis = (TextView) row.findViewById(R.id.synopsis);
row.setTag(holder);
} else {
holder = (ContactHolder) row.getTag();
}
holder.title.setText(movieArrayList.get(position).title);
holder.synopsis.setText(movieArrayList.get(position).synopsis);
newAsyncDownloadImage(holder.thumbnail).execute(movieArrayList.get(position).posters.get("thumbnail"));
return row;
}
static class ContactHolder {
ImageView thumbnail;
TextView title;
TextView synopsis;
}
}
Activity.class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
moviesListView = (ListView) findViewById(R.id.list_movies);
moviesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position > HEADER) {
Intent intent = new Intent(getBaseContext(), MovieActivity.class);
intent.putExtra(MOVIE_OBJECT, movieArrayList.get(position - 1));
startActivity(intent);
}
}
});
View header = (View) getLayoutInflater().inflate(R.layout.listview_row_header, null);
moviesListView.addHeaderView(header);
movieAdaptor = new MovieAdaptor(this, R.layout.listview_row_item, movieArrayList);
moviesListView.setAdapter(movieAdaptor);
AsyncDownloadImage.java:
public class AsyncDownloadImage extends AsyncTask<Object, Object, Object> {
ImageView iv;
private HttpURLConnection connection;
private InputStream is;
private Bitmap bitmap;
public AsyncDownloadImage(ImageView mImageView) {
iv = mImageView;
}
#Override
protected Object doInBackground(Object... params) {
URL url;
try {
url = new URL((String) params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
if (null != result) {
iv.setImageBitmap((Bitmap) result);
} else {
iv.setBackgroundResource(R.drawable.ic_launcher);
}
}
}
}
Can you send the return of
JSONfunction.getJSONfromURL("http://colmarmagazine.ctai.fr/issues.php");
Please ?
I think it's a bad parting ! Because you have :
Unable to decode stream: java.io.FileNotFoundException: /http:/colmarmagazine.ctai.fr/content/numerodemo/numerodemo.png: open failed: ENOENT (No such file or directory)
and a "/" too much in the url for your cover !