Android:尝试将API中的数据加载到列表视图时,应用程序崩溃

时间:2017-04-19 16:54:12

标签: java android api listview

我试图将API中的联赛表加载到列表视图中,但是当我使用联赛表访问活动时,应用程序仍然崩溃,有什么想法吗?

FootballAysncTask.Java

package gatt.geordey.homeassignment;

import android.os.AsyncTask;

import org.json.JSONException;

/**
 * Created by Geordey on 07/04/2017.
 */

public class FootballAsyncTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params){

        String data = ((new FootballHttpClient()).getStandings());

        String result = "";
        try {
            result =JSONFootballParser.getTeamName(data);
        }catch (JSONException e) {
            e.printStackTrace();
        }

        return result;
    }
}

FootballHttplient.Java

package gatt.geordey.homeassignment;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Geordey on 07/04/2017.
 */

public class FootballHttpClient {

    private static String BASE_URL = "http://api.football-data.org/v1/";

    public String getStandings(){
        HttpURLConnection con = null;
        InputStream is = null;

        try {
            String url = BASE_URL + "competitions/438/leagueTable";

            con = (HttpURLConnection) ( new URL(url)).openConnection();
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.connect();

            //read the response
            StringBuffer buffer = new StringBuffer();
            is = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            while (  (line = br.readLine()) != null )
                buffer.append(line + "\r\n");

            is.close();
            con.disconnect();

            return buffer.toString();
        }
        catch(Throwable t) {
            t.printStackTrace();
        }
        finally {
            try { is.close(); } catch(Throwable t) {}
            try { con.disconnect(); } catch(Throwable t) {}
        }

        return null;
    }
}

JsonFootballParser.Java

package gatt.geordey.homeassignment;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Geordey on 07/04/2017.
 */

public class JSONFootballParser {

    public static String getTeamName(String data) throws JSONException{
        JSONObject jObj = new JSONObject(data);

        JSONObject mainObj = jObj.getJSONObject("standing");
        return mainObj.getString("teamName");
    }

}

Standings.Java

package gatt.geordey.homeassignment;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

public class Standings extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_standings);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        TextView test = (TextView) findViewById(R.id.test);
        ListView standings = (ListView) findViewById(R.id.standings);

        ArrayAdapter<String> listAdapter;
        ArrayList teamNames = null;

        FootballAsyncTask task = new FootballAsyncTask();
        try{
            String teamName = task.execute().get();
            teamNames.add(teamName);

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        listAdapter = new ArrayAdapter<String>(this, R.layout.row, teamNames);
        standings.setAdapter(listAdapter);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

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

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_teams) {
            // Handle the team intent
            Intent showTeams = new Intent(this,Teams.class);
            startActivity(showTeams);

        } else if (id == R.id.nav_standings) {
            // Handle the Standings intent
            Intent showStandings = new Intent(this,Standings.class);
            startActivity(showStandings);

        } else if (id == R.id.nav_fixtures) {
            // Handle the Fixtures intent
            Intent showFixtures = new Intent(this, Fixtures.class);
            startActivity(showFixtures);

        } else if (id == R.id.nav_favourites) {
            // Handle the Favourites intent
            Intent showFavourites = new Intent(this, Favourites.class);
            startActivity(showFavourites);

        } else if (id == R.id.nav_logout){
            // Handle the Logout intent
            // End Session

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Error Image

2 个答案:

答案 0 :(得分:0)

我认为task.execute()。get();返回null

只尝试使用task.execute();并尝试使用recyclerview

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
     .....
    }

当你使用listvew并填充数据时,你需要getview方法

答案 1 :(得分:0)

您永远不会初始化teamNames列表。

ArrayList teamNames = null;

...

teamNames.add(teamName);

使用空列表实例化数组适配器,并在设置为列表视图时崩溃。

代码到此为止的原因是因为您正在捕获异常。您可以在白色打印的屏幕截图上看到堆栈跟踪。