calling image from server in android - android

Hello i have this Json output and i am calling in my android app. I am able to get picture path but how can i display picture instead of path . here is the code
public class Test extends ListActivity {
Prefs myprefs = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
this.myprefs = new Prefs(getApplicationContext());
// install handler for processing gui update messages
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/proj/androidjson.php?identifier=" +
Test.this.myprefs.getPersonalno());
try{
JSONArray earthquakes = json.getJSONArray("services");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("pic", "Picture : " + e.getString("employeepic"));
map.put("serviceinfo", "" + e.getString("employeename")+ " : "+ e.getString("starttime")
+" To " + e.getString("endtime"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "pic", "serviceinfo" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
This is path which i am getting in my android app
pictures/file83915.jpg
Here i am calling picture
map.put("pic", "Picture : " + e.getString("employeepic"));

I have used this class for downloading image from server
Hope it will help you...!! When you have got your image URLs list from your server or any source, then used it like this to download that particular Image.
GetImage.downloadFile("pictures/file83915.jpg", new ImageDownloaded()
{
#Override
public void imageDownloaded(Bitmap result){
image.setImageBitmap(result);
}
#Override
public void imageDownloadedFailed(){
}
});
Where the GetImage class is:
public class GetImage
{
public static void downloadFile(final String fileUrl, final ImageDownloaded img)
{
AsyncTask<String , Void, Bitmap> task = new AsyncTask<String , Void, Bitmap>()
{
#Override
protected Bitmap doInBackground(String... params) {
Bitmap bmImg;
URL myFileUrl =null;
if(fileUrl.equals(""))
{
return null;
}
try
{
myFileUrl= new URL("http://yourURl/" +fileUrl.replace(" ", "%20"));
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
return bmImg;
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap results)
{
if(results != null)
img.imageDownloaded(results);
else
img.imageDownloadedFailed();
}
};
task.execute("");
}
public static abstract class ImageDownloaded
{
public abstract void imageDownloaded(Bitmap result);
public abstract void imageDownloadedFailed();
}
}
I used CustomAdapter class to show the data in the list with Images like this.
in the method getView() I used this thread like this.
public View getView(params....)
{
View row ;//Inflataion blah blah
Bitmap thumb = myCustomObject.getBitmap();
final ImageView image = (ImageView) row.findViewById(R.id.image);
if(thumb == null)
{
GetImage.downloadFile(myCustomObject.getImagePath(), new ImageDownloaded()
{
#Override
public void imageDownloaded(Bitmap result){
myCustomObject.setBmp(result);
image.setImageBitmap(myCustomObject.getBitmap());
}
#Override
public void imageDownloadedFailed(){
}
});
}
else
image.setImageBitmap(thumb);
}
MyCustomObject is my class that encapsulates the data from server as well as Image from server and implements Parcelable interface. First I get data through JSON and then get Image in Adapter. It can also be passed to the any DetailActivity

Related

Unable to parse JSON data into Listview

im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Thanks for your input
Override getCount method into adapter class.

Update CustomArrayAdapter after AsyncTask in Android

I m having a CustomArrayAdapter which I m using to update a a custom ListView.
This is working fine but when I m trying to update the view
after getting results in AsyncView onPostExecute using notifyDataSetChanged it is not updating nor it is returning any exceptions.
The code for onCreate -
public class MainActivity extends ListActivity {
String[] presidents = {"Dwight D. Eisenhower","John F. Kennedy","Lyndon B. Johnson","Richard Nixon","Gerald Ford","Jimmy Carter","Ronald Reagan","George H. W. Bush","Bill Clinton","George W. Bush","Barack Obama"};
String[] pics = {"5237","5438", "184", "184", "184", "184", "184", "184", "184", "184", "184", "184"};
private String[] names;
private String[] pid;
ListActivity obj;
CustomArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obj = this;
try {
adapter =new CustomArrayAdapter(obj, presidents, pics);
setListAdapter(adapter);
new DownloadTextTask().execute("http://nvoids.com/rest/hello/users/");
} catch(Exception e) {
Log.d("Listview1", "Exception: " + e.getLocalizedMessage());
}
}
The AsyncTask's onPostExecute -
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result.substring(1, 10) ,Toast.LENGTH_SHORT).show();
try
{
JSONArray jarr = new JSONArray(result);
names = new String[jarr.length() -1];
pid = new String[jarr.length() -1];
for (int i =0; i< jarr.length(); i++) {
JSONObject jObj = new JSONObject(jarr.get(i).toString());
names[i] = jObj.getString("value");
pid[i] = jObj.getString("pid");
}
super.onPostExecute(result);
adapter =new CustomArrayAdapter(obj, names, pid);
adapter.notifyDataSetChanged();
} catch(Exception e) {
Log.d("ListView1", "after getting string: " + e.getLocalizedMessage());
}
}
By the way the CustomArrayAdapter class if required -
public class CustomArrayAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] presidents;
private final String[] imageIds;
public CustomArrayAdapter(Activity context,String[] presidents, String[] imageIds) {
super(context, R.layout.lvrowlayout, presidents);
this.context = context;
this.presidents = presidents;
this.imageIds = imageIds;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
//---print the index of the row to examine---
Log.d("Listview1",String.valueOf(position));
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.lvrowlayout, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txtPresidentName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
txtTitle.setText(presidents[position]);
//imageView.setImageResource(imageIds[position]);
new DownloadImageTask((ImageView) imageView )
.execute("http://nvoids.com/dir/image_" + imageIds[position] + ".jpeg");
return rowView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Log.d("CustomArrayGetImage Error", urldisplay);
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("CustomArrayGetImage Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
EDIT -
As in the answers passing the parameters also does not work -
try {
adapter =new CustomArrayAdapter(obj, presidents, pics);
setListAdapter(adapter);
new DownloadTextTask(adapter).execute( "http://nvoids.com/rest/hello/users/");
} catch(Exception e) {
Log.d("Listview1", "Exception: " + e.getLocalizedMessage());
}
In the DownloadAsyncTask -
private class DownloadTextTask extends AsyncTask<String, Void, String> {
CustomArrayAdapter ca;
public DownloadTextTask(CustomArrayAdapter ca) {
this.ca = ca;
}
......
protected void onPostExecute(String result) {
//Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), result.substring(1, 10) ,Toast.LENGTH_SHORT).show();
try
{
JSONArray jarr = new JSONArray(result);
names = new String[jarr.length() -1];
pid = new String[jarr.length() -1];
for (int i =0; i< jarr.length(); i++) {
JSONObject jObj = new JSONObject(jarr.get(i).toString());
names[i] = jObj.getString("value");
pid[i] = jObj.getString("pid");
ca.addAll(names[i] , pid[i]);
}
/*
super.onPostExecute(result);
adapter =new CustomArrayAdapter(obj, names, pid);
lv.setAdapter(adapter);
obj.setListAdapter(adapter);
*/
ca.notifyDataSetChanged();
} catch(Exception e) {
Log.d("ListView1", "after getting string: " + e.getLocalizedMessage());
}
}
Because, You are creating new object of Custom Adapter in AsyncTask's onPostExecute()
Like,
adapter =new CustomArrayAdapter(obj, names, pid);
adapter.notifyDataSetChanged();
Which is not set to ListView. So either write syntax for setListAdapter() to ListView in onPostExecute() (For this you need ListView reference in AsyncTask) or
Use the same object which you have created in onCreate() of Your ListActivity, Pass that adapter object in Constructor of AsyncTask and use Object in onPostExecute().
adapter =new CustomArrayAdapter(obj, names, pid);
adapter.notifyDataSetChanged();
notifyDataSetChange notify observers to update data.
So in your example you notify new adapter to update their data, but you don't attach adapter to your list.
But create each time new adapter - is not a good practise, you have to update data in your adapter (in your case list of presidents) and then call notifyDataSetChange on your existing adapter.
PS ArrayAdapter already have a list under it and you can call add and don't need to store list of presidents. In your case i think it's better to create
class PresidentsWrapper {
String name,
String photoUrl
}
And create ArrayAdapter<PresidentWrapper>
In this case you don't need any underlying structures and can do like this:
getItem(position);
add(new PresidentWrapper(...));

Implementation of Async Task

I am trying to implement Async Task in this class but the thing is that I am calling getInputStream function in my program which is returning a value and I am not sure Where to put it. Where should I define getInputStream in my async task?
I am getting the below exception
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity com.sparkplug.xxxx}: java.lang.NullPointerException
Below is my main class:
public class abcreaderextends ListActivity {
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
parsing p=new parsing();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_awsreader);
((PullToRefreshListView) getListView())
.setOnRefreshListener(new OnRefreshListener() {
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
InputStreamOperation in= new InputStreamOperation();
in.execute();
//p.parse();
for (int i = 0; i < p.headlines.size(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("title", p.headlines.get(i));
map.put("dcdate", p.lstDate.get(i));
map.put("description", p.description.get(i));
// adding HashList to ArrayList
menuItems.add(map);
}
ListAdapter rssFeedSection = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { "title", "dcdate",
"description" }, new int[] { R.id.name, R.id.date1,
R.id.desc });
setListAdapter(rssFeedSection);
}
class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected void onPostExecute(String[] result) {
// **menuItems.addFirst("Added after refresh...");
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) getListView()).onRefreshComplete();
super.onPostExecute(result);
}
#Override
protected String[] doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = Uri.parse((String) p.links.get(position));
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
This is my parsing class:
public class parsing {
List headlines;
List links;
List description;
List lstDate;
List newDate;
//String a,b,c,d;
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public HashMap<String, ArrayList<String>> parse() {
// Initializing instance variables
headlines = new ArrayList<String>();
links = new ArrayList<String>();
description = new ArrayList<String>();
lstDate = new ArrayList<String>();
try {
URL url = new URL(
"http://feeds.feedburner.com/xxxx");
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
// We will get the XML from an input stream
xpp.setInput(getInputStream(url), "UTF_8");
int i = 0;
boolean insideItem = false;
// Returns the type of current event: START_TAG, END_TAG, etc..
int eventType = xpp.getEventType();
int k = 0;
while (eventType != XmlPullParser.END_DOCUMENT) {
i++;
// Log.i("Tag : ",xpp.getName().toString());
// Log.i("Text : ",xpp.nextText().toString());
if (eventType == XmlPullParser.START_TAG) {
Log.i("Tag : ", xpp.getName().toString());
// Log.i("Text : ",xpp.nextText().toString());
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("title")) {
if (insideItem) {
String var = xpp.nextText().toString();
headlines.add(var); // extract the description of
// article
Log.i("Title : ", var);
// Log.i("Count : ",i+"");
}
} else if (xpp.getName().equalsIgnoreCase("description")) {
if (insideItem) {
String desc = xpp.nextText().toString();
description.add(desc); // extract the description of
// article
Log.i("Desc : ", desc);
}
} else if (xpp.getName().equalsIgnoreCase("dc:date")) {
if (insideItem) {
String strDate = xpp.nextText().toString();
System.out.println("rahul"+strDate.substring(0,10));
//lstDate = Arrays.asList(arr[k].substring(0,10));
lstDate.add(strDate.substring(0,10));
System.out.println("lstDate"+lstDate);
k = k+1;
Log.i("Date : ", strDate);
}
} else if (xpp.getName().equalsIgnoreCase("link")) {
if (insideItem)
links.add(xpp.nextText()); // extract the link of
// article
}
} else if (eventType == XmlPullParser.END_TAG
&& xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
}
eventType = xpp.next(); // move to next element
}// While end
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HashMap<String, ArrayList<String>> alllists =
new HashMap<String, ArrayList<String>>();
alllists.put("headlines",(ArrayList<String>) headlines);
alllists.put("links",(ArrayList<String>) links);
alllists.put("description",(ArrayList<String>) description);
alllists.put("lstDate",(ArrayList<String>) lstDate);
return alllists;
}
}
and this one is my InputStreamOperation class:
public class InputStreamOperation extends AsyncTask>> {
#Override
protected void onPreExecute() {
// show progress bar here(have not used any progress bar)
}
#Override
protected HashMap<String, ArrayList<String>>
doInBackground(Void... params) {
//call parse() method here
parsing parsingobj=new parsing();
HashMap<String, ArrayList<String>> alllists=parsingobj.parse();
return alllists; //<<< retun final result from here
}
#Override
protected void onPostExecute(HashMap<String, ArrayList<String>> result) {
// update UI here
}
}
Try like this..
class Search AsyncTask<String, Void, ArrayList<Movie>>() {
#Override
protected void onPreExecute() {
progressDialog= ProgressDialog.show(context, "Please Wait","Searching movies", true);
}
#Override
protected ArrayList<Movie> doInBackground(String... params) {
String moviesJson = retrieveStream[params[0]];
JSONObject moviesJson = new JSONObject(moviesJson);
ArrayList<Movie> movies = new ArrayList<Movie>();
/*
* Do your code to process the JSON and create an ArrayList of films.
* It's just a suggestion how to store the data.
*/
return movies;
}
protected void onPostExecute(ArrayList<Movie> result) {
progressDialog.dismiss();
//create a method to set an ArrayList in your adapter and set it here.
sampleActivity.mListAdapter.setMovies(result);
sampleActivity.mListAdapter.notifyDataSetChanged();
}
}
For more information..
Android issues with AsyncTask and InputStream
you will need to call getInputStream inside doInBackground method of AsyncTask as:
First Change parse method return type to HashMap<String, String> as :
public HashMap<String, ArrayList<String>> parse() {
///your code here...
HashMap<String, ArrayList<String>> alllists =
new HashMap<String, ArrayList<String>>();
alllists.put("headlines",headlines);
alllists.put("links",links);
alllists.put("description",description);
alllists.put("lstDate",lstDate);
return alllists;
}
and Create AsyncTask class as :
private class InputStreamOperation extends
AsyncTask<String, Void, HashMap<String, ArrayList<String>>> {
#Override
protected void onPreExecute() {
// show progress bar here
}
#Override
protected HashMap<String, ArrayList<String>>
doInBackground(String... params) {
//call parse() method here
parsing parsingobj=new parsing();
HashMap<String, ArrayList<String>> alllists=parsingobj.parse();
return alllists; //<<< retun final result from here
}
#Override
protected void onPostExecute(HashMap<String, ArrayList<String>> result) {
// update UI here
}
}
It should be written in the doInBackground() method.
Due to formatting problems i am not able to upload the exact code
1 create a class extending asyncTask with
2 Write getInputStream in doInBackground
3 Call the asynctask to get InputStream

android: update ListView with SimpleAdapter

I have a ListView with a SimpleAdapter. The Data for the ListView comes from json. I want to update the ListView every 5 min.
That works fine... But the ListView is allway a double. All items are to times in the ListView. Why? And wenn I update then 3 times....
I try
setListAdapter(null);
and
mylist.clear();
no effect
public class StartActivity extends ListActivity {
TextView text_1,text_2 ;
private Timer autoUpdate;
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
Button btnShowLocation;
// GPSTracker class
GpsData gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
btnShowLocation = (Button) findViewById(R.id.report_btn);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(StartActivity.this, ReportActivity.class);
startActivity(intent);
}
});
new task().execute();
}
#Override
public void onResume() {
super.onResume();
autoUpdate = new Timer();
autoUpdate.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
new task().execute();
}
});
}
}, 0, 300000); // updates each 5 min
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(StartActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Status Update...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
//mylist.clear();
JSONObject json = jsonFunctions.getJSONfromURL("http://my.de", mlat, mlon);
try{
//String text = getString(R.string.report_TJ);
JSONArray earthquakes = json.getJSONArray("uTraf");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("first", "Stau: " + e.getString("road") + ", " + e.getString("county"));
map.put("second", e.getString("timestamp") + ", " + e.getString("suburb"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
//setListAdapter(null);
ListAdapter adapter = new SimpleAdapter(StartActivity.this, mylist , R.layout.main,
new String[] { "first", "second" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(StartActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
this.progressDialog.dismiss();
}
}
#Override
public void onPause() {
autoUpdate.cancel();
super.onPause();
}
}
Your problem is with the call mylist.add(map); inside your for loop in doInBackground.
Your creating a map is fine but by calling the add function on mylist you are appending it to the list and not overriding the current map with the same keys. If you want to update existing items in the listview as opposed to just overwriting with fresh data then the mylist variable should probably be a HashMap also.
EDIT - Solution:
In doInBackground, just before you enter the loop to process data
(for(int i=0;i<earthquakes.length();i++))
call mylist.clear(). This will empty your array list before you start to add new data to it.
add mylist = new ArrayList<HashMap<String, String>>(); in doInBackGround() method
try{
//String text = getString(R.string.report_TJ);
JSONArray earthquakes = json.getJSONArray("uTraf");
mylist = new ArrayList<HashMap<String, String>>();
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("first", "Stau: " + e.getString("road") + ", " + e.getString("county"));
map.put("second", e.getString("timestamp") + ", " + e.getString("suburb"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}

Android: Json parse in listview

Im trying to parse some items in a listview and when I scroll down I want to get more products and add them to the list.
But my code doesnt do that it either refreshes it or crashes.
Any help?
Also adding a footer doesnt work either i get an classcastexception
JSONParser:
package com.lars.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.lars.R.drawable;
import android.R;
import android.util.Log;
/** A class to parse json data */
public class JSONParser {
// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){
JSONArray jProducts = null;
try {
// Retrieves all the elements in the 'countries' array
jProducts = jObject.getJSONArray("products");
} catch (JSONException e) {
e.printStackTrace();
}
// Invoking getCountries with the array of json object
// where each json object represent a country
return getProducts(jProducts);
}
private List<HashMap<String, Object>> getProducts(JSONArray jProducts){
int productsCount = jProducts.length();
List<HashMap<String, Object>> productList = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> product = null;
// Taking each country, parses and adds to list object
for(int i=0; i<productsCount;i++){
try {
// Call getCountry with country JSON object to parse the country
product = getJSON((JSONObject)jProducts.get(i));
productList.add(product);
} catch (JSONException e) {
e.printStackTrace();
}
}
return productList;
}
// Parsing the Country JSON object
private HashMap<String, Object> getJSON(JSONObject f){
HashMap<String, Object> country = new HashMap<String, Object>();
String id = "";
String naam = "";
String status = "";
String prijs = "";
String productnum = "";
try {
String priceone = f.getString("prijsex");
id = f.getString("id");
naam = f.getString("naam");
status = f.getString("status");
prijs = "€" + priceone;
productnum = f.getString("productnum");
country.put("id", id);
country.put("naam", naam);
country.put("img", com.lars.R.drawable.tlogotrans);
country.put("prijs", prijs);
country.put("img_path", "http://www.lars.com/images/" + productnum + ".jpg");
if(Integer.parseInt(status) > 0){
country.put("status", com.lars.R.drawable.stock);
}else{
country.put("status", com.lars.R.drawable.nostock);
}
} catch (JSONException e) {
e.printStackTrace();
}
return country;
}
}
Download tasks and Listview loaders:
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
// The parsing of the xml data is done in a non-ui thread
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
Log.i("Result", result);
if(result.equals(" ")){
Log.i("No img", "No Img");
}else{
listViewLoaderTask.execute(result);
}
// Start parsing xml data
}
}
/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
private List<HashMap<String, Object>> products;
// Doing the parsing of xml data in a non-ui thread
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try{
jObject = new JSONObject(strJson[0]);
JSONParser jsonpars = new JSONParser();
jsonpars.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
// Instantiating json parser class
JSONParser jsonpars = new JSONParser();
// A list object to store the parsed countries list
try{
// Getting the parsed data as a List construct
if(set == 0){
products = jsonpars.parse(jObject);
}else{
products.addAll(jsonpars.parse(jObject));
}
}catch(Exception e){
Log.d("Exception",e.toString());
}
// Keys used in Hashmap
String[] from = { "img","naam","status","prijs"};
// Ids of views in listview_layout
int[] to = { R.id.imPThumb,R.id.tvPRName,R.id.imstock,R.id.tvPRPrijs};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), products, R.layout.productlijstrow, from, to);
return adapter;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
publishProgress();
Log.i("ListView Loader Task", "Update");
super.onProgressUpdate(values);
}
/** Invoked by the Android on "doInBackground" is executed */
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(SimpleAdapter adapter) {
// View v = getLayoutInflater().inflate(R.layout.footerview, null);
//list.addFooterView(v);
// Setting adapter for the listview
list.setAdapter(adapter);
if(set == 0){
list.setOnScrollListener(onAnswersScrolled);
set++;
}
list.setOnItemClickListener(onAnswerClicked);
list.setTextFilterEnabled(true);
/* list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Bundle extra = new Bundle();
Intent i = new Intent("com.lars.productdescription");
extra.putString("id", o.get("id"));
i.putExtras(extra);
startActivity(i);
}
});*/
for(int i=0;i<adapter.getCount();i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("img_path");
Log.i("imgurlonPost", imgUrl);
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
HashMap<String, Object> hmDownload = new HashMap<String, Object>();
hmDownload.put("img_path",imgUrl);
hmDownload.put("position", i);
// Starting ImageLoaderTask to download and populate image in the listview
imageLoaderTask.execute(hmDownload);
adapter.notifyDataSetChanged();
}
/* list.setOnScrollListener(new OnScrollListener(){
});*/
}
}
/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream=null;
String imgUrl = (String) hm[0].get("img_path");
int position = (Integer) hm[0].get("position");
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
URL url;
try {
url = new URL(imgUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Log.i("imgUrl", imgUrl);
// Connecting to url
urlConnection.connect();
// Log.i("Response", urlConnection.getResponseMessage());
// Reading data from url
if(urlConnection.getResponseMessage().contains("OK")){
iStream = urlConnection.getInputStream();
// Getting Caching directory
File cacheDirectory = getBaseContext().getCacheDir();
cacheDirectory.delete();
// Temporary file to store the downloaded image
File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
// The FileOutputStream to the temporary file
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Creating a bitmap from the downloaded inputstream
Bitmap b = BitmapFactory.decodeStream(iStream);
// Writing the bitmap to the temporary file as png file
b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
//Close the FileOutputStream
fOutStream.close();
// Create a hashmap object to store image path and its position in the listview
// Storing the path to the temporary image file
hmBitmap.put("img",tmpFile.getPath());
// Storing the position of the image in the listview
hmBitmap.put("position",position);
// Returning the HashMap object containing the image path and position
return hmBitmap;
}else{
Log.i("nope", "nb");
String uriStr = "android.resource://" + "com.lars" + "/" + R.drawable.ic_launcher;
hmBitmap.put("img", uriStr);
hmBitmap.put("position",position);
return hmBitmap;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(HashMap<String, Object> result) {
// Getting the path to the downloaded image
String path = (String) result.get("img");
// Getting the position of the downloaded image
int position = (Integer) result.get("position");
// Getting adapter of the listview
adapter = (SimpleAdapter ) list.getAdapter();
// Getting the hashmap object at the specified position of the listview
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
// Overwriting the existing path in the adapter
hm.put("img",path);
// Noticing listview about the dataset changes
adapter.notifyDataSetChanged();
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
publishProgress();
adapter.notifyDataSetChanged();
Log.i("Image Task", "Update");
super.onProgressUpdate(values);
}
}
private OnItemClickListener onAnswerClicked = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) parent.getItemAtPosition(position);
Bundle extra = new Bundle();
Intent i = new Intent("com.lars.productdescription");
extra.putString("id", o.get("id"));
i.putExtras(extra);
startActivity(i);
}
};
private OnScrollListener onAnswersScrolled = new OnScrollListener() {
public void onScroll(AbsListView view, int first, int visibleitems, int totalitemcount) {
// TODO Auto-generated method stub
int lastInScreen = first + visibleitems;
if(lastInScreen == totalitemcount){
if(kf == 0){
Log.i("onScroll", "" + c);
Log.i("kf", "0");
String filfinal = keuze.replace(" ", "thisisaspace");
String strUrl = "http://www.lars.nl/getName.php?name=" + filfinal + "&page=" + c ;
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
c = c + o;
Log.i("After Scroll", "" + c);
}else{
Log.i("onScroll", "" + c);
Log.i("kf", "1");
String strUrl = "http://www.lars.nl/get.php?id=" + filter + "&page=" + c ;
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
c = c + o;
Log.i("After Scroll", "" + c);
}
}
}
public void onScrollStateChanged(AbsListView view, int scrollstate) {
// TODO Auto-generated method stub
}
};
}
I'd like to introduce you to CWAC-ENDLESS by non other than the brilliant mark murphy (commonsware). Not only is it a fine example of the power of putting an adapter inside another adapter, it handles all the background tasks for you as well as scrolling so that your data list may be added to very easily by following the demo
I sincerely hope this helps you as much as its helped me.

Categories

Resources