Android 两个不同活动中的两个异步任务同时运行

Android 两个不同活动中的两个异步任务同时运行,android,android-asynctask,Android,Android Asynctask,我正在使用AsyncTask完成我的工作,但当我在一个活动(tab.java)和Defaulttab视图(Feed.java)中有选项卡时,问题就出现了,即第一个选项卡显示为Default。两个类文件都有自己的XML。 我正在使用异步任务从服务器响应中(tab.java)列出清单&在(tab.java)中,我需要调用另一个服务器响应来显示在该页面上。 每次从(tab.java)serverUrl得到响应时,我的应用程序都会崩溃 怎样做这种手术 多谢各位 我的代码: tab.java: publi

我正在使用
AsyncTask
完成我的工作,但当我在一个活动(tab.java)和
Default
tab视图(Feed.java)中有选项卡时,问题就出现了,即第一个选项卡显示为Default。两个类文件都有自己的XML。 我正在使用异步任务从服务器响应中(tab.java)列出清单&在(tab.java)中,我需要调用另一个服务器响应来显示在该页面上。 每次从(tab.java)serverUrl得到响应时,我的应用程序都会崩溃

怎样做这种手术

多谢各位

我的代码:

tab.java:

public class Login_Header extends TabActivity
{
Button Find; 

 /** Called when the activity is first created. */

 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
//To show Custom Title as image 
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
//getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.login_header_bar);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_about_tab);




// Font size has been changed through Styles.xml for tab
    TabHost tabHost = getTabHost();

    Intent feeds = new Intent(this,Feeds.class);
    tabHost.addTab(tabHost.newTabSpec("Tab1")
                     .setIndicator("Feeds")
                     .setContent(feeds));


    Intent challenges = new Intent(this,Challenges.class);
    tabHost.addTab(tabHost.newTabSpec("Tab2")
                     .setIndicator("Challenges")
                     .setContent(challenges));

    Intent friends = new Intent(this,Friends.class);
    tabHost.addTab(tabHost.newTabSpec("Tab3")
                     .setIndicator("Friends")
                     .setContent(friends));

   Intent group = new Intent(this,Groups.class);
   tabHost.addTab(tabHost.newTabSpec("Tab4")
                     .setIndicator("Groups")
                     .setContent(group));

   Intent details = new Intent(this,Details.class);
   tabHost.addTab(tabHost.newTabSpec("Tab5")
                     .setIndicator("Details")
                     .setContent(details));

    tabHost.setCurrentTab(0);



   Find.setOnClickListener(new OnClickListener() 
   {
   @Override
   public void onClick(View v) 
   {
     // TODO Auto-generated method stub

     Intent find = new Intent(Login_Header.this,Find.class);
    startActivity(find);
   }
    });
   //To call async task
   callNotificationCount();
  }
private void callNotificationCount() 
{
    new NotificationCount_Async().execute("");
}



private class  NotificationCount_Async extends AsyncTask<String, Void, String>
{

      @Override
      protected String doInBackground(String... params)
      {
          try 
            {
                URL url=new URL(getString(R.string.WebServiceURL)+"/notifications/notificationcount");
                HttpPost httppost = new HttpPost(url.toString());
                HttpResponse responsePOST = LoginPage.httpClient.execute(httppost); 
                HttpEntity resEntity = responsePOST.getEntity();
                InputStream instream = resEntity.getContent();
                String result = convertStreamToString(instream);

                Log.i("User Feed",result);
                return result;
            }
              catch(Exception ex) 
              { 
                   Log.e("error", "error", ex);
                   return null;
              }
         }

        @Override
        protected void onPostExecute(String result)
          {
            try {
                     JSONObject json = new JSONObject(result);
                     //Below  code is for user count

                     JSONObject userNotificationjson = json.getJSONObject("user_notification");
                     if(json.has("user_notification"))
                     {
                         String userCount = userNotificationjson.getString("count");
                         int Count = Integer.parseInt(userCount);
                         if(Count > 0)
                         {
                             LinearLayout llUserCount = (LinearLayout)findViewById(R.id.llUserCount);
                             TextView userCountTextView =(TextView)findViewById(R.id.txtUserCount);
                             llUserCount.setVisibility(View.VISIBLE);
                             userCountTextView.setText(userCount);
                        }
                    }


           }
     private  String convertStreamToString(InputStream is)
      {
        //code
 }
public类登录\u头扩展TabActivity
{
按钮查找;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState)
{
//将自定义标题显示为图像的步骤
requestWindowFeature(Window.FEATURE\u自定义\u标题);
//getWindow().requestFeature(Window.FEATURE\u ACTION\u栏);
setContentView(R.layout.login\u标题\u栏);
super.onCreate(savedInstanceState);
getWindow().setFeatureInt(Window.FEATURE\u CUSTOM\u TITLE,R.layout.CUSTOM\u TITLE\u about\u选项卡);
//字体大小已通过tab的Styles.xml更改
TabHost TabHost=getTabHost();
Intent提要=新的Intent(这是feed.class);
tabHost.addTab(tabHost.newTabSpec(“Tab1”)
.setIndicator(“提要”)
.setContent(feeds));
意向挑战=新意向(此为challenges.class);
tabHost.addTab(tabHost.newTabSpec(“Tab2”)
.setIndicator(“挑战”)
.setContent(挑战);
意向朋友=新意向(这个,friends.class);
tabHost.addTab(tabHost.newTabSpec(“Tab3”)
.setIndicator(“朋友”)
.setContent(friends));
意向组=新意向(此,Groups.class);
tabHost.addTab(tabHost.newTabSpec(“Tab4”)
.setIndicator(“组”)
.setContent(组);
Intent details=新的Intent(this,details.class);
tabHost.addTab(tabHost.newTabSpec(“Tab5”)
.setIndicator(“详细信息”)
.setContent(细节);
tabHost.setCurrentTab(0);
Find.setOnClickListener(新的OnClickListener()
{
@凌驾
公共void onClick(视图v)
{
//TODO自动生成的方法存根
Intent find=新的Intent(Login_Header.this,find.class);
星触觉(find);
}
});
//调用异步任务
callNotificationCount();
}
私有void callNotificationCount()
{
新建NotificationCount_Async()。执行(“”);
}
私有类NotificationCount\u Async扩展了AsyncTask
{
@凌驾
受保护的字符串doInBackground(字符串…参数)
{
尝试
{
URL URL=新URL(getString(R.string.WebServiceURL)+“/notifications/notificationcount”);
HttpPost-HttpPost=newhttppost(url.toString());
HttpResponse responsePOST=LoginPage.httpClient.execute(httppost);
HttpEntity当前状态=responsePOST.getEntity();
InputStream instream=resEntity.getContent();
字符串结果=convertStreamToString(流内);
Log.i(“用户提要”,结果);
返回结果;
}
捕获(例外情况除外)
{ 
Log.e(“错误”、“错误”,例如);
返回null;
}
}
@凌驾
受保护的void onPostExecute(字符串结果)
{
试一试{
JSONObject json=新的JSONObject(结果);
//下面的代码用于用户计数
JSONObject userNotificationjson=json.getJSONObject(“用户通知”);
if(json.has(“用户通知”))
{
字符串userCount=userNotificationjson.getString(“count”);
int Count=Integer.parseInt(userCount);
如果(计数>0)
{
LinearLayout llUserCount=(LinearLayout)findViewById(R.id.llUserCount);
TextView userCountTextView=(TextView)findViewById(R.id.txtUserCount);
llUserCount.setVisibility(View.VISIBLE);
userCountTextView.setText(userCount);
}
}
}
私有字符串convertStreamToString(InputStream为)
{
//代码
}
`

我的默认选项卡提要活动

  public class Feeds extends Activity 
  {
SessionManager session;
String custom_phpsess_id,logged_in_id_User,returnString;

// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;

 static  String FIRST_NAME = "firstname";
 static  String LAST_NAME = "lastname";
 static  String ACTION = "action";
// static  String ACTIVITY_NAME = "activity_name";
 static  String IMAGE_URL = "image";
 static  String USER_ID = "user_id";
 static  String ACTIVITY_NAME = "activityname";

 String strUrl = =new URL(getString(R.string.WebServiceURL)+"/users/userfeeds";
 ListView mListView;
 String id_User;

 public void onCreate(Bundle savedInstanceState) 
 {
    super.onCreate(savedInstanceState);

    // Get the view from feeds.xml
     setContentView(R.layout.feeds);

    session = new SessionManager(getApplicationContext());

    //To get values from session
    HashMap<String, String> User = session.getUserDetails();

    logged_in_id_User = User.get(SessionManager.KEY_ID);
    custom_phpsess_id = User.get(SessionManager.KEY_USE);

    // Creating a new non-ui thread task to download json data 
    // Execute DownloadJSON AsyncTask

    Log.i("On Create", "Main On Create");
    new DownloadJSON().execute();
  }

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> 
{
    @Override
    protected void onPreExecute() 
    {
        Log.i("On DownloadJSON", "onPreExecute");
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(Feeds.this);
        // Set progressdialog title
        mProgressDialog.setTitle("");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) 
    {
        Log.i("On doInBackground", "doInBackground");
        // Create the array 
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrive JSON Objects from the given website URL in JSONfunctions.class
        jsonobject = JSONfunctions
                .getJSONfromURL(strUrl);
        Log.i("On doInBackground-jsonObject", jsonobject.toString());

        try 
        {
            // Locate the array name
            jsonarray = jsonobject.getJSONArray("userdata");

            Log.i("On doInBackground-jsonarray", jsonarray.toString());


            for (int i = 0; i < jsonarray.length(); i++) 
            {

                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    if(jsonobject.getString("actions").equals("Completed"))
                    {
                        map.put("firstname", jsonobject.getString("first_name"));
                        map.put("lastname", jsonobject.getString("last_name"));
                        map.put("action", jsonobject.getString("actions"));
                        map.put("image", jsonobject.getString("file_name"));
                        map.put("user_id", jsonobject.getString("id_user"));
                        map.put("activityname", jsonobject.getString("activity_name"));

                        Log.i("On doInBackground-Map", map.toString());
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
            } 
        }
        catch (JSONException e) 
        {
            Log.i("On doInBackground-JSONException", e.toString());
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) 
    {
        Log.i("On onPostExecute", "ON post exe");
        // Locate the listview in listview_main.xml
        listview = (ListView)findViewById(R.id.listview);

        Log.i("On onPostExecute-onPostExecute-arraylist", arraylist.toString());
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(Feeds.this, arraylist);
        Log.i("On onPostExecute-onPostExecute-Adapter", adapter.toString());
        // Binds the Adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}
 }
公共类提要扩展活动
{
会话管理器会话;
字符串custom_phpsess_id,logged_in_id_User,returnString;
//声明变量
JSONObject JSONObject;
JSONArray JSONArray;
列表视图列表视图;
ListViewAdapter适配器;
进程对话框;
ArrayList ArrayList;
静态字符串FIRST\u NAME=“firstname”;
静态字符串LAST\u NAME=“lastname”;
静态字符串ACTION=“ACTION”;
//静态字符串ACTIVITY\u NAME=“ACTIVITY\u NAME”;
静态字符串IMAGE\u URL=“IMAGE”;
静态字符串USER\u ID=“USER\u ID”;
静态字符串ACTIVITY\u NAME=“activityname”;
String strUrl==新URL(getString(R.String.WebServiceURL)+“/users/userfeeds”;
列表视图;
字符串id_用户;
创建时的公共void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//从feeds.xml获取视图
setContentView(R.layout.feeds);
session=newsessionmanager(getApplicationContext());
//从会话获取值的步骤
HashMap User=session.getUserDetails();
logged_in_id_User=User.get(SessionManager.KEY_id);
custom_phpsess_id=User.get(SessionManager.KEY_USE);
//创建新的非ui线程任务以下载json数据
//执行下载JSON异步任务
Log.i(“创建时”,“创建时主要”);
新建下载JSON().execute();
}
//下载JSON异步任务
私有类下载JSON扩展异步任务
{
@凌驾
受保护的void onPreExecute()
{
06-24 11:44:11.412: W/SingleClientConnManager(422): Invalid use of SingleClientConnManager: connection still allocated.
06-24 11:44:11.412: W/SingleClientConnManager(422): Make sure to release the connection before allocating another one.
06-24 11:44:11.531: E/log_tag(422): Error in http connection java.net.SocketException: Socket closed
06-24 11:44:11.551: E/log_tag(422): Error converting result java.lang.NullPointerException
06-24 11:44:11.571: E/log_tag(422): Error parsing data org.json.JSONException: End of input at character 0 of 
06-24 11:44:11.911: W/dalvikvm(422): threadid=10: thread exiting with uncaught exception (group=0x40014760)
06-24 11:44:12.701: E/AndroidRuntime(422): FATAL EXCEPTION: AsyncTask #2
06-24 11:44:12.701: E/AndroidRuntime(422): java.lang.RuntimeException: An error occured while executing doInBackground()
06-24 11:44:12.701: E/AndroidRuntime(422):  at android.os.AsyncTask$3.done(AsyncTask.java:266)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.lang.Thread.run(Thread.java:1020)
06-24 11:44:12.701: E/AndroidRuntime(422): Caused by: java.lang.NullPointerException
06-24 11:44:12.701: E/AndroidRuntime(422):  at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:97)
06-24 11:44:12.701: E/AndroidRuntime(422):  at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:1)
06-24 11:44:12.701: E/AndroidRuntime(422):  at android.os.AsyncTask$2.call(AsyncTask.java:252)
06-24 11:44:12.701: E/AndroidRuntime(422):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-24 11:44:12.701: E/AndroidRuntime(422):  ... 4 more
06-24 11:44:13.661: E/WindowManager(422): Activity com.si.gtc.Login_Header has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40feb498 that was originally added here
06-24 11:44:13.661: E/WindowManager(422): android.view.WindowLeaked: Activity com.si.gtc.Login_Header has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40feb498 that was originally added here
06-24 11:44:13.661: E/WindowManager(422):   at android.view.ViewRoot.<init>(ViewRoot.java:285)
06-24 11:44:13.661: E/WindowManager(422):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:152)
06-24 11:44:13.661: E/WindowManager(422):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
06-24 11:44:13.661: E/WindowManager(422):   at android.view.Window$LocalWindowManager.addView(Window.java:526)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.Dialog.show(Dialog.java:269)
06-24 11:44:13.661: E/WindowManager(422):   at com.si.gtc.Feeds$DownloadJSON.onPreExecute(Feeds.java:85)
06-24 11:44:13.661: E/WindowManager(422):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:549)
06-24 11:44:13.661: E/WindowManager(422):   at android.os.AsyncTask.execute(AsyncTask.java:499)
06-24 11:44:13.661: E/WindowManager(422):   at com.si.gtc.Feeds.onCreate(Feeds.java:66)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.ActivityThread.startActivityNow(ActivityThread.java:1589)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:130)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:342)
06-24 11:44:13.661: E/WindowManager(422):   at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:676)
06-24 11:44:13.661: E/WindowManager(422):   at android.widget.TabHost.setCurrentTab(TabHost.java:345)
06-24 11:44:13.661: E/WindowManager(422):   at android.widget.TabHost.addTab(TabHost.java:235)
06-24 11:44:13.661: E/WindowManager(422):   at com.si.gtc.Login_Header.onCreate(Login_Header.java:104)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1712)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1764)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.ActivityThread.access$1500(ActivityThread.java:122)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1002)
06-24 11:44:13.661: E/WindowManager(422):   at android.os.Handler.dispatchMessage(Handler.java:99)
06-24 11:44:13.661: E/WindowManager(422):   at android.os.Looper.loop(Looper.java:132)
06-24 11:44:13.661: E/WindowManager(422):   at android.app.ActivityThread.main(ActivityThread.java:4025)
06-24 11:44:13.661: E/WindowManager(422):   at java.lang.reflect.Method.invokeNative(Native Method)
06-24 11:44:13.661: E/WindowManager(422):   at java.lang.reflect.Method.invoke(Method.java:491)
06-24 11:44:13.661: E/WindowManager(422):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
06-24 11:44:13.661: E/WindowManager(422):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
06-24 11:44:13.661: E/WindowManager(422):   at dalvik.system.NativeStart.main(Native Method)
     try 
        {
            URL url=new URL(getString(R.string.WebServiceURL)+"/notifications/notificationcount");
            HttpPost httppost = new HttpPost(url.toString());
            HttpResponse responsePOST = LoginPage.httpClient.execute(httppost); 
            HttpEntity resEntity = responsePOST.getEntity();
            InputStream instream = resEntity.getContent();
            String result = convertStreamToString(instream);

            Log.i("User Feed",result);
            return result;
        }
        catch(Exception ex) 
        { 
               Log.e("error", "error", ex);
               return null;
        }
        finally{
               instream.close();
        }