【问题标题】:BufferedReader is null in Android but not in Java when attempting to connect to internet尝试连接到 Internet 时,BufferedReader 在 Android 中为空,但在 Java 中不为空
【发布时间】:2013-08-28 20:43:41
【问题描述】:

我有一个最初用 Java 创建的程序,我现在正尝试将其格式化为 Android 应用程序。该程序在 Java 控制台中的工作方式与我希望的一样,但当我将其作为 Android 应用程序运行时则不然。

这是我的活动类的相关代码:

public class ViewTeamStatsActivity extends Activity {

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


    ArrayList<Team> teams = new ArrayList<Team>();

    //Want to make sure there is a network available.  
    //This always returns true since I added the relevant permissions in the manifest
    if (isNetworkAvailable()) {
    Main m = new Main();
    teams = m.download();
    }

所以它调用了我的 Main 类,该类最终调用了 Retrieve 类。然后这个类应该从特定的 url 检索 HTML 并将内容解析为可用数据并将其作为 ArrayList 返回。

//Retrieves the HTML from the specified URL and then parses it into usable data.
public ArrayList<Game> Retrieve(String url)  {
    this.url = url;
    ArrayList<Game> data = new ArrayList<Game>();
    try {
        URL my_url = new URL(url);
        URLConnection conn = my_url.openConnection();

        //The following returns null when run "as an Android Application" but not in the Java console.  Why?
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        sort.addBufferedReader(br);
        data = sort.sort();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return data;
}

所以我想我的问题是,如果程序在 Android 上运行,为什么 BufferedReader 'br' 为空?我的代码缺少什么?

注意:我已经添加了相关权限,所以这里不是问题。

【问题讨论】:

    标签: java android nullpointerexception bufferedreader


    【解决方案1】:

    在你的情况下,打开连接返回 null 所以首先检查你是否有 Internet 权限:

    使用权限 android:name="android.permission.INTERNET"/

    【讨论】:

    • 我已经解决了这个问题stackoverflow.com/questions/4837050/…对不起:(
    • 您链接到的问题的解决方案需要在清单中添加权限的人。我已经这样做了,所以这一定不是解决方案。
    猜你喜欢
    • 2015-12-03
    • 2022-01-18
    • 2019-04-09
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多