0

我的应用程序总是在此行断开连接 (BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream()));)。我想从 url 中读取 JSON-Data 并将其添加到我的列表中。这段代码有什么问题请帮助我:)

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.os.StrictMode;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends Activity {
    final ArrayList names =new ArrayList();
    final ArrayList<City> cities = new ArrayList<City>();

    String urlMain= "http://************";

    //JSON names
private static final String TAG_CITIES="cities";
private static final String TAG_NAME="nameDe";
private static final String TAG_LNG="location_lng";
private static final String TAG_LAT="location_lat";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView list=(ListView) findViewById(R.id.listViewMain);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, this.names);
        list.setAdapter(adapter);

        ArrayList<HashMap<String, String>> citiesList = new ArrayList<HashMap<String, String>>();

        //get JSON

        try{
            URL url= new URL(urlMain);
            BufferedReader in =new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            String content="";
            while ((str = in.readLine()) !=null){
                content+=str;
            }
            in.close();
            JSONArray ja=new JSONArray(content);
            for (int i=0; i <ja.length();i++){
                String nameDe=ja.getJSONObject(i).getString("nameDe");
                Double lat=ja.getJSONObject(i).getDouble("location_lat");
                Double lng=ja.getJSONObject(i).getDouble("location_lng");
                cities.add(new City(nameDe,lat,lng));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }catch (JSONException e) {
            e.printStackTrace();
        }
        this.locationUpdate();
    }

    protected void locationUpdate() {
        LocationListener listener = new MyLocationListener();
        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 50, listener);
        Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        final ListView list = (ListView) findViewById(R.id.listViewMain);
        for (int i = 0;i<cities.size();i++){
            float[] results= new float[3];
            Location.distanceBetween(location.getLatitude(),location.getLongitude(),cities.get(i).getLat(),cities.get(i).getLng(),results);
            cities.get(i).setDistance(results[0]);
        }
        java.util.Collections.sort(cities);
        this.names.clear();
        for (City city : cities){
            this.names.add(city.getName());
        }
        list.refreshDrawableState();
    }


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

}
4

1 回答 1

0
`enter code here`Try this code. It woked for me..

private String downloadFileFromInternet(String url)
    {
        if(url == null /*|| url.isEmpty() == true*/)
            new IllegalArgumentException("url is empty/null");
        StringBuilder sb = new StringBuilder();
        InputStream inStream = null;
        try
        {
            url = urlEncode(url);
            URL link = new URL(url);
            inStream = link.openStream();
            int i;
            int total = 0;
            byte[] buffer = new byte[8 * 1024];
            while((i=inStream.read(buffer)) != -1)
            {
                if(total >= (1024 * 1024))
                {
                    return "";
                }
                total += i;
                sb.append(new String(buffer,0,i));
            }
        }catch(Exception e )
        {
            e.printStackTrace();
            return null;
        }catch(OutOfMemoryError e)
        {
            e.printStackTrace();
            return null;
        }
        return sb.toString();
    }

    private String urlEncode(String url)
    {
        if(url == null /*|| url.isEmpty() == true*/)
            return null;
        url = url.replace("[","");
        url = url.replace("]","");
        url = url.replaceAll(" ","%20");
        return url;
    }
}*

还要在清单文件中检查此权限:

于 2013-08-07T00:07:44.300 回答