dsk95913
2017-03-24 21:03
浏览 111

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.

    已采纳该答案
    打赏 评论
  • dtjxhf595733 2017-03-24 21:24

    You're appending your movie_id parameter as a URL query parameter (in your Java code) but looking in the PHP $_POST array: that's not going to work.

    Either change your PHP to look in both $_POST and $_GET, or change your Java to actually do a proper POST request.

    Also, as a side note, you may want to just do the new JSONObject() call inside the doInBackground: more efficient to do the JSON parsing on the background thread and just process the parsed object in the execute.

    EDIT: you'll also probably want to set the content-type header (try conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    打赏 评论

相关推荐 更多相似问题