问题描述
我的应用程序不工作在Android 4.1版本提供了异常,比如 android.os.NetworkOnMainThreadException
我对计算器的建议我做网络线程在后台搜索的AsyncTask
所以使用前backgroundtask,
我的屏幕看起来像这个使用backgroundtask后表现出营养的多行和成分标签我的屏幕看起来像这个显示的成分和营养标签
前,后台任务code是该见下面
公共类fifthscreen延伸活动{
字符串NUM = NULL;
TextView的成分;长Menu_ID;
串dish_name;字符串状态;HorizontalListView列表视图;
CategoryListAdapter3 CLA;
串DescriptionAPI;TextView的TXT1,TXT2,txt3;
ImageView的IMG1;
字符串URL,URL2;
串SelectMenuAPI;静态的ArrayList<龙> CATEGORY_ID =新的ArrayList<龙>();
静态的ArrayList<串GT; CATEGORY_NAME =新的ArrayList<串GT;();
静态的ArrayList<串GT; Category_image =新的ArrayList<串GT;();公共静态字符串allergen2;
私人AQuery androidAQuery;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.fifthscreen);
成分=(的TextView)findViewById(R.id.ingredient);
IMG1 =(ImageView的)findViewById(R.id.test_button_image); TXT1 =(的TextView)findViewById(R.id.menuname);
txt3 =(的TextView)findViewById(R.id.description); 意向书的iget = getIntent(); ImageView的选项=(ImageView的)findViewById(R.id.options5);
androidAQuery =新AQuery(本); options.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
意图iMenuList =新意图(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
}); dish_name = iGet.getStringExtra(dish_name); 列表视图=(HorizontalListView)this.findViewById(R.id.listview2); CLA =新CategoryListAdapter3(fifthscreen.this);
listview.setAdapter(CLA); parseJSONData();}无效clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();}公共无效parseJSONData(){ SelectMenuAPI = Utils.dishdescription + dish_name; clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(,%20); 尝试{ HttpClient的客户端=新DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(),15000);
HttpConnectionParams.setSoTimeout(client.getParams(),15000);
HttpUriRequest要求=新HTTPGET(URL2);
HTT presponse响应= client.execute(请求);
InputStream的atomInputStream = response.getEntity()的getContent()。
在的BufferedReader =新的BufferedReader(新的InputStreamReader(
atomInputStream)); 串线;
字符串str =;
而((行= in.readLine())!= NULL){
STR + =行;
} JSONObject的json2 =新的JSONObject(STR); 状态= json2.getString(状态);
如果(status.equals(1)){ JSONArray school2 = json2.getJSONArray(数据); 的for(int i = 0; I< school2.length();我++){ 字符串名称= school2.getJSONObject(0).getString(名称);
txt1.setText(名); 字符串描述= school2.getJSONObject(0).getString(
描述); txt3.setText(介绍); 字符串为url1 = school2.getJSONObject(0).getString(图像); androidAQuery.id(IMG1)在图像配(为url1,假的,假的); } JSONObject的school3 = json2.getJSONObject(dish_nutrition); 最后TableLayout表=(TableLayout)findViewById(R.id.table2); 对于(INT J = 0; J< school3.length(); J ++){ 字符串s =将String.valueOf第(j + 1); 最终视图行= createRow(school3.getJSONObject(S));
table.addView(行); } JSONArray school4 = json2.getJSONArray(dish_allergen);
//
的for(int i = 0; I< school4.length();我++){
的JSONObject对象= school4.getJSONObject(I) Category_ID.add((长)一);
Category_name.add(object.getString(名字));
Category_image.add(object.getString(图像));
listview.setAdapter(CLA); } 最终的LinearLayout表3 =(的LinearLayout)findViewById(R.id.table3); JSONArray school5 = json2.getJSONArray(dish_ingredient); 的for(int i = 0; I< school5.length();我++){ 最后查看ROW2 = createRow2(school5.getJSONObject(I));
table3.addView(ROW2); } } 其他{ JSONArray school2 = json2.getJSONArray(数据);
的for(int i = 0; I< school2.length();我++){
的JSONObject对象= school2.getJSONObject(I) Category_ID.add((长)一);
Category_name.add(object.getString(名字)); } } }赶上(MalformedURLException的E){
// TODO自动生成catch块
e.printStackTrace();
}赶上(IOException异常五){
// TODO自动生成catch块
// IOConnect = 1;
e.printStackTrace();
}赶上(JSONException E){
// TODO自动生成catch块
e.printStackTrace();
}
}公共查看createRow(JSONObject的项目)抛出JSONException {
查看排= getLayoutInflater()膨胀(R.layout.rows,NULL);
((的TextView)row.findViewById(R.id.localTime))。的setText(项目
.getString(数量));
((的TextView)row.findViewById(R.id.ap prentTemp))的setText。(项目
.getString(名字)); 返回行;
}公共查看createRow2(JSONObject的项目)抛出JSONException { 查看ROW2 = getLayoutInflater()膨胀(R.layout.row2,NULL);
((的TextView)row2.findViewById(R.id.name))。的setText(项目
.getString(名字));
((的TextView)row2.findViewById(R.id.subingredients))。的setText(项目
.getString(sub_ingredients)); 返回ROW2;
} }
使用后的AsyncTask
看到以下code
公共类fifthscreen延伸活动{
字符串NUM = NULL;
TextView的成分;长Menu_ID;
串dish_name;字符串状态;HorizontalListView列表视图;
CategoryListAdapter3 CLA;
串DescriptionAPI;TextView的TXT1,TXT2,txt3;
ImageView的IMG1;
字符串URL,URL2;
串SelectMenuAPI;
字符串描述;INT IOConnect = 0;
字符串名称;
串URL1;
TableLayout表;
表3的LinearLayout;
查看排;
查看ROW2;静态的ArrayList<龙> CATEGORY_ID =新的ArrayList<龙>();
静态的ArrayList<串GT; CATEGORY_NAME =新的ArrayList<串GT;();
静态的ArrayList<串GT; Category_image =新的ArrayList<串GT;();
公共静态字符串allergen2;
私人AQuery androidAQuery;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.fifthscreen);
如果(android.os.Build.VERSION.SDK_INT> 9){
StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()
.permitAll()建立()。
StrictMode.setThreadPolicy(政策);
}
成分=(的TextView)findViewById(R.id.ingredient);
IMG1 =(ImageView的)findViewById(R.id.test_button_image); TXT1 =(的TextView)findViewById(R.id.menuname);
// TXT2 =(的TextView)findViewById(R.id.test_button_text1);
txt3 =(的TextView)findViewById(R.id.description); 表=(TableLayout)findViewById(R.id.table2);
表3 =(的LinearLayout)findViewById(R.id.table3); 意向书的iget = getIntent(); ImageView的选项=(ImageView的)findViewById(R.id.options5);
androidAQuery =新AQuery(本); options.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
意图iMenuList =新意图(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
}); dish_name = iGet.getStringExtra(dish_name); 列表视图=(HorizontalListView)this.findViewById(R.id.listview2); CLA =新CategoryListAdapter3(fifthscreen.this); 新getDataTask()执行(); // listview.setAdapter(CLA); ImageView的btnback =(ImageView的)findViewById(R.id.btnback); btnback.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
完();
}
}); parseJSONData();}无效clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();}公共类getDataTask扩展的AsyncTask<太虚,太虚,太虚> { getDataTask(){ } @覆盖
在preExecute保护无效(){
// TODO自动生成方法存根 } @覆盖
保护无效doInBackground(虚空......为arg0){
// TODO自动生成方法存根
parseJSONData();
返回null;
} @覆盖
保护无效onPostExecute(虚空结果){
// TODO自动生成方法存根
txt1.setText(名);
txt3.setText(介绍);
androidAQuery.id(IMG1)在图像配(为url1,假的,假的); table.addView(行);
table3.addView(ROW2);
listview.setAdapter(CLA); }
}公共无效parseJSONData(){ SelectMenuAPI = Utils.dishdescription + dish_name; clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(,%20); 尝试{ HttpClient的客户端=新DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(),15000);
HttpConnectionParams.setSoTimeout(client.getParams(),15000);
HttpUriRequest要求=新HTTPGET(URL2);
HTT presponse响应= client.execute(请求);
InputStream的atomInputStream = response.getEntity()的getContent()。
在的BufferedReader =新的BufferedReader(新的InputStreamReader(
atomInputStream)); 串线;
字符串str =;
而((行= in.readLine())!= NULL){
STR + =行;
} JSONObject的json2 =新的JSONObject(STR); 状态= json2.getString(状态);
如果(status.equals(1)){ JSONArray school2 = json2.getJSONArray(数据); 的for(int i = 0; I< school2.length();我++){ 名称= school2.getJSONObject(0).getString(名称); 说明= school2.getJSONObject(0).getString(
描述); 为url1 = school2.getJSONObject(0).getString(图像); } JSONObject的school3 = json2.getJSONObject(dish_nutrition); 对于(INT J = 0; J< school3.length(); J ++){ 字符串s =将String.valueOf第(j + 1); 行= createRow(school3.getJSONObject(S)); } JSONArray school4 = json2.getJSONArray(dish_allergen);
//
的for(int i = 0; I< school4.length();我++){
的JSONObject对象= school4.getJSONObject(I) Category_ID.add((长)一);
Category_name.add(object.getString(名字));
Category_image.add(object.getString(图像)); } JSONArray school5 = json2.getJSONArray(dish_ingredient); 的for(int i = 0; I< school5.length();我++){ ROW2 = createRow2(school5.getJSONObject(I)); } } 其他{ JSONArray school2 = json2.getJSONArray(数据);
的for(int i = 0; I< school2.length();我++){
的JSONObject对象= school2.getJSONObject(I) Category_ID.add((长)一);
Category_name.add(object.getString(名字)); } } }赶上(MalformedURLException的E){
// TODO自动生成catch块
e.printStackTrace();
}赶上(IOException异常五){
// TODO自动生成catch块
// IOConnect = 1;
e.printStackTrace();
}赶上(JSONException E){
// TODO自动生成catch块
e.printStackTrace();
}
}公共查看createRow(JSONObject的项目)抛出JSONException {
查看排= getLayoutInflater()膨胀(R.layout.rows,NULL);
((的TextView)row.findViewById(R.id.localTime))。的setText(项目
.getString(数量));
((的TextView)row.findViewById(R.id.ap prentTemp))的setText。(项目
.getString(名字)); 返回行;
}公共查看createRow2(JSONObject的项目)抛出JSONException { 查看ROW2 = getLayoutInflater()膨胀(R.layout.row2,NULL);
((的TextView)row2.findViewById(R.id.name))。的setText(项目
.getString(名字));
((的TextView)row2.findViewById(R.id.subingredients))。的setText(项目
.getString(sub_ingredients)); 返回ROW2;
} }
请帮助
在此先感谢...:)
您可以使用 ** runOnUiThread()**
是这样的:
{尝试
// code在线程中运行
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){ //你的code }
});
}赶上(最终异常前){
Log.i(---,异常螺纹);
}
My app is not working on android version 4.1 gives exception like android.os.NetworkOnMainThreadException
i have search on stackoverflow advice me to do network thread in background AsyncTask
so before use backgroundtask,My screen look like this http://imgur.com/PlhS03i show multiple rows in nutrition's and ingredient tags after using backgroundtask my screen look like this http://imgur.com/zUvxNpy show only single row in ingredients and nutrition tags
before background task code is this see below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
txt3 = (TextView) findViewById(R.id.description);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
listview.setAdapter(cla);
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
String name = school2.getJSONObject(0).getString("name");
txt1.setText(name);
String description = school2.getJSONObject(0).getString(
"description");
txt3.setText(description);
String url1 = school2.getJSONObject(0).getString("image");
androidAQuery.id(img1).image(url1, false, false);
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
final TableLayout table = (TableLayout) findViewById(R.id.table2);
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
final View row = createRow(school3.getJSONObject(s));
table.addView(row);
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
listview.setAdapter(cla);
}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
final View row2 = createRow2(school5.getJSONObject(i));
table3.addView(row2);
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
After using AsyncTask
see this code below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
String description;
int IOConnect = 0;
String name;
String url1;
TableLayout table;
LinearLayout table3;
View row;
View row2;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
// txt2 = (TextView) findViewById(R.id.test_button_text1);
txt3 = (TextView) findViewById(R.id.description);
table = (TableLayout) findViewById(R.id.table2);
table3 = (LinearLayout) findViewById(R.id.table3);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new getDataTask().execute();
// listview.setAdapter(cla);
ImageView btnback = (ImageView) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
txt1.setText(name);
txt3.setText(description);
androidAQuery.id(img1).image(url1, false, false);
table.addView(row);
table3.addView(row2);
listview.setAdapter(cla);
}
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
name = school2.getJSONObject(0).getString("name");
description = school2.getJSONObject(0).getString(
"description");
url1 = school2.getJSONObject(0).getString("image");
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
row = createRow(school3.getJSONObject(s));
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
row2 = createRow2(school5.getJSONObject(i));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
Please Help
Thanks in Advance...:)
You can use **runOnUiThread()**
like this:
try {
// code runs in a thread
runOnUiThread(new Runnable() {
@Override
public void run() {
// YOUR CODE
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
这篇关于如何从后台任务更新用户界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!