- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
有人可以告诉我我的错误是什么吗?我从 AndroidHive.info 下载了这段代码。我一直收到“错误解析数据错误。还有人可以告诉我如何找出错误所在的行吗?
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://xxx.xxx.xxx.xxx/include/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() {
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();
}
}
}
这是我的日志
01-26 18:14:35.366: D/dalvikvm(12395): GC_CONCURRENT freed 72K, 52% free 2619K/5379K, external 1529K/2026K, paused 8ms+2ms
01-26 18:14:36.296: E/JSON Parser(12395): Error parsing data org.json.JSONException: Value Unknown of type java.lang.String cannot be converted to JSONObject
01-26 18:14:36.296: W/dalvikvm(12395): threadid=9: thread exiting with uncaught exception (group=0x2aac8560)
01-26 18:14:36.306: E/AndroidRuntime(12395): FATAL EXCEPTION: AsyncTask #1
01-26 18:14:36.306: E/AndroidRuntime(12395): java.lang.RuntimeException: An error occured while executing doInBackground()
01-26 18:14:36.306: E/AndroidRuntime(12395): at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.lang.Thread.run(Thread.java:1019)
01-26 18:14:36.306: E/AndroidRuntime(12395): Caused by: java.lang.NullPointerException
01-26 18:14:36.306: E/AndroidRuntime(12395): at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:129)
01-26 18:14:36.306: E/AndroidRuntime(12395): at com.example.androidhive.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:1)
01-26 18:14:36.306: E/AndroidRuntime(12395): at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-26 18:14:36.306: E/AndroidRuntime(12395): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
01-26 18:14:36.306: E/AndroidRuntime(12395): ... 4 more
01-26 18:14:36.566: E/WindowManager(12395): Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afca938 that was originally added here
01-26 18:14:36.566: E/WindowManager(12395): android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afca938 that was originally added here
01-26 18:14:36.566: E/WindowManager(12395): at android.view.ViewRoot.<init>(ViewRoot.java:265)
01-26 18:14:36.566: E/WindowManager(12395): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-26 18:14:36.566: E/WindowManager(12395): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-26 18:14:36.566: E/WindowManager(12395): at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-26 18:14:36.566: E/WindowManager(12395): at android.app.Dialog.show(Dialog.java:241)
01-26 18:14:36.566: E/WindowManager(12395): at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:116)
01-26 18:14:36.566: E/WindowManager(12395): at android.os.AsyncTask.execute(AsyncTask.java:391)
01-26 18:14:36.566: E/WindowManager(12395): at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57)
01-26 18:14:36.566: E/WindowManager(12395): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-26 18:14:36.566: E/WindowManager(12395): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-26 18:14:36.566: E/WindowManager(12395): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
01-26 18:14:36.566: E/WindowManager(12395): at android.app.ActivityThread.access$1500(ActivityThread.java:121)
01-26 18:14:36.566: E/WindowManager(12395): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
01-26 18:14:36.566: E/WindowManager(12395): at android.os.Handler.dispatchMessage(Handler.java:99)
01-26 18:14:36.566: E/WindowManager(12395): at android.os.Looper.loop(Looper.java:123)
01-26 18:14:36.566: E/WindowManager(12395): at android.app.ActivityThread.main(ActivityThread.java:3701)
01-26 18:14:36.566: E/WindowManager(12395): at java.lang.reflect.Method.invokeNative(Native Method)
01-26 18:14:36.566: E/WindowManager(12395): at java.lang.reflect.Method.invoke(Method.java:507)
01-26 18:14:36.566: E/WindowManager(12395): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:862)
01-26 18:14:36.566: E/WindowManager(12395): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
01-26 18:14:36.566: E/WindowManager(12395): at dalvik.system.NativeStart.main(Native Method)
01-26 18:16:02.626: I/Process(12395): Sending signal. PID: 12395 SIG: 9
谢谢!
编辑:这是 AllProductsActivity.java 的代码:
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://xxx.xxx.xxx.xxx/include/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() {
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);
}
});
}
}
}
最佳答案
首先,将您的方法包装在
try{
} catch(Throwable t) { Log.e("MyActivity", t.getMessage(), t); }
您应该更容易阅读堆栈跟踪。
要使此代码正常工作,您需要在 Web 服务器上安装“include/get_all_products.php”。然后,您需要使用服务器的 IP 地址更新 url_all_products 中定义的 URL。你做到了吗?
内部 JSON 解析器可用于少量数据。如需更多数据,GSON 之类的工具可以挽救您的理智。
关于android - AsyncTask #3 错误解析 JSON 对象。字符串无法转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14542631/
我一直在使用 AJAX 从我正在创建的网络服务中解析 JSON 数组时遇到问题。我的前端是一个简单的 ajax 和 jquery 组合,用于显示从我正在创建的网络服务返回的结果。 尽管知道我的数据库查
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
我在尝试运行 Android 应用程序时遇到问题并收到以下错误 java.lang.NoClassDefFoundError: com.parse.Parse 当我尝试运行该应用时。 最佳答案 在这
有什么办法可以防止etree在解析HTML内容时解析HTML实体吗? html = etree.HTML('&') html.find('.//body').text 这给了我 '&' 但我想
我有一个有点疯狂的例子,但对于那些 JavaScript 函数作用域专家来说,它看起来是一个很好的练习: (function (global) { // our module number one
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 8 年前。 Improve th
我需要编写一个脚本来获取链接并解析链接页面的 HTML 以提取标题和其他一些数据,例如可能是简短的描述,就像您链接到 Facebook 上的内容一样。 当用户向站点添加链接时将调用它,因此在客户端启动
在 VS Code 中本地开发时,包解析为 C:/Users//AppData/Local/Microsoft/TypeScript/3.5/node_modules/@types//index而不是
我在将 json 从 php 解析为 javascript 时遇到问题 这是我的示例代码: //function MethodAjax = function (wsFile, param) {
我在将 json 从 php 解析为 javascript 时遇到问题 这是我的示例代码: //function MethodAjax = function (wsFile, param) {
我被赋予了将一种语言“翻译”成另一种语言的工作。对于使用正则表达式的简单逐行方法来说,源代码过于灵活(复杂)。我在哪里可以了解更多关于词法分析和解析器的信息? 最佳答案 如果你想对这个主题产生“情绪化
您好,我在解析此文本时遇到问题 { { { {[system1];1;1;0.612509325}; {[system2];1;
我正在为 adobe after effects 在 extendscript 中编写一些代码,最终变成了 javascript。 我有一个数组,我想只搜索单词“assemble”并返回整个 jc3_
我有这段代码: $(document).ready(function() { // }); 问题:FB_RequireFeatures block 外部的代码先于其内部的代码执行。因此 who
背景: netcore项目中有些服务是在通过中间件来通信的,比如orleans组件。它里面服务和客户端会指定网关和端口,我们只需要开放客户端给外界,服务端关闭端口。相当于去掉host,这样省掉了些
1.首先贴上我试验成功的代码 复制代码 代码如下: protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
什么是 XML? XML 指可扩展标记语言(eXtensible Markup Language),标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。 你可以通过本站学习 X
【PHP代码】 复制代码 代码如下: $stmt = mssql_init('P__Global_Test', $conn) or die("initialize sto
在SQL查询分析器执行以下代码就可以了。 复制代码代码如下: declare @t varchar(255),@c varchar(255) declare table_cursor curs
前言 最近练习了一些前端算法题,现在做个总结,以下题目都是个人写法,并不是标准答案,如有错误欢迎指出,有对某道题有新的想法的友友也可以在评论区发表想法,互相学习🤭 题目 题目一: 二维数组中的
我是一名优秀的程序员,十分优秀!