从服务器获取图像时出错

时间:2017-05-29 21:37:50

标签: java android

这是我的主要活动课。我是Android开发的新手,我被困在这里。从服务器获取图像时遇到问题。

我有一个图像加载器类,可以在imageView和内存缓存以及工具等中加载图像。

    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;
        }
    }

适配器类

这是我的适配器类在数组列表中获取数据但图像没有得到。

它在看到它的代码的地方工作,但它在我的情况下不起作用。

    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是图像加载器类

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);
    }
}

}

1 个答案:

答案 0 :(得分:0)

使用Glide的替代解决方案

如果我理解,您可以通过链接获得图片列表。对?

要向服务器发出请求,请使用okhttp或volley库并以JSON格式返回结果。然后使用滑动库加载图像。

请参阅本教程以了解volley https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/

这是滑翔库https://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en

所以,在你的gradle中添加滑行

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

而不是使用ImageLoader,请使用此

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