Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从mainactivity中的另一个类执行asynctask_Java_Android_Android Asynctask_Android Context - Fatal编程技术网

Java 从mainactivity中的另一个类执行asynctask

Java 从mainactivity中的另一个类执行asynctask,java,android,android-asynctask,android-context,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 ;

我正在尝试从另一个类执行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);

}

}
主要活动

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



            }
        });
    }
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(策略);
按钮btn=(按钮)findViewById(R.id.button1);
btn.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
RelativeLayout rootView=(RelativeLayout)findViewById(R.id.rootLayout);
POPOOVERVIEW POPOPOOVERVIEW=新POPOPOOVERVIEW(POPOOVERVIEWActivity.this,R.layout.POPOPOVER\u显示\u视图);
setContentSizeForViewInPopover(新点(400480));
setDelegate(PopoverViewActivity.this);
popoverView.showPopoverFromRectInViewGroup(rootView,popoverView.getFrameForView(v),popoverView.PopOverErrorDirectionUp,true);
songsList=newarraylist();
fetch load=new fetch(getBaseContext());
load.execute();
}
});
}

这段代码有问题

progressDialog = new ProgressDialog(context);
这需要当前显示的活动的上下文。您似乎正在向它传递非显示活动上下文(在您的示例中,它是null)。它需要显示活动上下文才能显示进度条

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

   fetch(null);


希望这有帮助。

asynctask是否在单独的.java文件中?@Raghunandan是的。我想在单独的类中创建asyntask,并在添加时从MainActivity.classes访问它(这)…我得到
构造函数获取(new View.OnClickListener(){})是未定义的
…如果我用onCLickListener添加了新的构造函数,那么它会再次在同一个位置崩溃。我应该怎么做?你能建议更好的方法吗?我假设你的调用代码在onCreate()中,但如果在onCLickListener中,则使用更新的代码。很抱歉..我仍然得到错误<代码>类型new View的getActivity()方法未定义。OnClickListener(){}get ya。使用MainActivity.this。
   fetch(null);
   fetch(MainActivity.this);