so I wrote this but Android Studio says "class news is never used" what am I doing wrong?
public class news extends AsyncTask<Void,Void,Void> {
String words;
#Override
protected Void doInBackground(Void... params) {
try{
Document doc = Jsoup.connect("myurl").get();
Elements ele = doc.select("div#home-right");
words = ele.text();
}catch(Exception e){e.printStackTrace();}
return null;
}
TextView.setText(words);
}
In your activity class, put this code:
news n = new news();
n.execute();
You have to call your "news" class.
So in activity in onCreate method call new news(this).execute();
Remeber to make class with Uppercase letter.
Related
I successfully retrieved specific text from a website with Jsoup. But is it possible to style the text with CSS? Below you find my code for retrieving text from a website.
public class connect extends AsyncTask<Void, Void, Void> {
String string;
#Override
protected Void doInBackground(Void... voids) {
try {
Document document = Jsoup.connect("MY_URL").get();
Elements elements = document.select("div.MY_DIV_CLASS");
string = elements.text();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
webView.loadData(string, "text/html", "UTF-8");
}
}
Thank you in advance.
When you have selected element or elements you can style it by adding new class:
elements.addClass("your-class");
or by adding your own style attribute:
elements.attr("style", "text-align: center; color: red;");
These changes are saved in document object so to use updated HTML code you will probably want to use the output of: document.html().
So Azure spit the following code for me to insert into an activity (Android Studio is what I'm using)
Add the following line to the top of the .java file containing your launcher activity:
import com.microsoft.windowsazure.mobileservices.*;
Inside your activity, add a private variable
private MobileServiceClient mClient;
Add the following code the onCreate method of the activity:
mClient = new MobileServiceClient("https://pbbingo.azurewebsites.net", this);
Add a sample item class to your project::
public class ToDoItem{ public String id; public String Text;}
In the same activity where you defined mClient, add the following code:
ToDoItem item = new ToDoItem();
item.Text = "Don't text and drive";
mClient.getTable(ToDoItem.class).insert(item, new TableOperationCallback<item>(){
public void onCompleted(ToDoItem entity, Exception exception, ServiceFilter response)
{
if(exception == null){
//Insert Succeeded
} else {
//Insert Failed
}
}});
My goal is to create a login page. I understand that the above was probably offered up more with a ToList in mind. I just want to get the syntax correct today. The problem I think, is my basic class structure. I have created an OnClick Listener within my on create that gets the ID from a button in my layout. I don't need it checking for anything in the database until the button has been actually clicked to either login or register.
public class LoginClass extends AppCompatActivity{
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.MyLoginLayout);
MobileServiceClient mClient = null;
try {
mClient = new MobileServiceClient ("myAzureWebsite", "AzureKey", this);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Button Attempt = (Button) findViewById (R.id.mySubmitButton);
final MobileServiceClient finalMClient = mClient; // finalized so I can use it later.
Attempt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
final View thisView = v;
final MyToDoItemClass item = new MyToDoItemClass();
In MyToDoItemClass I have two variables (Both String) Just left over from
the example of a ToDoList (they are String ID and String Text)
item.Text = "Filler";
item.ID = "Fill";
finalMClient.getTable(MyToDoItemClass.class).insert(new Table OperationCallback<item>() { //<--- I'm getting an error that the variable, item
is from an unknown class...
public void onCompleted (Item entity, Exception exception, ServiceFilterResponse response){
if(exception == null) {
Intent i = new Intent (LoginClass.this, MainActivity.class);
startActivity(i);
}else{
Toast.makeText(thisView.getContext(), "Failed", Toast.LENGTH_LONG).show();
}}
});
}
});
}}
The problem is with that the TableOperationCallback is saying that the item from MyToDoItemClass class is from an unknown class.
There are many issues in your code, as below.
According to the javadoc for class MobileServiceClient, there is not a method insert(TableOperationCallback<E> callback), so the code finalMClient.getTable(MyToDoItemClass.class).insert(new Table OperationCallback<item>() {...} is invalid.
The generics E in Table OperationCallback<E> means that you need to write a POJO class name instead of E, not an object variable name like item, so the correct code should be new Table OperationCallback<MyToDoItemClass>, please see the Oracle tutorial for Generics to know more details.
The figure below shows all methods insert of class MobileServiceClient. The bold word Deprecated under the method name means that you should not use it for developing on new project, it‘s only compatible for old project on the new version of Java SDK.
Please follow the offical tutorial to develop your app. Any concern, please feel free to let me know.
I'm trying to parse data from this table. Let's say, for example, that I want to parse the second elements from the second row (called SLO).
I can see there is a TR inside TR and the SLO word doesn't even have an ID or anything. How can I parse this?
This is the code:
class Title extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
tw1.setText("Loading...");
}
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect("https://www.easistent.com/urniki/cc45c5d0d303f954588402a186f5cdba5edb51d6/razredi/16515").get();
Elements eles = doc.select("");
title = eles.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
tw1.setText(title);
}
}
I don't know what to put in the doc.select(""); because I've never parsed something like this. I've only parsed titles of webpages and such. Could someone help me with this?
There is plenty of information there for you to use, for example class names or title attributes. The URL you provided won't work for me, and I can't copy paste the HTML from your image so my example will show just the parsing of the span based on its title:
String html = "<span title='Slovenscina'>SLO</span>";
Document doc = Jsoup.parse(html);
Elements eles = doc.select("span[title=Slovenscina]");
String title = eles.text();
System.out.println(title);
Will output:
SLO
This will work in the scope of the other HTML that you provided. I suggest you read some more about the selector-syntax of Jsoup.
I've just gotten into android development, and while trying to create a login form i ran into some problems.
What I want to do is enter username and password and press login, when the login button is pushed I want it to do a JSON request with the account information to my server and get a response with whether or not the user is allowed to log in. If the user is allowed, I want to change to a new view.
My code receives the JSON information correctly, but from what I've understood the UI-code (pushing a new activity) should be done in onPostExecute(). My problem is that onPostExecute is never run, I've looked at other ppl with the same problem, but their solutions hasn't worked for me. What they have said is that i need to have an #Override before onPostExecute, but when I add that i get the compilation error that "the method does not override method from its superclass".
I've read solutions from people having that problem as well, and from what I have read the problem is that the method onPostExecute has to have the same parameters as the result parameter from doInBackground(). My problem is that I feel I already do, and when I try to look in what the superclass has (that is AsyncTask.java) it says that the method onPostExecute() looks like:
protected void onPostExecute(Result result) {
}
But I have no idea what class Result belongs to..
networkingTask is run using this line:
new networkingTask().execute(url);
If anyone could help me I'd be eternally grateful! :)
This is what my code looks like
private class networkingTask extends AsyncTask {
Context context;
private networkingTask(Context context) {
this.context = context.getApplicationContext();
}
public networkingTask() {
}
#Override
protected JSONObject doInBackground(Object... params) {
try {
String urlString = (String) params[0];
System.out.println(urlString);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json;
json = jParser.getJSONFromUrl(urlString);
String responseLogged = json.getString("logged");
System.out.println("can we log in?: "+ responseLogged);
return json;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
String responseLogged = "";
try {
responseLogged = result.getString("logged");
} catch (JSONException e) {
e.printStackTrace();
}
if(responseLogged.equals("true")){ //Login = true
Intent intent = new Intent(context, ShowListActivity.class);
intent.putExtra(EXTRA_JSON_OBJECT, result.toString());
startActivity(intent);
} else{ //Login = false
System.out.println("wrong password");
}
return;
}
}
In your line:
private class networkingTask extends AsyncTask
just change it to:
private class networkingTask extends AsyncTask<String, Void, JSONObject>
while String is the place for you to pass in the parameters, in your case it is url, the second parameter Void is for showing progress and the last one is the processed result to be passed from doInBackground to onPostExecute
For further explanation & info, please refer to Android Developers: AsyncTask
I think you may need to fill out the generic types for your AsyncTask. See the "Usage" section in the AsyncTask documentation.
Your class signature should look something like this:
private class networkingTask extends AsyncTask<Object, Void, JSONObject>
The types in the brackets here correspond to the argument types for doInBackground, onProgressUpdate, and onPostExecute, respectively, and are necessary if you're going to override these methods such that they are different from the generic method signatures.
Also, as a side note, it's a common convention in Java/Android to use upper CamelCase to start a class name. I'd also change the name of your class to "NetworkingTask" to help other developers looking at your code to better understand it.
The signatures don't match. You're attempting to override:
protected void onPostExecute(Result result)
with the signature
protected void onPostExecute(JSONObject result)
...which doesn't exist in the superclass.
This is my first time on here, so I'm bit nervous and please forgive me if I don't seem entirely clear about what I'm asking.
The problem is, Im trying to read in a file from a subfolder in the assets folder, using a method that I've created in a separate class. I've researched this for a couple of days but I'm unable to find the solution anywhere, so I've come here as a last resort. I needed the file reading method to be separate as there are other views/activities that will be utilising exactly the same method and I don't think it would be wise to keep copying and pasting the same code for each activity. Ok here's what I've done so far:
public class ReadAssets extends Activity {
public void read(Context context, String filepath, int textviewid) {
try {
InputStream input = getAssets().open(filepath);
int size = input.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
// Convert the buffer into a string.
String text = new String(buffer);
// Finally insert the string into the text view.
TextView tv = (TextView) findViewById(textviewid);
tv.setText(text);
} catch (IOException e) {
// Throws an exception if an error is found
throw new RuntimeException(e);
}
}
}
The activity that I would like to place this method in:
public class GeneralSetupActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gettingstarted_layout);
ReadAssets nA = new ReadAssets();
nA.read(this,"gettingstarted/GettingStarted.txt", R.id.displayTextView);
// try {
// InputStream input =getAssets().open("gettingstarted/GettingStarted.txt");
//
// int size = input.available();
//
// // Read the entire asset into a local byte buffer.
// byte[] buffer = new byte[size];
// input.read(buffer);
// input.close();
//
// // Convert the buffer into a string.
// String text = new String(buffer);
//
// // Finally insert the string into the text view.
// TextView tv = (TextView) findViewById(R.id.displayTextView);
// tv.setText(text);
//
// } catch (IOException e) {
// // Throws an exception if an error is found
// throw new RuntimeException(e);
// }
}
}
I'd really appreciate it file someone could point me towards the right direction. And also I hope I'm not taking advantage but I'd like to know how I'd import and display a series of text files, one after another.
Cheers Guys,
Thanks :)
If you need this available to all different types of Activity, you should consider putting the method in a superclass so all the children can use it.
public class ExtraFunctionalActivity extends Activity
{
public void read(...)
{
//your code
}
}
public class GeneralSetupUtility extends ExtraFunctionalActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.gettingstarted_layout);
read(this,"gettingstarted/GettingStarted.txt", R.id.displayTextView);
}
}
Otherwise, if this method is needed by a bunch of unrelated classes, you could put it in a utility class;
public class FileUtil
{
public static void read(...)
{
//your code
}
}
then you can call it where needed with
FileUtil.read(args here);
You may have a class like Fileparsingutility with the method you want to separate. You may define Inputstream as parameter(you may pass other required things as parameter for that method). What ever actvity you want to use this method, instantiate above class and invoke the method by passing parameters.
Fileparinsgutility util=new Fileparsingutility();
Returnobj retObj =util.parse(......);