dimanche 26 juin 2016

E/RegisterActivity: Registration Error: null

While I am somewhat familiar with Android programming, I am a complete beginner with PHP and SQL. I have been following the tutorial found at http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ and have gotten everything to run, except I keep getting a E/RegisterActivity: Registration Error: null when I try to make an account.

Every fix I have seen (changing my IP address, switching out DB_USER and DB_PASSWORD in Config.php) hasn't worked for me. I am running from localhost port 8080. If any of you see where my problem may lie, that would be great!

Main Activity

package example.com.musicapptest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.HashMap;

import example.com.musicapptest.helper.SQLiteHandler;
import example.com.musicapptest.helper.SessionManager;


public class MainActivity extends AppCompatActivity {

private SQLiteHandler db;
private SessionManager session;

/**
 * The {@link PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */

private TextView txtName;
private TextView txtEmail;
private Button btnLogout;



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

    txtName = (TextView) findViewById(R.id.name);
    txtEmail = (TextView) findViewById(R.id.email);
    btnLogout = (Button) findViewById(R.id.btnLogout);

    // SqLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // session manager
    session = new SessionManager(getApplicationContext());

    if (!session.isLoggedIn()) {
        logoutUser();
    }

    // Fetching user details from sqlite
    HashMap<String, String> user = db.getUserDetails();

    String name = user.get("name");
    String email = user.get("email");

    // Displaying the user details on the screen
    txtName.setText(name);
    txtEmail.setText(email);

    // Logout button click event
    btnLogout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            logoutUser();
        }
    });
}

/**
 * Logging out the user. Will set isLoggedIn flag to false in shared
 * preferences Clears the user data from sqlite users table
 * */

/**
 * Logging out the user. Will set isLoggedIn flag to false in shared
 * preferences Clears the user data from sqlite users table
 * */
private void logoutUser() {
    session.setLogin(false);

    db.deleteUsers();

    // Launching the login activity
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    startActivity(intent);
    finish();
}

/*
    Two classes to respond to button clicks
 */
public void onJoinButtonClick(View view) {
    Intent intent = new Intent(MainActivity.this, JoinMainPage.class);
    startActivity(intent);
}
public void onHostButtonClick(View view){
    Intent intent = new Intent(MainActivity.this, HostMainPage.class);
    startActivity(intent);
}
public void onHomeButtonClick(View view){
    Intent intent = new Intent(MainActivity.this, HomePage.class);
    startActivity(intent);
}
public void onJoinButtonClick(MenuItem item){
    Intent intent = new Intent(MainActivity.this, JoinMainPage.class);
    startActivity(intent);
}
public void onHostButtonClick(MenuItem item){
    Intent intent = new Intent(MainActivity.this, HostMainPage.class);
    startActivity(intent);
}
public void onHomeButtonClick(MenuItem item){
    Intent intent = new Intent(MainActivity.this, HomePage.class);
    startActivity(intent);
}

@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_main, 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);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */

    private TextView txtName;
    private TextView txtEmail;
    private Button btnLogout;

    private SQLiteHandler db;
    private SessionManager session;
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //Linking up values in fragment_main.xml to the MainActivity
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView splashTitleView = (TextView) rootView.findViewById(R.id.splash_title_text);
        TextView splashBodyView = (TextView) rootView.findViewById(R.id.splash_body_text);
        ProgressBar splashProgress = (ProgressBar) rootView.findViewById(R.id.welcome_progress_bar);

        /*
            Setting up which splash page will be displayed as the user progresses throughout the welcome splash page
         */
        if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
            splashTitleView.setText("Welcome Fragment");
            splashBodyView.setText("Here is some text about the Welcome Page");
            splashProgress.setProgress(100 / 6);
        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
            splashTitleView.setText("Join Fragment");
            splashBodyView.setText("Here is some text about the Join Page");
            splashProgress.setProgress(2 * (100 / 6));
        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3) {
            splashTitleView.setText("Vote Fragment");
            splashBodyView.setText("Here is some text about the Vote Page");
            splashProgress.setProgress(3 * (100 / 6));
        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
            splashTitleView.setText("Suggest Fragment");
            splashBodyView.setText("Here is some text about the Suggest Page");
            splashProgress.setProgress(4 * (100 / 6));
        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 5) {
            splashTitleView.setText("Host Fragment");
            splashBodyView.setText("Here is some text about the Host Page");
            splashProgress.setProgress(5 * (100 / 6));
        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 6) {
            splashTitleView.setText("Get Started Fragment");
            splashBodyView.setText("Here is some text about the Get Started Page");
            splashProgress.setProgress(100);
        }
        //Default frag if for some reason there is an IndexOutOfBoundsException()
        else {
            splashTitleView.setText("Get Started Fragment");
            splashBodyView.setText("Here is some text about the Get Started Page");
            splashProgress.setProgress(100);
        }

        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 6 total pages.
        return 6;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
            case 3:
                return "SECTION 4";
            case 4:
                return "SECTION 5";
            case 5:
                return "SECTION 6";
        }
        return null;
    }
}
}

Activity Main 2

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="20dp"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/welcome"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textColor="@color/lbl_name"
        android:textSize="24dp" />

    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="13dp" />

    <Button
        android:id="@+id/btnLogout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@color/btn_logut_bg"
        android:text="@string/btn_logout"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp" />
</LinearLayout>

</RelativeLayout>

Register Activity

/**
 * Author: Ravi Tamada
 * URL: www.androidhive.info
 * twitter: http://twitter.com/ravitamada
 */
package example.com.musicapptest;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
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.util.HashMap;
import java.util.Map;

import example.com.musicapptest.app.AppConfig;
import example.com.musicapptest.app.AppController;
import example.com.musicapptest.helper.SQLiteHandler;
import example.com.musicapptest.helper.SessionManager;

public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    inputFullName = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);

    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
    if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this,
                MainActivity.class);
        startActivity(intent);
        finish();
    }

    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString().trim();
            String email = inputEmail.getText().toString().trim();
            String password = inputPassword.getText().toString().trim();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerUser(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}

/**
 * Function to store user in MySQL database will post params(tag, name,
 * email, password) to register url
 * */
private void registerUser(final String name, final String email,
                          final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_register";

    pDialog.setMessage("Registering ...");
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Register Response: " + response.toString());
            hideDialog();

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (!error) {
                    // User successfully stored in MySQL
                    // Now store the user in sqlite
                    String uid = jObj.getString("uid");
                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user.getString("created_at");

                    // Inserting row in users table
                    db.addUser(name, email, uid, created_at);

                    Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();

                    // Launch login activity
                    Intent intent = new Intent(
                            RegisterActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                    finish();
                } else {

                    // Error occurred in registration. Get the error
                    // message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Registration Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("name", name);
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

private void showDialog() {
    if (!pDialog.isShowing())
        pDialog.show();
}

private void hideDialog() {
    if (pDialog.isShowing())
        pDialog.dismiss();
}
}

App Config

package example.com.musicapptest.app;

/**
 * Created by Carter Klein on 6/26/2016.
 */
public class AppConfig {
// Server user login url
public static String URL_LOGI= "http://10.0.2.2:8080/android_login_api/login.php";

// Server user register url
public static String URL_REGISTER = "http://10.0.2.2:8080/android_login_api/register.php";
}

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.musicapptest"
android:versionCode="1"
android:versionName="0.1">

<uses-sdk
    android:maxSdkVersion="8"
    android:targetSdkVersion="19"/>

<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:name="example.com.musicapptest.app.AppController"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".LoginActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustPan" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".RegisterActivity"
        android:label="@string/app_name"
        android:launchMode="singleTop"
        android:windowSoftInputMode="adjustPan" />
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
 ATTENTION: This was auto-generated to add Google Play services to your project for
 App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information.
    -->
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".HostMainPage"
        android:label="@string/title_activity_host_main_page"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity
        android:name=".JoinMainPage"
        android:label="@string/title_activity_join_main_page"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".HomePage"></activity>
</application>


</manifest>

Config

<?php

/**
 * Database config variables
 */
define("DB_HOST", "127.0.0.1:8080");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "android_login_api");
?>

Register


<?php

require_once 'include/DB_Functions.php';
$db = new DB_Functions();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {

// receiving the post params
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];

// check if user is already existed with the same email
if ($db->isUserExisted($email)) {
    // user already existed
    $response["error"] = TRUE;
    $response["error_msg"] = "User already existed with " . $email;
    echo json_encode($response);
} else {
    // create a new user
    $user = $db->storeUser($name, $email, $password);
    if ($user) {
        // user stored successfully
        $response["error"] = FALSE;
        $response["uid"] = $user["unique_id"];
        $response["user"]["name"] = $user["name"];
        $response["user"]["email"] = $user["email"];
        $response["user"]["created_at"] = $user["created_at"];
        $response["user"]["updated_at"] = $user["updated_at"];
        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, email or password) is missing!";
echo json_encode($response);
}
?>

DB Connect


<?php
class DB_Connect {
private $conn;

// Connecting to database
public function connect() {
    require_once 'include/Config.php';

     // Connecting to mysql database
     $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

     // return database handler
     return $this->conn;
 }
 }
 ?>

1 commentaire:

  1. hi , I just run into this blog and I wanted to know if you figured out how to solve your problem with the tutorial because i got the same error

    RépondreSupprimer