How to get html content using class name with jsoup (Android Studio)

I’m trying to create an app for my work, but I don’t have a lot of app development background.

Im trying to create a class that uses the jsoup library to make an object of elements from a website. After reading the documentation this is what I have:

public class storyObj {
public String title;
public String preview;
public String date;
String url = "http//:davisclipper.com";
Bitmap bitmap;

private class Title extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            Document doc = Jsoup.connect(url).get();
            Elements storyTitle = doc.getElementsByClass("story_item_title");
            title = storyTitle.attr("content");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

public String getTitle(){
    return title;
}

In my main activity I set a TextView to get the returned title:

storyObj story = new storyObj();
String text = story.getTitle();

TextView title = (TextView) findViewById(R.id.main_title);
title.setText(text);

All I get is an empty string. Can someone help set me in the right direction? I’m not sure how to go about this and I’m wasting a lot of time. Thanks.

Returning boolean result when searching a linked list for an existing member – java

I’m writing a program for class that enters the user into an infinite loop and accepts three different commands (add x, delete x, exists x) + an integer value. When the user enters “exists x” the program should return a boolean result indicating if the value exists in the list.

The methods for add x and delete x work just fine, but when searching the list I cannot produce a “true/false” result. I’ve tried it a few different ways, here is where I am currently at with the exists x method:

public class LinkedNode {
public int x;         // The data value

public LinkedNode next;  // Reference to the next LinkedNode

// Default constructor
LinkedNode() {
    next = null;
}

// Constructor that initializes the data values
LinkedNode(int x) {
    this.x = x;
}

public void display() {
    System.out.print(x + " ");
}

}


public class Set {

public LinkedNode firstLink;

Set(){
    firstLink = null;
}

public boolean isEmpty() {
    return (firstLink == null); //nothing in Set yet
}

public void add(int x) {
    LinkedNode newLink = new LinkedNode(x);

    newLink.next = firstLink;
    firstLink = newLink;
}

public boolean exists(int x) {

   LinkedNode theLink = firstLink;

   while (theLink.x != x) { // keep searching until match
       if (theLink.next == null) // we've hit the end without a match, return false
               return false;
           else
               theLink = theLink.next;
       }
       return true;
}

public LinkedNode delete(int x) {
    LinkedNode currentLink = firstLink;
    LinkedNode previousLink = firstLink;

    while (currentLink.x != x) { // search while no match is found
        if (currentLink.next == null) {
            return null; // not found
    }   else { // moves to next LinkedNode
        previousLink = currentLink;
        currentLink = currentLink.next;
        }
    }
    if (currentLink == firstLink) { // first link matches search
        firstLink = firstLink.next; // delete link
    }
    else { // any other link is a match except firstLink
        previousLink.next = currentLink.next;
    }
    return currentLink;
}

public String toString() {
    String str = "";

    LinkedNode cur = firstLink;
    while (cur!=null) {
        str += cur.x + " ";
        cur = cur.next;
    }
    return str;
}

}

Here is my Test/driver:

import java.util.*;

public class Test {

public static void main(String[] args) {
    Set dataSet = new Set();
    Scanner input = new Scanner(System.in);


        while (1<2) { // infinite loop on purpose

        String command, value;
        System.out.print("Enter command: ");
        String line = input.nextLine();
        String [] userInput = line.split(" ");
        command = userInput [0];
        value = userInput [1];

        if (!command.equalsIgnoreCase("add") && !command.equalsIgnoreCase("del") && !command.equalsIgnoreCase("exists")){
            System.out.println("Invalid command.");
            System.out.println("Valid commands are: add x, del x & exists x");
            System.out.print("Enter command: ");
        }
        else if (command.equalsIgnoreCase("add")) {
            dataSet.add(Integer.parseInt(value));
            System.out.println(dataSet);
        }
        else if (command.equalsIgnoreCase("del")){
            dataSet.delete(Integer.parseInt(value));
            System.out.println(dataSet);
        }
        else if (command.equalsIgnoreCase("exists"));{
            dataSet.exists(Integer.parseInt(value));
            System.out.println(dataSet);

        }
    }

I want the program to display “true/false” if the value searched exists in the link, similar to how it displays the current list after add/delete. Any hints as to where I’m going wrong?

Enter command: add 3
3 
Enter command: add 1
1 3 
Enter command: add 20
20 1 3 
Enter command: exists 20
Enter command: 

Can’t get value in my controller using ajax ?

i don’t know if i asked the right question but anyway that is my problem : i followed a tutorial showing how to use ajax with Java ee and i made a simple example and it worked, but i tried to apply what i learned in my project and it didnt work, here is my jsp file :

<div class="aimerSection">
     <div class="aime">
     <form>
     <input type="hidden" class="adore1" name="aime" value="${post.id}">
     <input type="button" class="adore2" value="J'aime">
     </form>
     </div>
     <c:if test="${ post.adore == 0 || post.adore == 1 }">
     <div class="nbreAimes"><p><span class="nbrAdore">${ post.adore }</span> personne aime ça</p></div>
     </c:if>

     <c:if test="${ post.adore != 0 && post.adore != 1 }">
     <div class="nbreAimes"><p><span class="nbrAdore">${ post.adore }</span> personnes aiment ça</p></div>
     </c:if>

</div>

What i wanted is to get the value in the hidden input by clicking on my button( input button) so here is my jquery file :

    $(".adore2").click(function(){
    var aime = $(this).parent().find(".adore1").val()
    var value=$(this).parent().parent().siblings().find(".nbrAdore").text()
    alert(value)

    $.ajax({
        type:"POST",
        data: {aime:aime},
        url:"acceuilServlet",
        success:function(result){
             $(this).parent().parent().siblings().find(".nbrAdore").html(result)
        }
    })

})

And i wanted to see the result in the console ( as a test ) so here is a part of my Controller ( doPost method ) but i am getting any response.

    resp.setContentType("text/plain");

    int aime = Integer.parseInt(req.getParameter("aime"));
    aime++;
    System.out.println("hello "+aime);

Any help would be much appreciated.

BufferredReader not recognizing spaces

BufferedReader br = new BufferedReader(newInputStreamReader(s.getInputStream()));
             String input = br.readLine().replaceAll("[^A-Za-z0-9]", "");

Say input is : “My name is Jack”

Printing it shows : MynameisJack

Can’t get it to show spaces, and i don’t see anything wrong with the code either.

Control activity from a service

I’m coding an Android app, and I have to use websockets… I use 2 activities and a service: I use my main activity to take information on server, and I use a service to connect to this server. I want from this service to start the other activity, or let know to my main activity, when to start the other one. How can I do that ?
Thanks for helping

Retrofit 2 onResponse method is never called

first of all I know that this question has already been asked many times. But I cannot find a solution to the problem. From the log I can see that the web service correctly returns the JSON to me. But for some reason it never enters the onResponse method. I would be very grateful if someone could give me a hint on this matter.

public void getAllTipo_evento() {
        mTipo_eventoService.getAll().enqueue(new Callback<List<Tipo_eventoDTO>>() {
            @Override
            public void onResponse(Call<List<Tipo_eventoDTO>> call, Response<List<Tipo_eventoDTO>> response) {

                if(response.isSuccessful()) {
                    Log.d("MainActivity", "posts loaded from API");
                }else if(response.errorBody() != null){
                        try {
                            String errorBody = response.errorBody().string();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                else {
                    int statusCode  = response.code();
                    // handle request errors depending on status code
                }
            }

            @Override
            public void onFailure(Call<List<Tipo_eventoDTO>> call, Throwable t) {
                t.printStackTrace();
                Log.d("MainActivity", "error loading from API");

            }
        });
    }

RetrofitClient

public class RetrofitClient {

    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl){

        Log.d("RetrofitClient.LOGTAG", "HTTPClient");

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        if (retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Interface

public interface Tipo_eventoService {
    @GET("tipo_evento/getAll")
    Call<List<Tipo_eventoDTO>> getAll();

}

Log output

D/RetrofitClient.LOGTAG: HTTPClient
D/RetrofitClient.LOGTAG: HTTPClient
D/OkHttp: --> GET http://10.0.2.2:3000/tipo_evento/getAll
D/OkHttp: --> END GET
D/OkHttp: <-- 200 OK http://10.0.2.2:3000/tipo_evento/getAll (63ms)
D/OkHttp: Content-Type: application/json; charset=utf-8
D/OkHttp: Date: Sat, 16 Dec 2017 00:32:33 GMT
D/OkHttp: Content-Length: 286
D/OkHttp: [{"ID":1,"Nombre":"Shopping"},{"ID":2,"Nombre":"Night Life"},{"ID":3,"Nombre":"Fun and games"},{"ID":4,"Nombre":"Classes and workshops"},{"ID":5,"Nombre":"Food and beverage"},{"ID":6,"Nombre":"Concert and show"},{"ID":7,"Nombre":"Outdoor activity"},{"ID":8,"Nombre":"Wellness centres"}]
D/OkHttp: <-- END HTTP (286-byte body)

For an ArrayList with long elements, how do you skip the first line?

I have an ArrayList of String where

System.out.println(Al.get(1))

AX225025 Equine influenza virus H3N8 // 8 (NS)
CAAAAGCAGGGTGACAAAAACATGATGGATTCCAACACTGTGTCAAGCTTTCAGGTAGACTGTTTTCTTT
GGCATGTCCGCAAACGATTTGCAGACCAAGAACTGGGTGATGCCCCATTCCTTGACCGGCTTCGCCGAGA

System.out.println(Al.get(2))

>LC335987 A/mute swan/Shimane/3211A001/2017 2017/11/05 8 (NS)
CCAGAAGTCCCTAAAAGGAAGAGGTAGCACTCTTGGTCTGGACATCGAAACAGCCACTCGTGCAGGAAAG
CAGATAGTGGAGCAGATTCTGGAAGAGGAATCAGATGAGGCACTTAAAATGACCATTGCCTCTGTTCCTG

Is there a way to skip the title line so I can run analysis on the sequence without separating the title from the sequence completely?

How to get permission in android app?

I have problem with getting permission to save file from raw on phone. I have in manifest this:

<uses-permission android:name="android.permissions.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permissions.READ_EXTERNAL_STORAGE" />

In java where I’m using onclick I have function to save file
saveTestButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

                InputStream in = null;
                FileOutputStream fout = null;
                try {
                    in = getResources().openRawResource(R.raw.testsound);
                    String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                    String filename = "testsound.mp3";
                    fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));

                    final byte data[] = new byte[1024];
                    int count;
                    while ((count = in.read(data, 0, 1024)) != -1) {
                        fout.write(data, 0, count);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fout != null) {
                        try {
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
        }

    });

And that to check permission:

private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

And when I try to save this file by click the button in app I’m getting error :
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Downloadtestsound.mp3: open failed: EACCES (Permission denied)

What is wrong? Pls help

Insert calculate value in the same row – Oracle

I created this table as a test for you to understand my issue

create table test(
   id integer primary key,
   date_f date,
   date_plus date
);

and here is the Trigger :

create or REPLACE trigger Tr_date
before insert on test
for each row
begin
    select :new.date_f + interval '12' day into :new.date_plus from test;
end;
/

when I try to insert into table test oracle gives me this error :

ERROR at line 1:
ORA-01403: no data found
ORA-06512: at “SYSTEM.TR_DATE”, line 2
ORA-04088: error during execution of trigger ‘SYSTEM.TR_DATE’

please can any one here help me to figure out what i did wrong !!

Unit testing assertion error for when getting Flowable> from local Content Provider/Resolver

I’m testing out a RxJava approach with a Content Provider in a project. The test code instantiate my local data source:

PropertyLocalDataSource.java

and calls its getProperties() for querying. But I’m scratching my head as to why I fail the one assertion noted below:

@Test
    public void getProperties_retrievesSavedProperties() {
        // Given 2 new properties in the persistent repository
        final Property newItem1 = Injection.provideMockProperty(3,2.5f, "Los Angeles");
        mLocalDataSource.saveProperty(newItem1, null);
        final Property newItem2 = Injection.provideMockProperty(12,2.4f, "Irvine");
        mLocalDataSource.saveProperty(newItem2, null);

        // Then the tasks can be retrieved from the persistent repository
        TestSubscriber<List<Property>> testSubscriber = new TestSubscriber<>();
        mLocalDataSource.getProperties().subscribe(testSubscriber);
        List<Property> result = testSubscriber.values().get(0);

        // passed, assert the result would only have 2 entries
        Assert.assertEquals(2,result.size());

        // passed, assert the first item contain the same values
        Assert.assertEquals(newItem1.getNumRooms(), result.get(0).getNumRooms());
        Assert.assertEquals(2.5f, result.get(0).getNumBaths());
        Assert.assertEquals("Los Angeles", result.get(0).getAddress().getLocality());
        Assert.assertEquals(newItem1.getUid(), result.get(0).getUid());

        // passed, assert the second item contain the same values
        Assert.assertEquals(newItem2.getNumRooms(), result.get(1).getNumRooms());
        Assert.assertEquals(2.4f, result.get(1).getNumBaths());
        Assert.assertEquals("Irvine", result.get(1).getAddress().getLocality());
        Assert.assertEquals(newItem2.getUid(), result.get(1).getUid());

        // FAILED this assertion, ??? why
        // assertThat(result, hasItems(newItem1, newItem2));

    }

Assertion Error

java.lang.AssertionError:
Expected: (a collection containing <Property with uid 4e7e8c8b-4c60-4529-bc66-969b409c89e2> and a collection containing <Property with uid ecabb243-8dff-422a-8dfb-2a8874fe0e81>)
but: a collection containing <Property with uid 4e7e8c8b-4c60-4529-bc66-969b409c89e2> was <Property with uid 4e7e8c8b-4c60-4529-bc66-969b409c89e2>, was <Property with uid ecabb243-8dff-422a-8dfb-2a8874fe0e81>

I’m designing the project with the MVP architecture. My implementation for the Local Data source uses Sqlbrite wrapper to wrap the content Resolver for querying items. I’m getting a very similar assertion error when I test getting a single item with id. I let my content provider handles the uri resolution and handle the database operation. Here is my code for the wrapped query in the

PropertyLocalDataSource.java :

@Override
public Flowable<List<Property>> getProperties() {
    Log.i(LOG_TAG,"getProperties called, getting properties with a content resolver query...");
    return mBriteContentResolver.createQuery(
            CONTENT_URI_PROPERTIES,
            null,
            null,
            null,
            null,
            true)
            .mapToList(mPropertyMapperFunction)
            .toFlowable(BackpressureStrategy.BUFFER);
}

I’m using the RxJava 2.0 with Sqlbrite 3.0, and following the Android-Architecture-Todo-RxJava example here.

Any tips or guidance would be greatly appreciated, thank you and have a nice day.