Issue with accessing data from database in my app

I am currently working on a project that involves retrieving data from my database. The user inputs a car registration number and a rating (ranging from 1 to 5) and then clicks a button. Upon clicking the button, my code is supposed to execute, fetching text from both EditText fields and sending it to my server. I have a PHP file that checks if the car registration number matches any value in the database, and if there's a match, it retrieves the current rating associated with that number. This retrieved value is then displayed on another activity. The PHP file is functioning properly as I tested by manually inserting values. However, the issue I'm facing is that nothing happens when the button is clicked. I've used similar code successfully for retrieving other details in a different app.

Here are the relevant Java classes:

public class DataRetrieve extends StringRequest {

private static final String REGISTER_REQUEST_URL = "https://dipteran-thin.000webhostapp.com/Login1.php";
private Map<String, String> params;

public DataRetrieve (String carreg, int rating, Response.Listener<String> listener) {

        super(Method.POST, REGISTER_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("carreg", carreg);
        params.put("rating", rating + "");
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }
}

Profile.java (where the user inputs car registration number and rating):

public class Profile extends AppCompatActivity {

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

    final EditText editText = (EditText) findViewById(R.id.carreg);
    final EditText editText1 = (EditText) findViewById(R.id.editText3);
    Button button = (Button) findViewById(R.id.button2);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String carreg = editText.getText().toString();
            final int rating = Integer.parseInt(editText1.getText().toString());

            // Server response handling
            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) {
                            int rating = jsonResponse.getInt("rating");

                            Intent intent = new Intent(Profile.this, UserAreaActivity.class);
                            intent.putExtra("rating", rating);
                            Profile.this.startActivity(intent);
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(Profile.this);
                            builder.setMessage("Login Failed")
                                    .setNegativeButton("Retry", null)
                                    .create()
                                    .show();
                        }

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

            DataRetrieve loginRequest = new DataRetrieve(carreg, rating, responseListener);
            RequestQueue queue = Volley.newRequestQueue(Profile.this);
            queue.add(loginRequest);
        }
    });
}
}

UserAreaActivity.java (where the retrieved value is shown):

public class UserAreaActivity extends AppCompatActivity {

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


    final TextView etusername = (TextView) findViewById(R.id.textView2);
    final TextView etwelcome = (TextView) findViewById(R.id.textView);
    final TextView etuname = (TextView) findViewById(R.id.textView3);
    final Button Logout = (Button) findViewById(R.id.logout);

    Intent intent = getIntent();
    username = intent.getIntExtra("rating", -1);
    etusername.setText(username + "");

}

@Override
public void onBackPressed(){

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
        Intent intent = new Intent(UserAreaActivity.this, Messages.class);
        UserAreaActivity.this.startActivity(intent);
    }
    return true;
}

Answer №1

An error is occurring on your php page:

<b>Parse error</b>:  syntax error, unexpected ']' in <b>/storage/ssd1/526/2972526/public_html/Login1.php</b> on line <b>8</b><br />

To view the output of your response in the log, add this line above your JSON parsing before it throws the exception:

Log.d("Response", response.toString());

I placed your success block within the exception block and it functioned correctly, indicating that the code is valid. It would be advisable to include some form of alert in the catch section to notify you of any failures once testing is completed.

As a side note, consider modifying your parameter line as follows for better readability:

params.put("rating", String.valueOf(rating));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging! My issue is: When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...

Exploring Vaadin 14 Slider Components

I'm looking for help on how to incorporate a slider into my Vaadin 14 project. I discovered that the slider component was removed in Vaadin 10, so I turned to this alternative: Once I added the Maven dependency and repository to my pom.xml, I success ...

Modifying the color of a variety of distinct data points

There was a previous inquiry regarding Changing Colour of Specific Data, which can be found here: Changing colour of specific data Building upon that question, I now have a new query. After successfully changing the 2017 dates to pink, I am seeking a way ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...

What steps should I take to change the orientation of these items from vertical to horizontal display?

I'm struggling to get these items to appear horizontally (side by side) instead of vertically on my webpage. They are linked to a database, hence the PHP code included here. If you need more information, please feel free to ask. body { font: no ...

What is the best way to create square editor tabs in Eclipse without using swt-border-radius?

The design of Eclipse's rounded and/or swooshing tabs is starting to feel outdated in today's modern era. I thought that by adding the following line in my default.css file, I could get rid of the rounded corners: swt-corner-radius: 0px Howeve ...

Is it acceptable to replicate another individual's WordPress theme and website design in order to create my own WordPress website that looks identical to theirs?

It may sound shady, but a friend of mine boasts about the security of his WordPress website, claiming it's impossible to copy someone else's layout or theme. However, my limited experience in web development tells me otherwise. I believe it is po ...

The calculator I designed using HTML, CSS, and JavaScript is experiencing difficulty adjusting to various screen sizes

I recently built a calculator using HTML, CSS, and JavaScript. It works perfectly on PC or big screens, but when viewed on smaller devices like phones or tablets, the display gets cut off and does not adjust properly. Here are some example pictures for ref ...

Troubleshooting a unique CSS problem on an Android PhoneGap

We are currently working on an Android application using PhoneGap, HTML, CSS, and jQuery Mobile. After compiling the application in Eclipse, everything seems to work correctly. However, I am facing an issue where my CSS styles are not updating when recompi ...

What is the best way to add custom styles to an Ext JS 'tabpanel' xtype using the 'style

Is there a way to change the style of a Ext.tab.Panel element using inline CSS structure like how it's done for a xtype: button element? { xtype: "button", itemId: "imageUploadButton1", text: "Uploader", style: { background : ' ...

Is there a way to enhance the appearance of a TextField in JavaFX to resemble the sleek design of Android or material UI?

Is there a way to create a window like this in JavaFX? Take a look at the textfield shown in the image below... I recently came across the Jphonex framework that allows for this type of display. However, when I package it into a Jar file and try to run it ...

The media query designed for iPads with a minimum width will also be effective for Android devices

As I delve into the realm of editing CSS created by others, I come across a peculiar situation involving media queries specifically designed for iPads. While one query is intended for portrait orientation and another for landscape, they are causing havoc o ...

Ensure that the "select" dropdown menu remains a constant size

One section of my Android app, powered by JQuery Mobile, displays a table with a combobox. The issue arises when selecting the option with a very long text, causing the combobox to expand and show half of the table off-screen. My goal is to set the combob ...

The specified selector is invalid or illegal in HTMLUnit

Attempting to mimic a login using htmlunit has presented me with an issue despite following examples. The console messages I have gathered are as follows: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' erro ...

Disable Chrome's suggestions bar on your Android phone

I'm having trouble disabling spelling suggestions for an input box and everything I've tried so far hasn't worked. I've already used attributes like autocomplete="off", autocapitalize="off", and spellcheck="off" for the input field, bu ...

How to Adjust the Padding of Tree Row in GWT?

Have you ever seen a GWT tree before? It sort of resembles the following structure: <div class="gwt-Tree"> <div style="padding-top: 3px; padding-right: 3px; padding-bottom: 3px; margin-left: 0px; padding-left: ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

Specify padding or margin for all sides in a single line of XML code

Is there a way to set the padding or margin for all four sides in xml with just one line, similar to how we can do it in css? For instance, in css: padding: 1px 2px 3px 4px; Is there an equivalent method in xml for accomplishing this? ...

Acquiring the applicable CSS for a JavaFX 8 widget

While working on JavaFX styling with CSS, I encountered a challenge in understanding which CSS properties are directly affecting the appearance of a GUI widget. It reminded me of using Firefox web developer tools to inspect elements and view the specific s ...