I have application, that get images by address "http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png"(for example) from server
public class MenuActivity extends Activity {
private static ArrayList<Products> myProducts;
ParseJSON parseJSON;
private static ArrayList <Bitmap> bm;
final String GetMenuUrl = "http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/get_menu.php";
String City = "Moscow";
String NameCinema = "Avrora";
private ProgressDialog dialog;
private String response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
init();
new RequestTask().execute(GetMenuUrl);
}
private void init(){
myProducts = new ArrayList<Products>();
parseJSON = new ParseJSON();
}
private void setAdapter(ArrayList<Products> products){
GridView grid;
for(int i = 0; i < myProducts.size(); i++){
try {
bm.add(downloadBitmap("http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("size == " + bm.size());
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
SetImg("http://xn--e1aybc.xn--76-6kc1ag2ab9l.xn--p1ai/food.png",imageView);
System.out.println("size == " + bm.size());
CustomGrid adapter = new CustomGrid(MenuActivity.this, products, bm);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MenuActivity.this, "Продукт " + myProducts.get(position).getProductName() + " добавлен в корзину", Toast.LENGTH_SHORT).show();
}
});
}
private void SetImg(final String url,final ImageView v){
final ProgressDialog dialog = ProgressDialog.show(this, "Download",
"downloading");
dialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap downloadBitma = downloadBitmap(url);
runOnUiThread(new Runnable() {
#Override
public void run() {
v.setImageBitmap(downloadBitma);
}
});
} catch (IOException e) {
e.printStackTrace();
} finally {
dialog.dismiss();
}
}
}).start();
}
private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
return bitmap;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
class RequestTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
DefaultHttpClient hc = new DefaultHttpClient();
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost(params[0]);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("city", City));
nameValuePairs.add(new BasicNameValuePair("name_cinema",NameCinema));
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = hc.execute(postMethod, res);
parseJSON.parse(response.toString());
Log.d("response == ", response.toString());
myProducts = parseJSON.getObjects();
Log.d("firstProduc == ", myProducts.get(0).getProductName());
} catch (Exception e) {
System.out.println("Exp=" + e);
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (dialog != null && dialog.isShowing())
dialog.dismiss();
ArrayList<String> products = new ArrayList<String>();
for(int i = 0 ; i < myProducts.size(); i++){
products.add(myProducts.get(i).getProductName());
}
if(products.size() != 0)
setAdapter(myProducts);
else Log.d("error", "can`t load");
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MenuActivity.this);
dialog.setMessage("Загружаюсь...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
super.onPreExecute();
}
}
}
//display images to gridview
public class CustomGrid extends BaseAdapter{
private Context mContext;
private final ArrayList<Products> web;
private final ArrayList<Bitmap> Imageid;
public CustomGrid(Context c,ArrayList<Products> web,ArrayList<Bitmap>Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return web.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#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
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.rowlayout, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
TextView textDescr = (TextView) grid.findViewById(R.id.grid_description);
final ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(web.get(position).getProductName());
textDescr.setText(String.valueOf(web.get(position).getProductPrice()) + "руб.");
// imageView.setImageResource(Imageid[position]);
imageView.setImageBitmap(Imageid.get(position));
} else {
grid = (View) convertView;
}
return grid;
}
}
But I have errors:
10-30 09:27:23.081 2820-2820/com.example.kinofood E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.example.kinofood.MenuActivity.downloadBitmap(MenuActivity.java:162)
at com.example.kinofood.MenuActivity.setAdapter(MenuActivity.java:79)
at com.example.kinofood.MenuActivity.access$400(MenuActivity.java:38)
at com.example.kinofood.MenuActivity$RequestTask.onPostExecute(MenuActivity.java:232)
at com.example.kinofood.MenuActivity$RequestTask.onPostExecute(MenuActivity.java:186)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
how can I change my code? thank you
You can't download on MainThread. If You want to do this Your way, You will have to load it asynchronously, i.e. using AsyncTask.
But the best way to load online images into ImageViews is use of 3rd party libraries.
Libraries known to me:
Universal Image Loader - https://github.com/nostra13/Android-Universal-Image-Loader
Picasso - http://square.github.io/picasso/
Besides simply loading images they handle for You caching, animations, event handling etc.
Related
I want to parse data and images via url of json.
I have used following code to do same. But i am not getting why the images disappear when i scroll down.
Can Anyone please tell me how can i stop to disappear images when i scroll down ?
Images are loading randomly how can i fix it?
Please find below link of source code :-
http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/
public class MainActivity extends Activity {
ArrayList<Actors> actorsList;
ActorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://milagro.in/wip/apps/n/THDC2.json");
ListView listview = (ListView)findViewById(R.id.list);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), actorsList.get(position).gettata_project_name(), Toast.LENGTH_LONG).show();
}
});
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.settata_project_name(object.getString("tata_project_name"));
actor.setproject_Typology(object.getString("project_Typology"));
actor.setproject_logo_url(object.getString("project_logo_url"));
actor.setprice(object.getString("price"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.Projectname = (TextView) v.findViewById(R.id.Projectname);
holder.typology = (TextView) v.findViewById(R.id.typology);
holder.price = (TextView) v.findViewById(R.id.price);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.imageview.setImageResource(R.drawable.ic_launcher);
//new DownloadImageTask(holder.imageview).execute(actorList.get(position).getproject_logo_url());
holder.Projectname.setText(actorList.get(position).gettata_project_name());
holder.typology.setText(actorList.get(position).getproject_Typology());
holder.price.setText("Price: " + actorList.get(position).getprice());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView Projectname;
public TextView typology;
public TextView price;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public class Actors {
private String tata_project_name;
private String project_Typology;
private String project_logo_url;
private String price;
public Actors() {
// TODO Auto-generated constructor stub
}
public Actors(String tata_project_name, String project_Typology,String project_logo_url, String price ) {
super();
this.tata_project_name = tata_project_name;
this.project_Typology = project_Typology;
this.project_logo_url = project_logo_url;
this.price = price;
}
public String gettata_project_name() {
return tata_project_name;
}
public void settata_project_name(String tata_project_name) {
this.tata_project_name = tata_project_name;
}
public String getproject_Typology() {
return project_Typology;
}
public void setproject_Typology(String project_Typology) {
this.project_Typology = project_Typology;
}
public String getproject_logo_url() {
return project_logo_url;
}
public void setproject_logo_url(String project_logo_url) {
this.project_logo_url = project_logo_url;
}
public String getprice() {
return price;
}
public void setprice(String price) {
this.price = price;
}
}
try this library Picaso this is the best image loading library from url.
After using Volley library The problem is solved.
I'm using the staggered grid view to display my information that I get via a webservice. when i displayed it in format portrait there is no problem.( I have 2 grids). In landscape mode I have 3 grids. The problem is here, the textview change the size and became bigger and when I scroll to the end, I will have 2 or 1 grids (not 3) and sometime no grid.
This is the adapter code:
public class StaggeredAdapterVraiCategorie extends ArrayAdapter<VraiCategorie> {
ArrayList<VraiCategorie> categorieList;
LayoutInflater vi;
int Resource;
private ImageLoader mLoader;
Context context;
public StaggeredAdapterVraiCategorie(Context context, int resource,ArrayList<VraiCategorie> objects) {
super(context, resource, objects);
categorieList = objects;
Resource = resource;
this.context=context;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mLoader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(getContext());
convertView = layoutInflator.inflate(R.layout.vrai_list_item_sample,null);
holder = new ViewHolder();
holder.imageView = (DynamicHeightImageView)convertView.findViewById(R.id.image);
holder.namecateg = (TextView)convertView.findViewById(R.id.namecateg);
holder.reftype = (TextView)convertView.findViewById(R.id.reftype);
holder.myid = (TextView)convertView.findViewById(R.id.myid);
convertView.setTag(holder);
}
// else {
holder =(ViewHolder)convertView.getTag();
// }
holder.namecateg.setText(categorieList.get(position).getNamecateg());
holder.reftype.setText(categorieList.get(position).getReftype());
holder.myid.setText(categorieList.get(position).getMyid());
String imgget=categorieList.get(position).getImagecateg();
if(!imgget.equals("null")){
String mylink="http://myserver/images/";
String imgexe=mylink+imgget;
new DownloadImageTask(holder.imageView).execute(imgexe);
}
else if (imgget.equals("null")){
holder.imageView.setHeightRatio(1.0); //ta3mel prob fel staggered
holder.imageView.setImageResource(R.drawable.nophoto);
}
if(!categorieList.get(position).getImagecateg().equals("null")) {
String mylink = "http://myserver/images/";
// holder = (ViewHolder) convertView.getTag();
mLoader.DisplayImage(mylink + categorieList.get(position).getImagecateg(), holder.imageView);
}
return convertView;
}
static class ViewHolder {
public DynamicHeightImageView imageView;
public TextView namecateg;
public TextView reftype;
public TextView myid;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
This is the main class:
public class VraiCateg extends BaseFragment implements StaggeredGridView.OnItemClickListener {
ArrayList<VraiCategorie> categorieList;
StaggeredAdapterVraiCategorie adapter;
StaggeredGridView staggeredGridView;
String passtitle="";
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES="My profile info";
public static final String keyidhotel="idH";
private String myidhotel="";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vrai_main, container, false);
Main activity = (Main) getActivity();
String myDataFromActivity = activity.getData();
myidhotel = myDataFromActivity;
final String url = "http://myserver/api/type_etablissement/categories/id/"+myidhotel;
//url = url + myidhotel;
Toast.makeText(getActivity().getApplicationContext(), "Adresse categ URL "+url, Toast.LENGTH_LONG).show();
staggeredGridView = (StaggeredGridView) view.findViewById(R.id.grid_view);
// myidhotel = getArguments().getString("idH");
int margin = getResources().getDimensionPixelSize(R.dimen.margin);
staggeredGridView.setPadding(margin, 0, margin, 0);
if(!(MySuperScaler.scaled))
MySuperScaler.scaleViewAndChildren(view, MySuperScaler.scale);
categorieList = new ArrayList<VraiCategorie>();
new CategorieAsyncTask().execute(url);
staggeredGridView.setOnItemClickListener(this);
return view;
}
class CategorieAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.cancel();
if (result == false){
//show a msg to user that data not parsed
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
else {
//call etab adapter and create now adapter
StaggeredAdapterVraiCategorie adapter = new StaggeredAdapterVraiCategorie(getActivity().getApplicationContext(),R.layout.vrai_list_item_sample,categorieList);
staggeredGridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
#Override
protected Boolean doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
//HttpPost post = new HttpPost(uri); //uri in oncreate method
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status ==200){
//get the response and pars it
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jObj = new JSONObject(data);
JSONArray jArray = jObj.getJSONArray("categories");
for(int i=0;i<jArray.length();i++ ){
VraiCategorie categ = new VraiCategorie();
JSONObject jRealObject = jArray.getJSONObject(i);
categ.setImagecateg(jRealObject.getString("image_categorie"));
categ.setNamecateg(jRealObject.getString("description_type"));
//ref_type=jRealObject.getString("ref_type");
categ.setReftype(jRealObject.getString("ref_type"));
categ.setMyid(jRealObject.getString("my_id"));
categorieList.add(categ);
}
return true; //verifie the parse
}
}catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
//http call
return false;
}
}
#Override
public void onItemClick(StaggeredGridView parent, View view, int position, long id) {
final String ref_type= categorieList.get(position).getReftype();
Fragment newFragment = new VraiRela();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle args=new Bundle();
args.putString("ref_type",ref_type);
args.putString("idH",myidhotel);
// Toast.makeText(getActivity().getApplicationContext(), "ref_type"+ref_type+"idH"+myidhotel, Toast.LENGTH_LONG).show();
newFragment.setArguments(args);
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
/* myidhotel="";
sharedpreferences = getActivity().getApplicationContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
myidhotel="";
editor.putString(keyidhotel, myidhotel);
editor.commit();*/
}
}
I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.
You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html
I am writing an App in which i am trying to fetch previous Order Details from Server PHPMYADMIN, and want to show these order details in ListView, but whenever i run my app getting NullPointerException, please check my code and tell me what i am missing and where i am doing mistake..
Log says:
05-22 12:33:35.652: E/AndroidRuntime(786): Caused by: java.lang.NullPointerException
05-22 12:33:35.652: E/AndroidRuntime(786): at OrdersActivity.showInfo(OrdersActivity.java:121)
05-22 12:33:35.652: E/AndroidRuntime(786): at OrdersActivity.onCreate(OrdersActivity.java:75)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.Activity.performCreate(Activity.java:5104)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-22 12:33:35.652: E/AndroidRuntime(786): ... 11 more
Error Line Number 75 is : showinfo();
Error Line Number 121 is : if(!strMemberID.equals(""))
OrdersActivity.java:
public class OrdersActivity extends Activity {
TextView total, items ;
String strMemberID,resultServer,MemberID;
ListView list;
OrdersAdapter adapter;
ArrayList<HashMap<String, String>> itemsList;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
showInfo();
itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new OrdersAdapter(this, itemsList);
list.setAdapter(adapter);
if (isNetworkAvailable()) {
new MyAsyncTask().execute();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(OrdersActivity.this).create();
alertDialog.setMessage("The Internet connection appears to be offline.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
public void showInfo()
{
total = (TextView)findViewById(R.id.txtTotalAmount);
items = (TextView)findViewById(R.id.txtItemDetails);
String url = "http://172.16.0.4/res/order_fetch.php";
Intent intent= getIntent();
MemberID = intent.getStringExtra("MemberID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMemberID", MemberID));
resultServer = getHttpPost(url,params);
String strTotal = "";
String strItems = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strTotal = c.getString("TotalAmount");
strItems = c.getString("ItemDetails");
if(!strMemberID.equals(""))
{
total.setText(strTotal);
items.setText(strItems);
}
else
{
total.setText("-");
items.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null);
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
private ProgressDialog progressDialog = new ProgressDialog(
OrdersActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading, Please wait.....");
progressDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new OrdersAdapter(OrdersActivity.this, itemsList);
list.setAdapter(adapter);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
}
OrdersAdapter.java:
public class OrdersAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
String strName,strMemberID ;
public OrdersAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
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.listrow_orders, null);
TextView title = (TextView)vi.findViewById(R.id.txtTotalAmount);
TextView description = (TextView)vi.findViewById(R.id.txtItemDetails);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(strName));
description.setText(strMemberID);
return vi;
}
}
Declare your strMemberID as String strMemberID = "";
NullPointorException will be solved... :)
The default initialization for the String type, when it is declared in the Class scope, is null. That's mean that you can not use before intialize it. You can change the if this way:
if(strMemberID != null && !strMemberID.equals("")) {
}
I am trying to load images from url and set in to gridview, when i scroll my screen images changes. I am a beginner in android. I don't know what is the problem in my code.
Here is my code..
public class Photos extends Activity {
public static final String TAG_IMAGE_NAME = "image_name";
public static final String TAG_IMAGE_THUMB_NAME = "image_thumb_name";
public static String URL = "http://...../..../..../mainAPI.php";
ArrayList<HashMap<String, String>> photoList;
String responseData = null;
static GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photos);
gridView = (GridView)findViewById(R.id.gridView);
photoList = new ArrayList<HashMap<String,String>>();
new AsyncData().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImage.class);
// passing array index
i.putExtra("ImageName", TAG_IMAGE_NAME);
startActivity(i);
}
});
}
class AsyncData extends AsyncTask<String, Void, Void> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Photos.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("rquest","{\"method\":\"photogallery\",\"body\":[{}]}"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
responseData = EntityUtils.toString(resEntity);
try {
JSONArray data = new JSONArray(responseData);
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = data.getJSONObject(i);
String photoName = c.getString(TAG_IMAGE_NAME);
String imageThumbName = c.getString(TAG_IMAGE_THUMB_NAME);
map.put(TAG_IMAGE_NAME, photoName);
map.put(TAG_IMAGE_THUMB_NAME, imageThumbName);
photoList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
gridView.setAdapter(new PhotosAdapter(Photos.this, R.layout.photo_row, photoList));
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
PhgotosAdapter Class
public class PhotosAdapter extends ArrayAdapter<HashMap<String, String>>{
Context context;
String uri;
Bitmap bitmap;
ArrayList<HashMap<String, String>> myList;
HashMap<String, String> myData;
int layout;
public PhotosAdapter(Context context, int textViewResourceId, List<HashMap<String, String>> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.myList = (ArrayList<HashMap<String, String>>) objects;
this.layout = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layout, parent, false);
myData = myList.get(position);
ImageView image = (ImageView)row.findViewById(R.id.imagePhoto);
try{
ImageDownloadTask task = new ImageDownloadTask(image);
task.execute();
uri = "" + myData.get(Photos.TAG_IMAGE_THUMB_NAME).replace(" ", "%20");
image.setImageBitmap(bitmap);
image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return row;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class ImageDownloadTask extends AsyncTask<Void, Integer, Bitmap> {
private ImageView mView;
ProgressDialog pDialog;
ImageDownloadTask(ImageView view){
mView = view;
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
bitmap = getBitmapFromURL(uri);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
mView.setImageBitmap(result);
}
}
}
I don't know what is the problem in it, Please Help me and give some solution.
ImageLoader imageLoader;
imageLoader=new ImageLoader(context.getApplicationContext());
imageLoader.DisplayImage(urlname, imageViewname);
try it