execute asynctask from another class in mainactivity

jason

I am trying to execute asynctask from another class and update listview and also toast. But I am unable to do that. Its crashing at:

progressDialog = new ProgressDialog(context);

I really appreciate any help.

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



            }
        });
    }
Sanjeev

Problem with this piece of code

progressDialog = new ProgressDialog(context);

is that this needs context of currently displayed activity. And it seems you are passing it the non-displaying activity context (In your case it is null). It needs displayed activity context in order to show the progress bar.

while calling fetch you are passing it as null in main activity. you should change

   fetch(null);

to

   fetch(MainActivity.this);

Hope this helps.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Call AsyncTask from another class?

From Dev

Calling a method of the MainActivity from another class?

From Dev

Access to WebView from another function in MainActivity class

From Dev

Calling a method of the MainActivity from another class?

From Dev

Run code from MainActivity in another Class

From Dev

calling method in mainactivity from another class in android

From Dev

How to return ArrayList from AsyncTask to another class?

From Dev

How to return ArrayList from AsyncTask to another class?

From Dev

How to put result from "AsyncTask doInBackground from different class" to "TextView in MainActivity"

From Dev

Problems in trying to create a Instance in MainActivity from another class

From Dev

Android studios how to pass a context from mainactivity to another class

From Dev

Execute function to call performSegueWithIdentifier from another class

From Dev

Execute function to call performSegueWithIdentifier from another class

From Dev

Android: Call and execute a Class on the MainActivity Class

From Dev

Sending data from AsyncTask in MainActivity to Fragment?

From Dev

AsyncTask How to get progress from MainActivity

From Dev

Can't post response from AsyncTask to MainActivity

From Dev

Sending data from AsyncTask in MainActivity to Fragment?

From Dev

how to fetch result from asynctask into mainactivity

From Dev

How to call notifyDataSetChanged() from AsyncTask onPostExecute() in another class

From Dev

How to get values from an AsyncTask when it is in another class

From Dev

How to access a listview that filled in asynctask, from another class?

From Dev

[Android]Update textview from another class running on asynctask?

From Dev

Callback from AsyncTask class

From Dev

Callback from AsyncTask class

From Dev

passing arrays another class and asynctask

From Dev

Calling an AsyncTask from another asynctask in doInBackground method?

From Dev

Start AsyncTask from another AsyncTask doInBackground()

From Dev

How to call AsyncTask from another AsyncTask?

Related Related

  1. 1

    Call AsyncTask from another class?

  2. 2

    Calling a method of the MainActivity from another class?

  3. 3

    Access to WebView from another function in MainActivity class

  4. 4

    Calling a method of the MainActivity from another class?

  5. 5

    Run code from MainActivity in another Class

  6. 6

    calling method in mainactivity from another class in android

  7. 7

    How to return ArrayList from AsyncTask to another class?

  8. 8

    How to return ArrayList from AsyncTask to another class?

  9. 9

    How to put result from "AsyncTask doInBackground from different class" to "TextView in MainActivity"

  10. 10

    Problems in trying to create a Instance in MainActivity from another class

  11. 11

    Android studios how to pass a context from mainactivity to another class

  12. 12

    Execute function to call performSegueWithIdentifier from another class

  13. 13

    Execute function to call performSegueWithIdentifier from another class

  14. 14

    Android: Call and execute a Class on the MainActivity Class

  15. 15

    Sending data from AsyncTask in MainActivity to Fragment?

  16. 16

    AsyncTask How to get progress from MainActivity

  17. 17

    Can't post response from AsyncTask to MainActivity

  18. 18

    Sending data from AsyncTask in MainActivity to Fragment?

  19. 19

    how to fetch result from asynctask into mainactivity

  20. 20

    How to call notifyDataSetChanged() from AsyncTask onPostExecute() in another class

  21. 21

    How to get values from an AsyncTask when it is in another class

  22. 22

    How to access a listview that filled in asynctask, from another class?

  23. 23

    [Android]Update textview from another class running on asynctask?

  24. 24

    Callback from AsyncTask class

  25. 25

    Callback from AsyncTask class

  26. 26

    passing arrays another class and asynctask

  27. 27

    Calling an AsyncTask from another asynctask in doInBackground method?

  28. 28

    Start AsyncTask from another AsyncTask doInBackground()

  29. 29

    How to call AsyncTask from another AsyncTask?

HotTag

Archive