这是我的代码,它可以100%运行:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.t1, container, false);
final ListView list = (ListView) inflatedView.findViewById(R.id.list);
class json extends AsyncTask<String,String, List<MovieModel> > {
...
@Override
protected void onPostExecute(final List<MovieModel> result) {
...
MainActivity.Adapter adapter = new MainActivity.Adapter(getActivity().getApplicationContext(), R.layout.row, result);
list.setAdapter(adapter);
list.setOnItemClickListener
...
}
}
但现在我也需要在另一个位置调用json类:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
....
class json .....
}
@Override
public void onRefresh() {
new json();// i can't recall in this way, but i need it
}
问题是列表,因为我无法从onCreateView中删除,因为如果我这样做,列表就不会被定义。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
....
new json();
}
class json extends AsyncTask<String,String, List<MovieModel> > {
...
@Override
protected void onPostExecute(final List<MovieModel> result) {
...
MainActivity.Adapter adapter = new MainActivity.Adapter(getActivity().getApplicationContext(), R.layout.row, result);
list.setAdapter(adapter);//this is an error now
现在的错误是&#34;无法解析simbol&#39; list&#39;&#34;。
答案 0 :(得分:1)
快速解决方案是使list
成为一个类变量。
public class MainActivty extends Activity {
private ListView mList;
private class json extends AsyncTask<String,String, List<MovieModel> > {
...
@Override
protected void onPostExecute(final List<MovieModel> result) {
...
mList.setAdapter(adapter);
...
}
}
但更好的解决方案是将result
从onPostExecute
传递回MainActivity以更新用户界面。
public class MainActivty extends Activity {
private ListView mList;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.t1, container, false);
mList = (ListView) inflatedView.findViewById(R.id.list);
...
}
private void updateUI(final List<MovieModel> result> {
MainActivity.Adapter adapter
= new MainActivity.Adapter(getActivity().getApplicationContext(), R.layout.row, result);
mList.setAdapter(adapter);
...
}
private class json extends AsyncTask<String,String, List<MovieModel> > {
...
@Override
protected void onPostExecute(final List<MovieModel> result) {
...
updateUI(result);
...
}
}
通过这种方式,您可以将AsyncTask
和所有用户界面处理中的所有数据处理保留在Activity
中。