dsk95913 2017-03-24 21:03
浏览 113
已采纳

JSONException故障排除:字符0 Android输入结束

Im having trouble with the error JSONException. my doInBackground() pass the param of the movieId which is 1 (already logged) to the php file and then the PHP file will do a query and return json. Running in the browser works for JSON response.

import android.app.ProgressDialog;
import android.net.ParseException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class FirstFragment extends Fragment {

    ImageView imageView;
    TextView name, id;
    public FirstFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View rootView =  inflater.inflate(R.layout.fragment_first, container, false);

        imageView = (ImageView) rootView.findViewById(R.id.movie_image);
        name = (TextView) rootView.findViewById(R.id.movie_name);
        id = (TextView) rootView.findViewById(R.id.movie_id);
        Bundle mBundle = new Bundle();
        mBundle = getArguments();
        name.setText(mBundle.getString("textMovieName"));
        id.setText(mBundle.getString("textMovieId"));


        Glide.with(getContext()).load(mBundle.getString("ivMovie"))
                .placeholder(R.drawable.placeholder)
                .error(R.drawable.ic_menu_camera)
                .into(imageView);

        new AsyncDate().execute(mBundle.getString("textMovieId"));
        return rootView;
    }

    private class AsyncDate extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(getActivity());
        HttpURLConnection conn;
        URL url = null;

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

        @Override
        protected String doInBackground(String... params) {
            try {
                url = new URL("http://100.74.245.14/finalproject/date_time.php");

            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "exception";
            }
            //Log.d("params", params[0]);
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);

                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("movieId", params[0]);
                String query = builder.build().getEncodedQuery();

                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();
            } catch (IOException e1) {
                e1.printStackTrace();
                return "exception";
            }

            try {
                int response_code = conn.getResponseCode();

                if (response_code == HttpURLConnection.HTTP_OK) {
                    //Log.d("response","ok");
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    Log.d("return", result.toString());
                    return (result.toString());
                } else {
                    return "unsuccessful";
                }
            } catch (IOException e2) {
                e2.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }
        }

        @Override
        protected void onPostExecute(String result) {

            List<listMovie> data = new ArrayList<>();

            try {
                JSONObject jsonObj = new JSONObject(result);
                JSONArray jArray = jsonObj.getJSONArray("test");
                //Log.d("json", result);
                for (int i = 0; i < jArray.length(); i++) {
                    //Log.d("json", "test");
                    JSONObject json_data = jArray.getJSONObject(i);
                    listMovie movieData = new listMovie();
                    movieData.movieDate = json_data.getString("date");
                    movieData.movieTime = json_data.getString("time");
                    data.add(movieData);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }
}

PHP File

<?php

include 'config.inc.php';

if(isset($_POST['movieId'])) {
    $movieId= $_POST['movieId'];


    $sql = 'SELECT * FROM movie_time WHERE movie_id = :movie_id';
    $stmt = $conn -> prepare($sql);
    $stmt -> bindParam(':movie_id', $movieId, PDO::PARAM_STR);

    $result = $stmt -> execute();

    if($result) {
        while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
            $flag['test'] = $row;
        }

    header('Content-type: application/json');

    echo json_encode($flag);
    }
}


?>

The error I got

W/System.err: org.json.JSONException: End of input at character 0 of 
W/System.err:     at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:155)
W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:172)
W/System.err:     at com.example..fyp.FirstFragment$AsyncDate$override.onPostExecute(FirstFragment.java:153)
W/System.err:     at com.example.fyp.FirstFragment$AsyncDate$override.access$dispatch(FirstFragment.java)
W/System.err:     at com.example.fyp.FirstFragment$AsyncDate.onPostExecute(FirstFragment.java:0)
W/System.err:     at com.example.fyp.FirstFragment$AsyncDate.onPostExecute(FirstFragment.java:75)
W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err:     at android.os.Looper.loop(Looper.java:136)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5017)
W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
W/System.err:     at dalvik.system.NativeStart.main(Native Method)

At this line

JSONObject jsonObj = new JSONObject(result);
  • 写回答

2条回答 默认 最新

  • douzhong8856 2017-03-24 21:17
    关注

    Hard to be sure about this, but I would place my bet in that you have some white spaces or line breaks before/after open/closing php tags.

    Check that php open tag (<?php) is the first character in your php file, and remove closing php tag.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!