OkHttp not posting to mysql - java

I have a problem here ..My app is supposed to send 3 values to the database, from text box etName,etEmailand etPassword
but instead, it is not send anything ...I'm new in android and I don't know some of the things I wrote in my code as I am following some tutorials
this in my code for register
package com.xulucreatives.taxisiyaya;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RegisterActivity extends AppCompatActivity {
EditText etName,etEmail,etPassword;
Button btnReg;
final String url_Register ="http://taxinote.000webhostapp.com/register_user.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = findViewById(R.id.RM);
etEmail = findViewById(R.id.et_email);
etPassword = findViewById(R.id.et_password);
btnReg = findViewById(R.id.btn_reg);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name = etName.getText().toString();
String Email = etEmail.getText().toString();
String Password = etPassword.getText().toString();
new RegisterUser().execute(Name,Email,Password);
// Toast.makeText(RegisterActivity.this,"Im working you bitch",Toast.LENGTH_LONG).show();
}
});
}
public class RegisterUser extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... strings) {
String Name = strings[0];
String Email = strings[1];
String Password = strings[2];
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(finalURL)
.build();
Response response = null;
try{
response = okHttpClient.newCall(request).execute();
if(response.isSuccessful())
{
String result = response.body().string();
if(result.equalsIgnoreCase("uaser registered successfully"))
{
Toast.makeText(RegisterActivity.this,"Registered Successfully",Toast.LENGTH_LONG).show();
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
else if(result.equalsIgnoreCase("user already exists")){
Toast.makeText(RegisterActivity.this,"User Already Exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(RegisterActivity.this,"Ooops ! Ran into a problem , try again",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(RegisterActivity.this,"response not successful!! :/",Toast.LENGTH_LONG).show();
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
public void showToast(final String Text){
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this,Text,Toast.LENGTH_LONG).show();
}
});
}
}
user_name, user_id and user_password are from my php file in the server
<?php
require_once('connect.php');
$userName = $_GET['user_name'];
$userID = $_GET['user_id'];
$userPassword = $_GET['user_password'];
$query = "select * from users where email = '$userID'";
$recordExists = mysqli_fetch_array(mysqli_query($conn, $query));
if(isset($recordExists)){
echo 'User already exists';
}else{
$query = "INSERT INTO users (name, email, password) VALUES ('$userName', '$userID', '$userPassword')";
if(mysqli_query($conn, $query)){
echo 'User registered successfully';
}else{
echo 'oops! please try again!';
}
}
?>
but its not working i dont know why

You are creating an invalid url
which is
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
and should be like this
String finalURL = url_Register + "?user_name=" + Name +
"&user_id="+ Email +
"&user_password="+ Password;

Related

Android app making JSON call gets unexpected data from server, but same call works in browser

I have an Android app that makes a server call which returns JSON.
The server code returns the right string if I enter the URL into a browser. But it creates exceptions in the Java app (different issues with http and https server calls).
https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989
Returns this string:
[{"user_id":"1601470","email":"test.name#gmail.com","first_name":"TestName","last_name":null}]
And this is the Java call that parses the JSON but gives an Exception:
#Override
protected void onPostExecute(String result)
{
try {
dialog.dismiss();
} catch (Exception ee) {
// nothing
}
if ( connectionError == true )
{
Toast.makeText(getApplicationContext(), "Please try again. Possible Internet connection error.", Toast.LENGTH_LONG).show();
}
if ( result != null && result.equals( "no_such_user") )
{
Toast.makeText(getApplicationContext(), "Your email and password do not match out records. Please try again or create and account.", Toast.LENGTH_LONG).show();
//final TextView login_error = (TextView) findViewById(R.id.login_error);
}
else
{
Log.d( "CONNECTION*** ERRORS: " , "ok 3 and result length: " + result.length() );
String firstName = null;
String lastName = null;
String email = null;
String user_id = null;
try
{
JSONArray obj = new JSONArray(result);
JSONObject o = obj.getJSONObject(0);
firstName = o.getString("first_name");
lastName = o.getString("last_name");
email = o.getString("email");
user_id = o.getString("user_id");
}
catch ( Exception e )
{
Log.d( "JSON ERRORS: " , "something happened ****" + e.getMessage() );
}
// 1) First, write to whatever local session file that the person is logged in
// - I just really need user id and name and email. And store that.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
LoginActivity.this);
if ( user_id != null && user_id.trim().length() > 0 && !user_id.trim().equals("null") )
{
prefs.edit()
.putString("first_name", firstName)
.putString("last_name", lastName)
.putString("email", email)
.putString("user_id", user_id)
.putBoolean("working", true)
.commit();
if ( user_id.equals("1"))
{
prefs.edit()
.putString("community_subscription", "1")
.commit();
}
}
}
}
}
And this is the exception message:
End of input at character 0 of
It just looks like the string is 0 characters long.
Any idea why this is happening? Before I switched my site to https this call used to work without problems.
Also the server makes an http call. If I change it to https it returns a whole bunch of HTML which is weird since I don't actually send that back.
This is my doInBackground method:
#Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
final String myEmail = theParams[1];
final String myPassword = theParams[2];
String charset = "UTF-8";
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( myEmail, myPassword.toCharArray());
}
});
Edit
If my doInBackground method is inside the
public class DownloadWebPageTask extends AsyncTask<String, Void, String>
Can it be that the server is just too slow to return the string and that is why it is getting null?
It is always crashing on this with the result string being empty:
JSONArray obj = new JSONArray(result);
Edit 2
Here is the full code:
package com.problemio;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.json.JSONArray;
import org.json.JSONObject;
import com.flurry.android.FlurryAgent;
import utils.SendEmail;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends BaseActivity
{
//private TextView textView;
private Dialog dialog;
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FlurryAgent.onStartSession(this, "8CA5LTZ5M73EG8R35SXG");
setContentView(R.layout.login);
//final TextView emailask = (TextView) findViewById(R.id.email_ask);
// Show form for login_email
final EditText loginEmail = (EditText) findViewById(R.id.login_email);
//String name = loginEmail.getText().toString();
// Show field for password
final EditText password = (EditText) findViewById(R.id.password);
//String text = password.getText().toString();
//Log.d( "First parameters: " , "Login email: " + loginEmail + " AND login password: " + text);
// Show button for submit
Button submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
String email = loginEmail.getText().toString();
String pass = password.getText().toString();
//Set the email pattern string
// Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
// //Match the given string with the pattern
// Matcher m = pattern.matcher(email);
// //check whether match is found
// boolean matchFound = m.matches();
// TODO: VALIDATE!!!
if ( email == null || email.trim().length() < 2 )
{
Toast.makeText(getApplicationContext(), "Please enter a valid email address.", Toast.LENGTH_LONG).show();
}
else
if ( pass == null || pass.trim().length() < 2 )
{
Toast.makeText(getApplicationContext(), "Please enter a correct password.", Toast.LENGTH_LONG).show();
}
else
{
sendFeedback(pass, email);
}
}
});
// Show button for submit
Button forgot_password = (Button)findViewById(R.id.forgot_password);
forgot_password.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, ForgotPasswordActivity.class);
LoginActivity.this.startActivity(intent);
}
});
// Now add messaging for creating a profile
final TextView create_profile_message = (TextView) findViewById(R.id.create_profile_message);
Button create_profile = (Button)findViewById(R.id.create_profile);
create_profile.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
//sendEmail("Create Profile Clicked", "From Login screen, someone clicked on the create profile button" );
Intent myIntent = new Intent(LoginActivity.this, CreateProfileActivity.class);
LoginActivity.this.startActivity(myIntent);
}
});
}
public void sendFeedback(String pass , String email)
{
String[] params = new String[] { "http://www.problemio.com/auth/mobile_login.php", email, pass };
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(params);
}
// Subject , body
public void sendEmail( String subject , String body )
{
String[] params = new String[] { "http://www.problemio.com/problems/send_email_mobile.php", subject, body };
SendEmail task = new SendEmail();
task.execute(params);
}
public class DownloadWebPageTask extends AsyncTask<String, Void, String>
{
private boolean connectionError = false;
#Override
protected void onPreExecute( )
{
dialog = new Dialog(LoginActivity.this);
dialog.setContentView(R.layout.please_wait);
dialog.setTitle("Logging You In");
TextView text = (TextView) dialog.findViewById(R.id.please_wait_text);
text.setText("Please wait while you are being logged in...");
dialog.show();
}
// orig
#Override
protected String doInBackground(String... theParams)
{
String myUrl = theParams[0];
final String myEmail = theParams[1];
final String myPassword = theParams[2];
String charset = "UTF-8";
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( myEmail, myPassword.toCharArray());
}
});
String response = null;
String stringUrl = "https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989";
String result = "";
String inputLine;
try
{
String query = String.format("login=%s&password=%s",
URLEncoder.encode(myEmail, charset),
URLEncoder.encode(myPassword, charset));
final URL url = new URL( myUrl + "?" + query );
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("login", myEmail);
conn.setRequestProperty("password", myPassword);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.connect();
final InputStream is = conn.getInputStream();
final byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1)
{
builder.append(new String(buffer, 0, readCount));
}
response = builder.toString();
}
catch (Exception e)
{
sendEmail ( "Login Activity 1 Network Error" , "Error: " + e.getMessage() );
}
return response;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try {
dialog.dismiss();
} catch (Exception ee) {
// nothing
}
if ( connectionError == true )
{
Toast.makeText(getApplicationContext(), "Please try again. Possible Internet connection error.", Toast.LENGTH_LONG).show();
}
if ( result != null && result.equals( "no_such_user") )
{
Toast.makeText(getApplicationContext(), "Your email and password do not match out records. Please try again or create and account.", Toast.LENGTH_LONG).show();
//final TextView login_error = (TextView) findViewById(R.id.login_error);
}
else
{
String firstName = null;
String lastName = null;
String email = null;
String user_id = null;
try
{
JSONArray obj = new JSONArray(result);
Log.d( "CONNECTION*** ERRORS: " , ".....5" );
JSONObject o = obj.getJSONObject(0);
firstName = o.getString("first_name");
lastName = o.getString("last_name");
email = o.getString("email");
user_id = o.getString("user_id");
}
catch ( Exception e )
{
Log.d( "JSON ERRORS: " , "some crap happened ****" + e.getMessage() );
}
// 1) First, write to whatever local session file that the person is logged in
// - I just really need user id and name and email. And store that.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
LoginActivity.this);
if ( user_id != null && user_id.trim().length() > 0 && !user_id.trim().equals("null") )
{
prefs.edit()
.putString("first_name", firstName)
.putString("last_name", lastName)
.putString("email", email)
.putString("user_id", user_id)
.putBoolean("working", true)
.commit();
if ( user_id.equals("1"))
{
prefs.edit()
.putString("community_subscription", "1")
.commit();
}
}
}
}
}
// TODO: see if I can get rid of this
public void readWebpage(View view)
{
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.problemio.com/auth/mobile_login.php" });
}
#Override
public void onStop()
{
super.onStop();
}
}
ISSUE #1
From your question description:
The server code returns the right string if I enter the URL into a
browser.
I'm assuming you are using HTTP GET. However you are using HTTP POST in your code instead:
String query = String.format("login=%s&password=%s",
URLEncoder.encode(myEmail, charset),
URLEncoder.encode(myPassword, charset));
final URL url = new URL( myUrl + "?" + query );
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST"); // <----------- replace with "GET"
ISSUE #2
conn.setDoOutput(true);
When set to true the request method is changed to POST, since GET or DELETE can't have a request body. To continue with a GET request you must set conn.setDoOutput(false);
Also, comment out those lines:
//conn.setRequestProperty("login", myEmail);
//conn.setRequestProperty("password", myPassword);
//conn.setDoOutput(true);
ISSUE #3
task.execute(new String[] { "http://www.problemio.com/auth/mobile_login.php" });
From Android 8: Cleartext HTTP traffic not permitted
You must change the URL from http to https or add android:usesCleartextTraffic="true" in the manifest. This will only effect on devices running API level 23+. Before 23+ http is allowed by default.
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
For me using https worked properly.
ISSUE #4
Upon providing wrong credentials your server is sending a plain text message
no_such_user
Which needs to be replaced with a valid JSON string.
From my end, the code you provided is working properly after fixing those issues.
I tried your code using HttpURLConnection in async task, It gave me the desired output without error.. But if I give different password in the get url.. the response is not JSONObject. It is coming as String value. may be that causing the issue(u handle that also in postexecute method)
public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String stringUrl = "https://www.problemio.com/auth/mobile_login.php?login=test.name#gmail.com&password=130989";
String result = "";
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
//Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
//Connect to our url
connection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
} catch (Exception e) {
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// textView.setText("Response is: " + response);
try {
JSONArray obj = new JSONArray(result);
JSONObject o = obj.getJSONObject(0);
String firstName = o.getString("first_name");
String lastName = o.getString("last_name");
String email = o.getString("email");
String user_id = o.getString("user_id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Looking your Json I can see a null
[
{
"user_id": "1601470",
"email": "test.name#gmail.com",
"first_name": "TestName",
"last_name": null
}
]
Json files accept nulls, but json objects do not accept it.
The application is crashing when you try to get the last_name.
Instead of null use empty.
[
{
"user_id": "1601470",
"email": "test.name#gmail.com",
"first_name": "TestName",
"last_name": ""
}
]
Regards
As per google this is old technique Retrieve API data using AsyncTask, I prefer Retrofit + RxJava + RxAndroid + GSON.
It will remove all your boilerplate code. It is so easy to use Retrofit.
Add Below dependency in your app,
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
//Rx android
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
Create MyRetrofit class,
import com.google.gson.GsonBuilder;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MyRetrofit {
private static Retrofit retrofit = null;
public static Retrofit getInstance() {
String BASE_URL = "https://www.problemio.com/";
if (retrofit == null) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.readTimeout(60, TimeUnit.MINUTES);
httpClient.connectTimeout(60, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
}
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient.build())
.build();
}
return retrofit;
}
}
Create APIService Class,
import in.kintanpatel.customrecylerview.model.LoginBean;
import io.reactivex.Observable;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by kintan on 8/11/18.
*/
public interface APIService {
//Add All your method here
#GET("auth/mobile_login.php/")
Observable<Response<ArrayList<LoginBean>>> doLogin(#Query("login") String login, #Query("password") String password);
}
That's it now call your API stuff here,
private void doLoginAPI(String userName, String password) {
//Show Loading here
MyRetrofit.getInstance().create(APIService.class).doLogin(userName, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Response<ArrayList<LoginBean>>>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Response<ArrayList<LoginBean>> response) {
//Hide Loading here
if (response.isSuccessful()) { //check HTTP Response
LoginBean bean = response.body().get(0);
Log.e("USER_INFO", "User ID: " + bean.getUserId());
Log.e("USER_INFO", "User First Name : " + bean.getFirstName());
Log.e("USER_INFO", "User Last Name : " + bean.getLastName());
Log.e("USER_INFO", "User Email : " + bean.getEmail());
}
}
#Override
public void onError(Throwable e) {
Log.e("USER_INFO", e.getMessage());
}
#Override
public void onComplete() {
}
});
}
And just call your method where you want:
doLoginAPI("test.name#gmail.com", "130989");
And Your output like,
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User ID: 1601470
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User First Name : TestName
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User Last Name : null
11-08 14:44:59.946 25447-25447/com.kintanpatel.baserecyclerview E/USER_INFO: User Email : test.name#gmail.com

User Registration using volley library in Android

Using a volley library I am sending a post request to a file register.php which should perform user registration and return JSONResponse after success. The code I have written is working fine in the local server(MAMP) but is not working in the live server. Logcat shows {success = 0} in the live server.
package com.example.androidregisterandlogin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText name, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
RequestQueue requestQueue;
private static String URL_REGIST = "https://domainname.com.np/mentordai/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading = findViewById(R.id.loading);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();
}
});
}
private void Regist(){
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
Log.d("TAG",response);
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")) {
Toast.makeText(MainActivity.this, "Register Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Server code
<?php
if ($_SERVER['REQUEST_METHOD'] =='POST'){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO student_users_table (name, email, password) VALUES ('$name', '$email', '$password')";
if ( mysqli_query($connection, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($connection);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($connection);
}
}
?>
```
I'm not an php expert but it looks like your server is the one who return the 'success=0'
And it looks like you have some problem with the if ( mysqli_query($connection, $sql) ) statement, your code going to the else who return the success = 0.
Try to debug the server to see what happens when you send register request.
I think you should put validation at both end (Client as well as server end) on all of your form field . If any one of the field is kept empty your query will not be able to run.
For Validation in server use this at the start of your code
if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']))
{
}
To Validate data in Client side use
if(this.name.getText().toString().trim().equals(""))
{
Toast.makeText(MainActivity.this, "Please Enter Name " + e.toString(), Toast.LENGTH_SHORT).show();
}
also for password and email

Activity crashes when sending a network request through php

Good day to all.
I'm creating a social android app for posting offers of services for the skilled & talented within our univerity. I'm using the conventional languages for android: Java and XML.
But whenever I invoke the createOffer method within the CreateOfferActivity the app crashes without producing any exceptions and simply restarts.
Here's the code for CreateOfferActivity:
package com.italent.italent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class CreateOfferActivity extends AppCompatActivity {
private EditText offerTitle;
private EditText offerDesc;
private EditText offerMinPrice;
private EditText offerMaxPrice;
private Spinner offerCategory;
private Button crtOffer;
String offCategory;
String imagePath;
public double minPrice;
public double maxPrice;
private static final String TAG = "CreateOfferActivity";
private static final String URL_FOR_CREATING_OFFER = "https://*****/create_offer.php";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_offer);
offerTitle = (EditText) findViewById(R.id.etOfferTitle);
offerDesc = (EditText) findViewById(R.id.etOfferDesc);
offerMinPrice = (EditText) findViewById(R.id.etMinPrice);
offerMaxPrice = (EditText) findViewById(R.id.etMaxPrice);
offerCategory = (Spinner) findViewById(R.id.spCategories);
crtOffer = (Button) findViewById(R.id.bCreateOffer);
ArrayAdapter<CharSequence> arrAdapter = ArrayAdapter.createFromResource(this,
R.array.category_Array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
arrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
offerCategory.setAdapter(arrAdapter);
//Create Offer button onClick listener
crtOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitOfferForm();
Toast.makeText(CreateOfferActivity.this, "It works...", Toast.LENGTH_LONG).show();
}
});
}
private void submitOfferForm() {
String offTitle = offerTitle.getText().toString();
String offDesc = offerDesc.getText().toString();
//////////Replace image path later with a valid one
imagePath = "Some Image Path";
offCategory = offerCategory.getSelectedItem().toString();
//getting sharedPreferences file named userInfo to retrieve MemberName, Username and branch
SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String ofMName = sharedPreferences.getString("MemberName:", "");
String ofUName = sharedPreferences.getString("UserName:", "");
String ofBranch = sharedPreferences.getString("Branch:", "");
String mnPri = " " + minPrice;
String mxPri = " " + maxPrice;
createOffer(ofMName, ofUName, offTitle, offDesc, ofBranch, mnPri, mxPri, imagePath, offCategory);
}
private void createOffer(final String oMName, final String oUName, final String oTitle, final String oText,
final String oBranch,final String oMinPri, final String oMaxPri, final String oImage, final String oCategory) {
// Tag used to cancel the request
String cancel_req_tag = "offer";
progressDialog.setMessage("Adding your offer...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_CREATING_OFFER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Offer Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) { // error is set to false, meaning no error
//String user = jObj.getJSONObject("offer").getString("name");
Toast.makeText(CreateOfferActivity.this, "Your Offer has been created!", Toast.LENGTH_SHORT).show();
// Launch Home activity
Intent HomeIntent = new Intent(CreateOfferActivity.this, HomeActivity.class);
startActivity(HomeIntent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(CreateOfferActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error in creating offer: " + error.getMessage());
Toast.makeText(CreateOfferActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to create offer url
Map<String, String> params = new HashMap<String, String>();
params.put("offerMemberName", oMName);
params.put("offerUserName", oUName);
params.put("offerTitle", oTitle);
params.put("OfferText", oText);
params.put("OfferBranch", oBranch);
params.put("OfferDateTime", DateFormat.getDateTimeInstance().format(new Date()));
params.put("OfferMinPrice", "" + oMinPri);
params.put("OfferMaxPrice", "" + oMaxPri);
params.put("OfferCategory", oCategory);
params.put("OfferImage", oImage);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
And the code for create_offer.php
<?php
require_once 'update_user_info.php';
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['offerTitle']) && isset($_POST['offerMname']) && isset($_POST['offerBranch']) && isset($_POST['offerText']) && isset($_POST['offerImageURL']) &&
isset($_POST['offerDateTime']) && isset($_POST['offerMinPrice']) && isset($_POST['offerMaxPrice']) && isset($_POST['offerCategory']) && isset($_POST['offerUname'])) {
// receiving the post params
$ofTitle = $_POST['offerTitle'];
$ofMName = $_POST['offerMname'];
$ofBranch = $_POST['offerBranch'];
$ofText = $_POST['offerText'];
$ofImageURL = $_POST['offerImageURL'];
$ofDateTime = $_POST['offerDateTime'];
$ofMinPri = $_POST['offerMinPrice'];
$ofMaxPri = $_POST['offerMaxPrice'];
$ofCategory = $_POST['offerCategory'];
$ofUName = $_POST['offerUname'];
// check if user is already existed with the same email
if (!($db->checkExistingUserThruUname($ofUName))) {
// user doesn't exist
$response["error"] = TRUE;
$response["error_msg"] = "Visitors cannot post an offer. Please register first.";
echo json_encode($response);
} else {
// create a new offer
$user = $db->storeOfferInfo($ofTitle, $ofMName, $ofBranch, $ofText, $ofImageURL, $ofDateTime, $ofMinPri, $ofMaxPri, $ofCategory, $ofUName);
if ($offer) {
// offer stored successfully
$response["error"] = FALSE;
$response["offer"]["offTitle"] = $offer["offTitle"];
$response["offer"]["offMname"] = $offer["offMname"];
$response["offer"]["offBranch"] = $offer["offBranch"];
$response["offer"]["offText"] = $offer["offText"];
$response["offer"]["offImageURL"] = $offer["offImageURL"];
$response["offer"]["offDateTime"] = $offer["offDateTime"];
$response["offer"]["offMinPrice"] = $offer["offMinPrice"];
$response["offer"]["offMaxPrice"] = $offer["offMaxPrice"];
$response["offer"]["offCategory"] = $offer["offCategory"];
$response["offer"]["offUname"] = $offer["offUname"];
echo json_encode($response);
} else {
// offer failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in offer creation!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "A required field is missing!";
echo json_encode($response);
}
?>
This is the Logcat:
04-22 03:24:38.950 27998-27998/com.italent.italent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.italent.italent, PID: 27998
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.italent.italent.CreateOfferActivity.createOffer(CreateOfferActivity.java:122)
at com.italent.italent.CreateOfferActivity.submitOfferForm(CreateOfferActivity.java:113)
at com.italent.italent.CreateOfferActivity.access$000(CreateOfferActivity.java:30)
at com.italent.italent.CreateOfferActivity$1.onClick(CreateOfferActivity.java:86)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
P.S. i used almost the exact same java code, php code and database for registration and it works fine but i can't find why it doesn't work with this class.
I appreciate any guidlines or help. Thank you!
progressDialog variable is not initialized. Add following code in your activity onCreate()
ProgressDialog progressDialog = new ProgressDialog(this);

Sending data from Android to SQL database using PHP

I was following this tutorial in which I was building login and registration app:
https://www.youtube.com/watch?v=T7Z4GVFaT4A
I've changed PHP and tested it by passing some arguments through address field, but when I'm clicking register button nothing happens.
There are some things in OnResponse function that should be doing something, something should be added to database, but nothing happens.
I was wondering if maybe anything at all is being send from app if I'm not getting any response.
Also, what's troubling me, function OnResponse is never called, but it should be.
Instead of using some ASP I create server using WAMP. Below there are Java and PHP files that are crucial to this problem.
RegisterRequest.java
package com.example.dominik.praca;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Dominik on 28.12.2016.
*/
public class RegisterRequest extends StringRequest {
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.ugu.pl/Register.php";
//private static final String REGISTER_REQUEST_URL = "http://kulturnik.byethost3.com/Register2.php";
private static final String REGISTER_REQUEST_URL = "http://127.0.0.1/kulturnik/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, String password, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
RegisterActivity.java
package com.example.dominik.praca;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final EditText etName = (EditText) findViewById(R.id.etName);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
AlertDialog.Builder builderSuccess = new AlertDialog.Builder(RegisterActivity.this);
builderSuccess.setMessage("Rejestracja zakończona powodzeniem")
.create()
.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Błąd rejestracji")
.setNegativeButton("Ponów", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
And Register.php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
$con = mysqli_connect("localhost", "root", "", "kulturnik");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name, $username, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
print_r(json_encode($response));
?>
Use Async task for faster send & retrieval to/fro server. Just create an object of the class and use execute function to pass parameters and start asynchronous sending and retrieval to/fro the server.
eg:- SendtoPhp stp = new SendtoPhp();
stp.execute(tname, phone)
public class SendtoPhp extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String tname = params[0]; //parameters you need to send to server
String phone = params[1];
String data = "";
int tmp;
try {
URL url = new URL("http://your.server.com/"); //url to php code
String urlParams = "tname=" + tname + "&tphone=" + phone;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
//System.out.println(data);
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
try {
//You might receive something on server code execution using JSON object
} catch (JSONException e) {
e.printStackTrace();
}
}
}

Android app can't insert data into MySQL DB

I'm fairly new to Android coding and I'm trying to create app that inserts some info into my MySQL DB. I've found a lot of tutorials and tips on web and created lite app to try procedures. Everything compiles OK, app runs and it seems to send data successfully. But in fact, no data appears in my table.
Here's my PHP code android_add.php:
<?php
$con = mysqli_connect(localhost, user, psswd, name); //those works
mysqli_set_charset($con, "utf8"); //working with special symbols
$name = $_POST['name']; //get name & author from App
$author = $_POST['author'];
$sql = "insert into kniha_test (k_autor_pr,k_nazev) values ('$name','$address')";
if(mysqli_query($con,$sql)){
echo 'success';
} else {
echo 'failure';
}
mysqli_close($con);
?>
And here's my MainActivity.java:
import android.content.ContentValues;
import android.os.AsyncTask;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText editTextName;
private EditText editTextAuthor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAuthor = (EditText) findViewById(R.id.editTextAuthor);
}
public void insert (View view){
String name = editTextName.getText().toString();
String author = editTextAuthor.getText().toString();
insertToDatabase(name,author);
}
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String name;
String author;
public void saveNameAut(String name, String author){
this.name = name;
this.author = author;
name = editTextName.getText().toString();
author = editTextAuthor.getText().toString();
}
#Override
protected String doInBackground(String... params){
String paramName = params[0];
String paramAuthor = params[1];
ContentValues values = new ContentValues();
values.put("name", this.name);
values.put("author", this.author);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
}
As I said, I'm just beginner, so there may be something really stupid, but I can't figure out what. And there can be some trash lines from different tries. PHP code should be OK, I'm using practically the same to insert from HTML, so I'm guessing, there is problem in my Java code.
I will be really thankful for advices/responses.
Thanks!
PS: Response code I'm getting is 200.
You are sending null values through AsyncTask
Have you printed the values that you are sending through
try this
protected void insertToDatabase(String name, String author){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
String cName=name;
String cAuthor=author;
#Override
protected String doInBackground(String... params){
ContentValues values = new ContentValues();
values.put("name", cName);
values.put("author", cAuthor);
String addUrl = "http://glaserproject.com/knihovna_kyber/android/android_add.php";
try {URL url = new URL(addUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
System.out.println("Response Code: " + conn.getResponseCode());
} catch (IOException e){};
return "Succes";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, author);
}
try again and let me know if it solves your problems....

Categories