我对AsyncTasks有近乎0的经验,所以请记住这一点!
我正在尝试通过Web服务访问外部数据库,所以我知道我必须使用AsyncTask。 Here's my code。在第73行,出于某种原因,一切都会破裂。
Here's the log file,异常开始在我的代码的第73行抛出。当我尝试通过单步执行代码进行调试时,我一直在“找不到源代码”。
也许我不理解AsyncTasks是如何工作的,但我假设在第67行之后,我的JSONArray对象'json'被设置然后我可以在该行之后使用它...
非常感谢任何帮助!
答案 0 :(得分:1)
不要在onCreate()
方法中创建类,类总是比方法更高的结构。
你有NPE bc asynctask需要一些时间才能完成,所以只需运行你的任务并在onPostExecute()
进行解析。
答案 1 :(得分:0)
你在第73行b / c失败了你的AsyncTask在你尝试使用时没有实例化json变量。记住,AsnycTask是在一个单独的进程上运行的,任何需要用json变量完成的工作都需要在AsyncTask的onPostExecute方法中完成。这个方法在UI线程上运行,因此可以在那里进行UI工作。
答案 2 :(得分:0)
创建一个在 onCreate()之外扩展 AsyncTask 的类。 (不仅在这种情况下)你总是需要在方法之外创建类(除了某些情况,比如匿名内部类,当然这又是另一个大讨论)。然后在onCreate()方法中创建AsyncTask类的对象,并使用该对象调用execute()
方法在另一个线程中运行该任务。根据您的代码,您无法区分事物。在 doInBackground()中编写代码以获取需要在不同线程上运行的数据,并在 onPostExecute()方法中获取您从中获取的数据doInBackground并更新UI。要更新UI,您可以使用 runOnUIThread(),如下所示。以下是根据您的要求的伪代码(未经测试)..
public class AllEventActivity extends Activity {
private ListView listView1;
private String tag = "all";
private JSONArray json;
View header;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<AllEvent> weather_data = new ArrayList<AllEvent>();
// AllEvent weather_data[] = new AllEvent[]
// {
// new AllEvent(R.drawable.a, "Soccer Field"),
// };
weather_data.add(new AllEvent(R.drawable.a, "a", "b", "c", "d", "e"));
listView1 = (ListView)findViewById(R.id.listView1); //
header = (View)getLayoutInflater().inflate(R.layout.listview_header_row, null);
new All_Events_DB_Connect().execute(new String[] {"all"});
}
class All_Events_DB_Connect extends AsyncTask<String, Void, JSONArray>
{
@Override
protected JSONArray doInBackground(String... arg0)
{
String tag = arg0[0];
UserFunctions u = new UserFunctions();
//JSONObject json = new JSONObject();
JSONArray json = new JSONArray();
try
{
json = u.getAllEvents(tag);
}
catch(Exception e)
{
Log.e("Error", e.getMessage());
}
return json;
}
@Override
protected void onPostExecute(JSONArray arr)
{
//returnedJson = json;
json = arr;
runOnUiThread(new Runnable() {
public void run() {
JSONObject j = new JSONObject();
for (int i = 0; i < json.length(); i++)
{
try
{
j = json.getJSONObject(i);
Toast.makeText(this, j.getString("hostName"), Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Log.e("JSON Error", e.getMessage());
}
}
AllEventAdapter adapter = new AllEventAdapter(this,
R.layout.listview_item_row, weather_data);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
}
});
}
}
}