数据未从上一页检索,从意图传递

时间:2014-01-05 12:22:36

标签: java android json android-intent

我的应用程序要求页面中的数据传递到另一个页面,但显然不会传递数据,而且我不确定错误。以下是警告代码和错误代码。

W/System.err(18031): org.json.JSONException: No value for employ
W/System.err(18031):    at org.json.JSONObject.get(JSONObject.java:354)
W/System.err(18031):    at org.json.JSONObject.getJSONArray(JSONObject.java:548)
W/System.err(18031):    at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:138)
W/System.err(18031):    at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:1)
W/System.err(18031):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
W/System.err(18031):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
W/System.err(18031):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
W/System.err(18031):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
W/System.err(18031):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
W/System.err(18031):    at java.lang.Thread.run(Thread.java:841)
E/ViewRootImpl(18031): sendUserActionEvent() mView == null

这是java类的代码。

package com.example.splashscreentwo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class EmployeePayslip extends Activity {

    private ProgressDialog pDialog;
    String pid;
    TextView employeeName;
    TextView Desc;
    TextView txtCreatedAt;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    JSONArray payslip = null;
    ArrayList<HashMap<String, String>> payslipList;

    // url to get all fulltime employees list
    private static String url_payslip = "http://rollit.sg/FYP/ExportPayslip.php";
    private static String url_employees = "http://rollit.sg/FYP/Existing_employees_FullTime.php";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PAYSLIP = "payslip";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PAYSLIPNO = "payslipno";
    private static final String TAG_NETSALARY = "netsalary";
    private static final String TAG_ISSUEDATE = "issuedate";
    private static final String TAG_STARTOFPAYSLIP = "startofpayslip";
    private static final String TAG_ENDOFPAYSLIP = "endofpayslip";
    private static final String TAG_TYPEOFALLOWANCE = "typeofallowance";
    private static final String TAG_ALLOWANCEAMT = "allowanceamt";
    private static final String TAG_ALLOWANCEDATE = "allowancedate";
    private static final String TAG_AVAILABLEALLOWANCE = "availableallowance";
    private static final String TAG_TYPEOFDEDUCTION = "typeofdeduction";
    private static final String TAG_DEDUCTIONAMT = "deductionamt";
    private static final String TAG_DEDUCTIONDATE = "deductiondate";
    private static final String TAG_AGREEDOVERTIMERATE = "agreedovertimerate";
    private static final String TAG_OVERTIMERATE = "overtimerate";
    private static final String TAG_STARTOFOVERTIMEPERIOD = "startofovertimeperiod";
    private static final String TAG_ENDOFOVERTIMEPERIOD = "endofovertimeperiod";
    private static final String TAG_BASICSALARY = "basicsalary";
    private static final String TAG_EXTRAPAYMENT = "extrapayment";

    private static final String TAG_EMPLOYEE = "employ";
    private static final String TAG_SALARY = "pay";
    private static final String TAG_DESCRIPTION = "description";




    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.employeepayslip);




     payslipList = new ArrayList<HashMap<String, String>>();

     // Loading all fulltime employees in Background Thread
     // getting employee details from intent
     Intent i = getIntent();

     // getting employee id (pid) from intent
     pid = i.getStringExtra(TAG_PID);


     new GetEmployeeDetails().execute();

    }
    class GetEmployeeDetails extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(EmployeePayslip.this);
            pDialog.setMessage("Loading employees details. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Getting employee details in background thread
         * */
        protected String doInBackground(String... params) {

            // updating UI from Background Thread

                     // Check for success tag
                     int success;
                     try {
                         // Building Parameters
                         List<NameValuePair> params1 = new ArrayList<NameValuePair>();
                         params1.add(new BasicNameValuePair("pid", pid));

                         // getting employee details by making HTTP request
                         // Note that employee details url will use GET request
                         JSONObject json = jParser.makeHttpRequest(
                                 url_employees, "GET", params1);

                         // check your log for json response
                         Log.d("Employee Details", json.toString());

                         // json success tag
                         success = json.getInt(TAG_SUCCESS);
                         if (success == 1) {
                             // successfully received employee details
                             JSONArray employeeObj = json
                                     .getJSONArray(TAG_EMPLOYEE); // JSON Array

                             // get first employee object from JSON Array
                             JSONObject employee = employeeObj.getJSONObject(0);

                             // employee with this pid found
                             // Edit Text
                             employeeName = (TextView) findViewById(R.id.employeeName);

                             Desc = (TextView) findViewById(R.id.departmenttext);

                             // display employee data in EditText
                             employeeName.setText(employee.getString(TAG_NAME));

                             Desc.setText(employee.getString(TAG_DESCRIPTION));

                         }else{
                             // employee with pid not found
                         }
                     } catch (JSONException e) {
                         e.printStackTrace();
                     }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            pDialog.dismiss();
        }
    }



}

这是上一页的代码。此页面中的数据将传递到上面的另一页。

 package com.example.splashscreentwo;

 import java.util.ArrayList; 
 import java.util.HashMap; 
 import java.util.List;

 import org.apache.http.NameValuePair; 
 import org.json.JSONArray;
 import org.json.JSONException; 
 import org.json.JSONObject;


 import android.app.ListActivity; 
 import android.app.ProgressDialog;
 import android.content.Intent; 
 import android.os.AsyncTask; 
 import android.os.Bundle; 
 import android.telephony.SmsManager; 
 import android.util.Log; 
 import android.view.LayoutInflater; 
 import android.view.View; 
 import android.widget.AdapterView; 
 import android.widget.AdapterView.OnItemClickListener;

 import android.widget.ImageButton; 
 import android.widget.ListAdapter; 
 import android.widget.ListView; 
 import android.widget.SimpleAdapter; 
 import android.widget.TextView;


 public class AllFTemployeesActivity extends ListActivity 
 {
 LayoutInflater inflater;    // Progress Dialog
 private ProgressDialog pDialog;

 // Creating JSON Parser object
 JSONParser jParser = new JSONParser();

 ArrayList<HashMap<String, String>> employeesList;

 // url to get all fulltime employees list

  private static String url_employees = "http://rollit.sg/FYP/Existing_employees_FullTime.php";

 // JSON Node names
 private static final String TAG_SUCCESS = "success";
 private static final String TAG_EMPLOYEE = "employee";
 private static final String TAG_PID = "pid";
 private static final String TAG_NAME = "name";
 private static final String TAG_DESCRIPTION = "description";


 // products JSONArray
 JSONArray employee = null;     private ListView listview;

 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.all_ft_employees);


     ImageButton ButtonPT = (ImageButton) findViewById(R.id.btnpt);
     ImageButton BtnAddEmployee = (ImageButton) findViewById(R.id.addEmployeeBtn);

     BtnAddEmployee.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View view) {
             // Launching emplopyee regstration Activity
             Intent i = new Intent(getApplicationContext(), RegisterEmployeeActivity.class);
             startActivity(i);

             finish();

         }
     });

     ButtonPT.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View view) {
             // Launching All fulltime employees Activity
             Intent i = new Intent(getApplicationContext(), AllPTemployeesActivity.class);
             startActivity(i);

             finish();

         }
     });



     // Hashmap for ListView
    employeesList = new ArrayList<HashMap<String, String>>();

     // Loading all fulltime employees in Background Thread
     new LoadAllEmployee().execute();

     // Get listview

     ListView lv = getListView();
     lv.setTextFilterEnabled(true);


     //inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    //  View header = inflater.inflate(R.layout.planets_heade_view, null);

    // lv.addHeaderView(header);

      // on seleting single fulltime employee
      // launching Edit single fulltime employee Screen
     lv.setOnItemClickListener(new OnItemClickListener() {

         @Override
         public void onItemClick(AdapterView<?> parent, View view,
                 int position, long id) {
             // getting values from selected ListItem
             String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                     .toString();


             // Starting new intent
             Intent in = new Intent(getApplicationContext(),
                   EmployeePayslip.class);
             // sending pid to next activity
             in.putExtra(TAG_PID, pid);

             // starting new activity and expecting some response back
             startActivityForResult(in, 100);
         }
     });

 }    // Response from Edit single fulltime employee Activity
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     // if result code 100
     if (resultCode == 100) {
         // if result code 100 is received
         // means user edited/deleted employee
         // reload this screen again
         Intent intent = getIntent();
         finish();
         startActivity(intent);


     }

 }

 /**
  * Background Async Task to Load all fulltime employees by making HTTP Request
  * */
 class LoadAllEmployee extends AsyncTask<String, String, String> {

     /**
      * Before starting background thread Show Progress Dialog
      * */
     @Override
   //  protected void onPreExecute() {
      //   super.onPreExecute();
       //  pDialog = new ProgressDialog(AllProductsActivity.this);
       //  pDialog.setMessage("Loading products. Please wait...");
        // pDialog.setIndeterminate(false);
       //  pDialog.setCancelable(false);
       //  pDialog.show();    //     }  //
     /**
      * getting All fulltime employees from url
      * */
     protected String doInBackground(String... args) {
         // Building Parameters
         List<NameValuePair> params = new ArrayList<NameValuePair>();
         // getting JSON string from URL
         JSONObject json = jParser.makeHttpRequest(url_employees, "GET", params);

         // Check your log cat for JSON reponse
         Log.d("All Products: ", json.toString());

         try {
             // Checking for SUCCESS TAG
             int success = json.getInt(TAG_SUCCESS);

             if (success == 1) {
                 // fulltime employees found
                 // Getting Array of fulltime employees
                 employee = json.getJSONArray(TAG_EMPLOYEE);

                 // looping through All fulltime employees
                 for (int i = 0; i < employee.length(); i++) {
                     JSONObject c = employee.getJSONObject(i);

                     // Storing each json item in variable
                     String id = c.getString(TAG_PID);
                     String name = c.getString(TAG_NAME);
                     String description= c.getString(TAG_DESCRIPTION);


                     // creating new HashMap
                     HashMap<String, String> map = new HashMap<String, String>();

                     // adding each child node to HashMap key => value
                     map.put(TAG_PID, id);
                     map.put(TAG_NAME, name);
                    map.put(TAG_DESCRIPTION, description);

                    // adding HashList to ArrayList
                     employeesList.add(map);
                 }
             } else {
                 // no fulltime employee found
                 // Launch Add New employee Activity
              //   Intent i = new Intent(getApplicationContext(),
                 //        NewProductActivity.class);
                 // Closing all previous activities
              //   i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
               //  startActivity(i);
             }
         } catch (JSONException e) {
             e.printStackTrace();
         }

         return null;
     }
     /**
      * After completing background task Dismiss the progress dialog
      * **/
     protected void onPostExecute(String file_url) {
         // dismiss the dialog after getting all products
       //  pDialog.dismiss();


         // updating UI from Background Thread
         runOnUiThread(new Runnable() {
             public void run() {
                 /**
                  * Updating parsed JSON data into ListView
                  * */

                 ListAdapter adapter = new SimpleAdapter(
                         AllFTemployeesActivity.this, employeesList,
                         R.layout.list_item_ft, new String[] { TAG_PID,
                                 TAG_NAME,TAG_DESCRIPTION},
                         new int[] { R.id.pid, R.id.name, R.id.description});

                 // updating listview
                 setListAdapter(adapter);


             }
         });

     }


 }   }

代码有什么问题?我错过了什么吗?如果是这样,请指导我,谢谢,我感谢任何帮助!

因此字符串存在拼写错误。纠正String中的拼写后,我得到了这个错误。

E/AndroidRuntime(2421): FATAL EXCEPTION: AsyncTask #4
E/AndroidRuntime(2421): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(2421):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
E/AndroidRuntime(2421):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
E/AndroidRuntime(2421):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
E/AndroidRuntime(2421):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
E/AndroidRuntime(2421):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
E/AndroidRuntime(2421):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
E/AndroidRuntime(2421):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
E/AndroidRuntime(2421):     at java.lang.Thread.run(Thread.java:841)
E/AndroidRuntime(2421): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
E/AndroidRuntime(2421):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6833)
E/AndroidRuntime(2421):     at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1082)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.widget.ScrollView.requestLayout(ScrollView.java:2120)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.widget.TableLayout.requestLayout(TableLayout.java:230)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.view.View.requestLayout(View.java:16775)
E/AndroidRuntime(2421):     at android.widget.TextView.checkForRelayout(TextView.java:7660)
E/AndroidRuntime(2421):     at android.widget.TextView.setText(TextView.java:4446)
E/AndroidRuntime(2421):     at android.widget.TextView.setText(TextView.java:4283)
E/AndroidRuntime(2421):     at android.widget.TextView.setText(TextView.java:4258)
E/AndroidRuntime(2421):     at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:153)
E/AndroidRuntime(2421):     at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.doInBackground(EmployeePayslip.java:1)
E/AndroidRuntime(2421):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
E/AndroidRuntime(2421):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
E/AndroidRuntime(2421):     ... 4 more
D/AbsListView(2421): onVisibilityChanged() is called, visibility : 0
D/AbsListView(2421): unregisterIRListener() is called 
D/AbsListView(2421): unregisterIRListener() is called 
E/WindowManager(2421): Activity com.example.splashscreentwo.EmployeePayslip has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42e528b0 V.E..... R.....ID 0,0-640,230} that was originally added here
E/WindowManager(2421): android.view.WindowLeaked: Activity com.example.splashscreentwo.EmployeePayslip has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42e528b0 V.E..... R.....ID 0,0-640,230} that was originally added here
E/WindowManager(2421):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:454)
E/WindowManager(2421):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
E/WindowManager(2421):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
E/WindowManager(2421):  at android.app.Dialog.show(Dialog.java:287)
E/WindowManager(2421):  at com.example.splashscreentwo.EmployeePayslip$GetEmployeeDetails.onPreExecute(EmployeePayslip.java:111)
E/WindowManager(2421):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
E/WindowManager(2421):  at android.os.AsyncTask.execute(AsyncTask.java:534)
E/WindowManager(2421):  at com.example.splashscreentwo.EmployeePayslip.onCreate(EmployeePayslip.java:93)
E/WindowManager(2421):  at android.app.Activity.performCreate(Activity.java:5372)
E/WindowManager(2421):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
E/WindowManager(2421):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
E/WindowManager(2421):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2362)
E/WindowManager(2421):  at android.app.ActivityThread.access$700(ActivityThread.java:168)
E/WindowManager(2421):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1329)
E/WindowManager(2421):  at android.os.Handler.dispatchMessage(Handler.java:99)
E/WindowManager(2421):  at android.os.Looper.loop(Looper.java:137)
E/WindowManager(2421):  at android.app.ActivityThread.main(ActivityThread.java:5493)
E/WindowManager(2421):  at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager(2421):  at java.lang.reflect.Method.invoke(Method.java:525)
E/WindowManager(2421):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
E/WindowManager(2421):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
E/WindowManager(2421):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

而不是在EmployeePayslip

中关注
 // Loading all fulltime employees in Background Thread
 // getting employee details from intent
 Intent i = getIntent();

 // getting employee id (pid) from intent
 pid = i.getStringExtra(TAG_PID);

尝试以下

Bundle extras = getIntent().getExtras();

if (extras != null)
{
    pid = extras.getString(TAG_PID);
}

已编辑:似乎 @ user666 是正确的。首先在两个类中更正TAG_EMPLOYEE的拼写如下:

private static final String TAG_EMPLOYEE = "employee";