如何使用http从服务器上的文件将text设置为textview

时间:2019-03-09 08:41:10

标签: java android aide-ide

尝试学习如何显示每隔几分钟在远程Web服务器(通过http提供)上的文件中更改的文本。目前,我只想学习如何从文本文件中读取内容。以下是我的学习应用程序中的MainActivity。我知道这很丑,但我仍在学习。如果知道的话,我会将其包装在代码标签中,

package com.mycompany.myapp3;

import android.app.*;
import android.os.*;
import android.widget.*;
import java.net.*;
import java.io.*;
import android.widget.TextView;

public class MainActivity extends Activity 
{

    String str = null;
// Change the text
    public void textviewsongset (){
        TextView textView = (TextView)findViewById(R.id.songtextview);
        textView.setText("Now Playing: "+str);
    }
    // Get the currently playing song title
    public void getCurrentSong(){

        try {

            // Create a URL for the desired page
            URL url = new URL("http://adovex.com/test.txt");

            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str = in.readLine();
            in.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getCurrentSong();
        TextView textView = (TextView)findViewById(R.id.songtextview);
        textView.setText("Now Playing: "+str);  
    }
}

0 个答案:

没有答案