2015-03-31 40 views
0

我有一个片段活动并希望从我的php脚本中获取数据。我需要这些数据来有效地绘制我的UI。我的问题是我的UI /碎片在我得到数据之前画出来,我不知道为什么,因为我尽早在onCreate中启动它。我把一个对话框放入前后,以有效地冻结用户界面,同时数据在后台被回收,但是......我没有看到这种情况发生,我认为在调试过程中出现对话时调用它太晚了,它显示了绘制屏幕的顶部这让我感到莫名其妙。在哪里发射片段活动中的异步脚本

我有一个替代的解决方案是在调用活动(之前的活动)中激发asyncTask并将结果传入包中,但我不喜欢此解决方案,因为它的刚性和可能导致屏幕旋转的问题。

我一直坚持这个很长时间,任何人都可以告诉我在哪里把我的异步执行 - 对话框应该有效地使其同步过程。我把我的异想天开地放在我认为可能/理智和没有运气的地方。

在下面我执行oncreate()。注意执行不会更新任何内容,而是预先更新一个“不变”的测试字符串,并在后缀中更改“已更改”,以便我可以在代码中的各个点上看到它的状态。它不会改变,然后我画我的屏幕。

public class StaggeredGridActivityFragment extends FragmentActivity { 


    String test ="not changed"; 
    private TilesAdapter mAdapter; 
    private ArrayList<String> mData; 
    private StaggeredGridView mGridView; 

    private static final String TAG = "StaggeredGridActivityFragment"; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     try 
     { 
      // Loading tile data in Background Thread 
      new GetLoginTiles().execute(); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     super.onCreate(savedInstanceState); 

     this.requestWindowFeature(Window.FEATURE_NO_TITLE); //remove title bar 

     final FragmentManager fm = getSupportFragmentManager(); 

     // Create the list fragment and add it as our sole content. 
     if (fm.findFragmentById(android.R.id.content) == null) { 
      final StaggeredGridFragment fragment = new StaggeredGridFragment(); 
      fm.beginTransaction().add(android.R.id.content, fragment).commit(); 
     } 
     Intent i=getIntent(); 
     Bundle extras = i.getExtras(); 
     String tmp = extras.getString("myKey"); 

    } 


    private class StaggeredGridFragment extends Fragment implements AbsListView.OnScrollListener, AbsListView.OnItemClickListener { 
       //private StaggeredGridView mGridView; 
       private boolean mHasRequestedMore; 
       // private TilesAdapter mAdapter; 

       //private ArrayList<String> mData; 

       @Override 
       public void onCreate(final Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setRetainInstance(true); 
       } 

       @Override 
       public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { 
        return inflater.inflate(R.layout.activity_sgv, container, false); 
       } 

       @Override 
       public void onActivityCreated(final Bundle savedInstanceState) { 
        List<NameValuePair> params = new ArrayList<NameValuePair>(); 

        //Encapsulate all within a post cereate from a async task or call a blocking http call 
        super.onActivityCreated(savedInstanceState); 

        mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view); 

        if (savedInstanceState == null) { 
         final LayoutInflater layoutInflater = getActivity().getLayoutInflater(); 
         View header = layoutInflater.inflate(R.layout.list_item_header_footer, null); 
         mGridView.addHeaderView(header); 
        } 

        if (mAdapter == null) { 
         mAdapter = new TilesAdapter(getActivity(), R.id.summary1_value); 
        } 

        if (mData == null) { 
         mData = ActivityTileData.getLoginTileDataArray(getActivity()); 
        } 


        for (String data : mData) { 
         mAdapter.add(data); //Add each mData TileAdapter element to an mAdapter where it will be further broken down and used by the TileAdapter 
        } 

        mGridView.setAdapter(mAdapter); 
        mGridView.setOnScrollListener(this); 
        mGridView.setOnItemClickListener(this); 
       } 

       @SuppressLint("LongLogTag") 
       @Override 
       public void onScrollStateChanged(final AbsListView view, final int scrollState) { 
        Log.d(TAG, "onScrollStateChanged:" + scrollState); 
       } 

       @SuppressLint("LongLogTag") 
       @Override 
       public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) { 
        Log.d(TAG, "onScroll firstVisibleItem:" + firstVisibleItem + 
          " visibleItemCount:" + visibleItemCount + 
          " totalItemCount:" + totalItemCount); 
        // our handling 
        if (!mHasRequestedMore) { 
         int lastInScreen = firstVisibleItem + visibleItemCount; 
         if (lastInScreen >= totalItemCount) { 
          Log.d(TAG, "onScroll lastInScreen - so load more"); 
          mHasRequestedMore = true; 
          onLoadMoreItems(); 
         } 
        } 
       } 

       //Loads all of the objects from the getLoginTileData() if called 
       private void onLoadMoreItems() { 
        while(mAdapter.getCount()<mData.size()) { 
         //final ArrayList<String> sampleData = SampleData.generateSampleData(); 
         final ArrayList<String> loginTileData = ActivityTileData.getLoginTileDataArray(getActivity()); 
         for (String data : loginTileData) { 
          mAdapter.add(data.toString()); 
         } 
         // stash all the data in our backing store 
         mData.addAll(loginTileData); 
         // notify the adapter that we can update now 
         mAdapter.notifyDataSetChanged(); 
         mHasRequestedMore = false; 
        } 
       } 

       @Override 
       public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { 
        Toast.makeText(getActivity(), "Item Clicked: " + position, Toast.LENGTH_SHORT).show(); 
       } 
      } 
    // Progress Dialog 
    private ProgressDialog qDialog; 
    // JSON parser class 
    JSONParser jParser = new JSONParser(); 
    String url_login ="http://xxx/xxx.php"; 
    /** 
    * Background Async Task to Load all images by making HTTP Request 
    * */ 
    class GetLoginTiles extends AsyncTask<String, String, String> { 
     /** 
     * Before starting background thread Show Progress Dialog 
     * */ 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      qDialog = new ProgressDialog(StaggeredGridActivityFragment.this); 
      qDialog.setMessage("Please wait..."); 
      qDialog.setIndeterminate(false); 
      qDialog.setCancelable(false); 
      qDialog.show(); 
     } 

     @Override 
     protected String doInBackground(String... args) { 
      // Building Parameters 
      List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      // getting JSON string from URL 
      JSONObject jsonLogin = jParser.makeHttpRequest(url_login, "GET", params); 
      test=jsonLogin.toString(); 

      return jsonLogin.toString(); 
     } 

     /** 
     * After completing background task Dismiss the progress dialog 
     * **/ 
     protected void onPostExecute(String jsonString) { 
      // dismiss the dialog after getting all questions 
      qDialog.dismiss(); 
      // updating UI from Background Thread 
      runOnUiThread(new Runnable() { 
       public void run() { 
        /** 
        * Updating parsed JSON data into imagebuttons 
        * */ 
        test="local test has changed"; 
       } 
      }); 

     } 
    } 
} 

回答

0

我有一个替代的解决方案这是火的AsyncTask呼吁活动(之前的活动),并通过导致包,但我不喜欢这样的解决方案,它的刚性,并可能导致屏幕旋转问题。

这是做

覆盖的onSaveInstanceState保存旋转

的演员也看到here更多细节

编辑一个好办法:看来你是试图改变文本使用

test =“本地测试已更改”;

whaat你需要做的是活动传递到的AsyncTask然后

VIEWTYPEHERE button= (VIEWTYPEHERE) activity.findViewById(R.id.YOUR_VIEW"S_ID_HERE); 

button.setText( “”);

上后一对夫妇的音符

执行对UI线程运行时你并不需要一个新的可运行 你也忘了打电话给.RUN()就可以了

+0

嗯ok了。这似乎很混乱,但也许这是标准。为什么我不能在开始创建异步任务并在开始绘制之前获取数据?我在prev活动中这样做,它没有问题。 – Fearghal 2015-03-31 11:05:44

+0

我不认为这是一个好主意,尝试和暂停的onCreate反正 电话在前面的活动异步任务 显示进度对话框前和隐藏的后 ,然后通过临时演员,开始活动如果你保持异步任务作为它自己的类别不杂乱我有一个项目约20异步任务,他们都以这种方式工作 – MetalDragon 2015-03-31 11:09:33

+0

这是一个工厂的建议。很高兴听到我没有一百万英里了。你知道每个机会为什么我的片段活动拒绝停止创建吗? – Fearghal 2015-03-31 11:21:22