I am using a modified version of the contacts project from AndroidHive.
It basically just pulls n list of articles and their contact from a Joomla Site.
I am using a Image Plugin that gets a image from a url. i can successfully use it on the article detail activity view but i don't know how to add it to each List Item on the MainAcitivity file. I am new to Android development so please excuse the confusion.
The script to add the image is:
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
and my MainActivity which generated the ListView:
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get articles JSON
private static String url = "http://192.168.12.21/sebastian/broadcast/index.php/blog?format=json";
// JSON Node names
private static final String TAG_ARTICLES = "articles";
// Get the fields
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_SHORTTEXT = "shorttext";
private static final String TAG_FULLTEXT = "fulltext";
private static final String TAG_IMAGE = "image";
private static final String TAG_DATE = "date";
// articles JSONArray
JSONArray articles = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> articleList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articleList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String shorttext = ((TextView) view.findViewById(R.id.shorttext)).getText().toString();
String fulltext = ((TextView) view.findViewById(R.id.fulltext)).getText().toString();
String image = ((TextView) view.findViewById(R.id.image)).getText().toString();
String date = ((TextView) view.findViewById(R.id.date)).getText().toString();
// Starting single article activity
Intent in = new Intent(getApplicationContext(),
SingleArticleActivity.class);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_SHORTTEXT, shorttext);
in.putExtra(TAG_FULLTEXT, fulltext);
in.putExtra(TAG_IMAGE, image);
in.putExtra(TAG_DATE, date);
startActivity(in);
}
});
// Calling async task to get json
new GetArticles().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetArticles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
articles = jsonObj.getJSONArray(TAG_ARTICLES);
// looping through All articles
for (int i = 0; i < articles.length(); i++) {
JSONObject c = articles.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String shorttext = c.getString(TAG_SHORTTEXT);
String fulltext = c.getString(TAG_FULLTEXT);
String image = c.getString(TAG_IMAGE);
String date = c.getString(TAG_DATE);
// tmp hashmap for single article
HashMap<String, String> article = new HashMap<String, String>();
// adding each child node to HashMap key => value
article.put(TAG_ID, id);
article.put(TAG_TITLE, title);
article.put(TAG_SHORTTEXT, shorttext);
article.put(TAG_FULLTEXT, fulltext);
article.put(TAG_IMAGE, image);
article.put(TAG_DATE, date);
// adding article to article list
articleList.add(article);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, articleList,
R.layout.list_item, new String[] {
TAG_TITLE,
TAG_SHORTTEXT,
TAG_FULLTEXT,
TAG_IMAGE,
TAG_DATE
},
new int[] {
R.id.title,
R.id.shorttext,
R.id.fulltext,
R.id.image,
R.id.date
});
setListAdapter(adapter);
}
}
}
**I don't know where in the MainActivity file do i add the script to add an image to each List Item.
I already got it working on the SingleArticleActivity but cannot get it to work on the List of Items**
Thanks for the help
UPDATE
What im trying to do:
foreach(ListItem in the List) {
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, "https://www.site.co.za/test.png");
}
You have to just use this one..
ImageView thumb = (ImageView) findViewById(R.id.thumb);
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
CustomAdapter cdp = new CustomAdapter(YourActivityName.this , articleList);
setListAdapter(adapter);
Now make class of CustomAdapter extends with BaseAdapter
public class CustomAdapter extends BaseAdapter {
ArrayList<HashMap<String, String>> list;
Context ctx;
public CustomAdapter(Context c , ArrayList<HashMap<String, String>> articleList){
this.ctx = c;
this.list = articleList;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.list_item,
parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
UrlImageViewHelper.setUrlDrawable(thumb, articleList.get(position).get(TAG_IMAGE));
return view;
}
class ViewHolder {
ImageView imageView;
}
}
I am using this method in the getView method of my ListView adapter which returns a drawable which I later set it to my ImageView.
public Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return default_image;
}
}
Hope this helps.
Try this A powerful image downloading and caching library for Android Picasso
Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application-often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Related
I'm new in android developer, I've problem in my custom Listview, the condition is when I click on my listview it should be go to detail activity. and yes, it works!
but the detail data and image isn't appear. only detail.xml without data and image.
Ymainactivity.java
private class GetData extends AsyncTask<String, Void, String> {
JSONArray str_json = null;
JSONObject json = null;
JSONParser jParser = new JSONParser();
ListView listx;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> data_map = new ArrayList<HashMap<String, String>>();
ProgressDialog dialog = new ProgressDialog(YmainActivity.this);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Memuat Item..");
this.dialog.show();
}
protected String doInBackground(String... param) {
json = jParser.AmbilJson(link_url);
try {
str_json = json.getJSONArray("berita");
for(int i = 0; i < str_json.length(); i++){
JSONObject ar = str_json.getJSONObject(i);
String kodebrg = "kode barang : "+ar.getString("kodebrg");
String gambar = ar.getString("gambar2");
String nama = ar.getString("nama");
String stok = "Stok : "+ar.getString("stok")+" "+ar.getString("satauan");
String harga = "Rp. "+ar.getString("harga")+" per "+ar.getString("satauan");
String info = ar.getString("info");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_nama, nama);
map.put(in_stok, stok);
map.put(in_kodebrg, kodebrg);
map.put(in_gambar, gambar);
map.put(in_harga, harga);
map.put(in_info, info);
data_map.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
dialog.dismiss();
listx = (ListView)findViewById(R.id.listos);
adapter = new LazyAdapter(YmainActivity.this, data_map);
listx.setAdapter(adapter);
if (adapter.getCount()==0) {
Toast.makeText(YmainActivity.this,"data tidak ditemukan",Toast.LENGTH_SHORT).show();
}
listx.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
HashMap<String, String> map = (HashMap<String, String>) adapter.getItem(position);
String kodebrgs = ((TextView) view.findViewById(R.id.kodebrgs)).getText().toString();
Intent inx = new Intent(YmainActivity.this, DetailActivity.class);
inx.putExtra(kodebrgs, map2.get(in_kodebrg));
startActivity(inx);
}
DetailActivity.java
private class GetData extends AsyncTask<String, Void, String> {
JSONArray artikel = null;
JSONObject json = null;
JSONParser jParser = new JSONParser();
Intent ins = getIntent();
String kode1s = ins.getStringExtra(in_kodebrg);
String link_url = "http:// my php file that call all data using primary id from table in my database mySQL"+kode1s;
ProgressDialog dialog = new ProgressDialog(DetailActivity.this);
protected void onPreExecute() {
super.onPreExecute();
this.dialog.setMessage("Memuat Detail Produk..");
this.dialog.show();
}
protected String doInBackground(String... params) {
json = jParser.AmbilJson(link_url);
return null;
}
protected void onPostExecute(String result) {
dialog.dismiss();
try {
artikel = json.getJSONArray("artikel");
for(int i = 0; i < artikel.length(); i++){
JSONObject ar = artikel.getJSONObject(i);
TextView judul1 = (TextView) findViewById(R.id.judul2);
TextView detail1 = (TextView) findViewById(R.id.detail2);
TextView isi1 = (TextView) findViewById(R.id.isi2);
TextView info1 = (TextView) findViewById(R.id.infobarang2);
TextView kodebarang1 = (TextView) findViewById(R.id.kodenyabrg2);
String judul_1 = ar.getString("nama");
String detail_1 = "harga Rp. "+ ar.getString("harga");
String isi_1 = "Stok Barang : "+ ar.getString("stok")+" "+ar.getString("satauan");
String info_1 = "Info : "+ar.getString("info");
String kodebarang_1 = "Kode Barang : "+ar.getString(in_kodebrg);
judul1.setText(judul_1);
detail1.setText(detail_1);
isi1.setText(isi_1);
info1.setText(info_1);
kodebarang1.setText(kodebarang_1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listimage_item, null);
TextView nama = (TextView)vi.findViewById(R.id.namas);
TextView stok = (TextView)vi.findViewById(R.id.stoks);
TextView kodebrg = (TextView)vi.findViewById(R.id.kodebrgs);
TextView harga = (TextView)vi.findViewById(R.id.hargas);
TextView info = (TextView)vi.findViewById(R.id.infos);
ImageView gambar=(ImageView)vi.findViewById(R.id.gambars);
HashMap<String, String> berita = new HashMap<String, String>();
berita = data.get(position);
nama.setText(berita.get(YmainActivity.in_nama));
stok.setText(berita.get(YmainActivity.in_stok));
kodebrg.setText(berita.get(YmainActivity.in_kodebrg));
harga.setText(berita.get(YmainActivity.in_harga));
info.setText(berita.get(YmainActivity.in_info));
imageLoader.DisplayImage(berita.get(YmainActivity.in_gambar), gambar);
return vi;
}
}
this is my custom listiview pict
http://cdn.gudangimages.com/v1/2015/06/05/gambarlistview.png
and this is detail xml when I clicked one of the list in my custom listview the result is blank, no data and image.
http://cdn.gudangimages.com/v1/2015/06/05/gambardetail.png
I don't know what's wrong with the code, because when I run the program it didn't force close.
first ,you need to debug on the detailActivity to find out whether getIntent() has got the data you desire , if you have got ,then use the view to contain these data ,if not , you need to think about whether the onitemclicklistener is ok
I think the problem is with inx.putExtra(kodebrgs, map2.get(in_kodebrg));
you should use key which doesn't change...
Intent i = new Intent(<currentActivity>.this,
<newactivity>.class);
i.putExtra("ticket", ticket);
i.putExtra("ticketid", tid);
startActivity(i);
and in other intent:
String ticketid = getIntent().getStringExtra("ticketid").toString();
String ticket = getIntent().getStringExtra("ticket").toString();
you can also send each string with different key and get them in detail page with help of key.
So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest
I'm really new to android programming, I successfully get data from server and then populated into a listview. But how do I auto-refresh the listview items within certain amount of time? There maybe new items coming in from the server when I refresh the new items may appear.
Here's my code of retrieving data from server:
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)getView().findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)getView().findViewById(R.id.number);
info = (TextView)getView().findViewById(R.id.info);
remark = (TextView)getView().findViewById(R.id.remark);
statuss = (TextView)getView().findViewById(R.id.statuss);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_view,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
String numberr = oslist.get(position).get("phonenumber");
Intent intent = new Intent(getActivity(), ThreeButton.class);
intent.putExtra("key", numberr);
startActivity(intent);
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i would recommend you to use handler for refreshing data. i.e
final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new JSONParse().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000);
this handler refresh data for every minute.
To prevent the adding the same data in list view you should use following things :
Please paste following code inside the onPost() method of the AsyncTask before for loop :
if(oslist!=null && oslist.size()>0)
oslist.clear();
I already getting the string value from JSON but it seems to have the problem in Hash map or something, im getting null value on my List adapter. Can anyone help me or tell me if i did something wrong in my code. Thanks in advance.
Here is my code.
The Activity -
public class TestJSON extends Activity{
public static ListView lv;
public static ProgressDialog pDialog;
public static LazyAdapter adapter;
static final String KEY_ITEMS = "items";
static final String KEY_TITLE = "title";
static final String KEY_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test_json_view);
new AsyncInitial().execute();
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
lv = (ListView)findViewById(R.id.list);
//lv.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, items));
}
private class AsyncInitial extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected void onPreExecute() {
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
menuItems = new ArrayList<HashMap<String, String>>();
try {
//if (vid_num <= 0) {
// Get a httpclient to talk to the internet
HttpClient client = new DefaultHttpClient();
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
//https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc
HttpUriRequest request = new HttpGet("http://gdata.youtube.com/feeds/api/playlists/SP86E04995E07F6BA8?v=2&start-index=1&max-results=50&alt=jsonc");
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into a readable string
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
// Create a JSON object that we can use from the String
JSONObject json = new JSONObject(jsonString);
// For further information about the syntax of this request and JSON-C
// see the documentation on YouTube http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html
// Get are search result items
JSONArray jsonArray = json.getJSONObject("data").getJSONArray(KEY_ITEMS);
// Get the total number of video
//String vid_num = json.getJSONObject("data").getString("totalItems");
//System.out.println("vid_num-------->"+ vid_num);
// Loop round our JSON list of videos creating Video objects to use within our app
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
// The title of the video
String title = jsonObject.getJSONObject("video").getString(KEY_TITLE);
System.out.println("Title-------->"+ title);
// A url to the thumbnail image of the video
// We will use this later to get an image using a Custom ImageView
//String TAG_thumbUrl = jsonObject.getJSONObject("video").getJSONObject("thumbnail").getString("sqDefault");
//System.out.println("thumbUrl-------->"+ thumbUrl);
String id = jsonObject.getJSONObject("video").getString(KEY_ID);
System.out.println("video_id-------->"+ id);
map.put(title, KEY_TITLE);
map.put(id, KEY_ID);
menuItems.add(map);
}
} catch (ClientProtocolException e) {
//Log.e("Feck", e);
} catch (IOException e) {
//Log.e("Feck", e);
} catch (JSONException e) {
//Log.e("Feck", e);
}
return menuItems;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
adapter = new LazyAdapter(TestJSON.this,menuItems);
lv.setAdapter(adapter);
pDialog.dismiss();
}
}
}
And The adapter
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
public LazyAdapter(TestJSON testJSON, ArrayList<HashMap<String, String>> menuItems) {
activity = testJSON;
data = menuItems;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title);
TextView id = (TextView)vi.findViewById(R.id.artist);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(TestJSON.KEY_TITLE));
id.setText(item.get(TestJSON.KEY_ID));
return vi;
}
}
I have implement Custom List in which i have stored data -> class->Hash Map->List->Adapter.It Places data successfully and shows me list.But when i click on Item in list.I am unable to retrieve clicked value.my code is
public class asasa extends Activity {
//ListView listView;
Intent intent;
private ProgressDialog pDialog;
//Class Declartion DataHolder
DataHolder obj;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
static final String URL = "http://10.0.2.2/android_connect/get_all_products.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_NAME = "name";
private static final String TAG_Description = "description";
private static final String TAG_URL = "url";
private static final String TAG_Price = "price";
private static final String TAG_class = "DataHolider";
LazyAdapter adapter;
// flag for Internet connection status
Boolean isInternetPresent = false;
// products JSONArray
JSONArray products = null;
// Connection detector class
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*ListView l1 = (ListView) findViewById(R.id.sportsList);
l1.setAdapter(new MyCustomAdapter(text, image));
*/
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
LoadAllProducts il = new LoadAllProducts();
il.execute(URL);
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
Toast.makeText(asasa.this, "No Internet Connection You don't have internet connection.", Toast.LENGTH_LONG).show();
}
}
public void longToast(CharSequence message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater=null;
private ArrayList<HashMap<Integer, Object>> data;
//public ImageLoader imageLoader;
int i=0;
public LazyAdapter(Activity a, ArrayList<HashMap<Integer, Object>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image);
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<Integer, Object> song = new HashMap<Integer, Object>();
song = data.get(position);
DataHolder objj=new DataHolder();
objj=(DataHolder) song.get(position);
Log.i("iiiiii "," " +i++);
Log.i("objj.GetName() ",objj.GetName());
Log.i("objj.GetDescription() ",objj.GetDescription());
Log.i("objj.GetPrice() ",objj.GetPrice());
title.setText(objj.GetName());
artist.setText(objj.GetDescription());
duration.setText(objj.GetPrice());
imageview.setImageBitmap(objj.Getimage());
//imageLoader.
return vi;
}
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// creating new HashMap
ArrayList<HashMap<Integer, Object>> productsList=new ArrayList<HashMap<Integer,Object>>();
Bitmap decodedByte;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(asasa.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(URL, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
Log.i("products ",products.toString());
// looping through All Products
Log.i("LENGTHHHH "," "+products.length());
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
Log.i("ccccccccc ",c.toString());
// Storing each json item in variable
// String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
Log.i("name::",name);
String description = c.getString(TAG_Description);
Log.i("description::",description);
/*String URl = c.getString(TAG_URL);
Log.i("URl",URl);
*/
String price = c.getString(TAG_Price);
Log.i("price",price);
byte[] decodedString = Base64.decode(c.getString(TAG_URL), Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
obj=new DataHolder();
obj.setData(name, description, price, decodedByte);
HashMap<Integer, Object> map = new HashMap<Integer, Object>();
// adding each child node to HashMap key => value
map.put(i, obj);
/*map.put(TAG_Description, description);
map.put(TAG_URL, decodedByte);
map.put(TAG_Price, price);*/
//Log.i("MAP",map.toString());
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
/*Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);*/
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
ListView list;
// dismiss the dialog after getting all products
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
//adapter=new LazyAdapter(a, d)
adapter=new LazyAdapter(asasa.this, productsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("Name---------------"," "+ productsList.get(view.getId()).get(position).getClass().getName());
}
});
if (pDialog.isShowing()) {
pDialog.dismiss();
// progressDialog.setCancelable(true);
}
}
}
public void onPause()
{
super.onPause();
}
public class DataHolder
{
String Name;
String Description;
String Price;
Bitmap image;
public void setData(String Name,String Descipton,String Price,Bitmap iamage)
{
this.Name=Name;
this.Description=Descipton;
this.Price=Price;
this.image=iamage;
}
public String GetName()
{return Name;}
public String GetDescription()
{return Description;}
public String GetPrice()
{return Price;}
public Bitmap Getimage()
{return image;}
}
}
i want help in this part of code
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("Name---------------"," "+ productsList.get(view.getId()).get(position).getClass().getName());
}
});
Q2:why GetView is called infinitely at back-end though list is displayed successfully
i HAVE SOLVED MY PROBLEM THIS WAY
HashMap<String, Object> item = productsList.get(position);
DataHolder Data= new DataHolder();
Data= (DataHolder) item.get(ITEMTITLE);
Log.i("productsListID ", Data.Get_Id())
;