gpt4 book ai didi

Android:从 URL 获取一个值作为静态字符串

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

网址 = http://troyka.esy.es/numberofrows.php

如果你把它放在你的浏览器中,你会得到一个数字(目前是 9)

我正在尝试将该号码拉到我的 android 应用程序并将其显示在 TextView 上

我已经尝试过这种方法,但它在模拟器上没有显示任何内容互联网和网络权限在 list 上设置

textview id = "textView"

我做错了什么?

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;


public class MainActivity extends Activity {
public static String ans;
private TextView T1;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

T1 = new TextView(this);

T1 = (TextView) findViewById(R.id.textView);
T1.setText(ans);

}
public String getDATA() throws IOException {
String fullString = "";
URL url = new URL("http://troyka.esy.es/numberofrows.php");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
public void setAns() throws IOException {
ans = getDATA();
}
}

最佳答案

请试试这个答案:

首先,像这样创建一个 AsyncTask 类来在 android 主线程之外为您执行实际的 HTTP 请求:

public class FetchColumnAsync extends AsyncTask<String, Void, String> 
{
private Context mContext;

public FetchColumnAsync( Context ctx){
this.mContext = ctx;
}

protected String doInBackground(String... urls)
{
String fullString = "";
try{

URL url = new URL(urls[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
}catch(Exception e ){
e.getMessage();
}

return fullString;
}

@Override
protected void onPostExecute(String value){
try{
((OnValueFetchedListener) mContext).onValueFetched(value);
}catch(ClassCastException e){}
}

public interface OnValueFetchedListener{
void onValueFetched(String columns);
}

}

然后在你的 Activity 类中,像这样实现上面的接口(interface);

public class MainActivity extends Activity implements FetchColumnAsync.OnValueFetchedListener{
public static String ans;
private TextView T1;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


T1 = (TextView) findViewById(R.id.textView);

//missing piece of code here
new FetchColumnAsync(this).execute("http://troyka.esy.es/numberofrows.php");

}

@Override
public void onValueFetched(String value){
T1.setText(value);
}

}

关于Android:从 URL 获取一个值作为静态字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32527250/

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