android


Get image in gridview from server


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 Links

How to fix Tabhost for All activity
Realm - Copy Realm Object to Another Realm Object Type
Changing names of android styles but app crashes
Cannot get sticky headers to work with SuperSLiM
Can't stop The frameanimation(android)
Why the lists of photos which were got by these two manners are different?
are there any predefined color values? like “primary_text_default_material_light”?
How delete row without deleting its _ID column value?
Javacv android loading avutil error
Action bar functionality lost after returning back from second activity to the main activity's fragment
To detect existing alarm
Android - ViewPager flipping just Layouts intead of Fragments
react-native android fontFamily does not take effect
Low Pass Filter android
Cannot parse response
Take a picture and saved it in /data/data

Categories

HOME
embedded
porting
cobalt
fftw
sh
knitr
ms-access-2016
seo
emscripten
pearson-correlation
vert.x
augeas
activecollab
jsonpath
supervisor
gource
qsqlquery
scsi
symfony-2.8
vuejs
jersey-1.0
lilypond
springfox
cgbitmapcontext
parcelable
tosca
windows-server-2003
progress-bar
handler
python-2.6
complex-numbers
utorrent
getpixel
indy10
parse-tree
laravel-elixir
postgresql-8.4
wmp
movilizer
oracle-service-bus
http-request
angular-http
snapchat
yii2-api
dbcontext
geotiff
seq
mapxtreme
reporting-services-2012
neon
android-dateutils
omniauth-facebook
kango-framework
tracker-enabled-dbcontext
php-socket
nio2
avisynth
oracle-spatial
jdi
google-books
ms-access-2000
rrule
delayed-execution
execve
ghcjs
machine-instruction
linkedin-jsapi
reflector
ray
buffering
maven-scm
decoupling
ora-06550
artemis
light
solace-mq
scrypt
beaker-testing
pagedown
wp7test
android-loadermanager
mkv
midlet
apache-commons-dbutils
google-maps-mobile
ikimagebrowserview
android-holo-everywhere
entitydatasource
umra
timertask
burndowncharts
google-wave
cldc
software-lifecycle

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App