简体   繁体   中英

Error in getting images from server

This is my Main Activity class.I am new in android development and I'm stuck here. Having a problem in getting images from the server.

I have an image loader class to which loads an image in imageView and memory cache and utils etc.

    public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {

        ListView list;
        SearchView mSearchView;
        LazyAdapter adapter;
        JSONArray jarray;
        String data = "", line = null, strresponse, txt, myjson;
        BufferedReader reader;


        String dataparseurl = "https://ndroid.000webhostapp.com/Php2/getListofrestaurant.php";

        public String Id;
        public String SName;
        public String ShortAdd;
        public String imagesserver;
        public String hour;
        public String address;
        ArrayList<HashMap<String, String>> arraylist;

        private String Name[] = {"Sagar Gaire Fast Food", "Sharma and Vishnu Fast Food", "Sharma FastFood",
                "Domino's Pizza", "Manohar Dairy", "Greek Food & Beyond"};
        private int images[] = {R.drawable.img5, R.drawable.img6, R.drawable.img9, R.drawable.img8,
                R.drawable.img7, R.drawable.img11};
        private String hours[] = {"10AM TO 11PM", "8AM To 10PM", "11AM To 10:30PM", "8AM To 11PM", "8AM To 9PM", "11AM To 11PM"};


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);



            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.setDrawerListener(toggle);
            toggle.syncState();

            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);

            DataFromServer();

            mSearchView = (SearchView) findViewById(R.id.searcview1);
            list = (ListView) findViewById(R.id.lv1);

        }

        @Override
        public void onDestroy() {
            list.setAdapter(null);
            super.onDestroy();
        }


        @Override
        public void onBackPressed() {
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
               finish();
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        @SuppressWarnings("StatementWithEmptyBody")
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            // Handle navigation view item clicks here.
            int id = item.getItemId();

            if (id == R.id.nav_order) {
                // Handle the order action
                Intent yourorder = new Intent(MainActivity.this, YourOrder_Layout.class);
                startActivity(yourorder);
                finish();
            } else if (id == R.id.nav_cart) {
                Intent cart = new Intent(MainActivity.this, Cart_Layout.class);
                startActivity(cart);
                finish();

            } else if (id == R.id.nav_profiledit) {

            } else if (id == R.id.nav_manage) {

            } else if (id == R.id.nav_share) {

            } else if (id == R.id.nav_send) {

            }

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }

        private void DataFromServer() {
            class ServerData extends AsyncTask<String, Void, String> {

                @Override
                protected String doInBackground(String[] params) {

                    arraylist = new ArrayList<HashMap<String, String>>();
                    try {

                        URL url = new URL(dataparseurl);

                        URLConnection conn = url.openConnection();
                        conn.setDoOutput(true);
                        OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
                        osw.write(data);
                        osw.flush();

                        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                        StringBuilder sb = new StringBuilder();

                        while (((line = reader.readLine()) != null)) {

                            sb.append(line);
                            strresponse = sb.toString();
                        }
                        txt = strresponse;

                    } catch (Exception e) {

                        try {
                            reader.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        Toast.makeText(getApplicationContext(), "OOPs Something went wrong Check Your Connection", Toast.LENGTH_SHORT).show();
                    }

                    return txt;
                }

                @Override
                protected void onPostExecute(String result) {

                    if (result == null && txt == null) {
                        Toast.makeText(getApplicationContext(), "can't be saved", Toast.LENGTH_SHORT).show();
                    } else {

                        myjson = result;
                        showlist();
                    }
                }

            }
            ServerData sd = new ServerData();
            sd.execute();

        }

        private void showlist() {

            try {
                JSONObject jsonObject = new JSONObject(myjson);
                jarray = jsonObject.getJSONArray("result");
                for (int i = 0; i < jarray.length(); i++) {
                    JSONObject c = jarray.getJSONObject(i);

                    Id = c.getString("Id");
                    SName = c.getString("RestName");
                    ShortAdd = c.getString("RestAddressshort");
                    imagesserver = c.getString("RestPic");
                    hour = c.getString("Resthours");
                    address = c.getString("RestAddress");

                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put("ID",Id);
                    map.put("RestName",SName);
                    map.put("ShortAddres",ShortAdd);
                    map.put("RestPic",imagesserver);
                    map.put("Hour",hour);
                    map.put("Address",address);

                    arraylist.add(map);

                }
                Toast.makeText(getApplicationContext(), arraylist.get(0)+""+arraylist.get(1)+"",Toast.LENGTH_LONG).show();

                adapter = new LazyAdapter(this,arraylist);
                list.setAdapter(adapter);
                list.setTextFilterEnabled(true);
                mSearchView.setOnQueryTextListener(this);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        Intent info = new Intent(MainActivity.this, Info_Layout.class);
                        startActivity(info);

                    }
                });


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    }

Adapter Class

This is my Adapter Class getting data in array list but images are not getting.

It's working where saw its code but it's not working in my case.

    public class LazyAdapter extends BaseAdapter {

        private Activity activity;
        private ArrayList<HashMap<String, String>> data;
        private static LayoutInflater inflater=null;
        public ImageLoader imageLoader;
        private HashMap<String, String> resultp = new HashMap<String, String>();

        public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> arraylist) {
            activity = a;
            data = arraylist;
            inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            imageLoader=new ImageLoader(activity.getApplicationContext());
        }

        public int getCount() {
            return data.size();
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View vi=convertView;
            if(convertView==null)
                vi = inflater.inflate(R.layout.listitem_1, parent,false);
            resultp = data.get(position);

            TextView text=(TextView)vi.findViewById(R.id.textviewitemname);
            TextView texttime = (TextView) vi.findViewById(R.id.textviewitemhours);
            ImageView image=(ImageView)vi.findViewById(R.id.imageviewitem);


            text.setText(resultp.get("RestName"));
            texttime.setText(resultp.get("Hour"));

           // image.setImageResource(data[position]);
           imageLoader.DisplayImage(resultp.get("RestPic"),image);
            return vi;
        }
    }

$ here is the image loader class

public class ImageLoader {

private MemoryCache memoryCache=new MemoryCache();
private FileCache fileCache;
private Map<ImageView, String> imageViews= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
private ExecutorService executorService;

public ImageLoader(Context context){
    fileCache=new FileCache(context);
    executorService= Executors.newFixedThreadPool(5);
}

private final int stub_id = R.drawable.image1;
public void DisplayImage(String url, ImageView imageView)
{
    imageViews.put(imageView, url);
    Bitmap bitmap=memoryCache.get(url);
    if(bitmap!=null)
        imageView.setImageBitmap(bitmap);
    else
    {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView)
{
    PhotoToLoad p=new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url)
{
    File f=fileCache.getFile(url);

    //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;

    //from the web
    try {
        Bitmap bitmap;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex){
        ex.printStackTrace();
        if(ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=70;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {e.printStackTrace();}
    return null;
}

//Task for the queue
private class PhotoToLoad
{
    String url;
    ImageView imageView;
    PhotoToLoad(String u, ImageView i){
        url=u;
        imageView=i;
    }
}

private class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;
    PhotosLoader(PhotoToLoad photoToLoad){
        this.photoToLoad=photoToLoad;
    }

    @Override
    public void run() {
        if(imageViewReused(photoToLoad))
            return;
        Bitmap bmp=getBitmap(photoToLoad.url);
        memoryCache.put(photoToLoad.url, bmp);
        if(imageViewReused(photoToLoad))
            return;
        BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
        Activity a=(Activity)photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
    }
}

private boolean imageViewReused(PhotoToLoad photoToLoad){
    String tag=imageViews.get(photoToLoad.imageView);
    return tag == null || !tag.equals(photoToLoad.url);
}

//Used to display bitmap in the UI thread
private class BitmapDisplayer implements Runnable
{
    Bitmap bitmap;
    PhotoToLoad photoToLoad;
    BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
    public void run()
    {
        if(imageViewReused(photoToLoad))
            return;
        if(bitmap!=null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

}

Alternative solution using Glide

If I understand, through your link you get a list of images. Right?

To make requests to the server use the okhttp or volley library and return the result in JSON format. Then load the images using the glide library.

See this tutorial for volley https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/

This is glide library https://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en

So, add glide in your gradle

dependencies {
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'com.android.support:support-v4:22.0.0'
}

and instead of using ImageLoader, use this

Glide.with(context)
    .load(resultp.get("RestPic"))
    .into(imageView);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM