我的应用程序采用产品的条形码ID,并以具有该产品的价格回馈市场。 在listview中我有市场和价格。 当我点击listview元素时,我想继续进行新的活动,其中市场细节应打印到textview或其他东西.. 但是,当我点击元素时,模拟器崩溃如“不幸停止”
这里是我的java代码,php代码和日志; (我从之前的活动中获取了条形码并将市场名称发送到下一个活动以进行必要的json,php,db查询)
public class Query_product extends ListActivity {
JSONArray products = null;
JSONParser jParser = new JSONParser();
String pid;
String market;
// Progress Dialog
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> productsList;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// url to get all products list
private static final String url_market = "http://furkan.feramor.gen.tr/webservice/enucuz.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "barcode";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_MARKET = "mname";
// products JSONArray
JSONArray product = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
productsList = new ArrayList<HashMap<String, String>>();
pid = getIntent().getExtras().getString(Constants.ID);
new GetProductDetails().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
// String mName = ((TextView) view.findViewById(R.id.marketName)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext() , Market_details.class);
in.putExtra("market", market);
Log.d("aaaaaa",market);
// starting new activity
startActivity(in);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Query_product.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) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair(TAG_PID, pid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_market, "GET", params1);
// 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
market = c.getString(TAG_MARKET);
String price = c.getString(TAG_PRICE);
//////// 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_MARKET, market);
map.put(TAG_PRICE, price);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
menu.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(Query_product.this, productsList,
R.layout.list_item, new String[] { TAG_MARKET, TAG_PRICE }, new int[] {R.id.marketName, R.id.price });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
PHP:
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if (isset($_GET["barcode"])) {
$barcode = $_GET['barcode'];
$result = mysql_query("SELECT *, markets.mname
FROM products
INNER JOIN markets ON products.marketid = markets.marketid
WHERE barcode = '$barcode'
ORDER BY price") or die (mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["barcode"] = $row["barcode"];
$product["name"] = $row["name"];
$product["description"] = $row["description"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
$product["mname"]= $row["mname"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products 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);
}
?>
市场细节java类:
public class Market_details extends Activity {
TextView txtMarketName, txtMarketLoc;
JSONArray markets = null;
String marketName;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_market_details = "http://furkan.feramor.gen.tr/webservice/marketinfo.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_MARKET = "mname";
private static final String TAG_MARKETLOC = "mloc";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.market_detail);
// getting market name from intent
marketName = getIntent().getExtras().getString("market");
Log.d("bbbbbbb",marketName);
// Getting market details in background thread
new GetMarketDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetMarketDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
Log.d("CCC","A");
super.onPreExecute();
pDialog = new ProgressDialog(Market_details.this);
pDialog.setMessage("Loading market details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
Log.d("DDD","");
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
Log.d("EEE","");
// 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("mname", marketName));
Log.d("FFF","");
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_market_details, "GET", params);
Log.d("GGG","");
// check your log for json response
Log.d("Single Market Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
Log.d("HHHH","");
markets = json.getJSONArray(TAG_PRODUCTS);
for (int i = 0; i < markets.length(); i++) {
JSONObject c = markets.getJSONObject(i);
String marketname = c.getString(TAG_MARKET);
String marketloc = c.getString(TAG_MARKETLOC);
Log.d("ccccccc",marketname);
txtMarketName = (TextView) findViewById(R.id.marketname);
txtMarketLoc = (TextView) findViewById(R.id.marketloc);
txtMarketName.setText(marketname);
txtMarketLoc.setText(marketloc);
Log.d("KKKK","");
}
}else{
}
} 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();
}
}
}
这里是merketinfo.php:
<?php
/*
* Following code will get single market details
* A market is identified by market 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($_POST["mname"])) {
$mname= $_POST['mname'];
// get a market from markets table
$result = mysql_query("SELECT * FROM markets WHERE mname = '$mname");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$market = array();
$market["marketid"] = $result["marketid"];
$market["mname"] = $result["mname"];
$market["mtelno"] = $result["mtelno"];
$market["mloc"] = $result["mloc"];
// success
$response["success"] = 1;
// user node
$response["market"] = array();
array_push($response["markets"], $market);
// echoing JSON response
echo json_encode($response);
} else {
// no market found
$response["success"] = 0;
$response["message"] = "No market found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no market found
$response["success"] = 0;
$response["message"] = "No market 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);
}
?>
这是我的日志:
12-24 17:17:15.783: D/libEGL(832): loaded /system/lib/egl/libEGL_emulation.so
12-24 17:17:15.793: D/(832): HostConnection::get() New Host Connection established 0x2a1dce88, tid 832
12-24 17:17:15.853: D/libEGL(832): loaded /system/lib/egl/libGLESv1_CM_emulation.so
12-24 17:17:15.873: D/libEGL(832): loaded /system/lib/egl/libGLESv2_emulation.so
12-24 17:17:15.973: W/EGL_emulation(832): eglSurfaceAttrib not implemented
12-24 17:17:15.993: D/OpenGLRenderer(832): Enabling debug mode 0
12-24 17:32:12.384: W/EGL_emulation(832): eglSurfaceAttrib not implemented
12-24 17:32:39.856: W/EGL_emulation(832): eglSurfaceAttrib not implemented
12-24 17:32:40.604: D/dalvikvm(832): GC_FOR_ALLOC freed 74K, 8% free 2946K/3176K, paused 293ms, total 394ms
12-24 17:32:46.194: D/dalvikvm(832): GC_FOR_ALLOC freed 37K, 6% free 3107K/3304K, paused 71ms, total 97ms
12-24 17:32:46.223: I/dalvikvm-heap(832): Grow heap (frag case) to 4.260MB for 1127536-byte allocation
12-24 17:32:46.393: D/dalvikvm(832): GC_FOR_ALLOC freed 1K, 5% free 4206K/4408K, paused 162ms, total 162ms
12-24 17:32:47.024: W/EGL_emulation(832): eglSurfaceAttrib not implemented
12-24 17:32:47.376: W/EGL_emulation(832): eglSurfaceAttrib not implemented
12-24 17:32:47.603: I/Choreographer(832): Skipped 44 frames! The application may be doing too much work on its main thread.
12-24 17:32:48.414: I/Choreographer(832): Skipped 41 frames! The application may be doing too much work on its main thread.
12-24 17:32:53.764: D/All Products:(832): {"success":1,"products":[{"mname":"KAS","created_at":"2013-12-24 14:17:13","barcode":"12345","updated_at":"0000-00-00 00:00:00","price":"2.00","description":"iyi","name":"mete"}]}
12-24 17:32:58.234: D/aaaaaa(832): KAS
12-24 17:32:59.014: D/bbbbbbb(832): KAS
12-24 17:32:59.024: D/CCC(832): A
12-24 17:32:59.683: W/EGL_emulation(832): eglSurfaceAttrib not implemented
12-24 17:33:00.404: W/EGL_emulation(832): eglSurfaceAttrib not implemented
12-24 17:33:00.923: D/AndroidRuntime(832): Shutting down VM
12-24 17:33:00.923: W/dalvikvm(832): threadid=1: thread exiting with uncaught exception (group=0x41465700)
12-24 17:33:01.586: E/AndroidRuntime(832): FATAL EXCEPTION: main
12-24 17:33:01.586: E/AndroidRuntime(832): android.os.NetworkOnMainThreadException
12-24 17:33:01.586: E/AndroidRuntime(832): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
12-24 17:33:01.586: E/AndroidRuntime(832): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
12-24 17:33:01.586: E/AndroidRuntime(832): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
12-24 17:33:01.586: E/AndroidRuntime(832): at java.net.InetAddress.getAllByName(InetAddress.java:214)
12-24 17:33:01.586: E/AndroidRuntime(832): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
12-24 17:33:01.586: E/AndroidRuntime(832): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-24 17:33:01.586: E/AndroidRuntime(832): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-24 17:33:01.586: E/AndroidRuntime(832): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-24 17:33:01.586: E/AndroidRuntime(832): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-24 17:33:01.586: E/AndroidRuntime(832): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-24 17:33:01.586: E/AndroidRuntime(832): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-24 17:33:01.586: E/AndroidRuntime(832): at com.example.ssa.JSONParser.makeHttpRequest(JSONParser.java:62)
12-24 17:33:01.586: E/AndroidRuntime(832): at com.example.ssa.Market_details$GetMarketDetails$1.run(Market_details.java:102)
12-24 17:33:01.586: E/AndroidRuntime(832): at android.os.Handler.handleCallback(Handler.java:730)
12-24 17:33:01.586: E/AndroidRuntime(832): at android.os.Handler.dispatchMessage(Handler.java:92)
12-24 17:33:01.586: E/AndroidRuntime(832): at android.os.Looper.loop(Looper.java:137)
12-24 17:33:01.586: E/AndroidRuntime(832): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-24 17:33:01.586: E/AndroidRuntime(832): at java.lang.reflect.Method.invokeNative(Native Method)
12-24 17:33:01.586: E/AndroidRuntime(832): at java.lang.reflect.Method.invoke(Method.java:525)
12-24 17:33:01.586: E/AndroidRuntime(832): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-24 17:33:01.586: E/AndroidRuntime(832): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-24 17:33:01.586: E/AndroidRuntime(832): at dalvik.system.NativeStart.main(Native Method)
12-24 17:33:01.924: D/dalvikvm(832): GC_FOR_ALLOC freed 174K, 7% free 4602K/4932K, paused 277ms, total 296ms
12-24 17:33:09.916: D/libEGL(871): loaded /system/lib/egl/libEGL_emulation.so
12-24 17:33:10.089: D/(871): HostConnection::get() New Host Connection established 0x2a1e0260, tid 871
12-24 17:33:10.164: D/libEGL(871): loaded /system/lib/egl/libGLESv1_CM_emulation.so
12-24 17:33:10.184: D/libEGL(871): loaded /system/lib/egl/libGLESv2_emulation.so
12-24 17:33:10.416: W/EGL_emulation(871): eglSurfaceAttrib not implemented
12-24 17:33:10.435: D/OpenGLRenderer(871): Enabling debug mode 0
答案 0 :(得分:0)
问题出在您的市场详细信息类中,其中: protected String doInBackground(String ... params){
Log.d("EEE","");
// 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("mname", marketName));
Log.d("FFF","");
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_market_details, "GET", params);
Log.d("GGG","");
......等等。 你使用doInBackground的原因是在后台线程中进行网络调用,但是你调用runOnUIThread会导致networkonmainthread异常。你不能做网络(这是jsonParser.makeHttpRequest(url_market_details,“GET”,params);在这种情况下的函数调用)在UI线程上删除runOnUI部分并移动doInBackground中的所有代码
答案 1 :(得分:0)
我认为您不应该使用runOnUiThread
AsyncTask
方法拨打doInBackground
,这是Market_details
。
我会在doInBackground
中完成所有繁重的网络工作,而不是在post方法中更新UI。