尝试调用虚方法'int java.lang.String.length()'

时间:2016-02-09 08:38:37

标签: java php android

here is my logcat file image我收到空对象引用错误而不是初始化变量?

这是我的java代码

Customer.java

package com.example.ishagoyal.lunchbox;

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.List;


    public class customer extends Activity {

        public EditText customer_name,email,password,confirm_password,contact_no,house_no,city,state ;
        public Button submit;
        public TextView registerErrorMsg;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_customer);
            email=(EditText)findViewById(R.id.editText);
            password=(EditText)findViewById(R.id.editText3);
            confirm_password=(EditText)findViewById(R.id.editText4);
            contact_no=(EditText)findViewById(R.id.editText6);
            customer_name=(EditText)findViewById(R.id.editText5);
            house_no=(EditText)findViewById(R.id.editText7);
            city=(EditText)findViewById(R.id.editText8);
            state=(EditText)findViewById(R.id.editText9);



            submit=(Button)findViewById(R.id.button);
            submit.setOnClickListener(new View.OnClickListener() {
                //submit button click event... a toast is set to alert when the fields are empty
                @Override
                public void onClick(View v) {

                    if((!customer_name.getText().toString().equals(""))&&(!house_no.getText().toString().equals(""))&&(!city.getText().toString().equals(""))&&(!state.getText().toString().equals(""))&&(!contact_no.getText().toString().equals(""))&&(!email.getText().toString().equals(""))&&(!password.getText().toString().equals(""))&&(!confirm_password.getText().toString().equals("")))
                    {
                        if(password.getText().toString().equals(confirm_password.getText().toString()))
                        {
                            NetAsync(v);
                            new CustomerUser().execute();
                        }else{
                            Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_SHORT).show();
                        }
                    }
                    else{
                        Toast.makeText(getApplicationContext(), "One or more fields are empty", Toast.LENGTH_SHORT).show();
                    }



                }
            });
        }

        public void NetAsync(View view)
        {
            //checking network connection
            if (isNetworkStatusAvailable(getApplicationContext()))
            {
                registerErrorMsg.setText("Error in Network connection");
            }
        }

        public static boolean isNetworkStatusAvailable(Context context)
        {
            ConnectivityManager connectivityManager =(ConnectivityManager)context.getSystemService(CONNECTIVITY_SERVICE);
            if(connectivityManager!=null)
            {
                NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
                if(networkInfo!=null)
                {
                    if(networkInfo.isConnected())
                        return true;
                }
            }
            return false;
        }

        /*Async task to set and get data to Mysql database through JSON response*/
        class CustomerUser extends AsyncTask<Void,Void,String> {
            ProgressDialog dialog;
            String cname, cno, cmail,res, cpswd, cconfirm_password, chouse_no, ccity, cstate;

            @Override
            protected void onPreExecute() {
                dialog = ProgressDialog.show(customer.this, "Contacting Servers", "Registering...");
                super.onPreExecute();
                cname = customer_name.getText().toString();
                cno = contact_no.getText().toString();
                cmail = email.getText().toString();
                cpswd = password.getText().toString();
                cconfirm_password = confirm_password.getText().toString();
                chouse_no = house_no.getText().toString();
                ccity = city.getText().toString();
                cstate = state.getText().toString();
            }

            @Override
            protected String doInBackground(Void... params) {

                HttpClient client = new DefaultHttpClient();

                HttpPost post = new HttpPost("http://10.0.2.2/webservice/Register.php");

                List<BasicNameValuePair> paramsForhttp = new ArrayList<BasicNameValuePair>();

                paramsForhttp.add(new BasicNameValuePair("tag", "register"));
                paramsForhttp.add(new BasicNameValuePair("name", cname));
                paramsForhttp.add(new BasicNameValuePair("number", cno));
                paramsForhttp.add(new BasicNameValuePair("email", cmail));
                paramsForhttp.add(new BasicNameValuePair("password", cpswd));
                paramsForhttp.add(new BasicNameValuePair("confirm_password", cconfirm_password));
                paramsForhttp.add(new BasicNameValuePair("house_no", chouse_no));
                paramsForhttp.add(new BasicNameValuePair("city", ccity));
                paramsForhttp.add(new BasicNameValuePair("state", cstate));

                try {
                    post.setEntity(new UrlEncodedFormEntity(paramsForhttp));
                    HttpResponse response = client.execute(post);
                    HttpEntity entity = response.getEntity();
                    InputStream stream = entity.getContent();
                    res = convertStreamToString(stream);
                    Log.e("Response", res);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {

                JSONObject obj;
                try {
                    obj = new JSONObject(res);
                    if (obj.getString("error").equalsIgnoreCase("false")) {
                        Toast.makeText(getApplicationContext(), "REGISTRATION SUCCESSFUL", Toast.LENGTH_LONG).show();
                        Intent in = new Intent(getApplicationContext(), loaction.class);
                        startActivity(in);
                        finish();
                    } else {
                        Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dialog.cancel();
                super.onPostExecute(result);

            }

            private String convertStreamToString(InputStream stream) {
                Log.i("convertstream method", "hello");
                InputStream is = stream;
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return sb.toString();
            }
        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_customer, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }
    }

这是我的注册php文件 regiter.php

<?php
    require_once 'DBWork.php';
    $response;
    global $list;
    $conn=new Database();
    $conn->construct();
    $response=$conn->Check();
    $response=FALSE;
    if(isset($_POST['tag'])=='register')
    {
        if(($_POST['name']!=null)&&($_POST['number']!=null)&&($_POST['email']!=null)&&($_POST['password']!=null)&&($_POST['confirm_password']!=null)&&($_POST['house_no']!=null)&&($_POST['city']!=null)&&($_POST['state']!=null))
        {
             // receiving the post params
            $name = $_POST['name'];
            $email = $_POST['email'];
            $number=$_POST['number'];
            $confirm_password=$_POST['confirm_password'];
            $password = $_POST['password'];
            $house_no=$_POST['house_no'];
            $city=$_POST['city'];
            $state=$_POST['state'];
             // check if user is already existed with the same email
            if ($conn->isUserExisted($email)) {
            // user already existed
            $response["error"] = TRUE;
            $response["error_msg"] = "User already existed with " . $email;
            echo json_encode($response);
            } else {
                $user=$conn->Add($name,$number,$email,$password,$confirm_password,$house_no,$city,$state);

                if ($user) {
                // user stored successfully
                $response["error"] = FALSE;
                $response["user"]["name"] = $user['Name'];
                $response["user"]["email"] = $user['Email_id'];
                $response["user"]["number"] = $user['Contact_no'];
                echo json_encode($response);
                } else {
                // user failed to store
                $response["error"] = TRUE;
                $response["error_msg"] = "Unknown error occurred in registration!";
                echo json_encode($response);
                }
            }
         }
    } else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameters (name, contact number,email or password) is missing!";
    echo json_encode($response);
}
?>

连接php文件 DBWork.php

<?php
    class Database
    {
        private $db;
        function construct()
        {
            $servername='localhost';
            $username='root';
            $password='';
            $dbname='LunchBox';
            $this->db=mysqli_connect($servername, $username, $password, $dbname);
        }
        function Check()
        {
            if($this->db)
                return true;
            else {
                return false;
            }
        }
        function Add($name,$number,$email,$password,$confirm_pswd,,$house_no,$city,$state)
        {
             $stmt=$this->db->prepare("INSERT INTO customer_table(Email_id,Password,Confirm_password,Customer_Name,Contact_no,House_no,City,State) VALUES(?,?,?,?,?,?,?,?)");
            $stmt->bind_param("ssssssss",$name,$number,$email,$password,$confirm_pswd,$house_no,$city,$state);
            if($stmt->execute())
            return true;
            else {
                return false;
            }

        }
         /**
     * Get user by email and password
     */
    function getUserByEmailAndPassword($email, $password) {

        $stmt = $this->db->prepare("SELECT * FROM customer_table WHERE Email_id =?");

        $stmt->bind_param("s", $email);

        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            return $user;
        } else {
            return NULL;
        }
    }
     /**
     * Check user is existed or not
     */
    function isUserExisted($email) {
        $stmt = $this->db->prepare("SELECT Email_id from customer_table WHERE Email_id = ?");
    if($stmt){
        $stmt->bind_param("s", $email);

        $stmt->execute();

        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            // user existed
            $stmt->close();
            return true;
        } else {
            // user not existed
            $stmt->close();
            return false;
        }
      }
    else{
        var_dump($this->db->error);
    }
    }

     function forgotPassword($email) {

        $stmt = $this->db->prepare("SELECT Password FROM customer_table WHERE Email_id =?");
        if($stmt)
        {
        $stmt->bind_param("s", $email);

        if ($stmt->execute()) {
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            return $user;
        } else
        {
            return NULL;
        }
      }

      else{
        var_dump($this->db->error);
    }
    }
  }
?>


  [1]: http://i.stack.imgur.com/iAwyk.jpg

0 个答案:

没有答案