从mainactivity中的另一个类执行asynctask

时间:2014-02-21 17:01:17

标签: java android android-asynctask android-context

我正在尝试从另一个类执行asynctask并更新listview和toast。 但我无法做到这一点。它崩溃在:

progressDialog = new ProgressDialog(context);

我真的很感激任何帮助。

fetch.class

 public class fetch extends AsyncTask<Void, Void, JSONObject> {


      Context context;

     Activity activity ;
ListView list;
        LazyAdapter adapter;


        ArrayList<HashMap<String, String>> songsList;
        ProgressDialog progressDialog ;

    @Override
    protected JSONObject doInBackground(Void... params) {

         String ResponseBody = null;

        try {

            String user = "1";

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.example.com/example.php");

            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

            nameValuePairs.add(new BasicNameValuePair("user",user) );


            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            reader.close();
            String result = sb.toString();


            // parsing data
            return new JSONObject(result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub

        super.onPreExecute();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                 progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("loading...");
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();

            }
        });

    }


    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);



        if (result != null) {
               JSONArray arr = result.getJSONArray("Array");

         for (int i = 0; i <arr.Length(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key =&gt; value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
            map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
            map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));

            // adding HashList to ArrayList
            songsList.add(map);
        }

    }
            list=(ListView)findViewById(R.id.ListView);
            // Getting adapter by passing xml data ArrayList
            adapter=new LazyAdapter(MainActivity.this, songsList);  
            list.setCacheColorHint(0);
            list.setScrollingCacheEnabled(false);
            list.setAdapter(adapter);

         // Click event for single list row
            list.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                    Toast.makeText(getBaseContext(), position+"  "+id, 5).show();

                }
            }); 


        } else {
            // error occured
        }


        runOnUiThread(new Runnable() {
            @Override
            public void run() {



                 progressDialog.dismiss();

                 Toast.makeText(getBaseContext(), "done", 5).show();

            }

        });
    }


    public fetch(Context context) {
      activity = (context instanceof Activity) ? (Activity) context : null;
     this.context = context;

     progressDialog = new ProgressDialog(context);

}

}

LazyAdapter.java

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList&lt;HashMap&lt;String, String&gt;&gt; data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader;

    public LazyAdapter(Activity a, ArrayList&lt;HashMap&lt;String, String&gt;&gt; d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_row, null);

        TextView title = (TextView)vi.findViewById(R.id.title); // title
        TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
        TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
        ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

        HashMap&lt;String, String&gt; song = new HashMap&lt;String, String&gt;();
        song = data.get(position);

        // Setting all values in listview
        title.setText(song.get(CustomizedListView.KEY_TITLE));
        artist.setText(song.get(CustomizedListView.KEY_ARTIST));
        duration.setText(song.get(CustomizedListView.KEY_DURATION));
        imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
        return vi;
    }
}

MainActivity

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 

        Button btn=(Button)findViewById(R.id.button1);





        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                RelativeLayout rootView = (RelativeLayout)findViewById(R.id.rootLayout);

                PopoverView popoverView = new PopoverView(PopoverViewActivity.this, R.layout.popover_showed_view);
                popoverView.setContentSizeForViewInPopover(new Point(400, 480));
                popoverView.setDelegate(PopoverViewActivity.this);
                popoverView.showPopoverFromRectInViewGroup(rootView, PopoverView.getFrameForView(v), PopoverView.PopoverArrowDirectionUp, true);



                 songsList = new ArrayList<HashMap<String, String>>();


                    fetch load=new fetch(getBaseContext());
                    load.execute();



            }
        });
    }

1 个答案:

答案 0 :(得分:2)

这段代码的问题

progressDialog = new ProgressDialog(context);

这需要当前显示的活动的上下文。而且似乎你传递的是非显示活动上下文(在你的情况下它是null)。它需要显示活动上下文才能显示进度条。

在调用fetch时,您在主活动中将其作为null传递。你应该改变

   fetch(null);

   fetch(MainActivity.this);

希望这有帮助。