Android JSON解析器性能低下
我在这里转载是为了得到一些帮助 我制作了一个JSON解析器,它返回一个JSONArray(以便从我的Web服务获取信息) 当我在IceScreamSandwich上测试NetworkException时,我的上一个代码抛出了一个NetworkException错误(在版本2.3.3上,它很长,但运行良好) 我更改了代码以停止它并尝试获得更好的性能。。但它仍然不能在我的ICS手机上工作:现在没有更多的错误,只有一个IOException:“无法读取JSON URL” 我向您展示我的活动:Android JSON解析器性能低下,android,json,http,parsing,request,Android,Json,Http,Parsing,Request,我在这里转载是为了得到一些帮助 我制作了一个JSON解析器,它返回一个JSONArray(以便从我的Web服务获取信息) 当我在IceScreamSandwich上测试NetworkException时,我的上一个代码抛出了一个NetworkException错误(在版本2.3.3上,它很长,但运行良好) 我更改了代码以停止它并尝试获得更好的性能。。但它仍然不能在我的ICS手机上工作:现在没有更多的错误,只有一个IOException:“无法读取JSON URL” 我向您展示我的活动: publ
public class TabNewsJSONParsingActivity extends ListActivity
{
}
谁知道如何获得更好的性能并使其成为4.0版的朗姆酒?
如何将其用于异步任务?
谢谢这可能是因为您在主线程上运行web连接。。尝试将这段代码运行到AsyncTask或其他线程中。您需要使用AsyncTask下载和解析数据 代码如下
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
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.os.StrictMode;
import android.view.MenuItem;
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;
import android.widget.Toast;
public class TabNewsJSONParsingActivity extends ListActivity
{
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// url to make request
private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8";
//JSON names
private static final String TAG_content = "content";
private static final String TAG_zone = "zone";
private static final String TAG_id = "id";
private static final String TAG_area = "area";
private static final String TAG_title = "title";
private static final String TAG_date = "date";
private static final String TAG_author = "author";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.onglet_news);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), TabNewsSingleMenuItemActivity.class);
in.putExtra(TAG_content, name);
in.putExtra(TAG_title, cost);
in.putExtra(TAG_author, description);
startActivity(in);
}
});
new DownloadData().execute();
}
public boolean onOptionsItemSelected(MenuItem item)
{
//On regarde quel item a été cliqué grâce à son id et on déclenche une action
switch (item.getItemId())
{
case R.id.credits:
//pop up
Toast.makeText(TabNewsJSONParsingActivity.this, "Un delire", Toast.LENGTH_SHORT).show();
return true;
case R.id.quitter:
//Pour fermer l'application il suffit de faire finish()
finish();
return true;
}
return false;
}
private class DownloadData extends AsyncTask<Void, Integer, ArrayList<HashMap<String, String>>>
{
ProgressDialog pd = null;
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TabNewsJSONParsingActivity.this);
pd.setTitle("Downloading...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
/* (non-Javadoc)
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
// TODO Auto-generated method stub
// Hashmap for ListView
ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json;
try {
json = jParser.getJSONFromUrl1(url);
for(int i=0; i < json.length(); i++)
{
JSONObject child = json.getJSONObject(i);
String id = child.getString(TAG_id);
String title = child.getString(TAG_title);
String content = child.getString(TAG_content);
String date = child.getString(TAG_date);
String author = child.getString(TAG_author);
String zone = child.getString(TAG_zone);
String area = child.getString(TAG_area);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_content, content);
map.put(TAG_title, title);
map.put(TAG_author, author);
// adding HashList to ArrayList
newsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newsList;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> newsList) {
// TODO Auto-generated method stub
super.onPostExecute(newsList);
pd.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(TabNewsJSONParsingActivity.this, newsList,R.layout.onglet_news_listitem,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile });
TabNewsJSONParsingActivity.this.setListAdapter(adapter);
}
}
}
import java.io.IOException;
导入java.util.ArrayList;
导入java.util.HashMap;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.StrictMode;
导入android.view.MenuItem;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
导入android.widget.Toast;
公共类选项卡NewsJSonParsingActivity扩展了ListActivity
{
静止的{
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
}
//发出请求的url
专用静态字符串url=”http://developer.prixo.fr/API/GetEvents?zone=8";
//JSON名称
私有静态最终字符串标记_content=“content”;
私有静态最终字符串标记_zone=“zone”;
私有静态最终字符串标记\u id=“id”;
私有静态最终字符串标记_area=“area”;
私有静态最终字符串标记_title=“title”;
私有静态最终字符串标记_date=“date”;
私有静态最终字符串标记\u author=“author”;
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.onglet_新闻);
//选择单个ListView项
ListView lv=getListView();
//在选择单个列表项时启动新屏幕
lv.setOnItemClickListener(新的OnItemClickListener()
{
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
//从选定的ListItem获取值
字符串名称=((TextView)view.findviewbyd(R.id.name)).getText().toString();
字符串成本=((TextView)view.findViewById(R.id.email)).getText().toString();
字符串描述=((TextView)view.findviewbyd(R.id.mobile)).getText().toString();
//开始新的意图
Intent in=new Intent(getApplicationContext(),TabNewsSingleMenuItemActivity.class);
in.putExtra(标签内容、名称);
额外费用(标签名称、成本);
in.putExtra(标记作者,描述);
星触觉(in);
}
});
新建下载数据().execute();
}
公共布尔值onOptionsItemSelected(菜单项项)
{
//关于regarde quel物品aétécliquégréceáson id和déclenche une action
开关(item.getItemId())
{
案例R.id.学分:
//弹出
Toast.makeText(TabNewsJSONParsingActivity.this,“undelire”,Toast.LENGTH_SHORT.show();
返回true;
案例R.id.退出者:
//浇注fermer l'涂料,以满足表面光洁度要求()
完成();
返回true;
}
返回false;
}
私有类下载数据扩展异步任务
{
ProgressDialog pd=null;
/*(非Javadoc)
*@see android.os.AsyncTask#onPreExecute()
*/
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
super.onPreExecute();
pd=新建进度对话框(选项卡newsJSonParsingActivity.this);
pd.setTitle(“下载…”);
设置消息(“请稍候…”);
pd.可设置可取消(假);
pd.show();
}
/*(非Javadoc)
*@see android.os.AsyncTask#doInBackground(Params[])
*/
@凌驾
受保护的ArrayList doInBackground(无效…参数){
//TODO自动生成的方法存根
//ListView的Hashmap
ArrayList newsList=新建ArrayList();
//创建JSON解析器实例
JSONParser jParser=新的JSONParser();
//从URL获取JSON字符串
JSONArray-json;
试一试{
json=jParser.getJSONFromUrl1(url);
for(int i=0;ivalue
地图放置(
static InputStream is = null;
static JSONObject jObj = null;
static String jsonstr = "";
public JSONParser() {}
// throws IOException just to tell the caller that something bad happened (and
// what) instead of simply returning 'null' without any more information.
public JSONArray getJSONFromUrl1(String url) throws IOException
{
try
{
// should be a member of the parser to allow multiple calls without recreating the client every time.
DefaultHttpClient httpClient = new DefaultHttpClient();
// Using POST means sending data (or it its not following HTTP RFCs)
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
// Here the client may not be entirely initialized (no timeout, no agent-string).
HttpResponse httpResponse = httpClient.execute(httpGet);
//HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// The native utility function is also handling other charsets
String httpString = EntityUtils.toString(httpEntity);
return new JSONArray(httpString);
} catch (IOException ioe) {
throw ioe;
} catch (Exception ex) {
throw new IOException("Failed to read JSON from Url");
}
}
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
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.os.StrictMode;
import android.view.MenuItem;
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;
import android.widget.Toast;
public class TabNewsJSONParsingActivity extends ListActivity
{
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// url to make request
private static String url = "http://developer.prixo.fr/API/GetEvents?zone=8";
//JSON names
private static final String TAG_content = "content";
private static final String TAG_zone = "zone";
private static final String TAG_id = "id";
private static final String TAG_area = "area";
private static final String TAG_title = "title";
private static final String TAG_date = "date";
private static final String TAG_author = "author";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.onglet_news);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), TabNewsSingleMenuItemActivity.class);
in.putExtra(TAG_content, name);
in.putExtra(TAG_title, cost);
in.putExtra(TAG_author, description);
startActivity(in);
}
});
new DownloadData().execute();
}
public boolean onOptionsItemSelected(MenuItem item)
{
//On regarde quel item a été cliqué grâce à son id et on déclenche une action
switch (item.getItemId())
{
case R.id.credits:
//pop up
Toast.makeText(TabNewsJSONParsingActivity.this, "Un delire", Toast.LENGTH_SHORT).show();
return true;
case R.id.quitter:
//Pour fermer l'application il suffit de faire finish()
finish();
return true;
}
return false;
}
private class DownloadData extends AsyncTask<Void, Integer, ArrayList<HashMap<String, String>>>
{
ProgressDialog pd = null;
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(TabNewsJSONParsingActivity.this);
pd.setTitle("Downloading...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
/* (non-Javadoc)
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
// TODO Auto-generated method stub
// Hashmap for ListView
ArrayList<HashMap<String, String>> newsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json;
try {
json = jParser.getJSONFromUrl1(url);
for(int i=0; i < json.length(); i++)
{
JSONObject child = json.getJSONObject(i);
String id = child.getString(TAG_id);
String title = child.getString(TAG_title);
String content = child.getString(TAG_content);
String date = child.getString(TAG_date);
String author = child.getString(TAG_author);
String zone = child.getString(TAG_zone);
String area = child.getString(TAG_area);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_content, content);
map.put(TAG_title, title);
map.put(TAG_author, author);
// adding HashList to ArrayList
newsList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newsList;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> newsList) {
// TODO Auto-generated method stub
super.onPostExecute(newsList);
pd.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(TabNewsJSONParsingActivity.this, newsList,R.layout.onglet_news_listitem,new String[] { TAG_content, TAG_title, TAG_author }, new int[] {R.id.name, R.id.email, R.id.mobile });
TabNewsJSONParsingActivity.this.setListAdapter(adapter);
}
}
}
JSONTask g = new JSONTask();
g.execute();
public abstract class JSONTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... arg) {
//Do http get json here
String htpStatus= "";
String httpJSON = "" // this is the json data from you web service
// Create here your JSONObject...
JSONObject json = new JSONObject(httpJSON);
for(int i=0; i < json.length(); i++){
JSONObject child = json.getJSONObject(i);
String id = child.getString(TAG_id);
String title = child.getString(TAG_title);
String content = child.getString(TAG_content);
String date = child.getString(TAG_date);
String author = child.getString(TAG_author);
String zone = child.getString(TAG_zone);
String area = child.getString(TAG_area);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_content, content);
map.put(TAG_title, title);
map.put(TAG_author, author);
// adding HashList to ArrayList
newsList.add(map);
}
return htpStatus; // This value will be returned to your onPostExecute(result) method
}
@Override
protected void onPostExecute(String result) {
}
}