这些是我在手机上运行应用程序后得到的日志
02-24 23:40:03.153: E/AndroidRuntime(32501): FATAL EXCEPTION: main 02-24 23:40:03.153: E/AndroidRuntime(32501): Process: sunshine.com.example.himanshu.sunshine, PID: 32501 02-24 23:40:03.153: E/AndroidRuntime(32501): android.os.NetworkOnMainThreadException 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) 02-24 23:40:03.153: E/AndroidRuntime(32501): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110) 02-24 23:40:03.153: E/AndroidRuntime(32501): at libcore.io.IoBridge.connectErrno(IoBridge.java:137) 02-24 23:40:03.153: E/AndroidRuntime(32501): at libcore.io.IoBridge.connect(IoBridge.java:122) 02-24 23:40:03.153: E/AndroidRuntime(32501): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183) 02-24 23:40:03.153: E/AndroidRuntime(32501): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456) 02-24 23:40:03.153: E/AndroidRuntime(32501): at java.net.Socket.connect(Socket.java:882) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.okhttp.internal.Platform.connectSocket(Platform.java:139) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.okhttp.Connection.connect(Connection.java:148) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106) 02-24 23:40:03.153: E/AndroidRuntime(32501): at sunshine.com.example.himanshu.sunshine.MainActivity$ForecastFragment$FetchWeatherTask.doInBackground(MainActivity.java:139) 02-24 23:40:03.153: E/AndroidRuntime(32501): at sunshine.com.example.himanshu.sunshine.MainActivity$ForecastFragment.onOptionsItemSelected(MainActivity.java:92) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v4.app.Fragment.performOptionsItemSelected(Fragment.java:1894) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v4.app.FragmentManagerImpl.dispatchOptionsItemSelected(FragmentManager.java:2034) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:356) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.app.ActionBarActivity.onMenuItemSelected(ActionBarActivity.java:155) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.app.ActionBarActivityDelegate$1.onMenuItemSelected(ActionBarActivityDelegate.java:74) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.app.ActionBarActivityDelegateBase.onMenuItemSelected(ActionBarActivityDelegateBase.java:556) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:802) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:949) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:939) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.support.v7.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:187) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.widget.AdapterView.performItemClick(AdapterView.java:300) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.widget.AbsListView.performItemClick(AbsListView.java:1143) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.widget.AbsListView$PerformClick.run(AbsListView.java:3044) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.widget.AbsListView$3.run(AbsListView.java:3833) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.os.Handler.handleCallback(Handler.java:739) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.os.Handler.dispatchMessage(Handler.java:95) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.os.Looper.loop(Looper.java:135) 02-24 23:40:03.153: E/AndroidRuntime(32501): at android.app.ActivityThread.main(ActivityThread.java:5312) 02-24 23:40:03.153: E/AndroidRuntime(32501): at java.lang.reflect.Method.invoke(Native Method) 02-24 23:40:03.153: E/AndroidRuntime(32501): at java.lang.reflect.Method.invoke(Method.java:372) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) 02-24 23:40:03.153: E/AndroidRuntime(32501): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
这是我的MainActivity.java文件:
package sunshine.com.example.himanshu.sunshine; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.os.Build; import android.widget.ArrayAdapter; import android.widget.ListView; import java.io.BufferedReader; import java.lang.reflect.Array; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.io.*; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new ForecastFragment()) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, 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); } /** * A placeholder fragment containing a simple view. */ public static class ForecastFragment extends Fragment { public ForecastFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecast_fragment,menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id=item.getItemId(); if(id==R.id.refresh_action) { FetchWeatherTask fetch=new FetchWeatherTask(); fetch.doInBackground(); return true; } return super.onOptionsItemSelected(item); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); String forecastArray[] = {"Today-sunny-23/34", "Tomorrow-foggy-45/67", "Wed-asteroid-54/34", "Thursday--sunny-34/56", "Fri-foggy-45/34" , "Sat-day-23/45" , "Sun-Sunny-34/65", "Someday-gloomy-78/90", "Sat-day-23/45", "Wed-asteroid-54/34", "Today-sunny-23/34"}; List weekForecast = new ArrayList(Arrays.asList(forecastArray)); ArrayAdapter mForecastAdapter = new ArrayAdapter(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast); ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); return rootView; } public class FetchWeatherTask extends AsyncTask { @Override protected Void doInBackground(Void... urls) { // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are available at OWM's forecast API page, at // http://openweathermap.org/API#forecast URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7"); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. forecastJsonStr = null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. forecastJsonStr = null; } forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e("PlaceholderFragment", "Error ", e); // If the code didn't successfully get the weather data, there's no point in attempting // to parse it. forecastJsonStr = null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("PlaceholderFragment", "Error closing stream", e); } } } return null; } } } }
这是我的Android Manifest文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sunshine.com.example.himanshu.sunshine" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
每当我在手机上运行时,应用都会崩溃。请帮助我,谢谢你找到解决方案 我创建了一个连接到INTERNET的AsyncTask,而不是使用主线程连接到Internet