[英]Android: App crashing when trying to load Data from API into a listview
I'm trying to load a league table from an API into a listview, but the app keeps crashing when I access the activity with the league table, any thoughts ? 我正在尝试将API的联赛表加载到列表视图中,但是当我使用联赛表访问活动时,该应用始终崩溃。
FootballAysncTask.Java 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 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 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 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;
}
}
i think task.execute().get(); 我认为task.execute()。get(); returning null 返回null
just try with only task.execute(); 只需尝试使用task.execute(); And try to use recyclerview 并尝试使用recyclerview
@Override
public View getView(int position, View convertView, ViewGroup parent) {
.....
}
when you use listvew and filling with data that time you need getview method 当您使用listvew并填充该时间的数据时,您需要getview方法
You are never initializing the teamNames
list. 您永远不会初始化teamNames
列表。
ArrayList teamNames = null;
...
teamNames.add(teamName);
The array adapter is instantiated with the null list, and crashes when is set to the listview. 数组适配器使用空列表实例化,当设置为列表视图时崩溃。
The reason why the code gets until that point is because you are catching exceptions. 直到那个时候代码才能得到的原因是因为您正在捕获异常。 You can see the stacktrace on the screenshot printed in white. 您可以在以白色打印的屏幕截图上看到stacktrace。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.