2016-10-10 26 views
-2

這是我的代碼,它工作在100%:錯誤無法解決辛博爾清單,list.setAdapter(適配器)

@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 

現在的錯誤是「無法解析simbol'list'」。

回答

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); 
     ... 
    } 
} 

但更好的解決辦法是從onPostExecuteresult傳回在MainActivity更新UI。

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和所有UI處理您的Activity