- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我刚开始开发 android 应用程序。我已经阅读了很多关于我提出的问题的相关帖子,但是帖子中的提示或解决方案并没有解决我的问题。 (已经寻找解决方案一周了,真的需要帮助才能继续我的项目)非常感谢...
import java.util.ArrayList;
import java.util.HashMap;
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 com.example.aroma.slidingmenu.listener.JSONParser;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class ResultListFragment extends ListFragment {
TextView resultView;
public ResultListFragment(){}
//progress dialog
private ProgressDialog pDialog;
//creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String,String>> customerList;
//url to get the customer list
private static String url_search="http://192.168.1.3:80/test/getAllCustomers.php";
//JSON Node names
private static final String TAG_SUCCESS="success";
private static final String TAG_CUSTOMER="customers";
private static final String TAG_FNAME="FirstName";
private static final String TAG_LNAME="LastName";
private static final String TAG_AGE="Age";
private static final String TAG_MOBILE="Mobile";
//product JSONArray
JSONArray customers=null;
//search key value
public String searchKey;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_searchresult_list, container, false);
Toast.makeText(getActivity(),"Search result in listview",Toast.LENGTH_LONG).show();
Intent intent = getActivity().getIntent();
searchKey = intent.getStringExtra("message");
//Toast.makeText(getActivity(), searchKey, Toast.LENGTH_LONG).show();
//hshmap for listview
customerList= new ArrayList<HashMap<String,String>>();
//Loading customer in background thread
new LoadCustomer().execute();
return rootView;
}
@Override
public void onViewCreated (View view, Bundle savedInstanceState) {
ListView lv =getListView();
lv.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String iid=((TextView)view.findViewById(R.id.FirstName)).getText().toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
/**
* Background Async Task to load customers by making HTTP request
* */
class LoadCustomer extends AsyncTask<String, String, String>{
/**
* Before starting background thread show progress dialog
* */
@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog=new ProgressDialog(getActivity()); //pDialog=new ProgressDialog(ResultListFragment.this);
pDialog.setMessage("Loading customers. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting customers url
* **/
protected String doInBackground(String... args){
//Building Parameters
List<NameValuePair> params= new ArrayList<NameValuePair>();
//value captured from previous intent
params.add(new BasicNameValuePair("FirstName", searchKey));
//getting JSON string from url
JSONObject json = jParser.makeHttpRequest(url_search, "GET", params);
//check your log cat for JSON response
Log.d("Search customer", json.toString());
try{
//checking for SUCCESS TAG
int success=json.getInt(TAG_SUCCESS);
if(success==1){
//product found
//Getting array of products
customers=json.getJSONArray(TAG_CUSTOMER);
//looping through all products
for(int i=0;i<customers.length();i++){
JSONObject c=customers.getJSONObject(i);
//storing each json item in variable
String fname=c.getString(TAG_FNAME);
String lname=c.getString(TAG_LNAME);
String age=c.getString(TAG_AGE);
String mobile=c.getString(TAG_MOBILE);
//creating new HashMap
HashMap<String, String> map=new HashMap<String, String>();
//adding each child node to HashMap key =>value
map.put(TAG_FNAME, fname);
map.put(TAG_LNAME, lname);
map.put(TAG_AGE, age);
map.put(TAG_MOBILE, mobile);
//adding HashList to ArrayList
customerList.add(map);
}
}else{
//no customer found
//do sth
Handler handler = new Handler(getActivity().getMainLooper());
handler.post( new Runnable(){
public void run(){
Toast.makeText(getActivity(),"no customer found" ,Toast.LENGTH_LONG).show();
}
});
}
}catch (JSONException e){
e.printStackTrace();
}
//return "success";
return null;
}
/**
* After completing background task dismiss the progress dialog
* **/
protected void onPostExecute(String file_url){
//dimiss the dialog after getting the related customer
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable(){
public void run(){
/**
* updating parsed JSON data into ListView
* **/
ListAdapter adapter =new SimpleAdapter(
getActivity(), customerList,
R.layout.list_item, new String[]{ TAG_FNAME, TAG_LNAME, TAG_AGE, TAG_MOBILE},
new int[]{R.id.FirstName,R.id.LastName,R.id.Age,R.id.Mobile});
//updating listview
setListAdapter(adapter);
}
});
}
}
}
JSONParser.java
package com.example.aroma.slidingmenu.listener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;http://stackoverflow.com/editing-help
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.apache.http.util.EntityUtils;
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.equals("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.equals("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();
String all=EntityUtils.toString(httpEntity);
Log.d("response",all);
}
} 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;
}
}
getAllCustomers.php
$response = array();
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdatabase", $con);
$FirstName=$_GET["FirstName"];
$result = mysql_query("SELECT * FROM customer where FirstName like '%$FirstName%' ");
if(mysql_num_rows($result)>0){
// looping through all results
// products node
$response["customers"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$customers = array();
$customers["FirstName"] = $row["FirstName"];
$customers["LastName"] = $row["LastName"];
$customers["Age"] = $row["Age"];
$customers["Mobile"] = $row["Mobile"];
// push single product into final response array
array_push($response["customers"], $customers);
}
// 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);
}
我从 Logcat 保存的错误:
02-12 17:17:50.599: E/Buffer Error(13636): Error converting result java.lang.NullPointerException: lock == null02-12 17:17:50.599: E/JSON Parser(13636): Error parsing data org.json.JSONException: End of input at character 0 of 02-12 17:17:50.604: E/AndroidRuntime(13636): FATAL EXCEPTION: AsyncTask #402-12 17:17:50.604: E/AndroidRuntime(13636): java.lang.RuntimeException: An error occured while executing doInBackground()02-12 17:17:50.604: E/AndroidRuntime(13636): at android.os.AsyncTask$3.done(AsyncTask.java:299)02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.run(FutureTask.java:239)02-12 17:17:50.604: E/AndroidRuntime(13636): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)02-12 17:17:50.604: E/AndroidRuntime(13636): at java.lang.Thread.run(Thread.java:838)02-12 17:17:50.604: E/AndroidRuntime(13636): Caused by: java.lang.NullPointerException02-12 17:17:50.604: E/AndroidRuntime(13636): at com.example.aroma.slidingmenu.ResultListFragment$LoadCustomer.doInBackground(ResultListFragment.java:136)02-12 17:17:50.604: E/AndroidRuntime(13636): at com.example.aroma.slidingmenu.ResultListFragment$LoadCustomer.doInBackground(ResultListFragment.java:1)02-12 17:17:50.604: E/AndroidRuntime(13636): at android.os.AsyncTask$2.call(AsyncTask.java:287)02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.run(FutureTask.java:234)02-12 17:17:50.604: E/AndroidRuntime(13636): ... 4 more
最佳答案
尝试在onActivityCreated
中调用asynctask
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_searchresult_list, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(),"Search result in listview",Toast.LENGTH_LONG).show();
Intent intent = getActivity().getIntent();
searchKey = intent.getStringExtra("message");
//Toast.makeText(getActivity(), searchKey, Toast.LENGTH_LONG).show();
//hshmap for listview
customerList= new ArrayList>();
//Loading customer in background thread
new LoadCustomer().execute();
}
关于android - 转换结果时出错 java.lang.NullPointerException : lock == null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28473841/
我正在将我的模板代码移植到 XTend。在某些时候,我在测试用例中有这种类型的条件处理: @Test def xtendIfTest() { val obj = new FD if (
我是新来的 kotlin , 当我开始 Null Safety 时,我对下面的情况感到困惑. There's some data inconsistency with regard to initia
我的应用程序一直在各种Android版本中保持良好状态。我有用户在Android 4.3、5.0、5.1和6.0上正常运行。但是,具有S7 Edge的用户刚刚更新了Android 7.0,将文本粘贴到
我使用的是最新版本的 LWUIT (1.5)。我在资源编辑器中设计了我的表单,然后将代码生成到 netbeans。问题是如果我想访问除表单之外的任何对象,我会收到此错误: java.lang.Null
更新: 我在 Fedora 21 上运行它。 SonarQube - 5.0。 SonarQube Runner - 2.4 更新 2:Findbugs v3.1,Java 插件 v2.8 更新3:
RecupData 我的类仅在 web 中返回 NullPointerException。我连接到 pgsql db 8.3.7 - 该脚本在“控制台”syso 中运行良好 - 但引发了测试 Web
我在 mac 上使用 Processing 2.08。我正在尝试使用文档中给出的 createShape 函数创建 PShape。 PShape s; void setup(){ size(500
我在 mac 上使用 Processing 2.08。我正在尝试使用文档中给出的 createShape 函数创建 PShape。 PShape s; void setup(){ size(500
每次运行此 jsp 时,都会收到以下错误异常: org.apache.jasper.JasperException: java.lang.NullPointerException root cause
Kotlin 在编译时有一个出色的 null 检查,使用分离到“可空?”和“不可为空”的对象。它有一个 KAnnotator 来帮助确定来自 Java 的对象是否可以为空。但是,如果 not-null
我有一个布局将显示一个TextView,用于显示一个滴答时间。我遵循了此链接中的代码 How to Display current time that changes dynamically for
Elasticsearch 1.4.1版(“lucene_version”:“4.10.2”) 我有一个像这样的文件: $ curl 'http://localhost:9200/blog/artic
这是我从另一个类调用函数的方法Selenium 设置已定义。 public void Transfer() throws Exception { System.out.println("\nTrans
我试图在主类中使用我在此类中创建的函数,但它崩溃并显示“警告:无法在根 0 处打开/创建首选项根节点 Software\JavaSoft\Prefsx80000002。 Windows RegCrea
这个问题已经有答案了: What is a NullPointerException, and how do I fix it? (12 个回答) 已关闭 3 年前。 我有一个 Java 代码,它将
我声明了两张牌: Card card1 = new Card('3', Card.Suit.clubs); Card card2 = new Card('T', Card.Suit.diamonds)
我编写了一段代码来解码 Base64 图像并在 javafx 中表示该图像。在我的 url base64 代码中不断变化。这就是我在 javafx 代码中使用任务的原因。但我收到错误:java.lan
我正在尝试使用 arrayList 的 arrayList 在 Java 中实现图形。 每当调用 addEdge 函数时,我都会收到 NullPointerException 。我似乎无法弄清楚为什么
我是 Java/android 的新手,所以很多这些术语都是外国的,但我愿意学习。我不打算详细介绍该应用程序,因为我认为它不相关。我目前的问题是,我使用了博客中的教程和代码 fragment ,并使我
我正在开发一个 Android 应用程序来在 Android developer guide 的帮助下录制视频.我程序上的所有代码都与此页面相同。 我在 之外定义了权限标签。 当应
我是一名优秀的程序员,十分优秀!