Asynctask Timer NullPointErexception

时间:2014-04-22 14:35:49

标签: android timer android-asynctask

按下后退按钮时异步任务崩溃。这是我的代码。

public class MainActivity extends ActionBarActivity {
private Handler handler = new Handler();
SimpleAdapter adapter;
ListView listView;  
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
    new Timer().schedule(new MyTimerTask(), 0, 1000);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        return rootView;
    }
}
// 
private class MyAsyncTask  extends AsyncTask<String, Void, String> {       
    @Override
    protected String doInBackground(String... params) {
        try {
            URL url = new URL("http://site/get_messages.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream is = connection.getInputStream();
                String content = convertInputStream(is, "UTF-8");
                is.close();
                return content;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    private String convertInputStream(InputStream is, String encoding) {
        Scanner scanner = new Scanner(is, encoding).useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);           
        if (result != null) {               
            if(result.indexOf(" splitter ")>0){
                String[] result_splitted = result.split(" splitter ");
                int a;

                List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

                for(a=1; a<result_splitted.length+1; a++){
                    String[] full_message = result_splitted[a-1].split("[|]");
                        HashMap<String, String> hm = new HashMap<String,String>();
                        hm.put("sender", full_message[0]);
                        hm.put("date",full_message[2]);
                        hm.put("txt", full_message[1]);
                        hm.put("phto", full_message[3]);
                        aList.add(hm);

                }

                String[] from = { "profile","sender","date","txt" };


                int[] to = { R.id.profile,R.id.sender,R.id.date,R.id.txt};


                listView = ( ListView ) findViewById(R.id.listview);

                adapter = new SpecialAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);


                listView.setAdapter(adapter);
            }               
        }
    }
}

public class MyTimerTask extends TimerTask {
    public void run() {
        handler.post(
            new Runnable() { 
                public void run() { 
                     new MyAsyncTask().execute("some", "some");
                }
            }
        );
    }
}
public class Utility {

    public void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }


 }

}

我在线上得到NullPointerException,其中是&#34; listView.setAdapter(adapter);&#34;。我花了两天时间来解决这个问题。但没有结果。如果你能帮助我,我会很高兴。)

1 个答案:

答案 0 :(得分:0)

如果listView不为null,请尝试此操作,然后适配器为null,看起来不太可能。

if(listView==null){
Log.i("error", "listView=null");
}else{
listView.setAdapter(adapter);
}