如何在异步任务中使用首选项?

时间:2012-10-17 07:21:46

标签: android android-asynctask sharedpreferences

我正在从URL解析JSON&在列表视图中显示它(ofc使用异步任务),工作正常,但现在当我尝试在异步任务中添加首选项时,程序会出错。

这是我的代码,直到现在:

public class VideoList extends ListActivity {

ArrayAdapter<String> adapter;
ListView lv;
PrefMethods pm= new PrefMethods();;
int vid_id;
public void getJson(){
      new LoadJsonTask().execute();
 }

 private class LoadJsonTask extends AsyncTask<Void, Void, ArrayList<String>>{
      ProgressDialog dialog ;
     protected void onPreExecute (){
          dialog = ProgressDialog.show(VideoList.this ,"Loading....","Retrieving Data,Please Wait !");

     }
      protected ArrayList<String> doInBackground(Void[] params) {

          return populate();
      }


      protected void onPostExecute(ArrayList<String> waveData) {

          adapter=new ArrayAdapter(
                  VideoList.this,android.R.layout.simple_list_item_1,
                    waveData);  
                  lv.setAdapter(adapter);  
                  lv.setTextFilterEnabled(true);
                  dialog.dismiss();
      };

 }

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.parser);
    lv=getListView();

    //vid_id=pm.loadprefs();
    vid_id=0;
    getJson();
}

public ArrayList<String> populate() {
    ArrayList<String> items = new ArrayList<String>();

    try {

        URL urlnew= new URL("www.mydummyjsonlinkhere.com");
        HttpURLConnection urlConnection =
            (HttpURLConnection) urlnew.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
                    // gets the server json data
        BufferedReader bufferedReader =
            new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
        String next;
        while ((next = bufferedReader.readLine()) != null){
            JSONArray ja = new JSONArray(next);
            vid_id=pm.loadprefs();// here i load the preferences & error is occured
            int k=ja.length();
            for (int i = 0; i < ja.length(); i++) {

                JSONObject jo = (JSONObject) ja.get(i);
                WaveData waveData = new WaveData(jo.getString("upload"), jo.getInt("id"),jo.getString("link"),jo.getString("custommsg"));
                if(jo.getInt("id")>vid_id){
                    if(i==k-1){
                        pm.saveprefs(jo.getInt("id"));  
                        Toast.makeText(getApplicationContext(), "Saved pref no :"+jo.getInt("id"), 500).show();
                    }else{}
                }else{}

                if(jo.has("id")){
                items.add(jo.getString("custommsg"));
                }

            }



        }

    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return items;
}




}

这是我的Preferences类的代码:

public class PrefMethods extends Activity {
SharedPreferences prefs;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefs=getPreferences(MODE_PRIVATE);

 }  


 public void saveprefs(int h){
   SharedPreferences.Editor editor=prefs.edit();
   editor.putInt("id", h);
   editor.commit();
  }
 public void saveprefs(boolean b){
       SharedPreferences.Editor editor=prefs.edit();
       editor.putBoolean("inserted", b);
       editor.commit();
  }

  public int loadprefs(){
int v=prefs.getInt("id",0);
return v;
  }

  public boolean loadprefsboolean(){
    boolean v=prefs.getBoolean("inserted", false);
    return v;
  }

}

我的Logcat错误:

http://pastebin.com/JNy5RmP8

错误是PrefMethods类中以下行的空指针异常:

int v=prefs.getInt("id",0);

任何人都可以帮助我吗?指出我哪里出错了?

谢谢

编辑:我在Manifest&amp ;;中添加了Internet权限如果没有首选方法,JSON就会被完全解析。

1 个答案:

答案 0 :(得分:2)

prefs未设置为任何内容,因为永远不会调用onCreate。

活动子类适用于“活动而不是首选项”。

创建一个PrefMethods类,该类不扩展Activity,但在构造函数中使用Context。

PrefMethods类应该使用该上下文来访问首选项。

像这样的东西

      public class PrefMethods {
SharedPreferences prefs;

private Context mContext;

private static final String PREF_NAME = "MyPrefs";

    public PrefMethods( Context c ) 
    {
        prefs= c.getSharedPreferences( PREF_NAME, Context.MODE_PRIVATE);   
    }  


 public void saveprefs(int h){
   SharedPreferences.Editor editor=prefs.edit();
   editor.putInt("id", h);
   editor.commit();
  }
 public void saveprefs(boolean b){
       SharedPreferences.Editor editor=prefs.edit();
       editor.putBoolean("inserted", b);
       editor.commit();
  }

  public int loadprefs(){
int v=prefs.getInt("id",0);
return v;
  }

  public boolean loadprefsboolean(){
    boolean v=prefs.getBoolean("inserted", false);
    return v;
  }

}