2015-02-25 3 views
4

Я создал небольшую программу андроида для синхронизации данных из облака, но всякий раз, когда я нажимаю кнопку обновления (для развивающихся целей) код не отвечает .. Logcat показывает:Как разрешить ошибку InputEventReceiver?

 
02-25 22:57:32.195: W/InputEventReceiver(17762): 
Attempted to finish an input event but the input event receiver has already 
been disposed. 

Ява код для MainActivity и классов FragmentActivity приведены ниже

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); 
    } 

} 

пакета 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; 
     } 
    } 
} 

ответ

1

Я думаю, что это происходит потому, что ваш объект выборки является локальной переменной метода onOptionsItemSelected(), к тому времени, AsyncTask завершает это уже сборщиком мусора.

Попробуйте сделать это поле, а затем назначить его в методе onOptionsItemSelected()

public class ForecastFragment extends Fragment { 

    private FetchWeatherTask fetch; 

    public ForecastFragment() { 
    } 

...

, а затем

@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); 
} 

теперь ваш объект выборки по-прежнему должны быть вокруг когда AsyncTask завершает работу.

+0

noops .. сообщение об ошибке @nPn – theSereneRebel

Смежные вопросы