Ways to retrieve content from a website

After conducting thorough research on this matter, I stumbled upon an answer here. Despite following the provided solution, the process is still not functioning as expected. My goal is simple - to extract text from a webpage like Google and convert it into a string. Below is my code, integrating the aforementioned tutorial's code:

public class Searching_Animation_Screen extends ActionBarActivity {
TextView loading_txt;
Animation blink;
public String pre_split;
public String[] split_string;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_searchinganimationscreen);
    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();
    int width = getWindowManager().getDefaultDisplay().getWidth();
    loading_txt = (TextView)findViewById(R.id.loading);
    text =(TextView)findViewById(R.id.textView);
    Typeface pacifico_typeface = Typeface.createFromAsset(getAssets(), "fonts/pacifico.ttf");
    loading_txt.setTypeface(pacifico_typeface);
    loading_txt.setTextSize(width / 20);
    blink = AnimationUtils.loadAnimation(getApplicationContext(),
           R.anim.blink);
    loading_txt.setAnimation(blink);
    Begin();

}

private void Begin() {
    Intent SEARCH_INTENT = getIntent();
    pre_split=SEARCH_INTENT.getStringExtra("Search_Text");
    split_string = pre_split.split(" ");
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_searchinganimationscreen, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    String google_url ="https://www.google.com/#safe=active&q=";

    @Override
    protected String doInBackground(String... urls) {
        String response = "";
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        text.setText(Html.fromHtml(result));
        //throw into summarizer
    }


    public void readWebpage(View view) {
        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] {"www.google.com"});

    }
}

}

Android Studio has pointed out that readWebpage is never utilized, as well as the actual DownloadWebPageTask class. Any suggestions? I aim for this class to execute immediately upon creation. Appreciate any help!

Answer №1

@Ethan, I've made the necessary adjustments to the code by adding the readWebpage method within the onCreate method of the Searching_Animation_Screen class. The View object has been removed as it was not being utilized,

    public class Searching_Animation_Screen extends ActionBarActivity {
TextView loading_txt;
Animation blink;
public String pre_split;
public String[] split_string;
TextView text;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_searchinganimationscreen);
    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();
    int width = getWindowManager().getDefaultDisplay().getWidth();
    loading_txt = (TextView)findViewById(R.id.loading);
    text =(TextView)findViewById(R.id.textView);
    Typeface pacifico_typeface = Typeface.createFromAsset(getAssets(), "fonts/pacifico.ttf");
   loading_txt.setTypeface(pacifico_typeface);
   loading_txt.setTextSize(width / 20);
   blink = AnimationUtils.loadAnimation(getApplicationContext(),
           R.anim.blink);
   loading_txt.setAnimation(blink);
   Begin();

  //* call webpage here, 
  //* note, i removed passing the view object since it is not being used
  readWebpage()

}

 //* (modify) by remvoving it from the code below 
 //* and removing the view object since it is not being used
 public void readWebpage() {
     DownloadWebPageTask task = new DownloadWebPageTask();
     task.execute(new String[] {"http://www.google.com"});

 }

private void Begin() {
    Intent SEARCH_INTENT = getIntent();
    pre_split=SEARCH_INTENT.getStringExtra("Search_Text");
    split_string = pre_split.split(" ");
}


@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_searchinganimationscreen, 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);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    String google_url ="https://www.google.com/#safe=active&q=";

    @Override
    protected String doInBackground(String... urls) {
        String response = "";
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    response += s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        text.setText(Html.fromHtml(result));
        //throw into summarizer
    }

  }

}

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

What is the proper way to include a closing tag for the canvas in a Canvas rendered by Three.js

Why does three js always add canvas elements without a closing tag to the page? Is there a specific reason for this? I'm interested in adding a closing tag to this canvas element. This example page was inspected, revealing something similar to this ...

Achieving the highest ranking for Kendo chart series item labels

Currently, I am working with a Kendo column chart that has multiple series per category. My goal is to position Kendo chart series item labels on top regardless of their value. By default, these labels are placed at the end of each chart item, appearing o ...

Ways to retrieve the text of the <Label> element without relying on the "id" attribute

I have a challenge in extracting text enclosed within the `Label` tag. My knowledge of Javascript and JQuery is limited, so I require guidance on accomplishing this task. Currently, I am attempting to use code that I found on a stackoverflow post titled ge ...

AngularJS: handling multiple asynchronous requests

When I make multiple ajax calls in my code, I noticed that the API is only reached after all the ajax calls have been executed. Below you can see the JavaScript code: function test = function(){ var entity = {}; entity.Number = 1; ...

Controlling an AJAX request to fetch individuals

I am currently using an ajax request to display people data on the page, which is retrieved from a backend database. The search form on the page includes options for location, sector, service, and job title. Below is the javascript code being used: //var ...

The proper way to send an email following an API request

I am currently developing an express API using node.js, and I want to implement a feature where an email is sent after a user creates an account. I have tried various methods, but none of them seem to be the perfect fit for my requirements. Here is some ps ...

Adjusting elements within nested JavaScript arrays

When using the code below, an empty array containing 7 empty arrays is expected to be created, essentially forming a 7x7 grid. While accessing elements within nested arrays seems to work correctly, attempting to modify their values causes all elements in ...

Dynamic Weight feature in Prestashop allows for automatically adjusting shipping costs

I'm curious about displaying the dynamic weight of each product combination on my product page. Currently, I have something like this: {l s='Weight: ' js=1}{sprintf("%1\$u",$product->weight)}&nbsp{Configuration::get('PS_WEI ...

What are the recommended methods or examples for implementing a scheduling calendar using JavaScript?

Here's a question that may be open to interpretation, and a red warning banner suggests it might be closed, but I'm not sure where else to turn for answers. I need an extremely lightweight display-only scheduling calendar for my application. Ess ...

Remove Vue Component from the styling of current application

We integrated a Vue component (using Vuetify) into our existing .NET MVC application. The issue we are facing is that the Vue component is inheriting all the CSS styles from the rest of the application. Here's a simplified version of the HTML structur ...

A sleek Javascript gallery similar to fancybox

I'm currently working on creating my own custom image gallery, inspired by fancybox. To view the progress so far, please visit: I've encountered some issues with the fade effects of #gallery. Sometimes the background (#gallery) fades out before ...

Ajax request received no data from API

I have been facing an issue with my code where I am posting an email on an API URL using an HTML form and PHP code with an Ajax call. However, the response I am getting is empty. I need to display this response on the same page below the form. I am sharing ...

Enriching an array with values using Mongoose

Is there a way to assign a User as an admin for the School? School Schema: const School = new Schema({ name: { type: String, required: true }, grades_primary: [{ type: Schema.Types.ObjectId, ref: 'Grade' }], grades_secondary: [{ type ...

When located at the bottom of a page, the Div element fails to display

I need some help with my javascript code. I am working on creating a scrollable panel that closes when scrolled and reveals a #toTop div when the bottom of the page is reached. Below is the function code I have written, but for some reason, the #toTop div ...

Retrieve specific information using the identifier from the URL parameters during server-side rendering

I am trying to fetch data with a parameter from the URL using Nextjs. However, I am facing an issue where the parameter value is undefined. Here is the code snippet: const Room = () => { let fetchData; let roomId; const getID = () => { con ...

Oops! The PNG file you're trying to use hasn't been compiled yet. Remember to compile it into a .flat file

Trying to generate a signed APK in react-native by following their guidelines, but encountering an error when running the ./gradlew assembleRelease command. The specific error details can be found here. Details of my platform: Operating System: Windows ...

Retrieving Files from POST Request Body Using Node.js and Angular

Currently, I am developing a MEAN Stack application and facing an issue while handling a form that should allow users to upload a file upon submission. The process seems to work seamlessly on the client side; however, when I inspect the request body after ...

If the element is checked and equal to a specific value, take action

I am trying to hide one of the 3 radio buttons on my page. Although they all have the same class, each button has a different value. I attempted to write code to achieve this, but unfortunately, it is hiding all radio buttons instead of just one. Could s ...

Can we set a restriction on the maximum number of children a particular div can contain?

I'm trying to find a way to restrict the number of children in a div. The concept is that there is a selected commands div where you can drag and drop available commands (essentially buttons) from another div called available commands. However, I wan ...

Update background to full screen and include text when hovering over DIV

Currently, I am utilizing Bootstrap and have a layout with 6 columns containing icons/text within. I desire to implement a hover effect where each column triggers a background change in transition for the entire section. In addition, text and button elemen ...