我正在尝试将我的应用与主机连接,我也获得了所有代码,但它没有连接 当我点击模拟器中的Menu按钮时,当我点击Refresh按钮
时,给我发送logcat中的消息详细这是MainActivity.java类:
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.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public ForecastFragment Commit() {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
}
这是ForecastFragment.java类:
public class ForecastFragment extends Fragment
{
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment()
{
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.forecastfragment, menu);
}
public boolean onOptionItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_refresh)
{
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] data =
{
"Today - Sunny - 88/63",
"Tomorrow - foggy - 70/46",
"weds - Cloudy - 72/63",
"Thurs - Rainy - 64/51",
"Fri - Foggy - 70/46",
"Sat - Sunny - 76/68"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(data));
mForecastAdapter =
new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public ForecastFragment Commit() {
return null;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]>
{
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
private String getReadableDateString(long time)
{
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[numDays];
for (int i = 0; i < weatherArray.length(); i++) {
String day;
String description;
String highAndLow;
JSONObject dayForecast = weatherArray.getJSONObject(i);
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params)
{
if (params.length == 0)
{
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try
{
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_param = "MODE";
final String UNITS_param = "UNITS";
final String DAYS_param = "CNT";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_param, format)
.appendQueryParameter(UNITS_param, format)
.appendQueryParameter(DAYS_param, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built Uri " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null)
{
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if (buffer.length() == 0)
{
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
}
catch (IOException e)
{
Log.e(LOG_TAG, "Error", e);
return null;
}
finally
{
if (urlConnection != null)
{
urlConnection.disconnect();
}
if (reader != null)
{
try
{
reader.close();
}
catch (final IOException e)
{
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try
{
return getWeatherDataFromJson(forecastJsonStr, numDays);
}
catch (JSONException e)
{
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result)
{
if (result != null)
{
mForecastAdapter.clear();
for (String dayForecastStr : result)
{
mForecastAdapter.add(dayForecastStr);
}
}
}
}
private String formatHighLows(double high, double low) {
return null;
}
}
现在我克服了所有错误并重新修改了ForecastFragment.java类中的代码,那么为什么它没有连接到主机给我同样的错误呢?
答案 0 :(得分:0)
您的doInBackground()
为空:
@Override
protected Void doInBackground(String... params) {
return null;
}
另一个doInBackGround()
方法名称中有一个拼写错误(应该有小写g
)。删除空方法并使用其中的代码重命名另一个方法,以便它可以由AsyncTask
运行。