gpt4 book ai didi

java - 从mysql数据库解析数据时出错

转载 作者:行者123 更新时间:2023-11-30 22:26:03 24 4
gpt4 key购买 nike

我正在开发一个安卓应用程序。我试图从 mysql 数据库中获取数据,但一直出现此错误。似乎无法弄清楚出了什么问题。这是我的代码和我的日志。

日志:

02-02 17:00:40.289        89-89/system_process W/InputManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@41993f60
02-02 17:00:48.338 1039-1056/com.example.busscheduledatarecorder E/My Error: Error D
02-02 17:00:48.461 1039-1056/com.example.busscheduledatarecorder E/My Error: Error D
02-02 17:01:05.339 1039-1056/com.example.busscheduledatarecorder E/response string: [ 02-02 17:01:05.762 1039:0x420 E/JSON Parser ]
Error parsing data org.json.JSONException: End of input at character 1 of
02-02 17:01:06.228 1039-1039/com.example.busscheduledatarecorder D/AndroidRuntime: Shutting down VM
02-02 17:01:06.265 1039-1039/com.example.busscheduledatarecorder W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
02-02 17:01:06.398 1039-1039/com.example.busscheduledatarecorder E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.busscheduledatarecorder.MainActivity$Load_Routes.onPostExecute(MainActivity.java:407)
at com.example.busscheduledatarecorder.MainActivity$Load_Routes.onPostExecute(MainActivity.java:375)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
02-02 17:01:06.534 89-473/system_process W/ActivityManager: Force finishing activity com.example.busscheduledatarecorder/.MainActivity

PHP代码:

<?php
$response = array();
$response["success"] = 0;
$response["message"] = "No routes found";

// include db connect class
include('db.php');

// connecting to db
$db = new DB_CONNECT();

// get all routes from route table
$result = mysql_query("SELECT * FROM route");

// check for empty result
if ($result && mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["routes"] = array();

while ($row = mysql_fetch_array($result)) {
// temp user array
$route = array();
$route["busRouteId"] = $row["busRouteId"];
$route["routeName"] = $row["routeName"];

// push single product into final response array
array_push($response["routes"], $route);
}
// success
$response["success"] = 1;

}
// Echo JSON anyway!
echo json_encode($response);
die();
?>

Java 代码:

public class JSONParser {

String result = null;
DBHelper db;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("My Error", "Error A " + e.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("My Error", "Error B " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("My Error", "Error C " + e.toString());
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.e("My Error", "Error D ");
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.e("My Error", "Error D ");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
Log.e("response string",json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}}

主要 Activity :

public class MainActivity extends Activity {

DBHelper db;
int routeloadsuccess;

JSONArray jArray = null

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

spinroute= (Spinner)findViewById(R.id.spinnerroute);
pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
db = new DBHelper(this);
}

public void shout(String voice)
{Toast.makeText(this, voice,Toast.LENGTH_LONG).show();}



public void insertNewRoutes(int id, String routename){
//check if route exists
boolean exists = db.checkRouteforId(id), result = false;
if(exists)
{
result = db.updateRoute(id, routename);

}
else{ result = db.insertRoute(id, routename);}
if(result){routeloadsuccess = 1;}

}

private class Load_Routes extends AsyncTask<String, String, JSONObject>{

InputStream is;
String url;
private static final String TAG_ROUTE = "bus_route";

public Load_Routes()
{
is = null;
url = "http://busscheduledata.com/RouteMobile.php";
}
@Override
protected JSONObject doInBackground(String... arg0) {

JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);

return json;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
shout("Loading Routes...");
pb.setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
pb.setVisibility(View.INVISIBLE);
try {
// Getting JSON Array

int success = json.getInt("success");
if (success == 1) {
JSONArray JAStuff = json.getJSONArray("response");

/** CHECK THE NUMBER OF RECORDS **/
int intStuff = JAStuff.length();

if (intStuff != 0) {

for (int i = 0; i < JAStuff.length(); i++) {
JSONObject JOStuff = JAStuff.getJSONObject(i);
Log.e("ALL THE STUFF", JOStuff.toString());

// Storing JSON item in a Variable
int routeid = JOStuff.getInt("busRouteId");
String routename = JOStuff.getString("routeName");

//Set JSON Data in spinner
insertNewRoutes(routeid,routename );

}
}
}




} catch (JSONException e) {
e.printStackTrace();
shout("Loading failed");
}



}
}//end of loading route thingy



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
populateMenu(menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
applyMenuChoice(item);
return(applyMenuChoice(item) ||super.onOptionsItemSelected(item));
}

private void populateMenu(Menu menu) {
menu.add(0, SIXTEEN_ID, 0, "Get Routes");
}
private boolean applyMenuChoice(MenuItem item) {
Intent intent;
switch (item.getItemId())
{
case SIXTEEN_ID:
db.deleteAllRoutes();
Load_Routes lr = new Load_Routes();
lr.execute();
if(routeloadsuccess == 1){
shout("Loading Complete");
intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);}
return(true);
//break;

}
return true ;
}


}

最佳答案

Log.e("response string",json);

这一行正在打印:E/response string: n

您的回答是“n”,它是字符串。在下一行中,您将其转换为 JsonObject,这肯定会引发异常。

jObj = new JSONObject(json);

将来自服务器的响应从 String 更改为 Json

关于java - 从mysql数据库解析数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35158760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com