I'm trying to load a facebook photo by ID and place it in a ListView with my custom adapter.
My issue is that in MyAdapter, mIcon1 can't be resolved to a variable, and in LoadAllProducts, mIcon1 is not used.
It's obvious that I'm not properly referencing mIcon1 in the adapter, or I didn't set it up properly in LoadAllProducts, but I don't know which one is wrong!
Any help appreciated greatly! Thank you!
LoadAllProducts AsyncTask:
public class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading videos...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
String fbid = fbID;
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fbid", fbid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_videos, "POST", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
//GETTING PROFILE PICTURE START-----------------------//
URL img_value = null;
try {
img_value = new URL("http://graph.facebook.com/"+TAG_FACEBOOKID+"/picture?width=100&height=100");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
//GETTING PROFILE PICTURE END-----------------------//
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);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String facebookid = c.getString(TAG_FACEBOOKID);
String to_user = c.getString(TAG_TO_USER);
String available = c.getString(TAG_AVAILABLE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_FACEBOOKID, facebookid);
map.put(TAG_TO_USER, to_user);
map.put(TAG_AVAILABLE, available);
// 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) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
MyAdapter adapter = new MyAdapter(AllProductsActivity.this, R.layout.list_item, productsList);
// updating listview
setListAdapter(adapter);
}
});
}
}
MyAdapter:
public class MyAdapter extends ArrayAdapter<HashMap<String, String>> {
Context context;
int resourceId;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> items;
public MyAdapter (Context context, int resourceId, ArrayList<HashMap<String, String>> items)
{
super(context, resourceId, items);
this.items =items;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
final ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.userpicture=(ImageView)findViewById(R.id.userpicture);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
HashMap<String,String> item = (HashMap<String,String> ) items.get(position);
if (item != null)
{
// This is where you set up the views.
holder.name.setText(item.get(TAG_FACEBOOKID));
holder.userpicture.setImageBitmap(mIcon1);
}
return convertView;
}
public class ViewHolder
{
TextView name;
ImageView userpicture;
}
}
You didnt put any reference in the holder.userpicture.setImageBitmap(mIcon1); so the compiler will tell you that that variable mIcon1 does not exist please make it.
Also in the Bitmap mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream()); no one can access mIcon1 outside the scope of the doInbackground.
Solution:
Make the MyAdapter as a inner of the LoadAllProducts and create a global variable inside the LoadAllProducts which is the Bitmap mIcon1 and use it in the background thread and in the adapter
Related
I am fetching data from server and passing this data to custom adapter to display it on image adapter. I am using asynchtask for fetching data. My problem is that I want to change image in list view after every 5 seconds. Please suggest me a solution. Here is my activity file
public class MainActivity extends Activity {
private String[] image,name,descr;
ListView list;
LazyImageLoadAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String serverURL = "http://10.0.2.2/JsonReturn.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
list=(ListView)findViewById(R.id.list);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
// Create custom adapter for listview
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition)
{
String tempValues = image[mPosition];
Toast.makeText(MainActivity.this,
"Image URL : "+tempValues,
Toast.LENGTH_LONG)
.show();
}
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
ListView lst=(ListView)findViewById(R.id.list);
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
String data ="";
//TextView uiUpdate = (TextView) findViewById(R.id.output);
/// TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
int sizeData = 0;
// EditText serverText = (EditText) findViewById(R.id.serverText);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8")+ "="+"RAja";//serverText.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
/*****************************************************/
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(), "Error"+Error, Toast.LENGTH_LONG).show();;
//uiUpdate.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
//uiUpdate.setText( Content );
Toast.makeText(getApplicationContext(), "content"+Content, Toast.LENGTH_LONG).show();;
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
image=new String[lengthJsonArr];
name=new String[lengthJsonArr];
descr=new String[lengthJsonArr];
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String nm = jsonChildNode.optString("name").toString();
String img = jsonChildNode.optString("image").toString();
String desc = jsonChildNode.optString("desc").toString();
image[i]=img;
name[i]=nm;
descr[i]=desc;
OutputData += " Name : "+ nm +" \n "
+ "Number : "+ img +" \n "
+ "Time : "+ desc +" \n "
+"--------------------------------------------------\n";
//Log.i("JSON parse", song_name);
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
Toast.makeText(getApplicationContext(), "Parsed Data"+ OutputData, Toast.LENGTH_LONG).show();;
adapter=new LazyImageLoadAdapter(MainActivity.this, image,name,descr);
//Set adapter to listview
list.setAdapter(adapter);
//lst.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
and my image adapter class file is as follow
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
private String[] data,name,desc;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, String[] d,String[] name,String[] desc) {
activity = a;
data=d;
this.name=name;
this.desc=desc;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create ImageLoader object to download and show image in list
// Call ImageLoader constructor to initialize FileCache
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listview_row, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.text);
holder.text1=(TextView)vi.findViewById(R.id.text1);
holder.image=(ImageView)vi.findViewById(R.id.image);
/************ Set holder with LayoutInflater ************/
vi.setTag( holder );
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText(name[position]);
holder.text1.setText(desc[position]);
ImageView image = holder.image;
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(data[position], image);
/******** Set Item Click Listner for LayoutInflater for each row ***********/
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
sct.onItemClick(mPosition);
}
}
}
I have tried to put set adapter() method in oncreate() of activity but it gives me error. So how can i change images display on list view after some specific time? Please suggest solution.
I am getting nullpointer exception in list.setAdapter(adapter); statement
Your declaration is wrong at here
YOUR CODE
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
list=(ListView)findViewById(R.id.list);
Here you declared the ListView after called AsyncTask so it'll never find ListView at Adapter set time.
Please Change it
list=(ListView)findViewById(R.id.list);
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
Problem comes with Initialization.
move this line list=(ListView)findViewById(R.id.list); above this line, new LongOperation().execute(serverURL);
I want to set the background color for the list which has the different values in an textbox like happy, sad coming from database and i want when in my text box happy comes background color changes to red and when angry it changes to green like this...
Here is my code....
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Feeds.this);
pDialog.setMessage("Loading Feeds. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All moods from url
* */
protected String doInBackground(String... args) {
// Session class instance
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// email
String email = user.get(SessionManage.KEY_EMAIL).toString();
Log.d("seesion", email);
// Building Parameters
List<NameValuePair> para = new ArrayList<NameValuePair>();
para.add(new BasicNameValuePair("email", email));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_get_moods, "GET",
para);
// Check your log cat for JSON reponse
Log.d("All Moods: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
Log.d("yjyth", Integer.toString(success));
if (success == 1) {
String data = null;
// Moods found
// looping through All Products
for (int i = 1; i <= json.length(); i++) {
try {
JSONObject c = json.getJSONObject(Integer
.toString(i));
Log.d("Loop", Integer.toString(i));
Log.d("Value of c", c.toString());
JSONObject dd = c.getJSONObject("data");
Log.d("value of dta", dd.toString());
String type = dd.getString("type");
Log.d("value of type", type);
String because = dd.getString("because");
Log.d("value of type", because);
String created = dd.getString("created");
Log.d("value of type", type);
String description = dd.getString("description");
Log.d("value of des", description);
//String datetime1 = dd.getString("datetime");
img=(ImageView)findViewById(R.id.imageFeeds);
LinearLayout l=(LinearLayout)findViewById(R.id.lisfeeds);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put("type", type);
map.put("because", because);
map.put("description", description);
map.put("created", created);
if(type.equals("Feeling Happy")){
map.put("img", R.drawable.happyhov);
map.put("color", R.drawable.angrygrad);
}
else if(type.equals("Feeling Angry")){
map.put("img", R.drawable.angryhov);
}
else if(type.equals("Feeling Confused")){
map.put("img", R.drawable.confusdhov);
}
else if(type.equals("Feeling Confident")){
map.put("img", R.drawable.confihov);
}
else if(type.equals( "Feeling Frustrated")){
map.put("img",R.drawable.frusthov);
}
else if(type.equals("Feeling Lonely")){
map.put("img", R.drawable.loneyhov);
}
else if(type.equals("Feeling Ecstatic")){
map.put("img", R.drawable.esthov);
}
else if(type.equals("Feeling Sad")){
map.put("img",R.drawable.sadhov);
}
// adding HashList to ArrayList
moodsList.add(map);
} catch (Exception e) {
Log.e(" Parser", "Error data " + e.toString());
}
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(), Home.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) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
MyAdapter adapter = new MyAdapter(Feeds.this,
moodsList, R.layout.item_list,
new String[] {
"img",TAG_TYPE,TAG_BECAUSE, TAG_DESCRIPTION, TAG_CREATED},
new int[] { R.id.imageFeeds,R.id.type, R.id.texbec, R.id.des,R.id.date });
// updating listview
lv.setAdapter(adapter);
}
});
}
}
class MyAdapter extends SimpleAdapter {
private String[] names;
private Activity c;
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
}
class ViewHolder {
public TextView texttype,bec,des,date;
public ImageView image;
}
public MyAdapter(Activity c, String[] names) {
super(c, moodsList, R.layout.item_list, names, null);
this.c = c;
this.names = names;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
Context context = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.item_list, null);
holder = new ViewHolder();
holder.texttype = (TextView) vi.findViewById(R.id.type);
holder.image = (ImageView) vi
.findViewById(R.id.imageFeeds);
holder.bec = (TextView) vi.findViewById(R.id.texbec);
holder.des = (TextView) vi.findViewById(R.id.des);
holder.date = (TextView) vi.findViewById(R.id.date);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
Log.d("fchs","dfvhes");
//holder.image.setBackgroundResource(TAG_IMAGE);
holder.texttype.setText(TAG_TYPE);
holder.bec.setText(TAG_TYPE);
holder.des.setText(TAG_TYPE);
if (TAG_TYPE.equals("Happy") ) {
vi.setBackgroundColor(Color.BLUE);
} else {
vi.setBackgroundColor(Color.RED);
}
}catch(Exception e)
{
}
return vi;
}
}
Inside your custom adapter (SimpleAdapter) class --> got to --> public View getView Method make sure that your code is simmiler with this
View vi = convertView;
final ViewHolder holder;
try {
if (convertView == null) {
vi = inflater.inflate(R.layout.my_group_list_item, null);
holder = new ViewHolder();
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (if sad if happy clause here ) {
vi.setBackgroundColor(Color.parseColor("#a1cc3b"));
} else {
vi.setBackgroundColor(Color.parseColor("#cfd0d1"));
}
hope this could help you.
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);
I am trying to Parse the JSON to list view
There is no error in log cat
The image is getting parsed but the data which should be displayed in
front of rank and country is not getting displayed
Why is the error occuring
How to resolve this
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("name", resultp.get(MainActivity.NAME));
// Pass all data country
intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://54.218.73.244:7002/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("name", jsonobject.getString("restaurantNAME"));
map.put("type", jsonobject.getString("restaurantTYPE"));
map.put("flag", jsonobject.getString("restaurantIMAGE"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
output
The image is getting parsed but the data which should be displayed in front of rank and country is not getting displayed
Any Ideas
hope i am clear
The image is getting parsed but the data which should be displayed in
front of rank and country is not getting displayed
because you are storing values in HashMap with different keys and trying to get values with different keys in Adapter so change it as inside doInBackground method for storing values with keys :
map.put(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("restaurantIMAGE"));
try below code:
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
and your map key also different: see restaurantNAME...
How to parsed JSON data from AsyncTask to custom Gridview inside Detail Fragment ?
I have Integer[] picture , String[] menu and String[] price
in GridView i have 1 ImageView and 2 TextView
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
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 Menu: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
System.out.println(success);
if (success == 1) {
// products found
// Getting Array of Products
menuresto = json.getJSONArray(TAG_MENU);
// looping through All Products
for (int i = 0; i < menuresto.length(); i++) {
JSONObject c = menuresto.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
// adding HashList to ArrayList
menuList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
/**
* How to parsed JSON data into GridView
* */
}
});
}
Should i work in GetView ?
EDIT
Code Complete of Adapter
public class MyAdapter extends BaseAdapter {
Context mContext;
private ProgressDialog pDialog;
// creating json parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> menuList;
static final String TAG_SUCCESS = "success";
static final String TAG_MENU = "menu";
static final String TAG_MID = "mid";
static final String TAG_NAME = "name";
static final String TAG_PICT = "picture";
static final String TAG_PRICE = "price";
// url to get all menu list
private static String url = "http://10.0.2.2/menu/food/get_all_products.php";
// menu JSONArray
JSONArray menuresto = null;
public Integer[] menupict = { R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher };
private LayoutInflater mInflater;
public MyAdapter(Context c) {
mContext = c;
mInflater = LayoutInflater.from(c);
// array menu
menuList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return menuList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return menuList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// Building Parameters
// System.out.println("MyAdapter.getView()");
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.gviewfill, parent, false);
holder = new ViewHolder();
/*
* holder.ImgView = new ImageView(mContext);
* holder.ImgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
*
* holder.ImgView = (ImageView) convertView
* .findViewById(R.id.iv_menu_image);
*/
holder.txtName = (TextView) convertView
.findViewById(R.id.tv_menu_name);
holder.price = (TextView) convertView
.findViewById(R.id.tv_menu_price);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.ImgView.setImageResource(menupict[position]);
holder.price.setText("Rp. " + menuList.get(position).get(TAG_PRICE));
holder.txtName.setText(menuList.get(position).get(TAG_NAME));
return convertView;
}
static class ViewHolder {
ImageView ImgView;
TextView txtName;
TextView price;
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mContext);
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 Menu: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
System.out.println(success);
if (success == 1) {
// products found
// Getting Array of Products
menuresto = json.getJSONArray(TAG_MENU);
// looping through All Products
for (int i = 0; i < menuresto.length(); i++) {
JSONObject c = menuresto.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
// adding HashList to ArrayList
menuList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
}
});
}
}
}
How to parsed JSON data into GridView
=> You just need to create an adapter to display data in GridView. Because you are already having ArrayList ready (in terms of menuList) inside doInBackground() of AsyncTask.
Now, it depends how do you want to display data in GridView, i mean type of item layout you want to display inside GridView.