您使用本教程连接到Web或本地的mySQL数据库。 here 虽然所有服务器端的php文件都是正确的并且可以在浏览器上运行,但是在Android端,应用程序在这一行崩溃了:
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
有了这条消息:不幸的是app已经停止了!
我在教程页面评论中发现我应该更改apache服务器上的一些设置。 这是我的代码:
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://127.0.0.1/android/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);
StrictMode.enableDefaults();
// 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();
Log.i("LOG", "load data preexecute");
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) {
Log.i("LOG", "load data inback ");
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
Log.i("LOG", "load data inback json 1 ");
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
Log.i("LOG", "load data inback json 2 "+json.toString());
// Check your log cat for JSON reponse
try {
Log.i("LOG", "load data inback json json 3");
// 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);
Log.i("LOG", "load data inback json json 4");
}
} else {
Log.i("LOG", "load data inback json json 5");
// 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);
}
Log.i("All Products: ","success:"+ success+"");
} catch (JSONException e) {
e.printStackTrace();
Log.i("LOG", "load data inback json on catch");
}
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);
}
});
}
}
}
这是log cat:
01-11 13:49:19.163: E/Trace(2045): error opening trace file: No such file or directory (2)
01-11 13:49:19.642: D/gralloc_goldfish(2045): Emulator without GPU emulation detected.
01-11 13:49:26.103: I/LOG(2045): load data preexecute
01-11 13:49:26.583: D/dalvikvm(2045): GC_FOR_ALLOC freed 78K, 3% free 8222K/8391K, paused 155ms, total 170ms
01-11 13:49:26.793: I/LOG(2045): load data inback
01-11 13:49:26.793: I/LOG(2045): load data inback json 1
01-11 13:49:27.022: I/Choreographer(2045): Skipped 38 frames! The application may be doing too much work on its main thread.
01-11 13:49:27.923: W/System.err(2045): org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-11 13:49:27.933: W/System.err(2045): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-11 13:49:27.933: W/System.err(2045): at com.mjs.test.phptest92.core.JSONParser.makeHttpRequest(JSONParser.java:61)
01-11 13:49:27.943: W/System.err(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:138)
01-11 13:49:27.943: W/System.err(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
01-11 13:49:27.943: W/System.err(2045): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-11 13:49:27.943: W/System.err(2045): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-11 13:49:27.943: W/System.err(2045): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-11 13:49:27.943: W/System.err(2045): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-11 13:49:27.953: W/System.err(2045): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-11 13:49:27.953: W/System.err(2045): at java.lang.Thread.run(Thread.java:856)
01-11 13:49:27.953: W/System.err(2045): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
01-11 13:49:28.023: W/System.err(2045): at libcore.io.IoBridge.connect(IoBridge.java:114)
01-11 13:49:28.023: W/System.err(2045): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-11 13:49:28.033: W/System.err(2045): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-11 13:49:28.033: W/System.err(2045): at java.net.Socket.connect(Socket.java:842)
01-11 13:49:28.033: W/System.err(2045): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-11 13:49:28.033: W/System.err(2045): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-11 13:49:28.033: W/System.err(2045): ... 15 more
01-11 13:49:28.033: W/System.err(2045): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
01-11 13:49:28.043: W/System.err(2045): at libcore.io.Posix.connect(Native Method)
01-11 13:49:28.053: W/System.err(2045): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
01-11 13:49:28.053: W/System.err(2045): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-11 13:49:28.053: W/System.err(2045): at libcore.io.IoBridge.connect(IoBridge.java:112)
01-11 13:49:28.053: W/System.err(2045): ... 20 more
01-11 13:49:28.053: E/Buffer Error(2045): Error converting result java.lang.NullPointerException
01-11 13:49:28.093: E/JSON Parser(2045): Error parsing data org.json.JSONException: End of input at character 0 of
01-11 13:49:28.123: W/dalvikvm(2045): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
01-11 13:49:28.143: E/AndroidRuntime(2045): FATAL EXCEPTION: AsyncTask #1
01-11 13:49:28.143: E/AndroidRuntime(2045): java.lang.RuntimeException: An error occured while executing doInBackground()
01-11 13:49:28.143: E/AndroidRuntime(2045): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.lang.Thread.run(Thread.java:856)
01-11 13:49:28.143: E/AndroidRuntime(2045): Caused by: java.lang.NullPointerException
01-11 13:49:28.143: E/AndroidRuntime(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:141)
01-11 13:49:28.143: E/AndroidRuntime(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
01-11 13:49:28.143: E/AndroidRuntime(2045): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-11 13:49:28.143: E/AndroidRuntime(2045): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-11 13:49:28.143: E/AndroidRuntime(2045): ... 4 more
01-11 13:49:28.843: I/Choreographer(2045): Skipped 76 frames! The application may be doing too much work on its main thread.
01-11 13:49:29.163: I/Choreographer(2045): Skipped 89 frames! The application may be doing too much work on its main thread.
01-11 13:49:29.713: E/WindowManager(2045): Activity com.mjs.test.phptest92.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41223f00 that was originally added here
01-11 13:49:29.713: E/WindowManager(2045): android.view.WindowLeaked: Activity com.mjs.test.phptest92.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41223f00 that was originally added here
01-11 13:49:29.713: E/WindowManager(2045): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
01-11 13:49:29.713: E/WindowManager(2045): at android.view.Window$LocalWindowManager.addView(Window.java:547)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.Dialog.show(Dialog.java:277)
01-11 13:49:29.713: E/WindowManager(2045): at com.mjs.test.phptest92.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:124)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.AsyncTask.execute(AsyncTask.java:534)
01-11 13:49:29.713: E/WindowManager(2045): at com.mjs.test.phptest92.AllProductsActivity.onCreate(AllProductsActivity.java:62)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.Activity.performCreate(Activity.java:5008)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.Handler.dispatchMessage(Handler.java:99)
01-11 13:49:29.713: E/WindowManager(2045): at android.os.Looper.loop(Looper.java:137)
01-11 13:49:29.713: E/WindowManager(2045): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-11 13:49:29.713: E/WindowManager(2045): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 13:49:29.713: E/WindowManager(2045): at java.lang.reflect.Method.invoke(Method.java:511)
01-11 13:49:29.713: E/WindowManager(2045): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-11 13:49:29.713: E/WindowManager(2045): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-11 13:49:29.713: E/WindowManager(2045): at dalvik.system.NativeStart.main(Native Method)
01-11 13:49:29.713: I/Choreographer(2045): Skipped 32 frames! The application may be doing too much work on its main thread.
我怎么能解决这个问题?
答案 0 :(得分:2)
如果您从设备中引用localhost
而不是使用http://10.0.2.2:8080/
而不是http://127.0.0.1/
或http://localhost/
。
因为您的Android模拟器在Virtual Machine(QEMU)
上运行,而您无法连接到直接在PC上运行的服务器。
如果您从物理Android设备运行您的应用程序,请从您的PC使用您的网络IP。
例如http://198.10.12.21:80/
....