我遇到了错误JSONException的问题。我的doInBackground()将movieId的param(已经记录)传递给php文件,然后PHP文件将执行查询并返回json。在浏览器中运行适用于JSON响应。
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文件
<?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);
}
}
?>
我得到的错误
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)
在这一行
JSONObject jsonObj = new JSONObject(result);
答案 0 :(得分:0)
很难确定这一点,但我会打赌你在打开/关闭php标签之前/之后有一些空格或换行符。
检查php open标签(&lt;?php)是否是php文件中的第一个字符,并删除关闭的php标记。
答案 1 :(得分:0)
您将movie_id参数附加为URL查询参数(在Java代码中),但查看PHP $_POST
数组:这不起作用。
更改PHP以查看$_POST
和$_GET
,或者将Java更改为实际执行正确的POST请求。
另外,作为旁注,您可能只想在new JSONObject()
内进行doInBackground
调用:在后台线程上执行JSON解析更有效率,并且只需处理解析后的对象执行。
编辑:你也可能想要设置内容类型标题(试试conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");