How do I select the text within this element in jsoup? - html

EDIT: The website is http://www.op.gg/statistics/champion/
I am trying to select the text withing the element highlighted in gray in this photo: https://i.gyazo.com/cc31794574692e2bc6709e193b27741c.png
I've tried the following plus some other variations but none seem to work.
Document doc = Jsoup.connect("http://www.op.gg/statistics/champion/").get();
String s = "";
s += doc.select("table.StatisticsChampionTable.sortable.tablesorter.tablesorter-default
.Content .Row.Top .Cell.ChampionName a").text();

Give this a try:
doc.select(".StatisticsChampionTable .ChampionName a").text()
Maybe this could help you next time.

Try this it may helps you.
You have to scrap the data with the combination of WebView and Jsoup.
First of all load the webpage in the webview and put the webview visibility invisible or gone. And than parse the HTML string into the JSoup.Than you can easily find that all tags which you needed and here is the example code as per your requirement.
public class MainActivity extends AppCompatActivity {
Handler handlerForJavascriptInterface = new Handler();
private WebView mWebView;
private String mURL = "http://www.op.gg/statistics/champion/";
private String html_source;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.wv);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new MyJavaScriptInterface(MainActivity.this), "HtmlViewer");
mWebView.loadUrl(mURL);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Page loading started
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.loadUrl("javascript:window.HtmlViewer.showHTML" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
}
class MyJavaScriptInterface {
private Context ctx;
MyJavaScriptInterface(Context ctx) {
this.ctx = ctx;
}
#JavascriptInterface
public void showHTML(final String html) {
//code to use html content here
handlerForJavascriptInterface.post(new Runnable() {
#Override
public void run() {
html_source = html;
new Description().execute();
}
});
}
}
private class Description extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Connect to the web site
Document mBlogDocument = Jsoup.parse(html_source);
int mPaginationSize = mBlogDocument.select("td[class=Cell ChampionName]").size();
for (int page = 0; page < mPaginationSize; page++) {
String mChampionName = mBlogDocument.select("td[class=Cell ChampionName]").eq(page).text();
Log.i("Champion Name " + page, mChampionName + "\n");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set description into TextView
}
}
}

import java.io.IOException;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class Snippet {
public static void main(String args[]) throws IOException, InterruptedException {
Document doc = Jsoup.connect("http://www.op.gg/statistics/ajax2/champion/").get();
List<Element> links = doc.select("table > tbody > tr > .Cell.ChampionName > a");
for (Element link : links) {
System.out.println(link.absUrl("href"));
}
}
}
Sample Output:
http://www.op.gg/champion/Taric/
http://www.op.gg/champion/Quinn/
http://www.op.gg/champion/Kled/
http://www.op.gg/champion/Draven/
http://www.op.gg/champion/MonkeyKing/
http://www.op.gg/champion/Yorick/
http://www.op.gg/champion/Zilean/
http://www.op.gg/champion/Zyra/
http://www.op.gg/champion/Morgana/
http://www.op.gg/champion/Singed/
http://www.op.gg/champion/Nocturne/
http://www.op.gg/champion/Nami/
http://www.op.gg/champion/Udyr/

Related

get the data in recyclerview

Hello everyone i am getting the messages of the users in android studio for that i am refreshing the recyclerview every second but the probem is scrolling when i am scrooling the recyclerview to old messages then its not scrooling becouse of the getting data every second can someone please help me in this
bellow is my activity code
public class Message_User_Activity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
content();
Clicks();
}
public void content()
{
getdata();
refresh(100);
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
toolbar_user_name.setText(name);
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}
}
below is my adapter code
public class Message_user_Adapter extends RecyclerView.Adapter<Message_user_Adapter.Message_user_Adapter_View_Holder>
{
List<responsemodel> data;
String mmessage_To;
public Message_user_Adapter(List<responsemodel> data, String message_To) {
this.data = data;
this.mmessage_To = message_To;
}
#NonNull
#Override
public Message_user_Adapter_View_Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_messages_layout,parent,false);
return new Message_user_Adapter_View_Holder(view);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onBindViewHolder(#NonNull Message_user_Adapter_View_Holder holder, int position) {
String time = calculateTime(data.get(position).getMessage_Time());
if (data.get(position).getMessage_From().equals(mmessage_To))
{
holder.other_user_message_message_layout.setVisibility(View.VISIBLE);
holder.other_user_message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.GONE);
}
else
{
holder.other_user_message_message_layout.setVisibility(View.GONE);
holder.message_message_layout.setText(data.get(position).getMessage() + "\n \n" + time);
holder.message_message_layout.setVisibility(View.VISIBLE);
}
}
#RequiresApi(api = Build.VERSION_CODES.N)
private String calculateTime(String post_time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
long time = sdf.parse(post_time).getTime();
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(time, now, DateUtils.MINUTE_IN_MILLIS);
return ago+"";
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
#Override
public int getItemCount() {
return data.size();
}
public String getdata() {
return mmessage_To.toString();
}
class Message_user_Adapter_View_Holder extends RecyclerView.ViewHolder
{
TextView other_user_message_message_layout;
TextView message_message_layout;
CircleImageView toolbar_user_profile;
public Message_user_Adapter_View_Holder(#NonNull View itemView) {
super(itemView);
other_user_message_message_layout = itemView.findViewById(R.id.other_user_message_message_layout);
message_message_layout = itemView.findViewById(R.id.message_message_layout);
}
}
}
According to my simple information
in your getdata() function. you send new data to Message_user_Adapter of RecyclerView every time you receive data from API or whatever you use ,so the data of adapter every second is change to new data ,so the RecyclerView being recreated every second with new data and the scroll will not work
just try to outage this lines from onResponse to the first of getdata():
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
and in its place add this line to notify the adapter about changed data :
adapter.notifyDatasetChanged()
something like this :
private void getdata() {
toolbar_user_name.setText(name);
String Choice = "Get Messages";
List<responsemodel> data = new ArrayList<>();//this line was change
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);//this line was change
messages_Message_user_RecyclerView.setAdapter(adapter);//this line was change
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
data = response.body();
adapter.notifyDatasetChanged()//this line was added
messages_Message_user_RecyclerView.scrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount() -1);
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}

RecyclerView with Retrofit2

I try to do recyclerView with retrofit2, but I do in my code: recyclerView Adapter Constructor and I get a error in my MainActivity part of this line -
"(flowersList, this)": I get error: List anonymous retrofit2.Callback
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
my code my MainActivity is:
try {
APIService service = ApiClient.getRetrofit().create(APIService.class);
retrofit2.Call<List<Flower>> call = service.getFlowerData();
call.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(retrofit2.Call<List<Flower>> call, Response<List<Flower>> response) {
List<Flower> flowersList = response.body();
mLinearLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
mRecyclerView.setAdapter(recyclerViewAdapter);
}
and the code in RecyclerViewFlowersAdapter is:
public class RecyclerViewFlowersAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private List<Flower> mFlowers;
private Context mContext;
public RecyclerViewFlowersAdapter(List<Flower> flowers, Context context) {
mContext = context;
mFlowers = flowers;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.flower_item_card, null);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.mTextViewTitle.setText(mFlowers.get(position).getName());
Picasso.with(mContext)
.load(mFlowers.get(position).getPhoto()).into(holder.mImageViewFlower);
}
#Override
public int getItemCount() {
return mFlowers.size();
}
}
and my code in RecyclerViewHolder is:
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextViewTitle;
public ImageView mImageViewFlower;
public RecyclerViewHolder(View itemView){
super(itemView);
itemView.setOnClickListener(this);
mTextViewTitle = itemView.findViewById(R.id.title);
mImageViewFlower = itemView.findViewById(R.id.imageViewFlower);
}
#Override
public void onClick(View v) {
}
}
I try to do alot of thing but is still error.
thanks for help :)
You are probably using a wrong context, try using MainActivity.this instead of this. Change this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
to this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, MainActivity.this);

notifyDataSetChanged on RecyclerView

I have a recyclerView and customAdaprer. I pass an list of an object (earthquakeList)to recycleradapter and then i do setAdapter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}
I create AsyncTask on onResume method:
#Override
protected void onResume() {
super.onResume();
// Kick off an {#link AsyncTask} to perform the network request
new EarthQuakeAsyncTask().execute();
}
in AsyncTask my class i get a new List from my object that i get from internet and when I replaced this new list with older list and call notifyDataSetChanged, recyclerView still nothing show??
I debug my app and I get object from net.
I do in this way on list view but recylerview seems efferent.
I replace old list with the new list one like blow:
private class EarthQuakeAsyncTask extends AsyncTask<Void, Void, List<Earthquake>> {
#Override
protected List<Earthquake> doInBackground(Void... urls) {
// Create URL object
URL url = HttpRequest.createUrl(USGS_REQUEST_URL);
// perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = HttpRequest.makeHttpRequest(url);
} catch (IOException e) {
e.printStackTrace();
}
List<Earthquake> earthquakes = HttpRequest.extractFeaturesFromJson(jsonResponse);
return earthquakes;
}
#Override
protected void onPostExecute(List<Earthquake> earthquakeList) {
super.onPostExecute(earthquakeList);
MainActivity.this.earthquakeList.clear();
MainActivity.this.earthquakeList.addAll(earthquakeList);
adapter.notifyDataSetChanged();
}
what is exactly my wrong?
************************ EDIT ********************
this is Adapter :
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {
List<Earthquake> earthquakes;
public RecyclerViewAdapter(List<Earthquake> earthquakes) {
this.earthquakes = earthquakes;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.earthquak_list_item, parent, false);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
Earthquake earthquake = earthquakes.get(position);
holder.magnitude.setText(earthquake.getmMagnitude());
holder.location.setText(earthquake.getmLocation());
holder.time.setText(earthquake.getmDate());
}
#Override
public int getItemCount() {
return (null != earthquakes ? earthquakes.size() : 0);
}
public void setItems(List<Earthquake> earthquakeList) {
this.earthquakes = earthquakeList;
}
public class MyHolder extends RecyclerView.ViewHolder {
#BindView(R.id.magnitude)
TextView magnitude;
#BindView(R.id.location)
TextView location;
#BindView(R.id.date)
TextView time;
public MyHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
Ops ,I forgot put LayoutManager for recyclerView .
this is right code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}

Web pages in a webview how to obtain position

public class MainActivity extends Activity {
private WebView webView;`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=(WebView) findViewById(R.id.web_view);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAppCacheEnabled(true);
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
webSettings.setAppCachePath(appCachePath);
webSettings.setGeolocationEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
}
#Override
public void onGeolocationPermissionsHidePrompt() {
super.onGeolocationPermissionsHidePrompt();
}
});
/*
* setWebViewClient()
* shouldOverrideUrlLoading
* */
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://uri.amap.com/line");
}
I write a map page in webview. This is a HTML page.
But can't locate.Unable to display. I want the webview positioning can be obtained.In the system browser can show the location.This is I write my own code, I don't know how to do

How to send a JSON object to a server with Volley library in android?

I want to send a json object to the server using the post method.
I have used volley library to pass the string params, and it's working fine, but when I run my app I am getting this:
BasicNetwork.performRequest: Unexpected response code 400
my code:-
public class MainActivity extends AppCompatActivity {
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
makeJsonObjReq();
}
private void makeJsonObjReq() {
JSONObject request=new JSONObject();
try {
request.put("ProductCode", "KK03672-038");
} catch (JSONException e) {
e.printStackTrace();
}
pd = ProgressDialog.show(MainActivity.this, "Alert", "Please Wait...");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
"URL",request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pd.dismiss();
System.out.println("Response is====>" + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
System.out.println("Error is====>" + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
// Adding request to request queue:-
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
}
AppContoller:-
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Try adding volley initialization code in Application class and reference this to your manifest application tag.