1

基本上,我正在開發一個包含4個選項卡的選項卡活動的應用程序,並且我正在使用actvityGroup來管理活動和backKey pressed()方法。當Android從其他活動回來時,活動再次從服務器重新載入整個數據

當我的應用第一次啓動時,它發送一個請求到服務器並顯示進度條(使用AsyncTask),如下圖所示。

enter image description here

這之後,會出現我的完整的用戶界面爲

enter image description here

它加載上的按鈕 「GO」 click事件新actvity(代碼如下所示)

btnGo.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
       Intent bookSearchResultActivityIntent = new Intent(); 
       bookSearchResultActivityIntent 
         .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       bookSearchResultActivityIntent.setClass(getParent(), 
         BookSearchResultActivity.class); 
       bookSearchResultActivityIntent.putExtra("LANG", language); 
       bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS", 
         edTxt_SearchField.getText().toString()); 
       MyActivityGroup activityStack = (MyActivityGroup) getParent(); 
       activityStack.push("BooksSearchActivity", 
         bookSearchResultActivityIntent); 

這裏也是我的ActivtyGroup.java代碼

public class MyActivityGroup extends ActivityGroup { 
    private Stack<String> stack; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     if (stack == null) { 
       stack = new Stack<String>(); 
     } 
     push("1stStackActivity", new Intent(this, Home.class)); 
    } 

    @Override 
    public void finishFromChild(Activity child) { 
     pop(); 
    } 

    @Override 
    public void onBackPressed() { 
     pop(); 
    } 

    public void push(String id, Intent intent) { 
     Window window = getLocalActivityManager().startActivity(id, 
         intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)); 
     if (window != null) { 
      stack.push(id); 
      setContentView(window.getDecorView()); 
     } 
    } 

    public void pop() { 
     if (stack.size() == 1) { 
      finish(); 
     } 
     LocalActivityManager manager = getLocalActivityManager(); 
     manager.destroyActivity(stack.pop(), true); 
     if (stack.size() > 0) { 
      Intent lastIntent = manager.getActivity(stack.peek()).getIntent() 
          .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
      Window newWindow = manager.startActivity(stack.peek(), lastIntent); 
      setContentView(newWindow.getDecorView()); 
     } 
    } 
} 

好吧,現在我的問題是,當我按backKey();它應該達到以前的行動。

  • 是的,它涉及到上一個活動,但它再次向服務器發送請求並再次顯示進度條並加載,直到服務器發送響應。這浪費了我的時間。
  • 我只想加載HomeTab一次(當我玩這個應用程序時)。不是一次又一次
  • 我也加入

    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

同時啓動活動

  • 還增加了以下的menifest.xml文件代碼

    機器人:configChanges = 「鍵盤| keyboardHidden |方向」

但還沒有工作。

,這裏是我的主頁選項卡的代碼(請求發送到服務器onCreate方法)

public class Home extends Activity { 
    /** Called when the activity is first created. */ 
    static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx"; 
    static final String KEY_ITEM = "Book"; // parent node 
    static final String KEY_BOOKAUTHOR = "BookAuthor"; 
    static final String KEY_BOOKDATEPUBLISHED = "DatePublished"; 
    static final String KEY_BOOKTITLE = "BookTitle"; 
    static final String KEY_BOOKCODE = "BookCode"; 
    static final String KEY_BOOKIMAGE = "BookImage"; 

    String searchLang; 
    String searchKeywords; 
    LayoutInflater inflater = null; 

    ArrayList<String> BookTitle = new ArrayList<String>(); 
    ArrayList<String> BookCoverPhotos = new ArrayList<String>(); 
    ArrayList<String> BookAuther = new ArrayList<String>(); 
    ArrayList<String> BookPublishDate = new ArrayList<String>(); 
    ArrayList<String> ImageByte = new ArrayList<String>(); 
    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>(); 

    Context ctx = this; 
    Activity act = this; 
    Context context = Home.this; 
    URL bookImageURL = null; 
    Bitmap bitMapImage = null; 

    Button btnGo; 
    Spinner spnrLanguage; 
    Spinner spnrBrowseBy; 
    String language; 
    EditText edTxt_SearchField; 

    GridView gridView; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     // setContentView(R.layout.home_activity); 
     View viewToLoad = LayoutInflater.from(this.getParent()).inflate(
       R.layout.home_activity, null); 
     this.setContentView(viewToLoad); 

     gridView = (GridView) findViewById(R.id.gridview); 
     spnrLanguage = (Spinner) findViewById(R.id.spnrLanguage); 
     spnrBrowseBy = (Spinner) findViewById(R.id.spnrBrowseBy); 
     edTxt_SearchField = (EditText) findViewById(R.id.EditTxt_Search); 
     btnGo = (Button) findViewById(R.id.btn_GO); 

     ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     // checking for availbe internet Connection 
     if (cm.getActiveNetworkInfo() != null 
       && cm.getActiveNetworkInfo().isAvailable() 
       && cm.getActiveNetworkInfo().isConnected()) { 

      new UIThread().execute(URL, "Imam Ali"); 
     } 

     gridView.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> arg0, View arg1, int pos, 
        long arg3) { 

       Toast.makeText(context, BookTitle.get(pos), Toast.LENGTH_SHORT) 
         .show(); 

       Intent bookSearchResultActivityIntent = new Intent(); 
       bookSearchResultActivityIntent.setClass(getParent(), 
         BookOverView.class); 
       bookSearchResultActivityIntent.putExtra("BITMAP", 
         bitmapArray.get(pos)); 
       bookSearchResultActivityIntent.putExtra("BOOK_TITLE", 
         BookTitle.get(pos)); 
       bookSearchResultActivityIntent.putExtra("BOOK_AUTHOR", 
         BookAuther.get(pos)); 
       bookSearchResultActivityIntent.putExtra("BOOK_PUBLISH_DATE", 
         BookPublishDate.get(pos)); 

       MyActivityGroup activityStack = (MyActivityGroup) getParent(); 
       activityStack.push("BookOverViewActivity", 
         bookSearchResultActivityIntent); 

      } 
     }); 

     // //////////////////// Spinners handler///////////////////////// 
     ArrayAdapter<String> adapterLanguage = new ArrayAdapter<String>(
       context, android.R.layout.simple_spinner_item, getResources() 
         .getStringArray(R.array.spnr_language_array)); 
     ArrayAdapter<String> adapterBrowseBy = new ArrayAdapter<String>(
       context, android.R.layout.simple_spinner_item, getResources() 
         .getStringArray(R.array.spnr_browse_array)); 
     spnrLanguage.setAdapter(adapterLanguage); 
     spnrBrowseBy.setAdapter(adapterBrowseBy); 

     spnrLanguage.setOnItemSelectedListener(new OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, 
        long arg3) { 
       Toast.makeText(getParent(), 
         spnrLanguage.getItemAtPosition(pos) + "", 
         Toast.LENGTH_SHORT).show(); 
       language = spnrLanguage.getItemAtPosition(pos).toString(); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> arg0) { 

      } 
     }); 

     spnrBrowseBy.setOnItemSelectedListener(new OnItemSelectedListener() { 

      @Override 
      public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, 
        long arg3) { 
       Toast.makeText(context, 
         spnrBrowseBy.getItemAtPosition(pos) + "", 
         Toast.LENGTH_SHORT).show(); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> arg0) { 

      } 
     }); 

     // ////////////////////Search Button Handler///////////////// 

     btnGo.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       if (!edTxt_SearchField.getText().toString().equals("")) { 
        Intent bookSearchResultActivityIntent = new Intent(); 
        bookSearchResultActivityIntent 
          .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        bookSearchResultActivityIntent.setClass(getParent(), 
          BookSearchResultActivity.class); 
        bookSearchResultActivityIntent.putExtra("LANG", language); 
        bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS", 
          edTxt_SearchField.getText().toString()); 
        MyActivityGroup activityStack = (MyActivityGroup) getParent(); 
        activityStack.push("BooksSearchActivity", 
          bookSearchResultActivityIntent); 

       } else { 
        Toast.makeText(context, "Search Field Empty", 
          Toast.LENGTH_SHORT).show(); 
       } 

      } 
     }); 

    } 

    private class UIThread extends AsyncTask<String, Integer, String> { 

     ProgressDialog progressDialog; 

     @Override 
     protected void onPreExecute() { 
      // TODO Auto-generated method stub 
      super.onPreExecute(); 
      progressDialog = ProgressDialog.show(getParent(), 
        "Acumlating Books from server...", 
        "This may Take a few seconds.\nPlease Wait..."); 
     } 

     @Override 
     protected String doInBackground(String... params) { 

      String URL = params[0]; 
      String searchKeywords = params[1]; 

      XMLParser parser = new XMLParser(); 
      String XMLString = parser.getXmlFromUrl(URL, searchKeywords, 
        searchLang); 
      // Log.i("XML Response", XMLString); 

      Document doc = parser.getDomElement(XMLString); 

      NodeList nl = doc.getElementsByTagName(KEY_ITEM); 

      // looping through all item nodes <item> 
      for (int i = 0; i < nl.getLength(); i++) { 
       Element e = (Element) nl.item(i); 

       BookTitle.add(parser.getValue(e, KEY_BOOKTITLE)); 
       BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/" 
         + parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg"); 
       BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR)); 
       BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED)); 
       Log.i("URLs", BookCoverPhotos.toString()); 
      } 
      for (int i = 0; i < BookAuther.size(); i++) { 

       try { 
        bookImageURL = new URL(BookCoverPhotos.get(i)); 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
        Log.i("URL", "ERROR at image position" + i + ""); 
       } 

       try { 
        bitMapImage = BitmapFactory.decodeStream(bookImageURL 
          .openConnection().getInputStream()); 
        bitmapArray.add(bitMapImage); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
        Log.i("BITMAP", "ERROR" + i); 
       } 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      progressDialog.dismiss(); 
      ImageAdapter adapter = new ImageAdapter(getBaseContext(), act); 
      gridView.setAdapter(adapter); 
     } 
    } 

    public class ImageAdapter extends BaseAdapter { 

     public ImageAdapter(Context c) { 
      context = c; 
     } 

     // ---returns the number of images--- 
     public int getCount() { 
      // return imageIDs.length; 
      return bitmapArray.size(); 
      // return 6; 
     } 

     public ImageAdapter(Context ctx, Activity act) { 

      inflater = (LayoutInflater) act 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     } 

     // ---returns the ID of an item--- 
     public Object getItem(int position) { 
      return position; 
     } 

     public long getItemId(int position) { 
      return position; 
     } 

     // ---returns an ImageView view--- 
     public View getView(int position, View convertView, ViewGroup parent) { 

      // ImageView bmImage; 

      final ViewHolder holder; 
      View vi = convertView; 
      if (convertView == null) { 
       vi = inflater.inflate(R.layout.grid_style, parent, false); 
       holder = new ViewHolder(); 
       holder.txt_BooksTitle = (TextView) vi 
         .findViewById(R.id.txt_BookTitle); 

       holder.img_BookCoverPhoto = (ImageView) vi 
         .findViewById(R.id.imgBookCover); 
       vi.setTag(holder); 
      } else { 

       holder = (ViewHolder) vi.getTag(); 
      } 
      holder.txt_BooksTitle.setText(BookTitle.get(position) + ""); 
      holder.img_BookCoverPhoto.setImageBitmap(bitmapArray.get(position)); 
      return vi; 
     } 
    } 

    class ViewHolder { 
     TextView txt_BooksTitle; 
     ImageView img_BookCoverPhoto; 
    } 
} 
  • ,請對我的活動組類一看,並告訴我應該怎麼做。 在此先感謝
+0

如果刪除'FLAG_ACTIVITY_CLEAR_TOP' FRM所有活動開始意圖,然後它應該工作,因爲你想要 –

+0

imran你會解釋一點嗎? –

回答

1

在Home標籤活動中加載數據時,將其放入一些靜態數組中。

ArrayList<String> BookTitle = new ArrayList<String>(); 
    ArrayList<String> BookCoverPhotos = new ArrayList<String>(); 
    ArrayList<String> BookAuther = new ArrayList<String>(); 
    ArrayList<String> BookPublishDate = new ArrayList<String>(); 
    ArrayList<String> ImageByte = new ArrayList<String>(); 
    ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>(); 

從對代碼的快速一瞥,讓他們static ArrayList<...> ... = null;並檢查onCreate()方法中:

if(BookTitle == null) 
{ 
    //needs init 
    BookTitle = new ArrayList<String>(); 
    //perform connect to server and parse response. 
} 

當應用程序活動主頁選項卡停止然後重新啓動,該數據將在內存中已經它會跳過if條款保留舊數據以供重複使用。

請務必將清除靜態變量當你真的想殺死應用程序 - 在一個退出按鈕點擊,調用一個靜態方法來初始化他們再次空,或者如果你想他們是有效的讓我們說12小時,將時間戳存儲在一個靜態變量中,並且每次你殺死/暫停主要活動時對其執行檢查(如果它有日期,則檢查是否已經過了12小時,如果是,清除靜態變量內容)

這是快速簡單的方法。如果您不想處理靜態變量,另一種方法是將它們存儲在應用程序數據庫中。

有很多的選擇,關鍵是你還挺有它們標記爲「全球持久」的數據與靜態,或將其存儲在DATABSE /文件等

+0

似乎是一個很好的解決方案。讓我試試看。感謝LonWolf –

+0

親愛的它的工作在一定程度上。但是當我回到以前的活動它現在不填充我的GridView。顯示空的活動。它應該顯示書籍(如圖2所示)。請幫忙。 –

+0

確保你在我寫的檢查之外調用你的gridview填充。換句話說,檢查gridview是否有孩子,如果沒有,填充駐留在靜態變量中的數據。代碼中有關函數調用的簡單錯誤。只要你不殺死整個應用程序,靜態變量仍然存在,所以只需對它們執行操作 - 在你的情況下,gridview重新填充。我經常在我的onCreate()方法中檢查兩種情況,並且他們從來沒有讓我失望:) – LonWolf

相關問題