我正在尝试从android连接到远程数据库。我想给一个名字作为输入。我的应用应显示包含该名称的行。我按照androidhive教程来实现这一目标。我的应用程序打开,输入名称后崩溃请帮帮我。我的主要活动如下:
package com.example.androidhive;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText branchname;
EditText counters;
EditText tokensserved;
EditText tokensissued;
EditText tokenswaiting;
Button btnGet;
String branch;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://10.0.2.2/android/getdata.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_BRANCH = "branchname";
private static final String TAG_COUNTERS= "counters";
private static final String TAG_SERVED = "tokensserved";
private static final String TAG_ISSUED = "tokenissued";
private static final String TAG_WAITING="tokenswaiting";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// save button
btnGet = (Button) findViewById(R.id.btnGet);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
branch = i.getStringExtra(TAG_BRANCH);
// save button click event
// Delete button click event
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// deleting product in background thread
new GetProductDetails().execute();
}
});
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("branchname", branch));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
branchname = (EditText) findViewById(R.id.branchname);
counters = (EditText) findViewById(R.id.counters);
tokensserved = (EditText) findViewById(R.id.tokensserved);
tokensissued=(EditText) findViewById(R.id.tokensissued);
tokenswaiting=(EditText) findViewById(R.id.tokenswaiting);
// display product data in EditText
branchname.setText(product.getString(TAG_BRANCH));
counters.setText(product.getString(TAG_COUNTERS));
tokensserved.setText(product.getString(TAG_SERVED));
tokensissued.setText(product.getString(TAG_ISSUED));
tokenswaiting.setText(product.getString(TAG_WAITING));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
我的JSONParser
package com.example.androidhive;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
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 {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Name Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Branch Name"
android:textSize="17dip" />
<!-- Input Name -->
<EditText
android:id="@+id/branchname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true" />
<!-- Price Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="counters"
android:textSize="17dip" />
<!-- Input Price -->
<EditText
android:id="@+id/counters"
android:layout_width="fill_parent"
android:layout_height="21dp"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:ems="10"
android:inputType="numberDecimal"
android:singleLine="true" >
<requestFocus />
</EditText>
<!-- Description Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Served"
android:textSize="17dip" />
<!-- Input description -->
<EditText
android:id="@+id/tokensserved"
android:layout_width="fill_parent"
android:layout_height="22dp"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:gravity="top"
android:lines="4" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Issued"
android:textSize="17dip" />
<!-- Input description -->
<EditText
android:id="@+id/tokensissued"
android:layout_width="fill_parent"
android:layout_height="22dp"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:layout_weight="0.00"
android:gravity="top"
android:lines="4" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:text="Waiting"
android:textSize="17dip" />
<!-- Input description -->
<EditText
android:id="@+id/tokenswaiting"
android:layout_width="fill_parent"
android:layout_height="26dp"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:gravity="top"
android:lines="4" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<!-- Button Create Product -->
<Button
android:id="@+id/btnGet"
android:layout_width="111dp"
android:layout_height="wrap_content"
android:text="Get" />
</LinearLayout>
</LinearLayout>
这是logcat:
06-10 17:18:02.184: W/dalvikvm(1607): threadid=1: thread exiting with uncaught exception (group=0xb2a2fba8)
06-10 17:18:02.204: E/AndroidRuntime(1607): FATAL EXCEPTION: main
06-10 17:18:02.204: E/AndroidRuntime(1607): Process: com.example.androidhive, PID: 1607
06-10 17:18:02.204: E/AndroidRuntime(1607): android.os.NetworkOnMainThreadException
06-10 17:18:02.204: E/AndroidRuntime(1607): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
06-10 17:18:02.204: E/AndroidRuntime(1607): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
06-10 17:18:02.204: E/AndroidRuntime(1607): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
06-10 17:18:02.204: E/AndroidRuntime(1607): at libcore.io.IoBridge.connect(IoBridge.java:112)
06-10 17:18:02.204: E/AndroidRuntime(1607): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
06-10 17:18:02.204: E/AndroidRuntime(1607): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
06-10 17:18:02.204: E/AndroidRuntime(1607): at java.net.Socket.connect(Socket.java:843)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-10 17:18:02.204: E/AndroidRuntime(1607): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-10 17:18:02.204: E/AndroidRuntime(1607): at com.example.androidhive.JSONParser.makeHttpRequest(JSONParser.java:62)
06-10 17:18:02.204: E/AndroidRuntime(1607): at com.example.androidhive.MainActivity$GetProductDetails$1.run(MainActivity.java:120)
06-10 17:18:02.204: E/AndroidRuntime(1607): at android.os.Handler.handleCallback(Handler.java:733)
06-10 17:18:02.204: E/AndroidRuntime(1607): at android.os.Handler.dispatchMessage(Handler.java:95)
06-10 17:18:02.204: E/AndroidRuntime(1607): at android.os.Looper.loop(Looper.java:136)
06-10 17:18:02.204: E/AndroidRuntime(1607): at android.app.ActivityThread.main(ActivityThread.java:5017)
06-10 17:18:02.204: E/AndroidRuntime(1607): at java.lang.reflect.Method.invokeNative(Native Method)
06-10 17:18:02.204: E/AndroidRuntime(1607): at java.lang.reflect.Method.invoke(Method.java:515)
06-10 17:18:02.204: E/AndroidRuntime(1607): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-10 17:18:02.204: E/AndroidRuntime(1607): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-10 17:18:02.204: E/AndroidRuntime(1607): at dalvik.system.NativeStart.main(Native Method)
我的PHP:
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["branchname"])) {
$branchname = $_GET['branchname'];
// get a product from products table
$result = mysql_query("SELECT *FROM branches WHERE branchname = $branchname");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["branchname"] = $result["branchname"];
$product["counters"] = $result["counters"];
$product["tokensserved"] = $result["tokensserved"];
$product["tokenissuedd"] = $result["tokensissued"];
$product["tokenswaiting"] = $result["tokenswaiting"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $branch);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
我将非常感谢任何能帮助我的人。我在这上面度过了许多不眠之夜。谢谢。我正在使用WAMP服务器和phpmyadmin。我的数据库包含5个字段,分支机构,计数器,服务,发布,等待。
答案 0 :(得分:1)
这一行:
runOnUiThread(new Runnable() {
您甚至没有在后台线程上运行httprequest,而是在主UI线程上运行它。正如@andreasrs所提到的,Android中不允许这样做。所有httprequests必须在另一个线程中完成。
答案 1 :(得分:0)
应用程序崩溃与您的PHP代码无关。
问题是Android / Java应用程序。 您正尝试在绘制用户界面的相同线程上访问网络。这是不好的做法,就像你在堆栈跟踪中看到的那样抛出异常。
要修复它,您可以在AsyncTask中执行网络请求。一旦你在一个单独的线程中进行网络连接,应用程序就不会以相同的方式崩溃。
参考:http://developer.android.com/reference/android/os/AsyncTask.html