gpt4 book ai didi

java - 在异步 http 请求下加载屏幕

转载 作者:行者123 更新时间:2023-12-01 18:27:17 25 4
gpt4 key购买 nike

启动时,会执行一个异步类,该类会抓取网站以获取信息。在此期间,在收集的信息填充到 ListView 之前,屏幕保持空白。有什么办法可以在这段时间添加加载屏幕吗?

我查看了这个( Add the loading screen in starting of the android application ),但我认为这不是我需要的,因为我不知道请求需要多长时间。

感谢您的宝贵时间。

看到一些答案后,我修改了代码,但两者都不可见。这是我的 Activity main 的 xml 文件。还有一个用于 ListView 中默认 TextView 元素的 TextView 布局 xml 文件。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_centerInParent="true"/>


<ListView
android:layout_width="match_parent"
android:layout_height="507dp"
android:id="@+id/listView"
android:smoothScrollbar="true" />



</RelativeLayout>

这是主要 Activity 的代码:

    package adam.example.com.stockexample;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;


public class MainActivity extends Activity {
private int index=-1;



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final ListView ListStock= (ListView)findViewById(R.id.listView);
final ArrayList<String>symbols= new ArrayList<String>();
final ProgressBar pb= (ProgressBar)findViewById(R.id.progressBar);
List<StockElement> stats= new ArrayList<StockElement>();
List<String> StringList= new ArrayList<String>();

pb.setVisibility(View.VISIBLE);

try {
InputStream inputStream = openFileInput("stocks.txt");

if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();

while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}

inputStream.close();
String []ret = stringBuilder.toString().split(",");

for(int x=0;x<ret.length;x++){
symbols.add(ret[x]);
}

}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}


for(int x=0;x<symbols.size();x++){
stats.add(addStock(symbols.get(x)));
}
for(int x=0;x<stats.size();x++){
StringList.add(stats.get(x).toString());
}


final ArrayAdapter<String> stockAdapter=
new ArrayAdapter<String>(
getApplicationContext(),
R.layout.list_item_textview,
R.id.list_item_textview,
StringList);
pb.setVisibility(View.GONE);
ListStock.setAdapter(stockAdapter);

final AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setMessage("Are you sure you would like to delete this?")
.setTitle("Warning")
.setPositiveButton("No", null)
.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
stockAdapter.remove(stockAdapter.getItem(index));
symbols.remove(index);

WriteBack(symbols);

stockAdapter.notifyDataSetChanged();
}
});


OnItemClickListener itemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView

TextView ItemText = (TextView) container;
String selectedItemText=(String)ItemText.getText();
String symbol =selectedItemText.substring(selectedItemText.indexOf(":")+1,selectedItemText.lastIndexOf(")"));

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com/finance?q="+symbol));
startActivity(browserIntent);
}
};

AdapterView.OnItemLongClickListener itemLongClickListener= new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?>parent, View container, final int position, long id){
TextView ItemText= (TextView) container;
String selectedItemText= (String) ItemText.getText();
index=position;

builder.show();
return true;

}
};

ListStock.setOnItemClickListener(itemClickListener);
ListStock.setOnItemLongClickListener(itemLongClickListener);
}

public void WriteBack(ArrayList <String> list){
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("stocks.txt", Context.MODE_PRIVATE));
for(int x=0;x<list.size()-1;x++){
outputStreamWriter.append(list.get(x)+",");
}
outputStreamWriter.append(list.get(list.size()-1));

outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

public StockElement addStock(String sym){
try {
String s = new HTTPRequest().execute("http://www.google.com/finance?q="+sym).get();

String symbol= s.substring(s.indexOf("<title>")+7,s.indexOf("</title>"));
String name= symbol.substring(0,symbol.indexOf(":"));
symbol=symbol.substring(symbol.indexOf(":")+2,symbol.indexOf(" quotes"));

String price= s.substring(s.indexOf("<meta itemprop=\"price\"")+25,s.indexOf("<meta itemprop=\"price\"")+50);

price= price.substring(price.indexOf("\"")+1,price.lastIndexOf("\""));

String priceChange= s.substring(s.indexOf("<meta itemprop=\"priceChange\"")+36,s.indexOf("<meta itemprop=\"priceChange\"")+60);

priceChange=priceChange.substring(priceChange.indexOf("\"")+1,priceChange.lastIndexOf("\""));

String percent= s.substring(s.indexOf("<meta itemprop=\"priceChangePercent\"")+36,s.indexOf("<meta itemprop=\"priceChangePercent\"")+60);

percent=percent.substring(percent.indexOf("\"")+1,percent.lastIndexOf("\""));

return new StockElement(name,symbol,price,priceChange,percent);

} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}catch (NullPointerException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
return null;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

最佳答案

您可以在 Activity 的布局中添加一个 ProgresBar(圆圈)。为了将加载圆圈设置在屏幕中间,您可以将布局设置为如下所示。

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="@null"
android:listSelector="@android:color/transparent"
android:layout_alignParentTop="true"/>

<ProgressBar
android:id="@+id/progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/> //to make it appear in the middle of screen

现在在您的 Activity

ProgressBar pb;
pb = (ProgressBar) findViewById(R.id.progress);

现在,当任务正在进行时,即联系您的网站时,您可以设置 pb.setVisibility(View.VISIBLE);

一旦你的任务完成就可以设置pb.setVisibility(View.GONE);

希望有帮助。

关于java - 在异步 http 请求下加载屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633508/

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