0

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

这种操作怎么做?

谢谢你。

我的代码:

标签.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)+"/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();
    }
}
 }

日志猫:

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)
4

1 回答 1

0

doInBackgroundAsyncTask 的方法中记得关闭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();
        }

您也可以查看问题和相关答案,也许它可以帮助您。

于 2013-06-24T10:40:56.573 回答