Android 无法将java.lang.String转换为JSON对象

Android 无法将java.lang.String转换为JSON对象,android,cordova,Android,Cordova,我的Downloader.java文件是 package com.phonegap.plugins.downloader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; impo

我的Downloader.java文件是

package com.phonegap.plugins.downloader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

public class Downloader extends Plugin {

    @Override
    public PluginResult execute(String action, JSONArray args, String callbackId) {

        if (!action.equals("downloadFile")) 
            return new PluginResult(PluginResult.Status.INVALID_ACTION);

        try {

            String fileUrl = args.getString(0);
            JSONObject params = args.getJSONObject(1);

            String fileName = params.has("fileName") ? 
                    params.getString("fileName"):
                    fileUrl.substring(fileUrl.lastIndexOf("/")+1);

            String dirName = params.has("dirName") ?
                    params.getString("dirName"):
                    "sdcard/download";

            Boolean overwrite = params.has("overwrite") ? params.getBoolean("overwrite") : false;

            return this.downloadUrl(fileUrl, dirName, fileName, overwrite, callbackId);

        } catch (JSONException e) {

            e.printStackTrace();
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());

        } catch (InterruptedException e) {
            e.printStackTrace();
            return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        }

    }

    private PluginResult downloadUrl(String fileUrl, String dirName, String fileName, Boolean overwrite, String callbackId) throws InterruptedException, JSONException {

        try {

            Log.d("PhoneGapLog", "Downloading "+fileUrl + " into " + dirName + "/" + fileName);

            File dir = new File(dirName);
            if (!dir.exists()) {
                Log.d("PhoneGapLog", "directory " + dirName + " created");
                dir.mkdirs();
            }

            File file = new File(dirName, fileName);

            if (!overwrite && file.exists()) {
                Log.d("DownloaderPlugin", "File already exist");

                JSONObject obj = new JSONObject();
                obj.put("status", 1);
                obj.put("total", 0);
                obj.put("file", fileName);
                obj.put("progress", 100);

                return new PluginResult(PluginResult.Status.OK, obj);
            }

            URL url = new URL(fileUrl);
            HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
            ucon.setRequestMethod("GET");
            ucon.setDoOutput(true);
            ucon.connect();

            Log.d("PhoneGapLog", "Download start");

            InputStream is = ucon.getInputStream();
            byte[] buffer = new byte[1024];
            int readed = 0, 
                progress = 0,
                totalReaded = 0,
                fileSize = ucon.getContentLength();

            FileOutputStream fos = new FileOutputStream(file);

            while ((readed = is.read(buffer)) > 0) {

                fos.write(buffer, 0, readed);
                totalReaded += readed;

                int newProgress = (int) (totalReaded*100/fileSize);             
                if (newProgress != progress)
                 progress = informProgress(fileSize, newProgress, fileName, callbackId);

            }

            fos.close();

            Log.d("PhoneGapLog", "Download finished");

            JSONObject obj = new JSONObject();
            obj.put("status", 1);
            obj.put("total", fileSize);
            obj.put("file", fileName);
            obj.put("progress", progress);

            return new PluginResult(PluginResult.Status.OK, obj);

        }
        catch (FileNotFoundException e) {
            Log.d("PhoneGapLog", "File Not Found: " + e);
            return new PluginResult(PluginResult.Status.ERROR, 404);
        }
        catch (IOException e) {
            Log.d("PhoneGapLog", "Error: " + e);
            return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
        }

    }

    private int informProgress(int fileSize, int progress, String fileName, String callbackId) throws InterruptedException, JSONException {

        JSONObject obj = new JSONObject();
        obj.put("status", 0);
        obj.put("total", fileSize);
        obj.put("file", fileName);
        obj.put("progress", progress);

        PluginResult res = new PluginResult(PluginResult.Status.OK, obj);
        res.setKeepCallback(true);
        success(res, callbackId);

        //Give a chance for the progress to be sent to javascript
        Thread.sleep(100);

        return progress; 
    }

}
我的downloader.js文件是

function Downloader() {}

Downloader.prototype.downloadFile = function(fileUrl,dirName,fileName,overwrite,win,fail) {

    //Make params hash optional.
    if (!fail) win = params;
    PhoneGap.exec(win, fail, "Downloader", "downloadFile", [fileUrl, dirName,fileName,overwrite]);
};

PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin("downloader", new Downloader());
    PluginManager.addService("Downloader", "com.phonegap.plugins.downloader.Downloader");
});
function downloadfile() {
     window.plugins.downloader.downloadFile("c:/Users/460725/Desktop/NIACustomerPhase.pdf","sdcard/cache/","NIACustomerPhase.pdf", false,
             function(data){
             if(data=="exist"){
             alert("File already exist");
             }
             else{
             alert("File saved on sd card")
             }
             },function(data){ alert("error: "+data); });

}
main.js文件是

function Downloader() {}

Downloader.prototype.downloadFile = function(fileUrl,dirName,fileName,overwrite,win,fail) {

    //Make params hash optional.
    if (!fail) win = params;
    PhoneGap.exec(win, fail, "Downloader", "downloadFile", [fileUrl, dirName,fileName,overwrite]);
};

PhoneGap.addConstructor(function() {
    PhoneGap.addPlugin("downloader", new Downloader());
    PluginManager.addService("Downloader", "com.phonegap.plugins.downloader.Downloader");
});
function downloadfile() {
     window.plugins.downloader.downloadFile("c:/Users/460725/Desktop/NIACustomerPhase.pdf","sdcard/cache/","NIACustomerPhase.pdf", false,
             function(data){
             if(data=="exist"){
             alert("File already exist");
             }
             else{
             alert("File saved on sd card")
             }
             },function(data){ alert("error: "+data); });

}
我已经将其集成到android phonegap项目中。但是当我运行该项目时,我得到了Ale rt错误:值sdcard/cache/at 1的类型java.lang.String无法转换为JSON对象a有人能告诉我问题出在哪里吗..提前谢谢


我用以前的代码替换了相同的代码,还更改了url

function downloadfile () {

    window.plugins.downloader.downloadFile("http://www.toforge.com/archive.zip","sdcard/cache/","archive.zip", false,
             function(data){
             if(data=="exist"){
             alert("File already exist");
             }
             else{
             alert("File saved on sd card");
             }
             },function(data){ alert("error: "+data); });

}
现在,当我点击下载文件链接无法解析主机时,我收到一个错误警报
“www.toforge.com”:没有与主机名关联的地址
有人能帮我解决此错误吗??提前感谢..

您正在从Javascript传递一个字符串数组,但随后尝试将其中一个值转换为JSON,这是不可能的

将当前功能替换为以下功能将起作用:

Downloader.prototype.downloadFile = function(fileUrl,dirName,fileName,overwrite,win,fail) 
{
    //Make params hash optional.
    if (!fail) win = params;
    PhoneGap.exec(win, fail, "Downloader", "downloadFile", [fileUrl, {dirName: dirName,  fileName: fileName, overwrite: overwrite} ]);
};
虽然您的代码仍然无法正常工作,因为
c:/Users/460725/Desktop/niacusterphase.pdf
不是有效的URL,但它是windows的文件系统路径


尝试捕获您正试图转换为JSONObject的字符串,并使用
Log.v(string,string)
检查其json是否有效以调试问题。。。也就是说,在代码中添加日志,并检查以确保在流程的每个步骤都将正确的输出写入logcat。