When attempting to call methods after executing a new Class in Android Studio, the application crashes

I have been working on an app that utilizes JSON data. The issue I am facing is that when I retrieve the JSON using HentData.execute() and assign it to a string variable, my program crashes when I try to perform any operations with it.

HentData extends AsyncTask, so I am confident that it provides me with a valid JSON string.

Within the onCreate() method:

new HentData().execute(); 
jsonToArray();
arrayToText();

This sequence of actions results in a crash.

However, if I execute them like this, everything works fine. Could it be related to closing the HentData class properly?

protected void onPostExecute(String resultat){
    json_string = resultat;
    jsonToArray();
    arrayToText(); 
}

This is the doInBackground() method:

protected String doInBackground(Void... voids){
        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream IS = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS));
            StringBuilder sb = new StringBuilder();
            while((json_string = bufferedReader.readLine())!=null){
                sb.append(json_string+"\n");
            }

            bufferedReader.close();
            IS.close();
            httpURLConnection.disconnect();
            return sb.toString().trim();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

Answer №1

Is it necessary to close the HentData class when running it in this manner? It seems to work fine as is.

protected void onPostExecute(String resultat){
    json_string = resultat;
    jsonToArray();
    arrayToText(); 
}

There is no need to explicitly close anything. The functionality works due to the asynchronous nature of AsyncTask, allowing the code to run in the background.

In simpler terms,

new HentData().execute();  // Execution continues without waiting for result
jsonToArray(); // Proceeds even if the result isn't ready yet --> leading to an error
arrayToText();

If you prefer a more versatile method for obtaining results, refer to How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

For those who find writing AsyncTasks (for HTTP methods) cumbersome, check out Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley

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

Empty nested Map in POST request

I am currently working on a springboot application with a React/Typescript frontend. I have defined two interfaces and created an object based on these interfaces. export interface Order { customer_id: number; date: Date; total: number; sp ...

Discovering WebElements: The key to effective web development

Our automation process currently relies heavily on @FindBy with Selenium/WebDriver/Java. This includes: @FindBy(css="a[name='bcrumb']") protected List<WebElement> breadCrumbLinks; @FindBy(id="skuError") protected WebElement skuE ...

leveraging ajax callbacks, the significance of http status codes and essential validation concepts

Recently, I've been working on a server side AJAX class designed to return a JSON string in response to an AJAX request. One question that has been on my mind is when it would be appropriate to return HTTP status codes based on the server's respo ...

Unpacking JSON in C#

Having trouble deserializing JSON in C# and receiving a NullReferenceException without understanding why. Here is the specific JSON being parsed: {"Entries": {"Entry": {"day": "28","month": "10","year": "1955","type": "birthday","title": "Bill Gates was ...

Instructions for duplicating the current website address into another browser window or document without user input

I have a desire to create a button within a web browser that, when clicked, will either copy the current URL address into a file or open another web browser and paste it there. Being new to programming, I am unsure of which language to use for this task. ...

Highcharts still unable to display series data despite successful decoding efforts

After receiving JSON decoded data from the server and using $.parseJSON to decode it, I am assigning it to the series in Highcharts. Although there are no console errors, the chart refuses to display. Below is the code snippet: <!DOCTYPE html> < ...

Changing a Unique JSON Structure into a VB.NET Object

I have a JSON object that is structured as follows. { "Errors":{ "err1":[ //* Array of err1 objects ], "err2":[ //* Array of err2 objects ] } } This object is used to report errors identified in a request to a PHP page. My goal i ...

Jackson's @JsonView is not functioning properly as per expectations

Currently, I am working with Jackson JSON 1.9.12 in conjunction with SpringMVC. As part of this, I have created a data transfer object (dto) with JSON fields. To have two profiles of the same dto with different JSON fields, I took the approach of creating ...

Exploring the process of breaking down a substantial string object into manageable key/value pairs using AngularJS

I gathered information from a text file called sample_resume.txt Name: John Doe Phone: (555) 555-5555 Email: [email protected] TARGET To succeed in the field of web development. SKILL SET Development: HTML5, JavaScript, Bootstrap, AngularJS, Rea ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

Discovering the key and corresponding value within a JSON object based on a different key-value pair

I am currently working in PostgreSQL and I'm attempting to extract the key (r_dirigeant, r_actionnaire, r_beneficiaire) or generate a text containing all keys when "r_ppe" = "oui" and one of the keys (r_dirigeant, r_actionnaire, r_beneficiaire) is als ...

Transforming CSV data into JSON format by converting each column into a separate array

I have a set of csv data examples that are structured like the following: id,hex1,hex2,hex3,hex4,hex5 388,#442c1c,#927450,#664c31,#22110c, 387,#6a442f,#826349,,, 1733,#4d432e,#75623f,,, 1728,#393e46,#5f4433,#ad7a52,#362c28,#a76042 I am interested in tran ...

Problem with JSON in Spring Boot REST API

Within my spring boot rest application, there is a controller containing the method below. This method utilizes hibernate to retrieve data from an Oracle DB. The problem arises when I call this service, as it returns a HTTP ERROR 500. Strangely, no error ...

Creating a comprehensive response involves merging two JSON responses from asynchronous API calls in a nodejs function block. Follow these steps to combine two REST API

New to JavaScript and the async/await methodology. I am working with two separate REST APIs that return JSON data. My goal is to call both APIs, combine their responses, and create a final JSON file. However, I am facing issues with updating my final varia ...

Is there a way to execute an SQL query using ajax?

I recently came across an interesting problem involving passing an SQL query through to an ajax file. let qry = mysqli_query($this->con,"SELECT * FROM products"); To ensure proper containment, I embedded the variable within HTML using the following co ...

Learn how to utilize the foreach loop in C# to iterate through an array and retrieve its

{ "Config": { "controls": [ { "id": 1, "name": "test", "inputs": [ { } ] }, { "id": 2, "name": "xyz", "inputs": [ { } ] } ...

It appears that the :first / :first-child selector is not functioning properly with Selenium 2

During my transition from Selenium 1 to Selenium 2, I encountered an issue. The structure I currently have is similar to the following: <ul id="documentType"> <li><a href="http://somelink.com">first</a></li> <li& ...

Utilizing Highcharts for Dynamic Data Loading via AJAX

Just delving into the world of Highcharts and hoping that the issue I'm facing is just a simple oversight on my part. I decided to work off the example provided in the Highcharts live update demo - and made changes only to the series data portion to ...

Encountering a 500 error when sending JSON requests to a Ruby on Rails server application

I developed a Ruby on Rails server application hosted on Heroku that is designed to accept HTTP POST requests containing JSON strings and then add the JSON objects to the database. The application consists of two database models: thanksgivings and requests ...

Utilizing Angular.JS to sort items based on the chosen option in a select dropdown menu

I am utilizing the WP API to display a list of posts on a page from a JSON file. I have successfully implemented filtering through an input field named searchrecipe, which allows me to search for post titles. However, I am facing a challenge with filterin ...