• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Login tutorial app crashes

Dannnorman

Lurker
Jul 23, 2017
6
1
Hi guys, I am new to android and I am trying to develop my first app, I started with this tutorial and got to the step #4 so far

I got to the point of interaction between the app and the database but here something happens, specifically when I click the registerHere link, the app crashes and I don't know whats going on. I have tried it in my phone and also in the virtual nexus 5 and on both is the same result.
The Host provider I am using is https://profreehost.com/ there I created a SQL table.
Please if you can give me your support to see how can I fix this issue. Thanks!

The register request.java
Code:
package com.example.android.loginregister;

import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
* Created by DeadMarshes on 7/21/2017.
*/

public class RegisterRequest extends StringRequest {
    private static final String REGISTER_REQUEST_URL = "http://danielandnorman.unaux.com/Register.php";
    private Map<String, String> params;
    public RegisterRequest(String name, String username, int age, 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);
        params.put("age", age + "");
    }

    [USER=1021285]@override[/USER]
    public Map<String, String> getParams() {
        return params;
    }

For the register activity.Java

Code:
public class RegisterActivity extends AppCompatActivity {

    [USER=1021285]@override[/USER]
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        final EditText etAge = (EditText) findViewById(R.id.etAge);
        final EditText etName = (EditText) findViewById(R.id.etName);
        final EditText etUsername = (EditText) findViewById(R.id.etUsername);
        final EditText etPassword = (EditText) findViewById(R.id.etPassword);
        final Button bRegister = (Button) findViewById(R.id.bRegister);

        bRegister.setOnClickListener(new View.OnClickListener() {
            [USER=1021285]@override[/USER]
            public void onClick(View view) {
                final String name = etName.getText().toString();
                final String username = etUsername.getText().toString();
                final String password = etPassword.getText().toString();
                final int age = Integer.parseInt(etAge.getText().toString());

                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    [USER=1021285]@override[/USER]
                    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);
                            } else{
                                AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                                builder.setMessage("Register Failed")
                                        .setNegativeButton("Retry", null)
                                        .create()
                                        .show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                };



                RegisterRequest registerRequest = new RegisterRequest(name, username,age, password, responseListener );
                RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
                queue.add(registerRequest);
            }
        });
    }
}


Also the php file Register.php

Code:
<?php
    $con = mysqli_connect("sql111.unaux.com", "username", "password", "table");
  
    $name = $_POST["name"];
    $age = $_POST["age"];
    $username = $_POST["username"];
    $password = $_POST["password"];
    $statement = mysqli_prepare($con, "INSERT INTO UserTable (name, username, age, password) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $name, $username, $age, $password);
    mysqli_stmt_execute($statement);
  
    $response = array();
    $response["success"] = true; 
  
    echo json_encode($response);
?>
 
Last edited by a moderator:
  • Like
Reactions: Rob
Please provide the stacktrace and also format your code with code tags

Hi , there is the Logcat, is that what you need?
How do I post my code in blocks in the forum?
Thank you for your reply

Code:
07-23 20:29:38.198 7679-7679/com.example.android.loginregister E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: com.example.android.loginregister, PID: 7679
                                                                                 java.lang.NumberFormatException: For input string: ""
                                                                                     at java.lang.Integer.parseInt(Integer.java:620)
                                                                                     at java.lang.Integer.parseInt(Integer.java:643)
                                                                                     at com.example.android.loginregister.RegisterActivity$1.onClick(RegisterActivity.java:36)
                                                                                     at android.view.View.performClick(View.java:6219)
                                                                                     at android.view.View$PerformClick.run(View.java:24482)
                                                                                     at android.os.Handler.handleCallback(Handler.java:769)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                                     at android.os.Looper.loop(Looper.java:164)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 
Last edited:
Upvote 0
Have you read https://androidforums.com/threads/please-read-me-before-posting.987318/ before posting ?

If you have a coding issue that you would like advice on, please enclose your code in code tags. This will ensure that the code is nicely formatted, indented, and easy to read. You would be surprised how many people asking a programming related question here do not include their code, or include only a small isolated fragment of code. This makes it virtually impossible to answer the question. Include all relevant code parts to allow someone to understand the problem. This includes layout XML code.
 
Last edited:
Upvote 0
How do I post my code in blocks in the forum?

I edited your original post to add the code tags. To explain further - if you post your code like this it should be nicely formatted


[code]
// Paste some code in here
[/code]


To elaborate on the above answer as to why you get the problem with your app, it looks like what you typed into the 'etAge' EditText was not a proper number. So when the code tried to convert whatever you typed into a numeric value, it couldn't e.g. the String "hello" can not be converted to a value. Does this make sense?
 
Upvote 0
Actually looking at the stack trace, it's clear that you typed nothing into the EditText. So parseInt() method tries to convert a blank string "" into a number. That's what caused your exception.

Code:
java.lang.NumberFormatException: For input string: ""

To catch this error, you could add some defensive checking code, to detect either a null value, or blank String, and display an error message to the user.
 
  • Like
Reactions: Dannnorman
Upvote 0
Thank you very much for your help,
It makes total sense, I didn't realize that was making extra trouble when left blank, so fixing that issue I get now the following, looks like a problem with the request

Code:
07-24 22:24:08.078 13365-13365/com.example.android.loginregister I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3d264d85 time:45296072
07-24 22:24:11.878 13365-13365/com.example.android.loginregister D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
07-24 22:24:12.018 13365-22010/com.example.android.loginregister I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
07-24 22:24:12.028 13365-22010/com.example.android.loginregister I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
07-24 22:24:12.028 13365-22010/com.example.android.loginregister I/qtaguid: Tagging socket 37 with tag d3987bb100000000{3549985713,0} uid -1, pid: 13365, getuid(): 10239
07-24 22:24:12.508 13365-22010/com.example.android.loginregister I/qtaguid: Untagging socket 37
07-24 22:24:12.538 13365-13365/com.example.android.loginregister W/System.err: org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at com.example.android.loginregister.RegisterActivity$1$1.onResponse(RegisterActivity.java:42)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at com.example.android.loginregister.RegisterActivity$1$1.onResponse(RegisterActivity.java:38)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at android.os.Looper.loop(Looper.java:145)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5835)
07-24 22:24:12.548 13365-13365/com.example.android.loginregister W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
07-24 22:24:12.558 13365-13365/com.example.android.loginregister W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
07-24 22:24:12.558 13365-13365/com.example.android.loginregister W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
07-24 22:24:12.558 13365-13365/com.example.android.loginregister W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
07-24 22:24:15.418 13365-13365/com.example.android.loginregister D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
07-24 22:24:22.028 13365-13365/com.example.android.loginregister D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
07-24 22:24:22.188 13365-22163/com.example.android.loginregister I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
07-24 22:24:22.188 13365-22163/com.example.android.loginregister I/qtaguid: Tagging socket 37 with tag d3987bb100000000{3549985713,0} uid -1, pid: 13365, getuid(): 10239
07-24 22:24:22.198 13365-22163/com.example.android.loginregister I/qtaguid: Untagging socket 37
07-24 22:24:22.198 13365-22163/com.example.android.loginregister E/Volley: [35745] BasicNetwork.performRequest: Unexpected response code 400 for http://danielandnorman.unaux.com/Register.php

Do you know what this may be due to?
 
Upvote 0
You would be wise to take some time to understand how the request is being made to your remote PHP service. I don't see the code which is making the HTTP request, but I think it could be in class StringRequest, which you have not shown.
So the parameter passed in to your onResponse() method should be a JSON String, but it isn't

Code:
public void onResponse(String response) {

It looks like the HTML response String. You then try to construct a JSON object using this String

Code:
JSONObject jsonResponse = new JSONObject(response);

Which causes the exception because it's not valid JSON.
If you don't know what JSON is, then now would be a good time to read up about that.
Bottom line is that response needs to be a valid JSON String.
 
Upvote 0
You would be wise to take some time to understand how the request is being made to your remote PHP service. I don't see the code which is making the HTTP request,


HI @LV426,
Isn't the request file "Register request.java"?
I am trying to get to know this JSON method better, and checking how I can modify to be a valid JSON string. I appreciate your help
 
Upvote 0
Well RegisterRequest doesn't do very much. It extends StringRequest, which I presume is doing all the heavy lifting work by calling the remote service via a HTTP request. It also probably invokes your listener callback method - onResponse(). It's that code we need to see.
 
Upvote 0
ok, you mean this

String request.java
Code:
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.android.volley.toolbox;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;

import java.io.UnsupportedEncodingException;

/**
* A canned request for retrieving the response body at a given URL as a String.
*/
public class StringRequest extends Request<String> {
    private final Listener<String> mListener;

    /**
     * Creates a new request with the given method.
     *
     * @param method the request {@link Method} to use
     * @param url URL to fetch the string at
     * @param listener Listener to receive the String response
     * @param errorListener Error listener, or null to ignore errors
     */
    public StringRequest(int method, String url, Listener<String> listener,
            ErrorListener errorListener) {
        super(method, url, errorListener);
        mListener = listener;
    }

    /**
     * Creates a new GET request.
     *
     * @param url URL to fetch the string at
     * @param listener Listener to receive the String response
     * @param errorListener Error listener, or null to ignore errors
     */
    public StringRequest(String url, Listener<String> listener, ErrorListener errorListener) {
        this(Method.GET, url, listener, errorListener);
    }

    @Override
    protected void deliverResponse(String response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }
        return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
    }
}
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones