运行两个异步任务时出错

时间:2013-06-27 11:49:39

标签: android android-asynctask

我被困在这个堆栈跟踪上,我不知道它背后的原因是什么。

06-27 17:05:14.841: W/SingleClientConnManager(1519): Invalid use of SingleClientConnManager: connection still allocated.
06-27 17:05:14.841: W/SingleClientConnManager(1519): Make sure to release the connection before allocating another one.
06-27 17:05:15.031: E/log_tag(1519): Error in http connection java.net.SocketException: Socket closed
06-27 17:05:15.077: E/log_tag(1519): Error converting result java.lang.NullPointerException
06-27 17:05:15.181: E/log_tag(1519): Error parsing data org.json.JSONException: End of input at character 0 of 
06-27 17:05:15.531: W/dalvikvm(1519): threadid=10: thread exiting with uncaught exception (group=0x40014760)
06-27 17:05:15.821: E/AndroidRuntime(1519): FATAL EXCEPTION: AsyncTask #2
06-27 17:05:15.821: E/AndroidRuntime(1519): java.lang.RuntimeException: An error occured while executing doInBackground()
06-27 17:05:15.821: E/AndroidRuntime(1519):     at android.os.AsyncTask$3.done(AsyncTask.java:266)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.lang.Thread.run(Thread.java:1020)
06-27 17:05:15.821: E/AndroidRuntime(1519): Caused by: java.lang.NullPointerException
06-27 17:05:15.821: E/AndroidRuntime(1519):     at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:87)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at com.si.gtc.Feeds$DownloadJSON.doInBackground(Feeds.java:1)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at android.os.AsyncTask$2.call(AsyncTask.java:252)
06-27 17:05:15.821: E/AndroidRuntime(1519):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-27 17:05:15.821: E/AndroidRuntime(1519):     ... 4 more

在不同的活动中,有两个json响应同时起作用。如果我运行单个响应,则Null指针错误不会影响我的输出。

第一个活动包含tabhost(Tab)。第一个选项卡(默认选项卡)具有另一个异步任务。

这是我的第一个包含Json调用和Tab主机的活动。

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
}

现在这是我的第二个活动,Default Tab活动,它再次有json请求。

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

和空指针行是..

行号97是= Log.i(“on doInBackground-jsonObject”,jsonobject.toString());

0 个答案:

没有答案