0

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

这是我到目前为止的代码:

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 中添加了 Internet 权限,并且在没有首选项方法的情况下,JSON 解析得非常好。

4

1 回答 1

2

prefs 没有被设置为任何东西,因为从未调用过 onCreate。

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

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

然后 PrefMethods 类应该使用该上下文来访问 Preferences。

像这样的东西

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

}
于 2012-10-17T07:28:45.610 回答