Why is my Android app inserting blank records into MySQL database?

Currently I am working on developing an app through Android Studio and working on coding the login and registration capabilities. We send newly registered users’ info to a MySQL database externally (i.e. not locally) through PHP, and also want to log registered users into the app. At the moment, the Android app is not sending the PHP file the information the user types into the text boxes. I put a tracer into the PHP file and it shows that the values are coming up null.

Here is my MainActivity.java:

package android.capstone.registerlogin;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;


public class MainActivity extends Activity {

    private EditText etUserName, etPassWord, etEmail;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);

        etPassWord = (EditText) findViewById(etCreateAccPassword);
        etUserName = (EditText) findViewById(etCreateAccUsername);
        etEmail = (EditText) findViewById(etCreateAccEmail);
        final TextView createAcc = (TextView) findViewById(R.id.tvCreateAcc);
        createAcc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* creating this intent shows where you're starting and
                where you want to go, we want to get the to the create account page
                called RegisterUser.java
                   first line creates the intent
                 */
                Intent createIntent = new Intent(MainActivity.this, CreateAccount.class);
                //second line makes the intent actually happen .startActivity
                MainActivity.this.startActivity(createIntent);
            }
        });

    }



    public void signup(View v) {
        String UserName = etUserName.getText().toString();
        String PassWord = etPassWord.getText().toString();
        String Email = etEmail.getText().toString();



        Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();

        new SignupActivity(this).execute(UserName, PassWord, Email);
    }


    }

Here is my SignupActivity.java:

package android.capstone.registerlogin;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SignupActivity extends AsyncTask<String, Void, String> {
    private Context context;

    public SignupActivity(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... arg0) {
        String userName = arg0[0];
        String passWord = arg0[1];
        String eMail = arg0[2];



        String link;
        String data;
        BufferedReader bufferedReader;
        String result;

        try {
            data = "?username=" + URLEncoder.encode(userName, "UTF-8");
            data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
            data += "&email=" + URLEncoder.encode(eMail, "UTF-8");



            link = "http://cgi.soic.indiana.edu/~gabschle/signup.php" + data;
            URL url = new URL(link);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            result = bufferedReader.readLine();
            return result;
        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());
        }
    }

    @Override
    protected void onPostExecute(String result) {
        String jsonStr = result;
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                String query_result = jsonObj.getString("query_result");
                if (query_result.equals("SUCCESS")) {
                    Toast.makeText(context, "Data inserted successfully. Signup successful.", Toast.LENGTH_SHORT).show();
                } else if (query_result.equals("FAILURE")) {
                    Toast.makeText(context, "Data could not be inserted. Signup failed." + jsonStr, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
        }
    }
}

Here is my CreateAccount.java:

package android.capstone.registerlogin;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;

public class CreateAccount extends Activity {


    private EditText etUserName, etPassWord, etEmail;
    private Button mButton;
    //private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_account);

        etPassWord = (EditText) findViewById(etCreateAccPassword);
        etUserName = (EditText) findViewById(etCreateAccUsername);
        etEmail = (EditText) findViewById(etCreateAccEmail);

        final String UserName = etUserName.getText().toString();
        final String PassWord = etPassWord.getText().toString();
        final String Email = etEmail.getText().toString();


        mButton = (Button) findViewById(R.id.bCreateAccSignUp);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
                new SignupActivity(CreateAccount.this).execute(UserName, PassWord, Email);


            }

            });
        }




    public void signup(View v) {
        String UserName = etUserName.getText().toString();
        String PassWord = etPassWord.getText().toString();
        String Email = etEmail.getText().toString();



        Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
        new SignupActivity(this).execute(UserName, PassWord, Email);
    }
}

Here is my PHP file:

<?php
$con=mysqli_connect("db.soic.indiana.edu","caps16_team19","capstoneteam19","caps16_team19");
if (mysqli_connect_errno($con))
{
   echo '{"query_result":"ERROR"}';
}


$userName = $_GET['username'];
$passWord = $_GET['password'];
$tDate = $_GET['date'];
$tDate = date('Y-m-d');
$eMail =$_GET['email'];

if($eMail == null) {
    echo '{"query_result":"FAILURE"}';
} else {

$result = mysqli_query($con,"INSERT INTO account (username, password, activated, email) VALUES ('$userName', '$passWord', '$tDate','$eMail')");

if($result == true) {
    echo '{"query_result":"SUCCESS"}';
}
else{
    echo '{"query_result":"FAILURE"}';
}
}

mysqli_close($con);
?>

Let me know if you need additional files!
Thanks for your help!


Source: stackoverflow-php

Android unable to launch the app in emulator

I am newbie in mobile app development. I am working on android studio. I have created two tables in mysql DB, one of them is users and the other one is activity. For now i am working with the users table. My task is to make an app in which there should be a dropdown and all the user names will be in it. When a user selects any of the name the id of that user will be shown.

For this i created a php file in which i have returned a json result.

Below is my php code

$sql = "SELECT * FROM users";


$r = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($r)){
   array_push($result,array(
    'Id'=>$row['Id'],
    'Name'=>$row['Name']
   ));
}

  echo json_encode(array('result'=>$result));

  mysqli_close($con);

Below is the result of the above code

{"users":[{"Id":"1","Name":"Faisal"},{"Id":"2","Name":"Salman"},{"Id":"3","Name":"Asim"},{"Id":"4","Name":"Asad"},{"Id":"5","Name":"Mateen"}]}

Now shifting towards my android part

Below is my Config file

public class Config {

//JSON URL
public static final String DATA_URL = "http://10.0.2.2:8000/MobileApp/index.php";

//Tags used in the JSON String

public static final String TAG_NAME = "Name";

public static final String TAG_ID = "Id";

//JSON array name
public static final String JSON_ARRAY = "users";

}

MainActivity

public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener {

  //Declaring an Spinner
 private Spinner spinner;

//An ArrayList for Spinner Items
private ArrayList<String> users;

//JSON Array
private JSONArray result;

//TextViews to display details
private TextView textViewResult;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    //Initializing the ArrayList
    users = new ArrayList<String>();

    //Initializing Spinner
    spinner = (Spinner)findViewById(R.id.spinner);


    //Adding an Item Selected Listener to our Spinner
    //As we have implemented the class Spinner.OnItemSelectedListener to this class iteself
    // we are passing this to setOnItemSelectedListener

    spinner.setOnItemClickListener((AdapterView.OnItemClickListener) this);

    //Initializing TextView

    textViewResult = (TextView)findViewById(R.id.textView);

    //This method will fetch the data from the URL
    getData();
}

private void getData() {

    //Creating a string request
    StringRequest stringRequest = new StringRequest(Config.DATA_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    JSONObject j = null;
                    try {
                        //Parsing the fetched Json String to JSON Object
                        j = new JSONObject(response);

                        //Storing the Array of JSON String to our JSON Array
                        result = j.getJSONArray(Config.JSON_ARRAY);

                        //Calling method getStudents to get the students from the JSON Array
                        getUsers(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    //Creating a request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void getUsers(JSONArray j) {

    //Traversing through all the items in the json array
    for(int i =0; i<j.length(); i++)
    {
        try
        {
            //Getting json object
            JSONObject json = j.getJSONObject(i);

            //Adding the name of the student to array list
            users.add(json.getString(Config.TAG_NAME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

 //Setting adapter to show the items in the spinner

    spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_dropdown_item, users));
}

private void getUsers() {


}

//Method to get student name of a particular position
private String getName(int position)
{
    String name = "";
    try
    {
        //Getting object of given index
        JSONObject json = result.getJSONObject(position);
        //Fetching name from that object
        name = json.getString(Config.TAG_NAME);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return name;
}

//Method to get student Id of a particular position
private String getId (int postion)
{
    String Id="";
    try{
        JSONObject json = result.getJSONObject(postion);

        Id = json.getString(Config.TAG_ID);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return Id;
}

//this method will execute when we pic an item from the spinner
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    //Appending the values to textview for a selected item

    textViewResult.append("Hi " + getName(position) + "Your ID is " + getId(position));
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

    textViewResult.setText("");

}}

For now i am running the app in the emulator using 10.0.2.2. When i run the app the app crashes and at logcat i get the following error

 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.accurat.webaccess/com.example.accurat.webaccess.MainActivity}: java.lang.ClassCastException: com.example.accurat.webaccess.MainActivity cannot be cast to android.widget.AdapterView$OnItemClickListener
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                             at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:135)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at java.lang.reflect.Method.invoke(Method.java:372)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                          Caused by: java.lang.ClassCastException: com.example.accurat.webaccess.MainActivity cannot be cast to android.widget.AdapterView$OnItemClickListener
                                                                             at com.example.accurat.webaccess.MainActivity.onCreate(MainActivity.java:64)
                                                                             at android.app.Activity.performCreate(Activity.java:5990)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                             at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                             at android.os.Looper.loop(Looper.java:135) 
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                             at java.lang.reflect.Method.invoke(Native Method) 
                                                                             at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

And it hits at textViewResult = (TextView)findViewById(R.id.textView);

I know there are many questions on it i have looked into them but still i am unable to solve the issue.

I have no idea what is the problem. Any help would be highly appreciated.


Source: stackoverflow-php