2015-10-03 50 views
1

我想設置圖像查看頁面我成功完成,但在我的應用程序視圖分頁圖像來自web服務器。當圖像來自Web服務器時,我如何設置圖像。 Link for web service如何在圖像來自web服務器時在ViewPager中設置圖像

HomeFragment.java:-

public class HomeFragment extends Fragment { 

ViewPager viewPager; 
CustomSwipAdapter swipAdapter; 

public HomeFragment() { 
    // Required empty public constructor 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_home, container, false); 

     viewPager = (ViewPager)rootView.findViewById(R.id.viewpager); 
     swipAdapter = new CustomSwipAdapter(getContext()); 
     viewPager.setAdapter(swipAdapter); 




    // Inflate the layout for this fragment 
    return rootView; 
} 

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
} 

@Override 
public void onDetach() { 
    super.onDetach(); 
}} 

CustomSwipAdapter.java:-

public class CustomSwipAdapter extends PagerAdapter { 

private Context ctx; 
private LayoutInflater layoutInflater; 
private String image_path; 
private ImageView imageView; 
private int[] flag; 

public CustomSwipAdapter(Context ctx){ 
    this.ctx = ctx; 

} 
@Override 
public int getCount() { 
    return flag.length; 
} 

@Override 
public boolean isViewFromObject(View view, Object o) { 
    return (view==(LinearLayout)o); 
} 
@Override 
public Object instantiateItem(ViewGroup container, int position) { 
    layoutInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View item_view = layoutInflater.inflate(R.layout.swip_layout,container,false); 

    imageView = (ImageView)item_view.findViewById(R.id.image_view); 

    new Slider().execute("http://opencart.codeniques.com/shopping/?route=feed/web_api/slider&key=test123$"); 

    new DownloadImageTask(imageView).execute(image_path); 

    imageView.setImageResource(flag[position]); 
    container.addView(item_view); 

    return item_view; 
} 

@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
    container.removeView((LinearLayout)object); 
    // super.destroyItem(container, position, object); 
} 

public class Slider extends AsyncTask<String,Void,Void>{ 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

    } 

    @Override 
    protected Void doInBackground(String... params) { 
     try { 
      HttpClient client = new DefaultHttpClient(); 
      HttpPost post = new HttpPost(params[0]); 
      HttpResponse response = client.execute(post); 

      int sattus = response.getStatusLine().getStatusCode(); 

      if(sattus==200){ 
       HttpEntity entity = response.getEntity(); 
       String data = EntityUtils.toString(entity); 

       JSONObject jsonObject = new JSONObject(data); 
       JSONArray jsonArray = jsonObject.getJSONArray("banners"); 

       for(int i=0;i<jsonArray.length();i++){ 


        JSONObject jsonObject1 = jsonArray.getJSONObject(i); 
        image_path = jsonObject1.getString("sliderimage"); 
        flag = new int[]{1,2,3,4,5}; 
        Log.d("Slider imaage count ayr",jsonArray.length()+""); 


       } 
      } 
     }catch (IOException |JSONException e){ 
      Log.e("Error ",e.getMessage()); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void aVoid) { 
     super.onPostExecute(aVoid); 
    // new DownloadImageTask(imageView).execute(image_path); 

    } 
} 

public class DownloadImageTask extends AsyncTask<String,Void,Bitmap>{ 

    ImageView bitmap; 

    public DownloadImageTask(ImageView bitmap){ 
     this.bitmap = bitmap; 
    } 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 

    @Override 
    protected Bitmap doInBackground(String... params) { 
     String urldisplay = params[0]; 
     Bitmap bitmap = null; 
     try{ 
      InputStream in = new java.net.URL(urldisplay).openStream(); 
      bitmap = BitmapFactory.decodeStream(in); 
     }catch (IOException e){ 
      Log.e("Error :",e.getMessage()); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Bitmap result) { 
     bitmap.setImageBitmap(result); 

    } 
}} 

我在新開發Android,請幫助我。

錯誤

FATAL EXCEPTION: main 
Process: com.catalyst.android.shoppingmazza, PID: 3550 
java.lang.NullPointerException: Attempt to read from null array 
    at com.catalyst.android.shoppingmazza.activity.CustomSwipAdapter.instantiateItem(CustomSwipAdapter.java:68) 
    at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:870) 
    at android.support.v4.view.ViewPager.populate(ViewPager.java:1020) 
    at android.support.v4.view.ViewPager.populate(ViewPager.java:952) 
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) 
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) 
    at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1112) 
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:632) 
    at android.view.View.measure(View.java:18788) 
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715) 
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) 
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 
    at android.view.View.measure(View.java:18788) 
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:901) 
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) 
    at android.view.View.measure(View.java:18788) 
    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:940) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) 
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 
    at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) 
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) 
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) 
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) 
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) 
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) 
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) 
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951) 
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 
    at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643) 
    at android.view.View.measure(View.java:18788) 
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100) 
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216) 
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452) 
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107) 
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013) 
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) 
    at android.view.Choreographer.doCallbacks(Choreographer.java:670) 
    at android.view.Choreographer.doFrame(Choreographer.java:606) 
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) 
    at android.os.Handler.handleCallback(Handler.java:739) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

回答

0

你的返回值始終是空在doInBackground方法

將其更改爲下面的代碼

try{ 
    InputStream in = new java.net.URL(urldisplay).openStream(); 
    bitmap = BitmapFactory.decodeStream(in); 
    return bitmap; // added 
}catch (IOException e){ 
    Log.e("Error :",e.getMessage()); 
} 
return null; 
+0

我加了你的變化,但仍應用暗戀 –

+0

發表您的logcat – Kunu

+0

可以請你告訴我如何發佈logcat的 –

0

你可以從這裏http://square.github.io/picasso/ 下載畢加索圖書館可以像這樣使用

//Initialize ImageView 
ImageView imageView = (ImageView) findViewById(R.id.imageView); 

//Loading image from below url into imageView 

Picasso.with(this) 
    .load("YOUR IMAGE URL HERE") 
    .into(imageView); 
0

這樣做。在你的片段中初始化一個列表,並執行以下操作。您不應該從適配器獲取圖像,因爲適配器可能會在片段中多次調用。

class SomeFragment extends Fragment { 
    List<Bitmap> imageList; 
    FetchImagesFromServerTask task; 
    ... 
    ... 
    . 
    . 
    @Override 
    public onCreateView(Bundle ..) { 
    . 
    . 
    . 
     imagelist = new Arraylist(); 
     task = new FetchImagesFromServerTask(); 
     task.execute(); 

    } 

    ... 
    ... 
    ... 
    public class FetchImagesFromServerTask extends AsyncTask<Void,Void,List<Bitmap>> { 


     @SuppressLint("LongLogTag") 
     @Override 
     protected List<Bitmap> doInBackground(Void... params) { 

      String buffer = ""; 
      HttpURLConnection connection = null; 
      BufferedReader reader = null; 

      String urlString = "http://opencart.codeniques.com/shopping/?route=feed/web_api/slider&key=test123$"; 

      try { 
       URL url = new URL(urlString); 
       connection = (HttpURLConnection) url.openConnection(); 
       connection.setRequestMethod("GET"); 
       connection.connect(); 

       InputStream inputStream = connection.getInputStream(); 
       StringBuilder builder = new StringBuilder(); 
       reader = new BufferedReader(new InputStreamReader(inputStream)); 

       String line; 
       while ((line = reader.readLine()) != null) { 
        builder.append(line + "\n"); 
       } 

       buffer = builder.toString(); 
      } catch (IOException e) { 
       Log.e("Fetching Images From Server", "Error ", e); 
      } finally { 
       if (connection != null) { 
        connection.disconnect(); 
       } 
       if (reader != null) { 
        try { 
         reader.close(); 
        } catch (final IOException e) { 
         Log.e("FetchVideosTask", "Error closing stream", e); 
        } 
       } 
      } 
      List<Bitmap> images = new ArrayList<>(); 
      try { 
       images = fetchImages(buffer); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      for(int i = 0; i < images.size(); i++) { 
       Log.d("Image fetched:",images.get(i).toString()); 
      } 

      return images; 
     } 

    @Override 
    protected void onPostExecute(List<Bitmap> v) { 
    imagelist = v; 
    swipAdapter = new CustomSwipAdapter(getContext(),imagelist); 
    viewPager.setAdapter(swipAdapter); 
    } 


    public List<Bitmap> fetchImages(String urlList) throws IOException { 
     JSONObject myjson; 
     List<Bitmap> myImagesList = new ArrayList<>(); 
     List<String> urls = new ArrayList<>(); 
     try { 
      myjson = new JSONObject(urlList); 
      Log.d("", myjson.toString()); 
      JSONArray page1 = myjson.getJSONArray("banners"); 

      for (int i = 0; i < page1.length(); i++) { 

       JSONObject movieObject = page1.getJSONObject(i); 
       urls.add(movieObject.getString("sliderimage")); 

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

     for (String s : urls) { 
      byte[] stream = getByteArrayOutputStream(s); 
      Bitmap bitmap = BitmapFactory.decodeByteArray(stream,0,stream.length); 
      myImagesList.add(bitmap); 
     } 
     return myImagesList; 
    } 


    @NonNull 
    private byte[] getByteArrayOutputStream(String s) throws IOException { 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     URL url = new URL(s); 
     InputStream is = null; 
     try { 
      is = url.openStream(); 
      byte[] byteChunk = new byte[8092]; // Or whatever size you want to read in at a time. 
      int n; 

      while ((n = is.read(byteChunk)) > 0) { 
       stream.write(byteChunk, 0, n); 
      } 
     } catch (IOException e) { 
      System.err.printf("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage()); 
      e.printStackTrace(); 
      // Perform any other exception handling that's appropriate. 
     } finally { 
      if (is != null) { 
       Log.d("Recieved image", is.toString()); 
       is.close(); 
      } 
     } 
     return stream.toByteArray(); 
    } 


    } 
} 

創建另一個構造爲您pageradapter這樣的:

public class CustomSwipAdapter extends PagerAdapter { 

    private Context ctx; 
    private LayoutInflater layoutInflater; 
    private String image_path; 
    private ImageView imageView; 
    private int[] flag; 
    private List<Bitmap> imagelist; */Make sure you do this/* 

    public CustomSwipAdapter(Context ctx, List<Bitmap> imagelist){ 
     this.ctx = ctx; 
     this.imagelist = imagelist; 

    } 

然後在您的實例化方法只是設置從位圖的列表中的圖像資源。

imageView.setImageResource(imagelist(position)); 
+0

onCreateView給出錯誤 –

+0

它是什麼錯誤?發佈你的logcat。 –

+0

沒有它沒有爲我工作,請提供更多的選項 –

相關問題