Android:从URL获取静态字符串值

时间:2015-09-11 15:41:11

标签: android

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

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

我试图将该号码提取到我的Android应用并将其显示在textview上

我尝试过这种方法,但它在模拟器上没有显示任何内容 在清单

上设置了互联网和网络权限

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();
    }
}

1 个答案:

答案 0 :(得分:1)

请尝试这个答案:

首先,创建一个这样的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);
    }

}

然后在你的活动类中,像这样实现上面的接口;

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);
   }

}