php - android使用php脚本从数据库中检索值

标签 php android json android-listview

我是 android 的新手,现在我在 ListView 中遇到了一些问题,一个列表屏幕在列表中有一些名字,当我点击这些名字中的任何一个时,它应该将该 id 传递给另一个 Activity 以及在哪里它必须根据代码从数据库中获取一些数据 但我的 Activity 正在停止......所以请任何人帮助我...... alluseractivity 连接到显示一些列表的列表,它正在工作,但 employeedetails 该 Activity 有一些问题....我也给了 xml 代码和 php 代码所以请在这里帮助我.. 这是 logcat View ...... 同一个代码中的另一个问题先生,当我尝试更新这些东西并再次从头开始运行它停止到达此屏幕之前我正在将代码添加到 empdetailsactivity 所以请检查它并让我知道

     E/AndroidRuntime(803): android.os.NetworkOnMainThreadException
     android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
 libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
 libcore.io.IoBridge.connectErrno(IoBridge.java:127)
 libcore.io.IoBridge.connect(IoBridge.java:112)
     java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
 java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
 java.net.Socket.connect(Socket.java:842)

      org.apache.http.conn.scheme.PlainSocketFactory.connectSocket
     (PlainSocketFactory.java:119)
  org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(
      DefaultClientConnectionOperator.java:144)
 org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
     org.apache.http.impl.conn.AbstractPooledConnAdapter.open
      (AbstractPooledConnAdapter.java:119)
 org.apache.http.impl.client.DefaultRequestDirector.execute
     (DefaultRequestDirector.java:360)
 org.apache.http.impl.client.AbstractHttpClient.execute
     (AbstractHttpClient.java:555)
 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
 com.example.demo3.JSONParser.makeHttpRequest(JSONParser.java:61)
     com.example.demo3.EmpDetailsActivity$GetEmployeeDetails$1.run
        (EmpDetailsActivity.java:95)
 android.os.Handler.handleCallback(Handler.java:725)
 android.os.Handler.dispatchMessage(Handler.java:92)
 android.os.Looper.loop(Looper.java:137)
     android.app.ActivityThread.main(ActivityThread.java:5041)
 java.lang.reflect.Method.invokeNative(Native Method)
 java.lang.reflect.Method.invoke(Method.java:511)
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 dalvik.system.NativeStart.main(Native Method)




      public class AllUserActivity extends ListActivity {

        private ProgressDialog pDialog;


JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> employeesList;

private static String url_all_emp =       "http://10.0.2.2/get_all_employees.php";


private static final String TAG_SUCCESS = "success";
private static final String TAG_EMPLOYEES = "emp";
private static final String TAG_EID = "eid";
private static final String TAG_NAME = "username";


JSONArray employees = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_employees);
    // Hashmap for ListView
    employeesList = new ArrayList<HashMap<String, String>>();

    new LoadAllProducts().execute();
            ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

    String eid = ((TextView) view.findViewById(R.id.eid)).getText().toString();   

            Intent in = new Intent(getApplicationContext(),EmpDetailsActivity.class);
                    in.putExtra(TAG_EID, eid);


                    startActivityForResult(in, 100);
                }
            });}

    class LoadAllProducts extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(AllUserActivity.this);
            pDialog.setMessage("Loading employees. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }


        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

    JSONObject json = jParser.makeHttpRequest(url_all_emp, "GET", params);


            Log.d("All Employees: ", json.toString());

            try {

                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                employees = json.getJSONArray(TAG_EMPLOYEES);


            for (int i = 0; i < employees.length(); i++) {
                JSONObject c = employees.getJSONObject(i);


                String eid = c.getString(TAG_EID);
                String username = c.getString(TAG_NAME);


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


                        map.put(TAG_EID, eid);
                        map.put(TAG_NAME, username);


                        employeesList.add(map);
                    }
                } else {


                Intent i = new Intent(getApplicationContext(),
                            MainActivity.class);

                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }


        protected void onPostExecute(String file_url) {

            pDialog.dismiss();

            runOnUiThread(new Runnable() {
                public void run() {

            ListAdapter adapter = new SimpleAdapter(
                AllUserActivity.this, employeesList,
        R.layout.list_item, new String[] { TAG_EID,TAG_NAME},
                    new int[] { R.id.eid, R.id.username });

                    setListAdapter(adapter);
                }
            });

        }

    }

           }





             public class EmpDetailsActivity extends Activity
                {
EditText txtName;
EditText txtfname;
EditText txtlname;
EditText txtpwd;
EditText txtloc;

EditText txtcnct;
String eid;


private ProgressDialog pDialog;


JSONParser jsonParser = new JSONParser();

private static final String url_get_emp =    "http://10.0.2.2/img1/get_emp_det.php";
private static final String url_update_emp = "http://10.0.2.2/img1/update_emp.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_EMPLOYEE = "emp";
private static final String TAG_EID = "eid";
private static final String TAG_NAME = "username";
private static final String TAG_FNAME = "firstname";
private static final String TAG_LNAME = "lastname";
private static final String TAG_PWD = "password";


private static final String TAG_LOC = "location";
private static final String TAG_CNCT= "contact";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_employee);
    if (android.os.Build.VERSION.SDK_INT > 9){ StrictMode.ThreadPolicy policy = new
    StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy);
     }
        Intent i = getIntent();

    eid = i.getStringExtra(TAG_EID);

    new GetEmployeeDetails().execute();
        btnSave.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // starting background task to update employee
            new SaveemployeeDetails().execute();
        }
    });
}

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



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EmpDetailsActivity.this);
        pDialog.setMessage("Loading employee details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... params) {


        runOnUiThread(new Runnable() {
            public void run() {

                int success;
                try {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("eid", eid));


                JSONObject json = jsonParser.makeHttpRequest(
                        url_get_emp, "GET", params);


                Log.d("Single employee Details", json.toString());


                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {

            JSONArray employeeObj = json
                    .getJSONArray(TAG_EMPLOYEE); 


                JSONObject employee = employeeObj.getJSONObject(0);



                txtName = (EditText) findViewById(R.id.inputName);                  
                txtfname = (EditText) findViewById(R.id.inputfName);
                txtcnct = (EditText) findViewById(R.id.cnct);
                txtpwd = (EditText) findViewById(R.id.pwd);
                txtlname= (EditText) findViewById(R.id.inputlName);
                txtloc = (EditText) findViewById(R.id.loc);



                txtName.setText(employee.getString(TAG_NAME));
                txtfname.setText(employee.getString(TAG_FNAME));
                txtlname.setText(employee.getString(TAG_LNAME));
                txtpwd.setText(employee.getString(TAG_PWD));
                txtjob.setText(employee.getString(TAG_JOB));
                txtloc.setText(employee.getString(TAG_LOC));
                txtcnct.setText(employee.getString(TAG_CNCT));
                        }else{

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }



    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
    }
 }

   class SaveemployeeDetails extends AsyncTask<String, String, String> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(EmpDetailsActivity.this);
        pDialog.setMessage("Saving employee ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


    protected String doInBackground(String... args) {

        // getting updated data from EditTexts
        String name = txtName.getText().toString();
        String fname = txtfname.getText().toString();
        String lname = txtlname.getText().toString();
        String cnct = txtcnct.getText().toString();
        String pwd = txtpwd.getText().toString();
        String loc = txtloc.getText().toString();


        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_EID, eid));
        params.add(new BasicNameValuePair(TAG_NAME, name));
        params.add(new BasicNameValuePair(TAG_FNAME, fname));
        params.add(new BasicNameValuePair(TAG_LNAME, lname));
        params.add(new BasicNameValuePair(TAG_PWD, pwd));
        params.add(new BasicNameValuePair(TAG_CNCT, cnct));
        params.add(new BasicNameValuePair(TAG_LOC, loc));


        // sending modified data through http request
        // Notice that update employee url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_update_employee,
                "POST", params);

        // check json success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully updated
                Intent i = getIntent();

                setResult(100, i);
                finish();
            } else {
                // failed to update employee
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }



    protected void onPostExecute(String file_url) {
        // dismiss the dialog once employee uupdated
        pDialog.dismiss();
    }
}


     }

       <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
      android:layout_height="wrap_content"
    android:text="Employee Name"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

     <!-- Input Name -->
<EditText android:id="@+id/inputName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true"/>

 <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Employee fName"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

   <!-- Input Name -->
<EditText android:id="@+id/inputfName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true"/>

 <!-- Name Label -->
     <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Employee lName"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

      <!-- Input Name -->
<EditText android:id="@+id/inputlName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true"/>


 <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Employee pwd"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

     <!-- Input Name -->
<EditText android:id="@+id/pwd"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true"/>

 <!-- Name Label -->
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Employee cnct"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

     <!-- Input Name -->
<EditText android:id="@+id/cnct"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:singleLine="true"/>


<!-- salary Label -->
    <TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="loc"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:paddingTop="10dip"
    android:textSize="17dip"/>

    <!-- Input salary -->
<EditText android:id="@+id/loc" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dip"
    android:layout_marginBottom="15dip"
    android:gravity="top"/>



<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

   <Button android:id="@+id/btnSave" 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/save_changes"
    android:layout_weight="1"/>


</LinearLayout>

     </LinearLayout>

   <?php




  $response = array();
  require_once __DIR__ . '/db_connect.php';


   $db = new DB_CONNECT();
  if (isset($_GET["eid"])) {
   $eid = $_GET['eid'];


   $result = mysql_query("SELECT * FROM userss WHERE eid = $eid");

   if (!empty($result)) {

    if (mysql_num_rows($result) > 0) {

        $result = mysql_fetch_array($result);

        $emp = array();
        $emp["eid"] = $result["eid"];
      $emp["firstname"] = $result["firstname"];
  $emp["lastname"] = $result["lastname"];
        $emp["username"] = $result["username"];
        $emp["password"] = $result["password"];
        $emp["location"] = $result["location"];
        $emp["contact"] = $result["contact"];
        // success
        $response["success"] = 1;

        // user node
        $response["emp"] = array();

        array_push($response["emp"], $emp);

        // echoing JSON response
        echo json_encode($response);
    } else {
        // no emp found
        $response["success"] = 0;
        $response["message"] = "No emp found";

        // echo no users JSON
        echo json_encode($response);
      }
    } else {
    // no emp found
    $response["success"] = 0;
    $response["message"] = "No emp found";

    // echo no users JSON
    echo json_encode($response);
     }
    } else {

   $response["success"] = 0;
   $response["message"] = "Required field(s) is missing";


   echo json_encode($response);
   }
        ?>

最佳答案

  Put the below code just below the setContentView() in your activity.

    if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }

If error comes after saving your application then just mouseover the error and add  @SuppressLint("NewApi")(Eclipse will give you option on mouse over).For example you will get an error on the word "build".Inform me if it works.

关于php - android使用php脚本从数据库中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793563/

相关文章:

php - 我在哪里可以获得反射修饰符值的列表?

javascript - 如何在网站上保留用户的事件日志?

Android:如何从原始短信中获取发件人和收件人的电话号码

android - 使用 Amazon Device Farm 或类似工具检查浏览器

json - OPENJSON - 关键字 'with' 附近的语法不正确

c# - 在转换为 XML 之前更改 JSON 对象中的属性名称

php - 如何从 PDO 故障 "Error!: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined"中获取更多信息?

php - 根据要求强行删除 .php

android - 如何以编程方式访问android根目录(/system/app)?

javascript - ES6 - 如何将 JSON 语法与模板文字保持一致?