问题描述
我在android的创建了一个小程序来同步从云中的数据,但每当我preSS的刷新按钮(用于开发目的)的code不响应..在logcat中显示:
02-25 22:57:32.195:W / InputEventReceiver(17762): 试图完成输入事件,但该输入事件接收器具有已 被释放。
在Java code为MainActivity和FragmentActivity类下面给出
包sunshine.com.example.himanshu.sunshine;
进口android.os.Bundle;
进口android.support.v4.app.Fragment;
进口android.support.v7.app.ActionBarActivity;
进口android.view.Menu;
进口android.view.MenuItem;
公共类MainActivity扩展ActionBarActivity {
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
如果(savedInstanceState == NULL){
。getSupportFragmentManager()的BeginTransaction()加(R.id.container,新ForecastFragment())提交()。 }
}
@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
//充气菜单;这增加了项目操作栏,如果它是present。
。getMenuInflater()膨胀(R.menu.menu_main,菜单);
返回true;
}
@覆盖
公共布尔onOptionsItemSelected(菜单项项){
//处理动作栏项目点击这里。将操作栏
//自动在主/向上按钮操作的点击,只要
//你在AndroidManifest.xml中指定一个父活动。
INT的id = item.getItemId();
如果(ID == R.id.action_settings){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
}
包sunshine.com.example.himanshu.sunshine;
进口android.annotation.TargetApi;
进口android.net.Uri;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.support.v4.app.Fragment;
进口android.util.Log;
进口android.view.LayoutInflater;
进口android.view.Menu;
进口android.view.MenuInflater;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.ArrayAdapter;
进口android.widget.ListView;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;
进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.net.HttpURLConnection中;
进口的java.net.URL;
进口java.text.SimpleDateFormat的;
进口的java.util.ArrayList;
进口java.util.Arrays中;
进口java.util.Date;
进口的java.util.List;
/ **
*在2015年2月25日创建于人士Himanshu。
* /
公共类ForecastFragment扩展片段
{
公共ForecastFragment(){
}
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(真正的);
}
@覆盖
公共无效onCreateOptionsMenu(功能菜单,MenuInflater充气){
inflater.inflate(R.menu.forecast_fragment,菜单);
}
@覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT的id = item.getItemId();
如果(ID == R.id.refresh_action)
{
FetchWeatherTask取=新FetchWeatherTask();
fetch.execute(716217);
返回true;
}
返回super.onOptionsItemSelected(项目);
}
@覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
捆绑savedInstanceState){
查看rootView = inflater.inflate(R.layout.fragment_main,集装箱,假);
字符串forecastArray [] =
{今天,阳光明媚-23/34,
明天,雾,67分之45
周三,小行星三十四分之五十四
周四 - 阳光明媚-34/56,
周五,雾,三十四分之四十五
周六日-四十五分之二十三
太阳阳光-34/65,
有一天,阴沉-九十分之七十八
周六日-45分之23
周三,小行星三十四分之五十四
今天,阳光明媚-23/34号};
名单<字符串> weekForecast =新的ArrayList<字符串>(Arrays.asList(forecastArray));
ArrayAdapter<字符串> mForecastAdapter =新的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);
返回rootView;
}
公共类FetchWeatherTask扩展的AsyncTask<字符串,太虚,太虚> {
私人最终字符串LOG_TAG = FetchWeatherTask.class.getSimpleName();
@覆盖
保护无效doInBackground(字符串... PARAMS)
{
如果(params.length == 0)
返回null;
//这两个需要在try / catch语句外声明
//使他们可以在关闭finally块。
HttpURLConnection类的URLConnection = NULL;
BufferedReader中读= NULL;
//将包含原始JSON响应为字符串。
字符串forecastJsonStr = NULL;
尝试 {
//构造的URL OpenWeatherMap查询
//可能的参数是缴费在OWM的预测API页面,在
// http://openweathermap.org/API#forecast
字符串格式=JSON;
字符串单位=指标;
INT天= 7;
最后弦乐SURL =http://api.openweathermap.org/data/2.5/forecast/daily?;
最后串P code =Q;
最终的字符串模式=模式;
最后弦乐单位=单位;
最后弦乐daysy =CNT;
乌里urlbulilt = Uri.parse(SURL).buildUpon()。appendQueryParameter(P code,则params [0])
.appendQueryParameter(模式,格式)
.appendQueryParameter(台,个)
.appendQueryParameter(daysy,Integer.toString(天))建立()。
网址URL =新的URL(urlbulilt.toString());
//创建请求OpenWeatherMap,并打开连接
的URLConnection =(HttpURLConnection类)url.openConnection();
urlConnection.setRequestMethod(GET);
urlConnection.connect();
//读取输入流转换为字符串
InputStream中的InputStream = urlConnection.getInputStream();
StringBuffer的缓冲区=新的StringBuffer();
如果(的InputStream == NULL){
// 没事做。
返回null;
}
读者=新的BufferedReader(新的InputStreamReader(InputStream中));
串线;
而((行= reader.readLine())!= NULL){
//因为它是JSON,增加一个新行是没有必要的(不会影响解析)
//但它确实使调试*很多*容易,如果你打印出完成
//缓冲区进行调试。
buffer.append(行+\ N);
}
如果(buffer.length()== 0){
//流是空的。没有点解析。
返回null;
}
forecastJsonStr = buffer.toString();
}赶上(IOException异常E){
Log.e(LOG_TAG,错误,E);
//如果code没有顺利拿到天气数据,还有在attemping没有意义
//解析它。
返回null;
} 最后 {
如果(URLConnection的!= NULL){
urlConnection.disconnect();
}
如果(读者!= NULL){
尝试 {
reader.close();
}赶上(最终IOException异常E){
Log.e(LOG_TAG,错误收盘流,E);
}
}
}
返回null;
}
}
}
我想这是因为你的提取对象是一个局部变量的onOptionsItemSelected()方法,通过AsyncTask的完成它已经被垃圾回收的时间。
尝试使其成为一个字段,然后在onOptionsItemSelected分配给它()方法
公共类ForecastFragment扩展片段{
私人FetchWeatherTask获取;
公共ForecastFragment(){
}
...
然后
@覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT的id = item.getItemId();
如果(ID == R.id.refresh_action)
{
取=新FetchWeatherTask();
fetch.execute(716217);
返回true;
}
返回super.onOptionsItemSelected(项目);
}
现在你取的对象应该还是围绕AsyncTask的完成时。
I have created a small program in android to sync the data from the cloud but whenever I press the refresh button (for developing purposes) the code does not responds..The Logcat shows:
02-25 22:57:32.195: W/InputEventReceiver(17762): Attempted to finish an input event but the input event receiver has already been disposed.
The java code for the MainActivity and the FragmentActivity classes are given below
package sunshine.com.example.himanshu.sunshine;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package sunshine.com.example.himanshu.sunshine;
import android.annotation.TargetApi;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
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.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
* Created by Himanshu on 2/25/2015.
*/
public 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);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.refresh_action)
{
FetchWeatherTask fetch=new FetchWeatherTask();
fetch.execute("716217");
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<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));
ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(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<String, Void, Void> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
@Override
protected Void doInBackground(String... params)
{
if(params.length==0)
return null;
// 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 avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
String format="json";
String unit="metric";
int days=7;
final String surl="http://api.openweathermap.org/data/2.5/forecast/daily?";
final String pcode="q";
final String mode="mode";
final String units="units";
final String daysy="cnt";
Uri urlbulilt=Uri.parse(surl).buildUpon().appendQueryParameter(pcode,params[0])
.appendQueryParameter(mode,format)
.appendQueryParameter(units,unit)
.appendQueryParameter(daysy,Integer.toString(days)).build();
URL url=new URL(urlbulilt.toString());
// 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.
return 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.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
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);
}
}
}
return null;
}
}
}
I think this is because your fetch object is a local variable to the onOptionsItemSelected() method, by the time the AsyncTask completes it has already been garbage collected.
Try making it a field and then assigning it in the onOptionsItemSelected() method
public class ForecastFragment extends Fragment {
private FetchWeatherTask fetch;
public ForecastFragment() {
}
...
and then
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==R.id.refresh_action)
{
fetch=new FetchWeatherTask();
fetch.execute("716217");
return true;
}
return super.onOptionsItemSelected(item);
}
now your fetch object should still be around when the AsyncTask completes.
这篇关于我该如何解决InputEventReceiver错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!