Registration in android with php MYSQL

此生再无相见时 提交于 2020-01-07 02:42:46

问题


I am trying to do registration in my android app but I am not able to register my values inside the table. It is giving me a mesage in Toast saying error in registeration' Below is my php script for it.

   <?php
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        $title = $_POST['title'];
        $image = $_POST['image'];
        $description = $_POST['description'];
        $date = $_POST['date'];

        if($title == '' || $image == '' || $description == '' || $date ==''){
            echo 'please fill all values';
        }else {
            require_once('dbConnect.php');
            $sql = "SELECT * FROM advertise WHERE title='$title' OR description='$description'";

            $check = mysqli_fetch_array(mysqli_query($con, $sql));

            if (isset($check)) {
                echo 'Title and Description are already present';
            } else {
                $sql = "INSERT INTO advertise (title,image,description,date) VALUES('$title','$image','$description',$date)";
                if (mysqli_query($con, $sql)) {
                    echo 'successfully registered';
                } else {
                    echo 'oops! Please try again!';
                }
            }
            mysqli_close($con);
        }
    } else {
        echo 'error';
    }
?>

and this is my java android file InstantBanner.java

public class InstantBanner extends AppCompatActivity implements View.OnClickListener{
public static final String UPLOAD_URL = "http://10.0.2.2/instant-advertise.php";
public static final String UPLOAD_KEY = "image";
public static final String TAG = "MY MESSAGE";

private int PICK_IMAGE_REQUEST = 1;
private Bitmap bitmap;

private Uri filePath;
private ImageView imageView;

private Button btnChooseFile,btnSubmit;
private EditText editDate,editTitle,editDescription;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.instant);
    imageView= (ImageView) findViewById(R.id.imageView);
    btnChooseFile= (Button) findViewById(R.id.btnChooseFile);
    btnSubmit= (Button) findViewById(R.id.btnSubmit);
    editDate= (EditText) findViewById(R.id.editDate);
    editTitle= (EditText) findViewById(R.id.editTitle);
    editDescription= (EditText) findViewById(R.id.editDescription);

    btnSubmit.setOnClickListener(this);
    btnChooseFile.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    if (v==btnChooseFile){
        showFileChooser();
    }
    if (v==btnSubmit){
        registerBanner();
        uploadImage();
    }

}

private void registerBanner() {

   String title = editTitle.getText().toString().trim();
    String description = editDescription.getText().toString().trim();
    String date = editDate.getText().toString().trim();

    register_instant_banner(title,description,date);
}

private void register_instant_banner(String title, String description, String date) {

     class RegisterBanner extends AsyncTask<String,Void,String>{
         ProgressDialog progressDialog;
         InstantRequestHandler instantRequestHandler = new InstantRequestHandler();

         @Override
         protected void onPostExecute(String s) {
             super.onPostExecute(s);
             progressDialog.dismiss();
             Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show();
         }

         @Override
         protected void onPreExecute() {
             super.onPreExecute();
             progressDialog = ProgressDialog.show(InstantBanner.this, "Please Wait",null, true, true);
         }

         @Override
         protected String doInBackground(String... params) {
             HashMap<String, String> data = new HashMap<String,String>();
             data.put("title",params[0]);
             data.put("description",params[1]);
             data.put("date",params[2]);
             String result = instantRequestHandler.sendPostRequest(UPLOAD_URL,data);
             return result;
         }
     }

        RegisterBanner rb = new RegisterBanner();
         rb.execute(title,description,date);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

private void uploadImage() {
    class UploadImage extends AsyncTask<Bitmap, Void, String> {

        ProgressDialog loading;
        InstantRequestHandler rh = new InstantRequestHandler();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(InstantBanner.this, "Uploading Image", "Please wait...", true, true);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(Bitmap... params) {
            Bitmap bitmap = params[0];
            String uploadImage = getStringImage(bitmap);

            HashMap<String, String> data = new HashMap<>();
            data.put(UPLOAD_KEY, uploadImage);

            String result = rh.sendPostRequest(UPLOAD_URL, data);

            return result;
        }

    }
}

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}

}

This is the requestHandler class InstantRequestHandler.class

public class InstantRequestHandler {

public String sendGetRequest(String uri) {
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

String result;

StringBuilder sb = new StringBuilder();

while((result = bufferedReader.readLine())!=null){
sb.append(result);
}

return sb.toString();
} catch (Exception e) {
return null;
}
}

public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

URL url;
String response = "";
try {
url = new URL(requestURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);


OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));

writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}

return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}

return result.toString();
}
}

来源:https://stackoverflow.com/questions/37157329/registration-in-android-with-php-mysql

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