2012-12-28 245 views
1

我使用asynctask下载图像,然后一旦它完成下载,它应该将图像加载到我的水平库中。可能吗?asynctask下载图像,然后将图像加载到水平库

现在我已经尝试过,但它总是崩溃:

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 

new downloadFile().execute(); 
gallery = (Gallery) findViewById(R.id.examplegallery); 
gallery.setAdapter(new AddImgAdp(this)); 

    gallery.setOnItemClickListener(new OnItemClickListener() { 
     public void onItemClick(AdapterView parent, View v, int position, long id) { 
      // Displaying the position when the gallery item in clicked 
      Toast.makeText(MainActivity.this, "Position=" + position, Toast.LENGTH_SHORT).show(); 
    } 
    }); 

} 

/** 
    * Background Async Task to Load all product by making HTTP Request 
    * */ 
    class downloadFile extends AsyncTask<String, String, String> { 

     /** 
     * getting all magazines from url 
     * */ 
     protected String doInBackground(String... args) { 
      URL myFileUrl = null; 

     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // getting JSON string from URL 
     JSONObject json = jParser.makeHttpRequest(url_login, "GET", params); 

     // Check your log cat for JSON reponse 
     Log.d("All Products: ", json.toString()); 

     try { 
      // Checking for SUCCESS TAG 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // products found 
       // Getting Array of Products 
       mag = json.getJSONArray(TAG_MAGAZINE); 

       for (int i = 0; i < mag.length(); i++) { 
        JSONObject c = mag.getJSONObject(i); 

        // Storing each json item in variable 
        String magLink = c.getString(TAG_MAGAZINE_URL); 
        String magThumb = c.getString(TAG_MAGAZINE_THUMBNAIL); 
        //String magazineIssue = c.getString(TAG_MAGAZINE_ISSUE); 

        urlList.add(magLink); 
        //urlList.add(magazineIssue); 
        thumbnailList.add(magThumb); 

        System.out.println(thumbnailList); 
       }     
      } 
      else { 

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


     for (int i = 0; i < thumbnailList.size(); i ++) 
     { 
     thumbnail = thumbnailList.get(i).toString(); 
     Log.d("thumbnail", thumbnail); 
     number = i; 
      try { 
       myFileUrl = new URL(thumbnail); // RETRIEVE IMAGE URL 
       } 
      catch (MalformedURLException e) { 
       e.printStackTrace(); 
      } 
      try { 
       HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); 
       conn.setDoInput(true); 
       conn.connect(); 
       InputStream in = conn.getInputStream(); 
       Log.i("im connected", "Download"); 
       bmImg = BitmapFactory.decodeStream(in); 

       File filename; 
       try { 
        // GET EXTERNAL STORAGE, SAVE FILE THERE 
        File storagePath = new File(Environment.getExternalStorageDirectory(),"Covers"); 
        storagePath.mkdirs(); 

        filename = new File(storagePath + "/photo"+number+".jpg"); 
        FileOutputStream out = new FileOutputStream(filename); 
        bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out); 

        out.flush(); 
        out.close(); 
        MediaStore.Images.Media.insertImage(getContentResolver(),filename.getAbsolutePath(), filename.getName(), 
          filename.getName());   



       // displayImage(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 



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

     } 

      return null; 
     } 

     /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute() {  

     runOnUiThread(new Runnable() { 
      public void run() { 

       ArrayList<String> mStringList= new ArrayList<String>(); 
       File strPath = new File(Environment.getExternalStorageDirectory() + "/Covers"); 
       int lists = strPath.listFiles().length; 
       Log.d("number of items in array ",String.valueOf(lists)); 

       File yourDir = new File(strPath, ""); 
       for (File f : yourDir.listFiles()) { 
        if (f.isFile()) 
        { 
         String name = f.getName(); 
         String v = strPath + "/" + name; 
         mStringList.add(v); 
        } 
       } 

       mImageIds = new String[mStringList.size()]; 
       mImageIds = mStringList.toArray(mImageIds); 

       for(int a = 0; a < mImageIds.length ; a++){ 
        Log.d("string is",(mImageIds[a])); 
       } 


      } 



     }); 
    } 
    } 

    public class AddImgAdp extends BaseAdapter { 
     int GalItemBg; 
     private Context cont; 

     public AddImgAdp(Context c) { 
      cont = c; 
      TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); 
      GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0); 
      typArray.recycle(); 
      } 
     public int getCount() { 
      return mImageIds.length; 
     } 

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

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

     public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView imgView = new ImageView((Context) cont); 

     imgView.setImageDrawable(Drawable.createFromPath(mImageIds[position])); 

     // Fixing width & height for image to display 
     imgView.setLayoutParams(new Gallery.LayoutParams(80, 70)); 
     imgView.setScaleType(ImageView.ScaleType.FIT_XY); 
     imgView.setBackgroundResource(GalItemBg); 

     return imgView; 
     } 
     } 

} 

这是我的logcat输出:

12-28 12:08:10.510: E/AndroidRuntime(5567): FATAL EXCEPTION: main 
12-28 12:08:10.510: E/AndroidRuntime(5567): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.horizontalviewing/com.example.horizontalviewing.MainActivity}: java.lang.NullPointerException 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1978) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2003) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.ActivityThread.access$600(ActivityThread.java:123) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1169) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.os.Handler.dispatchMessage(Handler.java:99) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.os.Looper.loop(Looper.java:137) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.ActivityThread.main(ActivityThread.java:4446) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at java.lang.reflect.Method.invokeNative(Native Method) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at java.lang.reflect.Method.invoke(Method.java:511) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at dalvik.system.NativeStart.main(Native Method) 
12-28 12:08:10.510: E/AndroidRuntime(5567): Caused by: java.lang.NullPointerException 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at com.example.horizontalviewing.MainActivity$AddImgAdp.getCount(MainActivity.java:247) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.widget.AbsSpinner.setAdapter(AbsSpinner.java:113) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at com.example.horizontalviewing.MainActivity.onCreate(MainActivity.java:69) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.Activity.performCreate(Activity.java:4465) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1942) 
12-28 12:08:10.510: E/AndroidRuntime(5567):  ... 11 more 
+0

在'mimageids'中添加元素后,只需移动'gallery.setAdapter(new AddImgAdp(this));'在onPostExecute()内移动'并且不需要在'onPostExecute()'中使用'runOnUiThread',因为我们可以从'onPostExecute()'方法访问/更新Ui AsyncTask –

+0

我试过了,但它说“构造函数MainActivity.AddImgAdp(MainActivity.downloadFile)未定义“。 – user1234555

+0

是的,它说的正确使用'gallery.setAdapter(new AddImgAdp(MainActivity.this));'而不是'gallery.setAdapter(new AddImgAdp(this));' –

回答

0

错误是告诉你mimageids尚未当getCount()运行初始化。问题是mImageIds不是适配器的变量。一个适配器应该是自包含的。您应该在适配器上创建添加/删除图像方法,以便在从服务器下载它们时添加它们。或类似的东西。

+0

我应该如何添加/删除图像到我的适配器?我搞不清楚了。 – user1234555

1

getCount方法中有一个空指针异常,因为您在post执行初始化之前初始化适配器,要么将您的适配器创建移动到postexecute代码中,要么首先初始化数组mImageIds。

+0

我试图将我的适配器创建移动到postExecute代码,但它似乎不工作。 – user1234555