2013-06-24 30 views
0

我爲0123工作完成時使用AsyncTask,但是當我在一個活動(tab.java)和Default tab-view(Feed.java)中有選項卡時出現問題。即默認顯示的第一個標籤。這兩個類文件都有自己的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 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)+"https://stackoverflow.com/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(); 
    } 
} 
} 

的logcat:

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 [email protected] 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 [email protected] 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) 
+0

「Feeds.java」的第97行發生了什麼?我問這個的原因是因爲你的logcat輸出說錯誤是:'6-24 11:44:12.701:E/AndroidRuntime(422):引起:java.lang.NullPointerException 06-24 11:44 :12.701:E/AndroidRuntime(422):at com.si.gtc.Feeds $ DownloadJSON.doInBackground(Feeds.java:97)' – Tigger

+0

Line no。 97 is = Log.i(「On doInBackground-jsonObject」,jsonobject.toString()); – user2495890

+0

所以...修復該行的'NullPointerException'並更新你的問題。 – Tigger

回答

0

內的AsyncTask的doInBackground方法記得關閉InputStream就象這樣:

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

您還可以檢查this問題的相關答案,也許它可以幫助你。

相關問題