gpt4 book ai didi

android - 当从 Android 中的其他 Activity 返回时, Activity 再次从服务器重新加载全部数据

转载 作者:行者123 更新时间:2023-11-30 03:54:21 25 4
gpt4 key购买 nike

基本上,我正在开发一个应用程序,它有一个包含 4 个选项卡的选项卡 Activity ,我还使用 actvityGroup 来管理 Activity 和 backKey pressed() 方法。

当我的应用首次启动时,它会向服务器发送请求并显示进度条(使用 AsyncTask),如下图所示。

enter image description here

在此之后,我的完整 UI 显示为

enter image description here

它在按钮“GO”的点击事件上加载新的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() 时;应该会出现在之前的 Activity 中。

  • 是的,它涉及到之前的 Activity ,但它再次向服务器发送请求并再次显示进度条并加载直到服务器发送响应。这浪费了我的时间。
  • 我只想加载 HomeTab 一次(当我玩应用程序时)。不是一次又一次
  • 我也在添加

    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

开始 Activity 时

  • 还在 menifest.xml 文件中添加了以下代码

    android:configChanges="keyboard|keyboardHidden|orientation"

但还没有工作。

这是我的主页选项卡的代码(它在 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;
}
}
  • 请看一下我的 Activity 组课,告诉我该怎么做。提前致谢

最佳答案

在主页选项卡 Activity 中加载数据时,将其放入一些静态数组中。

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

当应用程序 Activity 主页选项卡停止然后重新启动时,数据将已经在内存中并且它将跳过 if保留旧数据以供重复使用的条款。

确保在您真的想终止应用程序时清除静态变量 - 单击退出按钮,调用静态方法再次将它们初始化为 null,或者如果您希望它们在 12 小时内有效, 记住静态变量中的时间戳,每次你杀死/暂停主要 Activity 时对其进行检查(是否为空或有日期,如果有日期,检查是否已经过去 12 小时,如果是,清除静态变量内容)

这是一种快速简便的方法。如果您不想处理静态变量,另一种方法是将它们存储在应用程序数据库中。

有很多选项,关键是你必须将它们标记为静态的“全局持久”数据,或者将它们存储在数据库/文件等中。

关于android - 当从 Android 中的其他 Activity 返回时, Activity 再次从服务器重新加载全部数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13581805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com