AsyncTask 中的 getDefaultSharedPreferences(getActivity())

Posted

技术标签:

【中文标题】AsyncTask 中的 getDefaultSharedPreferences(getActivity())【英文标题】:getDefaultSharedPreferences(getActivity()) in AsyncTask 【发布时间】:2017-01-24 04:42:02 【问题描述】:
public  class MainActivityFragment extends Fragment 
    public static ArrayAdapter<String> mForecastAdapter; 

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 


        View rootView = inflater.inflate(R.layout.fragment_main, container, false);


        mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, new ArrayList<String>());

        ListView listview = (ListView) rootView.findViewById(R.id.listview_forecast);
        listview.setAdapter(mForecastAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) 
                String Forecast = mForecastAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra(Intent.EXTRA_TEXT, Forecast);
                startActivity(intent);


            
        );


        return rootView;
    

      public  class FetchWeatherTask extends AsyncTask<String, Void, String[]> 

          Context mContext;
          private void FetchWeatherTask(Context context)
             mContext = context;
          




          private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

          public String formatHighLows(double high, double low) 


              SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
              String unitType = sharedPrefs.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));

/*
              if(unitType.equals(getString(R.string.pref_units_imperial)))

              
                  high = (high*1.8) + 32;
                  low = (low * 1.8) +32;

               else if (!unitType.equals(getString(R.string.pref_units_metric)))
              

              
*/


              // For presentation, assume the user doesn't care about tenths of a degree.
              long roundedHigh = Math.round(high);
              long roundedLow = Math.round(low);

              String highLowStr = roundedHigh + "/" + roundedLow;
              return highLowStr;
          


           /* The date/time conversion code is going to be moved outside the asynctask later,
 * so for convenience we're breaking it out into its own method now.
 */


           private String getReadableDateString(long time)


               // Because the API returns a unix timestamp (measured in seconds),
               // it must be converted to milliseconds in order to be converted to valid date.
               Date date = new Date(time * 1000);
               SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
               return format.format(date).toString();
           

           /**
            * Prepare the weather high/lows for presentation.
            */


           /**
            * Take the String representing the complete forecast in JSON Format and
            * pull out the data we need to construct the Strings needed for the wireframes.
            *
            * Fortunately parsing is easy:  constructor takes the JSON string and converts it
            * into an Object hierarchy for us.
            */
           private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
                   throws JSONException 

               // These are the names of the JSON objects that need to be extracted.
               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++) 
                   // For now, using the format "Day, description, hi/low"
                   String day;
                   String description;
                   String highAndLow;

                   // Get the JSON object representing the day
                   JSONObject dayForecast = weatherArray.getJSONObject(i);

                   // The date/time is returned as a long.  We need to convert that
                   // into something human-readable, since most people won't read "1400356800" as
                   // "this saturday".
                   long dateTime = dayForecast.getLong(OWM_DATETIME);
                   day = getReadableDateString(dateTime);

                   // description is in a child array called "weather", which is 1 element long.
                   JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                   description = weatherObject.getString(OWM_DESCRIPTION);

                   // Temperatures are in a child object called "temp".  Try not to name variables
                   // "temp" when working with temperature.  It confuses everybody.
                   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) 

                // 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;

                String format = "json";
                String units = "metric";
                int numDays = 7;
                String ApiKey = "8f044afff5747f43d54f5229904c5dbb";

                try 
                    // Construct the URL for the OpenWeatherMap query
                    // Possible parameters are avaiable at OWM's forecast API page, at
                    // http://openweathermap.org/API#forecast
                    final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";

                    final String QUERY_PARM = "q";
                    final String FORMAT_PARM = "mode";
                    final String UNITS_PARM = "units";
                    final String DAYS_PARM = "cnt";
                    final String KEY_PARM = "appid";

                    Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                            .appendQueryParameter(QUERY_PARM,params[0])
                            .appendQueryParameter(FORMAT_PARM,format)
                            .appendQueryParameter(UNITS_PARM,units)
                            .appendQueryParameter(DAYS_PARM,Integer.toString(numDays))
                            .appendQueryParameter(KEY_PARM,ApiKey).build();






                    URL url = new URL(builtUri.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.
                        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();

                  //  Log.v(LOG_TAG,"Forecast JSON String"+forecastJsonStr);
                 catch (IOException e) 
                    Log.e("PlaceholderFragment", "Error ", e);
                    // If the code didn't successfully get the weather data, there's no point in attemping
                    // 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);
                        
                    
                






                try 
                  String[] FinalValue = getWeatherDataFromJson(forecastJsonStr,numDays);

                    for (String s : FinalValue)
                    
                        Log.v(LOG_TAG,"Forecast entry: "+s);
                    

                    return FinalValue;
                 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);
                   


               
           
       




    

这是日志猫

致命异常:AsyncTask #1 进程:app.com.example.administrator.sunshineapp,PID:19227 java.lang.RuntimeException:执行时发生错误 做背景() 在 android.os.AsyncTask$3.done(AsyncTask.java:300) 在 java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 在 java.util.concurrent.FutureTask.setException(FutureTask.java:222) 在 java.util.concurrent.FutureTask.run(FutureTask.java:242) 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 在 java.lang.Thread.run(Thread.java:818) 引起:java.lang.NullPointerException:尝试调用虚拟 方法'java.lang.String android.content.Context.getPackageName()' on 空对象引用 在 android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374) 在 android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369) 在 app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.formatHighLows(MainActivityFragment.java:90) 在 app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.getWeatherDataFromJson(MainActivityFragment.java:184) 在 app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.doInBackground(MainActivityFragment.java:300) 在 app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.doInBackground(MainActivityFragment.java:74) 在 android.os.AsyncTask$2.call(AsyncTask.java:288) 在 java.util.concurrent.FutureTask.run(FutureTask.java:237) 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 在 java.lang.Thread.run(Thread.java:818)

这是主要的活动代码:

package app.com.example.administrator.sunshineapp;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

public class MainActivity extends AppCompatActivity 


  public   Activity mActivity;

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setLogo(R.mipmap.sun);
        ;

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    


    @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_refresh) 
          updateWeather();


            return true;
        
        if (id == R.id.action_settings) 
            startActivity(new Intent(this,SettingsActivity.class));

            return true;
        


        return super.onOptionsItemSelected(item);
    


    private  void updateWeather ()
    




        MainActivityFragment x = new MainActivityFragment();
        MainActivityFragment.FetchWeatherTask WeatherTask = x.new FetchWeatherTask();


        SharedPreferences prefs = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
        String location = prefs.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));
        WeatherTask.execute(location);




    

    @Override
    public void onStart() 
        super.onStart();
        updateWeather();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://app.com.example.administrator.sunshineapp/http/host/path"));
        AppIndex.AppIndexApi.start(client, viewAction);
    

    @Override
    public void onStop() 
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://app.com.example.administrator.sunshineapp/http/host/path"));
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    




【问题讨论】:

什么时候调用formatHighLows?您可能在 Activity 完全初始化之前调用了该函数。 我试图在 OnPreExecute 方法中初始化 sharedPreference 但没有用.....这个方法也在 doInBackground 中被调用 您的异步任务类与活动类不同,对吧?它不是一个片段类,所以你为什么要通过 getActivity() ?您是否尝试单独获取上下文对象? AsyncTask 是 MainFragmentActivity 的子类......问题是我不明白如何将上下文传递给这个 AsyncTask 在哪里调用 FetchWeatherTask()?我在您发布的代码中没有看到这一点。 【参考方案1】:

使用 ActivityName.this 代替 mContext

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ActivityName.this)

而不是

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext)

【讨论】:

不可用! 什么不可用使用 getDefaultSharedPreferences(MainActivity.this)【参考方案2】:

创建一个构造函数并通过该构造函数传递上下文。

【讨论】:

是的,我做到了,但问题仍然存在 只需检查 getApplicationContext() 选项是否可用并尝试一下 SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext.getApplicationContext()); 试过每个人......似乎没有任何改变......可能是什么问题?! .......

以上是关于AsyncTask 中的 getDefaultSharedPreferences(getActivity())的主要内容,如果未能解决你的问题,请参考以下文章

匿名 AsyncTask 中的构造函数,例如“new AsyncTask<Exercise,Void,Void>()”?

android中的asynctask可不可以并行执行多个

AsyncTask 中的httpClient 需要wakeLock 吗?

无法覆盖 AsyncTask 类中的 onPostExecute() 方法或使其触发

AsyncTask 中的 getDefaultSharedPreferences(getActivity())

AsyncTask中的IOException