1

I am new in android , right now I am facing some issue with list view, one list screen is there with some name in list and when i click on any one of those name it should pass that id to another activity and where it has to fetch some data from database according to code but my activity is getting stopped... so please anyone help me out here... alluseractivity is connected to list which is showing some list, its working but employeedetails that activity is having some problem.... i have given xml code and php code also so please help me here.. here is logcat view....... one more issue sir in the same code when i am trying to update the things and running from start again its getting stopped reaching before this screen here i am adding code into empdetailsactivity so please review it and let me know

     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);
   }
        ?>
1
  • sir.. i have posted logcat view. its very difficult to posting things here...please sir you just review the things and try to help me.... Commented Apr 2, 2014 at 13:39

3 Answers 3

1
  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.
Sign up to request clarification or add additional context in comments.

4 Comments

sir its awesome.... working you are great sir.... please can you explain me what was the reason.... it was not working before..
StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11, which in short, does not allow network operation. (eg: HttpClient and HttpUrlConnection) get executed on UI thread. If you do this, you get NetworkOnMainThreadException. You can easily solve this error By two ways:- 1.using asynctask() 2.You can override this thread policy by adding the code(I have provided) into your main activity’s onCreate() method.Happy to help.Now you shuld upvote my answer :-) :-)
sir i have added some new issues in the same code... i have added some code to update the profile so its getting stop again in same way....this time i can see some null point exception error in logcat view so sir please review it again ...
sir in EmpDetailsActivity class i have added one code for updating the profile so one method in this class after setcontent view you can find in 3-4 lines and then one asycn class i have added in the same activity for updating profile so by that itself its getting... stopped and sir i am new so i can debug but i cant find the error and cant understand ... i will try ... sir please help me out ....and am frseher in my job so please sir...
0

You can not make any network calls on the main thread, create a separate thread or an asynctask and to the network call.

Take out the runOnUiThread in your do in background.

Comments

0

for your null pointer exception.... first you have to check manifest file and add activity of your new class and also include xml-file in class-file properly. sometimes null pointer exception error comes just because of this little mistake and if still problem not solved then taust the parameter before you passed from one page to another.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.