在Android中从服务器保存SD卡中的图像

时间:2015-08-04 12:13:53

标签: android json

我想从服务器下载图像并保存到模拟器中的SD卡中。 首先,我必须获取JSON String图像并传递下载服务器URL以供下载并保存到SD卡中。 我在运行时遇到NullPointerException错误。

请有人帮助我。

这是我的代码

public void getAllImagePath_List() {
        String strUrl_GetAll_Activity = "http://xxx/xxx/xxx.svc/xxx/xx/"+str_UserId+"/xx/"+xxx+"/xxx/"+xxx;
        Log.e("strUrl_GetAll_Activity ", " = " + strUrl_GetAll_Activity);
        InputStream inputStream = null;

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse httpResponse = httpclient.execute(new HttpGet(strUrl_GetAll_Activity));
            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null)
                strResult = convertInputStreamToString(inputStream);
            else
                strResult = "Did not work!";

            String jsonStr = strResult;

            try {

                JSONObject jsonObj = new JSONObject(jsonStr);
                String jsonResult = jsonObj.toString().trim();
                Log.e("jsonResult ", " = " + jsonResult);

                JSONObject getAllActivity_List = jsonObj.getJSONObject("Get_ALL_ActivityListResult");
                Log.e("getAllActivity_List ", " = " + getAllActivity_List.toString());

                String strSync = getAllActivity_List.getString("Sync_Time");
                Log.e("strSync ", " = " + strSync.toString());

                JSONArray jarr = getAllActivity_List.getJSONArray("ActivityObjectList");
                Log.e("jarr ", " = " + jarr.toString());

                SQLiteDatabase mDb = dbhelper.getWritableDatabase();
                int imageNum = 0;
                BufferedOutputStream bos;
                 imagesArray = new String[jarr.length()];
                for (int j = 0; j < jarr.length(); j++)
                {
                    JSONObject jobjVessels = jarr.getJSONObject(j);

                    str_imgList_imageaudioPath = jobjVessels.getString("imageaudioPath");
                    Log.e("", "" + str_imgList_imageaudioPath);


                    String str_ImageUrl = "http://xxx/xxx/xxx.svc/DownloadFile/FileName/"+str_imgList_imageaudioPath;
                    downloadUrl(str_ImageUrl);

                    Log.e("Downloaded Completed","!!!!!");

                }

            }

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

    private Bitmap downloadUrl(String strUrl) throws IOException{
        Bitmap bitmap=null;
        InputStream iStream = null;
        try{
            URL url = new URL(strUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();
            bitmap = BitmapFactory.decodeStream(iStream);
            Log.e("bitmap while  url", "downloading " + bitmap.toString());



            saveBitmap(bitmap);
        }catch(Exception e){
            Log.e("Exception while  url", "downloading " + e.toString());
        }finally{
            iStream.close();
        }

        return bitmap;
    }




void saveImage(Bitmap bmp) {
    File filename;
    try {
        String path = Environment.getExternalStorageDirectory().toString();
        Log.i("in save()", "after mkdir");
        new File(path + "jsonObj_Images").mkdirs();
        filename = new File(path + "jsonObj_Images");
        Log.i("in save()", "after file");
        FileOutputStream out = new FileOutputStream(filename);
        Log.i("in save()", "after outputstream");
        bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
        Log.e("bmp "," = "+bmp);
        out.flush();
        out.close();
        Log.i("in save()", "after outputstream closed");
        MediaStore.Images.Media.insertImage(getContentResolver(),
                filename.getAbsolutePath(), filename.getName(),
                filename.getName());
        //bt.setText("Saved...");
        Toast.makeText(getApplicationContext(),
                "File is Saved in  " + filename, Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

这是我的Logcat错误

08-04 12:28:06.424    4350-4402/? E/Downloaded Completed﹕ !!!!!
08-04 12:28:06.424    4350-4402/? E/﹕ 3_20150623145579002.png
08-04 12:28:06.704    4350-4402/? E/im connected﹕ Download
08-04 12:28:07.215    4350-4402/? I/in save()﹕ after mkdir
08-04 12:28:07.225    4350-4402/? I/in save()﹕ after file
08-04 12:28:07.254    4350-4402/? W/System.err﹕ java.io.FileNotFoundException: /mnt/sdcard/mvc/jsonObj_Images: open failed: EACCES (Permission denied)
08-04 12:28:07.284    4350-4402/? W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:416)
08-04 12:28:07.295    4350-4402/? W/System.err﹕ at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
08-04 12:28:07.314    4350-4354/? D/dalvikvm﹕ GC_CONCURRENT freed 1276K, 73% free 6523K/23608K, paused 4ms+9ms, total 84ms
08-04 12:28:07.314    4350-4402/? W/System.err﹕ at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
08-04 12:28:07.314    4350-4402/? W/System.err﹕ at com.example.tazeen.classnkk.AllPosts_Page.saveImage(AllPosts_Page.java:287)
08-04 12:28:07.314    4350-4402/? W/System.err﹕ at com.example.tazeen.classnkk.AllPosts_Page.downloadFile(AllPosts_Page.java:270)
08-04 12:28:07.324    4350-4402/? W/System.err﹕ at com.example.tazeen.classnkk.AllPosts_Page.getAllImagePath_List(AllPosts_Page.java:236)
08-04 12:28:07.324    4350-4402/? W/System.err﹕ at com.example.tazeen.classnkk.AllPosts_Page$GetImageDetails.doInBackground(AllPosts_Page.java:173)
08-04 12:28:07.324    4350-4402/? W/System.err﹕ at com.example.tazeen.classnkk.AllPosts_Page$GetImageDetails.doInBackground(AllPosts_Page.java:156)
08-04 12:28:07.324    4350-4402/? W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
08-04 12:28:07.324    4350-4402/? W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
08-04 12:28:07.324    4350-4402/? W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
08-04 12:28:07.334    4350-4402/? W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
08-04 12:28:07.334    4350-4402/? W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
08-04 12:28:07.334    4350-4402/? W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
08-04 12:28:07.334    4350-4402/? W/System.err﹕ Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
08-04 12:28:07.344    4350-4402/? W/System.err﹕ at libcore.io.Posix.open(Native Method)
08-04 12:28:07.344    4350-4402/? W/System.err﹕ at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
08-04 12:28:07.344    4350-4402/? W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:400)

提前致谢。

2 个答案:

答案 0 :(得分:0)

您不应该使用JSON下载图像,我建议您使用以下代码。你必须发送相应的网址。为了我的工作正常,您收到图像并将其保存在Bitmap类型的变量中。然后你必须将它保存到你的SD。我建议你使用一个独特的文件夹,用mkdirs函数以编程方式创建它。问候

好!!

class GetFromServer extends AsyncTask<String, Void, Bitmap>
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(FotoEmergenteControlador.this);
        pDialog.setMessage("Por Favor, Espere...");
        pDialog.setCancelable(false);
        pDialog.show();
    }
    @Override

    protected Bitmap  doInBackground(String... params) {
        String httpAdress = params[0];
        Bitmap imagenObtenida=null;
        try {
        URL ImgUrl = new URL(httpAdress);
        HttpURLConnection conn = (HttpURLConnection) ImgUrl.openConnection();
        conn.connect();
            imagenObtenida = BitmapFactory.decodeStream(conn.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imagenObtenida;
    }
    @Override
    protected void onPostExecute(Bitmap result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        pDialog.dismiss();
        contentImage.setImageBitmap(result);
    }
}

答案 1 :(得分:0)

不要忘记在AndroidManifest.xml上声明正确的权限! 在您的情况下,您需要android.permission.WRITE_EXTERNAL_STORAGE。类似的东西:

<manifest>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application>
        <!-- ... -->
    </application>
</manifest> 

然后,检查外部存储器是否已安装。

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

另外,更改这些行

String path = Environment.getExternalStorageDirectory().toString();
// ...
new File(path + "jsonObj_Images").mkdirs();
filename = new File(path + "jsonObj_Images");

String folderName = "jsonObj_Images";
String fileName = "YourFile.jpg";
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File root = new File(path + File.separator + folderName);
if (!root.mkdirs()) {
    Log.w("TAG","Folder not created!");
}

File file = new File (root,fileName);

// ...

FileOutputStream out = new FileOutputStream(file);
Log.i("in save()", "after outputstream");
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
Log.e("bmp "," = "+bmp);
out.flush();
out.close();