Response:wrong. [User registration via android app using http post not working]

邮差的信 提交于 2019-12-25 08:14:02

问题


I was able to successfully make login work. Now, I am stuck up with registration. Response is wrong.

public class Register extends Activity implements OnClickListener{

    private String mTitle = "Write.My.Action";

    private static final String LOGTAG = "tag";
    public EditText fullname, email, password;
    private Button register; 
    private ProgressDialog mDialog; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        getActionBar().setTitle(mTitle);

        fullname = (EditText) findViewById(R.id.fullname);
        email = (EditText) findViewById(R.id.editText2);
        password = (EditText) findViewById(R.id.editText1);

        register = (Button) findViewById(R.id.button1);

        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            mDialog = new ProgressDialog(Register.this);
            mDialog.setMessage("Attempting to Register...");
            mDialog.setIndeterminate(false);
            mDialog.setCancelable(false);
            mDialog.show();
            new Thread(new Runnable() {

                @Override
                public void run() {
                    register();

                }
            }).start();
        }

    }

     void register() {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("myurl");

            System.out.println("httpPost is: " + httpPost);

            String fullname_input = fullname.getText().toString().trim();
            String email_input = email.getText().toString().trim();
            String password_input = password.getText().toString().trim();

            //adding data into list view so we can make post over the server

            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            nameValuePair.add(new BasicNameValuePair("fullname",  fullname_input));
            nameValuePair.add(new BasicNameValuePair("email",  email_input));
            nameValuePair.add(new BasicNameValuePair("password",  password_input));

            System.out.println("namevaluepair is: " + nameValuePair);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

            //execute http post resquest

            HttpResponse httpResponse = httpClient.execute(httpPost);



            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpClient.execute(httpPost, responseHandler);

            System.out.println("Response is: " + response);

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mDialog.dismiss();

                }
            });
            if(response.equalsIgnoreCase("Signed Up")){
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        startActivity(new Intent(Register.this, Registration_Success.class));

                    }
                });
            }else {
                showAlert();
            }

        } catch (Exception e) {
            mDialog.dismiss();
            Log.i(LOGTAG, "Exception found"+ e.getMessage());
        }

    }
     public void showAlert(){
         Register.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                builder.setTitle("Registration Error");
                builder.setMessage("Please, try registration again!")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub

                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();

            }
        });
     }
}

Please Note: Every activities are registered in Manifest, INTERNET permission also included.

php file:

include "dbconnection.php";

$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];

$insert_data = "INSERT INTO register
    Values ('', '$fullname', '$email', '$password')";

$insert_result = mysql_query($insert_data);
//echo "Signed Up";

if($insert_result){
echo "Signed Up";
}
else{
 echo "wrong!";
} 

I don't understand why it keeps on saying Response is : Wrong. Tired of spending almost a day .. I am here seeking help. Excuse me if my questions seems naive. Thank you in advance.


回答1:


try below code:-

                HttpResponse httpResponse = httpClient.execute(httpPost);

                if (httpResponse != null)
                {
                    InputStream in = httpResponse.getEntity().getContent();
                    result = ConvertStreamToString.convertStreamToString(in);
                    // System.out.println("result =>" + result);
                }

convertStreamToString method

public String convertStreamToString(InputStream is) 
{
    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();
}

do not under stand :-

 HttpResponse httpResponse = httpClient.execute(httpPost); // getting response from server 

// where you use this response and why using below line or whats the benefit of below line

                    ResponseHandler<String> responseHandler = new BasicResponseHandler();
                    final String response = httpClient.execute(httpPost, responseHandler);



回答2:


Follow that tutorial very usefull, and clear how to work on json webservices with android.

How to connect Android with PHP, MySQL




回答3:


Try this code using AsyncTask

public class Register extends Activity implements OnClickListener{

    private String mTitle = "Write.My.Action";

    private static final String LOGTAG = "tag";
    public EditText fullname, email, password;
    private Button register; 
    private ProgressDialog mDialog; 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        getActionBar().setTitle(mTitle);

        fullname = (EditText) findViewById(R.id.fullname);
        email = (EditText) findViewById(R.id.editText2);
        password = (EditText) findViewById(R.id.editText1);

        register = (Button) findViewById(R.id.button1);

        register.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            mDialog = new ProgressDialog(Register.this);
            mDialog.setMessage("Attempting to Register...");
            mDialog.setIndeterminate(false);
            mDialog.setCancelable(false);
            mDialog.show();

            new RegisterUser().execute();
        }

    }

    public class RegisterUser extends AsyncTask<Void, Void, String>
    {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("myurl");

            System.out.println("httpPost is: " + httpPost);

            String fullname_input = fullname.getText().toString().trim();
            String email_input = email.getText().toString().trim();
            String password_input = password.getText().toString().trim();

            //adding data into list view so we can make post over the server

            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            nameValuePair.add(new BasicNameValuePair("fullname",  fullname_input));
            nameValuePair.add(new BasicNameValuePair("email",  email_input));
            nameValuePair.add(new BasicNameValuePair("password",  password_input));

            System.out.println("namevaluepair is: " + nameValuePair);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

            //execute http post resquest

            HttpResponse httpResponse = httpClient.execute(httpPost);



            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpClient.execute(httpPost, responseHandler);

            System.out.println("Response is: " + response);

            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

             if(response.equalsIgnoreCase("Signed Up")){
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            startActivity(new Intent(Register.this, Registration_Success.class));

                        }
                    });
                }else {
                    showAlert();
                }
        }

    }

     public void showAlert(){
         Register.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
                builder.setTitle("Registration Error");
                builder.setMessage("Please, try registration again!")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub

                            }
                        });
                AlertDialog alert = builder.create();
                alert.show();

            }
        });
     }
}

Hope this helps you!!!

If its not working please let me know i will try to help more...




回答4:


Try using Volley if not. It's faster than the ussual HTTP connection classes. Example:

RequestQueue queue = Volley.newRequestQueue(this);
    String url = "url";
       JSONObject juser = new JSONObject();     
       try {                   
                juser.put("locationId", locID);
                juser.put("email",  email_input);
                juser.put("password",  password_input);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, juser, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            // TODO Auto-generated method stub
            txtDisplay.setText("Response => "+response.toString());
            findViewById(R.id.progressBar1).setVisibility(View.GONE);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            // TODO Auto-generated method stub

        }
    });

    queue.add(jsObjRequest);



回答5:


Like @Andrew T suggested , I am posting my solution. The mysql_error()helped me debug the issue. mysql_error() displayed in the Logcat that "register table is not found" .. but the table name is registers. I was missing "s" at the end.

    $fullname = $_POST['fullname'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    $insert_data = "INSERT INTO registers(id, fullname, email, password)
        Values ('','$fullname', '$email', '$password')";

    $insert_result = mysql_query($insert_data) or die(mysql_error());
    //echo "Signed Up";

    if($insert_result){
    echo "Signed Up";
    }
    else{
     echo "wrong!";
    } 

Everything worked perfect after that. Again, thank you all for your time and solutions. Everyone's suggestions are great, but I can not accept any answer at this point.. sorry:(



来源:https://stackoverflow.com/questions/23259638/responsewrong-user-registration-via-android-app-using-http-post-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!