开发者社区> 问答> 正文

Android Studio-从URL致命异常中提取JSON

因此,在使该代码正常工作时遇到了一些问题,我在网上找到了一些代码,但无法正常工作。我曾尝试调整一些代码,但是无论我在做什么,该应用程序都会因错误而崩溃。经过数小时的谷歌搜索和观看YouTube教程,我一直在努力使其工作几天,但似乎无法正常工作。

有人可以阐明我在这里做错了什么吗?

码:

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

    @Override
    protected String doInBackground(Void... params) {

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        URL url;
        try {
            url = new URL("www.link.to.json");
            urlConnection.setRequestMethod("GET"); //Your method here
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

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

            if (buffer.length() == 0)
                return null;

            return buffer.toString();
        } catch (IOException e) {
            Log.e(TAG, "IO Exception", e);
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(TAG, "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(String response) {
        if(response != null) {
            JSONObject json = null;
            try {
                json = new JSONObject(response);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject jsonResponse = null;
            try {
                jsonResponse = json.getJSONObject("Question1");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MainActivity.jsonPrint.setText((CharSequence) jsonResponse);
        }
    }
}

错误:


E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: uk.co.jrtevents.fetchjsonfromurltest, PID: 4019
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:318)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.lang.NullPointerException: Attempt to invoke a virtual method on a null object reference
        at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:31)
        at uk.co.jrtevents.fetchjsonfromurltest.fetchJSON.doInBackground(fetchJSON.java:18)
        at android.os.AsyncTask$2.call(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)

第31行: urlConnection.setRequestMethod("GET");

展开
收起
Puppet 2020-01-13 10:21:22 689 0
1 条回答
写回答
取消 提交回答
  • 为了显示点心栏,您必须引用您的应用程序已构建的特定支架实例,并告诉它显示点心栏。如果上下文方便,您可以说Scaffold.of(context).showSnackbar(快餐栏); 由于您无权访问上下文,因此引用支架的另一种方法是为支架定义一个键,然后确保将该键分配给Webviewer的支架。

    你可以说

    
    class MessageHandler extends StatefulWidget {
        // pass a reference to the scaffold key to the message handler when it is created
        final GlobalKey<ScaffoldState> scaffoldKey;
        MessageHandler({this.scaffoldKey});
    
        @override
        _MessageHandlerState createState() => _MessageHandlerState();
        }
    class _MessageHandlerState extends State<MessageHandler>{
        final FirebaseMessaging _fcm = FirebaseMessaging();
        @override
    void initState(){
        super.initState();
        _fcm.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("here");
        print("onMessage: $message");
        final snackbar = SnackBar(
          content: Text(message['notification']['title']),
        );
    
        // reference the scaffold with its key and call showSnackBar
        widget.scaffoldKey.currentState.showSnackbar(snackbar);
      },
     );
    

    然后在可以传递给消息处理程序和支架的地方定义支架的密钥:

    final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
    ....
    
    Scaffold(
       key: scaffoldKey,
    ...
    

    更多信息:

    在Flutter中显示SnackBar

    2020-01-18 10:41:09
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载