2017-05-29 54 views
0

這是我的主要Activity類。我是android開發中的新手,我被卡在了這裏。在從服務器獲取圖像時遇到問題。從服務器獲取圖片時出錯

我有一個圖像加載器類加載的圖像中的ImageView和存儲器高速緩存和utils的等

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

$這裏的圖像加載類

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

}

+0

圖像是問題還是整個適配器?如果是圖像,那麼你需要添加ImageLoader代碼 –

+0

只有圖像..我正在獲取其他數據 –

+0

幫我我有截止日期完成,我卡在這裏 –

回答

0

使用滑翔

如果我明白了,通過你的鏈接,你得到的圖像列表的替代解決方案。對?

要向服務器發出請求,請使用okhttp或volley庫並以JSON格式返回結果。然後使用滑動庫加載圖像。

請參見本教程的凌空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); 
+0

圖書館的鏈接不回答問題 –

+0

這是爲了方便代碼。 –

+0

瞭解,但我認爲我們應該嘗試瞭解問題,而不是建議從頭開始重新啓動,本質上 –