getDefaultSharedPreferences(getActivity()) in AsyncTask

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


               }
           }
       }




    }

This is the logcat

FATAL EXCEPTION: AsyncTask #1 Process: app.com.example.administrator.sunshineapp, PID: 19227 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374) at android.preference.PreferenceManager.g etDefaultSharedPreferences(PreferenceManager.java:369) at app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.formatHighLows(MainActivityFragment.java:90) at app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.getWeatherDataFromJson(MainActivityFragment.java:184) at app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.doInBackground(MainActivityFragment.java:300) at app.com.example.administrator.sunshineapp.MainActivityFragment$FetchWeatherTask.doInBackground(MainActivityFragment.java:74) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818)

this the main activity code :

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



}

use ActivityName.this instead of mContext

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(ActivityName.this)

instead of

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext)

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

链接地址: http://www.djcxy.com/p/78424.html

上一篇: aysnc任务中logcat文件中的json错误

下一篇: AsyncTask中的getDefaultSharedPreferences(getActivity())