我尝试按照以下教程将Android连接到PHP,MySQL:
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
然而,在本教程的下载源中直接运行应用程序并单击任一按钮时,我自己和大多数遵循本教程的用户都会收到强制关闭错误。
(看看评论部分 - 几乎每个人都遇到本教程的问题)
03-17 14:40:10.064: D/dalvikvm(2936): GC_CONCURRENT freed 177K, 5% free 7488K/7812K, paused 2ms+11ms, total 33ms
03-17 14:40:16.294: D/dalvikvm(2936): GC_CONCURRENT freed 80K, 4% free 7856K/8140K, paused 3ms+2ms, total 26ms
03-17 14:40:16.784: E/JSON Parser(2936): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
03-17 14:40:16.794: W/dalvikvm(2936): threadid=15: thread exiting with uncaught exception (group=0x41d42930)
03-17 14:40:16.794: E/AndroidRuntime(2936): FATAL EXCEPTION: AsyncTask #5
03-17 14:40:16.794: E/AndroidRuntime(2936): java.lang.RuntimeException: An error occured while executing doInBackground()
03-17 14:40:16.794: E/AndroidRuntime(2936): at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.lang.Thread.run(Thread.java:856)
03-17 14:40:16.794: E/AndroidRuntime(2936): Caused by: java.lang.NullPointerException
03-17 14:40:16.794: E/AndroidRuntime(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98)
03-17 14:40:16.794: E/AndroidRuntime(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:1)
03-17 14:40:16.794: E/AndroidRuntime(2936): at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-17 14:40:16.794: E/AndroidRuntime(2936): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
03-17 14:40:16.794: E/AndroidRuntime(2936): ... 3 more
03-17 14:40:17.284: E/WindowManager(2936): Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42488ea0 V.E..... R.....ID 0,0-296,153} that was originally added here
03-17 14:40:17.284: E/WindowManager(2936): android.view.WindowLeaked: Activity com.example.androidhive.NewProductActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42488ea0 V.E..... R.....ID 0,0-296,153} that was originally added here
03-17 14:40:17.284: E/WindowManager(2936): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-17 14:40:17.284: E/WindowManager(2936): at android.app.Dialog.show(Dialog.java:281)
03-17 14:40:17.284: E/WindowManager(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.onPreExecute(NewProductActivity.java:75)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.AsyncTask.execute(AsyncTask.java:534)
03-17 14:40:17.284: E/WindowManager(2936): at com.example.androidhive.NewProductActivity$1.onClick(NewProductActivity.java:55)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.View.performClick(View.java:4204)
03-17 14:40:17.284: E/WindowManager(2936): at android.view.View$PerformClick.run(View.java:17355)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Handler.handleCallback(Handler.java:725)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 14:40:17.284: E/WindowManager(2936): at android.os.Looper.loop(Looper.java:137)
03-17 14:40:17.284: E/WindowManager(2936): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-17 14:40:17.284: E/WindowManager(2936): at java.lang.reflect.Method.invokeNative(Native Method)
03-17 14:40:17.284: E/WindowManager(2936): at java.lang.reflect.Method.invoke(Method.java:511)
03-17 14:40:17.284: E/WindowManager(2936): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-17 14:40:17.284: E/WindowManager(2936): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-17 14:40:17.284: E/WindowManager(2936): at dalvik.system.NativeStart.main(Native Method)
JAVA: NewProductActivity.java
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.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 NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://linkingmanager.zxq.net/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
}
XML: add_product.xml
<?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:text="Product Name"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input Name -->
<EditText android:id="@+id/inputName"
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:text="Price"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input Price -->
<EditText android:id="@+id/inputPrice"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:singleLine="true"
android:inputType="numberDecimal"/>
<!-- Description Label -->
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Description"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="10dip"
android:textSize="17dip"/>
<!-- Input description -->
<EditText android:id="@+id/inputDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:layout_marginBottom="15dip"
android:lines="4"
android:gravity="top"/>
<!-- Button Create Product -->
<Button android:id="@+id/btnCreateProduct"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Create Product"/>
</LinearLayout>
JAVA: AllProductsActivity.java
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://linkingmanager.zxq.net/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
XML: all_products.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Main ListView
Always give id value as list(@android:id/list)
-->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
答案 0 :(得分:0)
Caused by: java.lang.NullPointerException
03-17 14:40:16.794: E/AndroidRuntime(2936): at com.example.androidhive.NewProductActivity$CreateNewProduct.doInBackground(NewProductActivity.java:98)
如果我没错,就是这条线
Log.d("Create Response", json.toString());
所以这意味着由于某种原因你在这里得到空白
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
也许您的网址不正确。