gpt4 book ai didi

java - 为什么我不断收到 NetworkOnMainThreadException?

转载 作者:行者123 更新时间:2023-11-29 09:53:33 27 4
gpt4 key购买 nike

我已经通过所有 SO 的解决方案来解决 NetworkOnMainThreadException 包括 ASync 类 - 但仍然有问题

这是我的简单代码:

ActivityMain 类:

public class MainActivity extends Activity
{
ArrayList<City> alCities = new ArrayList<City>();
Activity activity=null;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity=this;

new MyTask(activity, alCities).execute(); //<--- running ASYNC here
}
}

MyTask 类:

public class MyTask extends AsyncTask<Void, Void, ArrayList<City>>
{
ArrayList<City> alCities = null;
Activity ac = null;

public MyTask(Activity activity, ArrayList<City> al) //ctor
{
alCities = al;
this.activity= activity;
}

@Override
protected ArrayList<City> doInBackground(Void... params)
{
try
{
Object myJsonObject = Util.getJson("http://jsbin.com/lobel/2.js"); //internet job

try
{
//...fill array list...
return alCities;

} catch (Exception e)
{
...
}
}
} catch (Exception e)
{
...
}
return null;
}


protected void onPostExecute(ArrayList<City> alCities)
{
...
//update UI
ListView l1 = (ListView) ac.findViewById(R.id.list_view_1);
///
}

}

但还是:

enter image description here

注意:

如果我输入:

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

它确实有效:

enter image description here

问题

我做错了什么?

完整堆栈跟踪:http://jsbin.com/bilafi/2/edit

我所做的就是加载 json 文件!

onPostExecute 完整代码:

protected void onPostExecute(ArrayList<City> alCities)
{
CustomArrayAdapter adapter = new CustomArrayAdapter(ac, alCities);

ListView l1 = (ListView) ac.findViewById(R.id.list_view_1);
l1.setAdapter(adapter);
l1.setOnItemClickListener(new OnItemClickListener()
{

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
// Util.Toast(getBaseContext(), "You have selected " + 1);

}
});
}

最佳答案

这是你崩溃的地方:

at com.example.listview3.Util.getBitmapFromURL(Util.java:179)
at com.example.listview3.CustomArrayAdapter.getView(CustomArrayAdapter.java:67)

您已正确使用 AsyncTask。但是,在填充列表时,您正在尝试使用网络获取图像,再次。这一次,您没有使用 AsyncTask,因此没有使用 NetworkOnMainThreadException

关于java - 为什么我不断收到 NetworkOnMainThreadException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25877722/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com