How do I successfully refresh Recyclerview in fragment using SwipeRefreshLayout - android

I am fetching data from a website using jsoup into recyclerview but I can't quite figure out exactly what I should do to refresh and update the recyclerview using the swiperefreshlayout. Can someone please help explain what code do I put in onRefresh in the code below to be able to refresh on pull down?
Content content = new Content();
content.execute();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
//What do I put in here??
}
});
return root;
}
private class Content extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
//progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.setVisibility(View.GONE);
//progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
adapter.notifyDataSetChanged();
}
#Override
protected Void doInBackground(Void... voids) {
try {
String url = "https://www.mywebsite.com";
Document doc = Jsoup.connect(url).get();
Elements data = doc.select(".thisurl");
int size = data.size();
Log.d("doc", "doc: " + doc);
Log.d("data", "data: " + data);
Log.d("size", "" + size);
for (int i = 0; i < size; i++) {
String date = doc.select(".b-time").eq(i).text();
String league = doc.select(".card-competition-title").eq(i).text();
String homeLogo = data.select(".card-vs-left")
.select("img")
.eq(i)
.attr("src");
String homeTeam = doc.select(".card-vs-left").eq(i).text();
String awayLogo = data.select(".card-vs-right")
.select("img")
.eq(i)
.attr("src");
String awayTeam = doc.select(".card-vs-right").eq(i).text();
String pick = doc.select("span.card-our-prono").eq(i).text();
sportyParseItems.add(new SportyParseItem(date, league, homeLogo, homeTeam, awayLogo, awayTeam, pick));
Log.d("items", "img: " + homeLogo + "img:" + awayLogo + " . title: " + league);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
content.execute();
}
});

Related

How to select an Object in my Listview

I have a RemoteCar Control app where on the MainActivity page there is a button "location" which you can click on to get redirected into another activity (locationActivity). In this activity im displaying a JSON File in a Listview and now I want to click on those objects to select them and display the location on the main page in something like a simple TextView nothing special. How can I do that?
This is my location page:
public class location extends AppCompatActivity {
private String TAG = location.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> locationList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
locationList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(location.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "url";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray locations = jsonObj.getJSONArray("");
JSONArray locations_ = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < locations_.length(); i++) {
JSONObject c = locations_.getJSONObject(i);
String type = c.getString("type");
String name = c.getString("name");
String address = c.getString("address");
String lat = c.getString("lat");
String lon = c.getString("lon");
String icon;
if(c.has("icon")){
//your json is having "icon" Key, get the value
icon = c.getString("icon");
}
else{
//your json is NOT having "icon" Key, assign a dummy value
icon = "/default/icon_url()";
}
// tmp hash map for single contact
HashMap<String, String> location = new HashMap<>();
// adding each child node to HashMap key => value
location.put("type", type);
location.put("name", name);
location.put("address", address );
location.put("lat", lat);
location.put("lon", lon);
location.put("icon", icon);
// adding contact to contact list
locationList.add(location);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(location.this, locationList,
R.layout.list_item, new String[]{"type", "name", "address", "lat", "lon", "icon"},
new int[]{R.id.type, R.id.name, R.id.address, R.id.lat, R.id.lon, R.id.icon});
lv.setAdapter(adapter);
}
}
and this is my MainActivity page
public class MainActivity extends AppCompatActivity {
public ProgressBar fuelBar;
public Button lockButton;
public Button engButton;
public Button refuelButton;
public Button locationButton;
public SeekBar seekBarButton;
public TextView seekText;
int incFuel = 0;
final String FUELBAR = "fuelBar";
final String AC_BARTEXT = "acBarText";
final String AC_BAR = "acBar";
final String REFUELBUTTON = "refuelButton";
final String STARTENGINE = "startEngineButton";
SharedPreferences sharedPref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = (Button) findViewById(R.id.locationB);
lockButton = (Button) findViewById(R.id.lockB);
engButton = (Button) findViewById(R.id.engB);
refuelButton = (Button) findViewById(R.id.refuelB);
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
fuelBar.setMax(100);
fuelBar.setProgress(30);
refuelButton.setText(R.string.refuelB);
lockButton.setText(R.string.lockB);
locationButton.setText(R.string.locationB);
engButton.setText(R.string.engB);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
sharedPref = getPreferences(Context.MODE_PRIVATE);
editor = sharedPref.edit();
seek_bar();
lockPage();
locationPage();
}
#Override
protected void onPause(){
super.onPause();
editor.putInt(FUELBAR, fuelBar.getProgress());
editor.commit();
String tmpAC = "AC : " + String.valueOf(seekBarButton.getProgress()+18) + "°";
editor.putString(AC_BARTEXT, tmpAC);
editor.commit();
editor.putInt(AC_BAR, seekBarButton.getProgress());
editor.commit();
editor.putString(REFUELBUTTON, refuelButton.getText().toString());
editor.commit();
editor.putString(STARTENGINE, engButton.getText().toString());
editor.commit();
}
#Override
public void onResume(){
super.onResume();
fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar);
incFuel = sharedPref.getInt(FUELBAR, 0);
fuelBar.setProgress(incFuel);
seekText = (TextView) findViewById(R.id.seekText);
String tmpAC = sharedPref.getString(AC_BARTEXT, "error");
seekText.setText(tmpAC);
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
int tmpInt = sharedPref.getInt(AC_BAR, 18);
seekBarButton.setProgress(tmpInt);
tmpAC = sharedPref.getString(REFUELBUTTON, "REFUEL");
refuelButton.setText(tmpAC);
tmpAC = sharedPref.getString(STARTENGINE, "START ENGINE");
engButton.setText(tmpAC);
}
#Override
public void onStop(){
super.onStop();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.engB:
if (engButton.getText() == "ENGINE RUNNING") {
engButton.setText("START ENGINE");
} else {
if (fuelBar.getProgress() > 0) {
Toast.makeText(MainActivity.this, "starting engine..", Toast.LENGTH_SHORT).show();
engButton.setText("ENGINE RUNNING");
if (fuelBar.getProgress() >= 10) {
incFuel = fuelBar.getProgress();
incFuel -= 10;
fuelBar.setProgress(incFuel);
if (fuelBar.getProgress() < 100)
refuelButton.setText("REFUEL");
}
} else if (fuelBar.getProgress() == 0) {
Toast.makeText(MainActivity.this, "no fuel", Toast.LENGTH_SHORT).show();
engButton.setText("EMPTY GASTANK");
} else
engButton.setText("START ENGINE");
}
break;
case R.id.refuelB:
if (fuelBar.getProgress() == 0) {
engButton.setText("START ENGINE");
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else if (fuelBar.getProgress() < 100) {
incFuel = fuelBar.getProgress();
incFuel += 10;
fuelBar.setProgress(incFuel);
} else {
Toast.makeText(MainActivity.this, "tank is full", Toast.LENGTH_SHORT).show();
refuelButton.setText("FULL");
}
break;
}
}
public void seek_bar() {
seekBarButton = (SeekBar) findViewById(R.id.seekBar);
seekText = (TextView) findViewById(R.id.seekText);
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
seekBarButton.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressNum;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressNum = progress;
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekText.setText("AC : " + (seekBarButton.getProgress() + 18) + "°");
}
});
}
public void lockPage() {
lockButton = (Button) findViewById(R.id.lockB);
lockButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent lockPage = new Intent(MainActivity.this, lockDoor.class);
startActivity(lockPage);
}
});
}
public void locationPage() {
locationButton = (Button) findViewById(R.id.locationB);
locationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent locationPage = new Intent(MainActivity.this, location.class);
startActivity(locationPage);
}
});
}
}
Sorry for the wall of code I'm always unsure how much information to provide.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MyActivity.this, "location:" + " "+ stringList[position] + " " + "hauptbahnhof selected", Toast.LENGTH_SHORT).show();
}
});
define your list of string as private out of onCreate

running asyntask concurrently (android)

I am trying to have a asynctask to run in the background and the other one to load something from the webservice to have a new listview.
Here is my code.
AsyncCallForwardListWS
private class AsyncCallForwardListWS extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
//List<Request_model> thisList = newList;
//List<Tn_Parent> thisList = listDataParent;
List<Request_model> thisList = lvList;
System.out.println("there2: " + thisList.size());
for (int y = 0; y< thisList.size(); y++){
//Request_model model = thisList.get(y);
//Tn_Parent model = thisList.get(y);
Request_model model = thisList.get(y);
if(model.isSelected()){
if(action.equals("deny")){
//getComment = model.getApproverComment();
getComment = model.getApprComments();
}else
getComment = "This request is " + ACTION_MSG + " by " + model.getUser_fullName() + " via mobile app";
//getComment = "This request is " + ACTION_MSG + " by " + model.getApproverName() + " via mobile app";
taskActivity_forward = model.getTaskActivity();
getRequestID = model.getRequestId();
System.out.println("testing");
db.addInfo(new Request_model(model.getRequestId()));
System.out.println("requestid: " + getRequestID);
ForwardWebService();
}
}
return null;
}
AsyncCallListWS
private class AsyncCallListWS extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.show();
progressDialog.setContentView(R.layout.custom_progressbar);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
TextView textView1 = (TextView) progressDialog.findViewById(R.id.textView1);
Typeface dsr = Typeface.createFromAsset(getActivity().getAssets(), getResources().getString(R.string.droid_sans));
textView1.setTypeface(dsr);
System.out.println("here1");
isThereAnyRequest = false;
if(lvAdapter!=null) {
lvAdapter.clear();
lvAdapter.notifyDataSetChanged();
}
}
#Override
protected Void doInBackground(Void... params) {
//listDataParent = new ArrayList<Tn_Parent>();
listPending();
System.out.println("here2");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dismissLoadingDialog();
System.out.println("here3");
selectAll.setChecked(false);
if(getContext()!=null) {
lvAdapter = new Tn_ListViewAdapter(getActivity(), lvList, selectAll);
listView.setAdapter(lvAdapter);
progressDialog.dismiss();
}
if (isThereAnyRequest){
buttonLayout.setVisibility(View.VISIBLE);
//selectAll.setVisibility(View.VISIBLE);
checkBox_layout.setVisibility(View.VISIBLE);
//textView.setVisibility(View.GONE);
no_request_noti.setVisibility(View.GONE);
}
else{
buttonLayout.setVisibility(View.INVISIBLE);
//selectAll.setVisibility(View.INVISIBLE);
checkBox_layout.setVisibility(View.GONE);
//textView.setVisibility(View.VISIBLE);
no_request_noti.setVisibility(View.VISIBLE);
}
}
}
}
I have this somewhere else to trigger the asynctask.
new AsyncCallForwardListWS().execute();
new AsyncCallListWS().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Both asynctasks really run together at the same time but it is so weird that the for loop in AsyncCallForwardListWS will not loop according to the number of checkbox that I have selected. Please help.
did System.out.println("there2: " + thisList.size()); show the exact number of the list?
if not try
List<Request_model> thisList=new List<Request_model>();
thisList.addAll(lvList);
//at post of
List<Request_model> thisList = lvList;

Android empty listview with poor internet connection

I have a listview being populated with data from the server. If I use wifi connection everything works fine.
Is there anything that I could do to improve this code to wait until the data is full loaded from the server with bad connections like 3G or poor wifi connection?
Sometimes listview gets empty.
public class LoadAsync extends AsyncTask<String, Boolean, Boolean>{
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListEvents.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
// Creating volley request obj
JsonArrayRequest eventReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.dismiss();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Event event = new Event();
event.setImovel_id(obj.getString("imovel_id"));
event.setThumbnailUrl(obj.getString("arquivo"));
event.setNegocio(obj.getString("negocio"));
event.setImovel(obj.getString("imovel"));
event.setMobilia(obj.getString("mobilia"));
event.setGaragem(obj.getString("garagem"));
event.setPreco(obj.getString("preco"));
city = obj.getString("city").trim();
statee = obj.getString("state").trim();
checkNegocio = obj.getString("negocio").trim();
checkImovel = obj.getString("imovel").trim();
checkMobilia = obj.getString("mobilia").trim();
checkGaragem = obj.getString("garagem").trim();
checkPreco = obj.getString("preco").trim();
checkPreco = checkPreco.replace("R", "");
checkPreco = checkPreco.replaceAll("[$.,]", "");
int serverprice = Integer.parseInt(checkPreco);
String app_price = checkP.getText().toString();
app_price = app_price.replace("R", "");
app_price = app_price.replaceAll("[$.,]", "");
int i_price = Integer.parseInt(app_price);
if(estado.getText().toString().trim().equalsIgnoreCase(statee) &&
cidade.getText().toString().trim().equalsIgnoreCase(city) &&
checkN.getText().toString().trim().equalsIgnoreCase(checkNegocio)){
if(/*checkI.getText().toString().equalsIgnoreCase(checkImovel) ||
checkM.getText().toString().equalsIgnoreCase(checkMobilia) ||
checkG.getText().toString().equalsIgnoreCase(checkGaragem) ||*/
serverprice <= i_price){
// adding event to events array
eventList.add(event);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} if(eventList.size() > 0){
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
}else{
noEvent.setText("Nothing found.");
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.dismiss();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(eventReq);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String imovelID = ((TextView) view.findViewById(R.id.imovel_id)).getText().toString();
ImageView eFile = ((ImageView) view.findViewById(R.id.thumbnail));
String imgUrl = (String) eFile.getTag();
String negocio = ((TextView) view.findViewById(R.id.negocio)).getText().toString();
String imovel = ((TextView) view.findViewById(R.id.imovel)).getText().toString();
String mobilia = ((TextView) view.findViewById(R.id.mobilia)).getText().toString();
String garagem = ((TextView) view.findViewById(R.id.garagem)).getText().toString();
String preco = ((TextView) view.findViewById(R.id.preco)).getText().toString();
Intent i = new Intent(getApplicationContext(), EventDetails.class);
i.putExtra(TAG_ID, imovelID);
i.putExtra(TAG_ARQUIVO, imgUrl);
i.putExtra(TAG_NEGOCIO, negocio);
i.putExtra(TAG_IMOVEL, imovel);
i.putExtra(TAG_MOBILIA, mobilia);
i.putExtra(TAG_GARAGEM, garagem);
i.putExtra(TAG_PRECO, preco);
startActivity(i);
}
});
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//pDialog.dismiss();
}
}
Show an indeterminate ProgressBar, till your data is loaded. Cancel the progress bar once the loading is complete
Refer:
http://developer.android.com/reference/android/widget/ProgressBar.html
Also see Android indeterminate progress bar

Disable loading in Pull to refresh listview

I am having Pull to Refresh https://github.com/chrisbanes/Android-PullToRefresh as given in this link. Everything works fine. But when my list item finishes, the loading icon and pull to refresh label is still visible. So, how to disable the scrolling when end of list reached?
mainListView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh(PullToRefreshBase refreshView) {
String total_bk_count = subCategory .getTotal_Book_Count();
count_of_book = Integer.parseInt(total_bk_count);
listCountt = mainbooksAdpater.getCount();
Log.e("StroreActivity","Total book count---====----====---+"+count_of_book);
Log.e("StroreActivity","list Count---====----====---+"+listCountt);
if(listCountt < count_of_book)
{
int bookCount = Common.getBookCountNumber();
Common.setBookCount(bookCount+1);
String refresh_Pull_Url = Common.getUrlForeCategoryBooks(id, Common.NUMBER_OF_BOOKS_PER_REQUEST);
Log.e("Rathis to Check url", Common.getUrlForeCategoryBooks(id, Common.NUMBER_OF_BOOKS_PER_REQUEST));
PulltoRefreshAsync onCatBooksTaskScroll = new PulltoRefreshAsync(Common.getUrlForeCategoryBooks(id, Common.NUMBER_OF_BOOKS_PER_REQUEST));
onCatBooksTaskScroll.execute();
Log.e("StroreActivity","Total Book count::" + book_count_no);
}
else
{
mainListView.setMode(Mode.DISABLED);
Toast.makeText(getApplicationContext(), "end of list", Toast.LENGTH_SHORT).show();
}
}
});
Asynctask Class:
public class PulltoRefreshAsync extends AsyncTask<Object,Object,Object> {
int refreshCount;
String refresh_URL;
public PulltoRefreshAsync(String url) {
refresh_URL = url;
}
/*
* PulltoRefreshAsync(int i) { refreshCount = i; }
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("Checking Purpose", refresh_URL);
}
#Override
protected String doInBackground(Object... arg0) {
JsonParserRefresh jp = new JsonParserRefresh();
Log.e("StroreActivity","Array to String::" + refresh_URL);
String jsonString = jp.getJSONFromURL(refresh_URL);
Log.e("StroreActivity","JsonString::" + jsonString);
jsonParseForCategoryBooksGridScroll(jsonString);
return null;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
/*
* if(mProgressDialog.isShowing()) { mProgressDialog.dismiss(); }
*/
final MainBooksAdapter mainbooksAdpater = new MainBooksAdapter(
StoreActivity.this, R.layout.aa, mainBooksList);
final int old_pos = mainListView.getRefreshableView()
.getFirstVisiblePosition() + 1;
mainListView.setAdapter(mainbooksAdpater);
tvvisiblebookCount.setText("" + mainbooksAdpater.getCount());
/*if(listCountt < count_of_book)
{
mainListView.setMode(Mode.DISABLED);*/
mainListView.post(new Runnable() {
#Override
public void run() {
mainListView.onRefreshComplete();
mainListView.getRefreshableView().setSelection(old_pos);
}
});
//}
mainbooksAdpater.notifyDataSetChanged();
}
}
For other people who might have similat issue:
you don't have to implement it this way
mainListView.post(new Runnable() {
#Override
public void run() {
mainListView.onRefreshComplete();
mainListView.getRefreshableView().setSelection(old_pos);
}
});
instead do just like this :
mainListView.onRefreshComplete();
one more thing I noticed, instead of saving the old pos value to get back to it, why not just use notifyDataSetChanged it leaves the position of the list the way it is, just try not to re-instanciate you list, i.e: mainBooksList = ..., instead try this:
mainBooksList.clear();
mainBooksList.addAll(YOUR DATA);
adapter.notifyDataSetChanged();
voila!
hope this helps someone

Jsoup in Android, extracting the "middle word" in text from an element after title=

Im making an Android App and i need help with targeting a specific text in an Element
This is where im at:
Elements bookietemp = item.getElementsByClass("name");
String bookie1 = bookietemp.select("a[title]").first().text(); //This dosnt work
Log.d("test", bookie1);
I have tried with the above, but it dosnt work or return anything:
"bookietemp" will contain the following code, from this i want to extract only: "Toto" or "Tobet" (The second word/the word after "Open ", after title=)
This is the value from "bookietemp"
<a rel="nofollow" class="name" title="Open Toto website!" target="_blank" href="/bookmakers/toto/web/"><span class="BK b6"> </span></a>
<a rel="nofollow" class="name" title="Open Tobet website!" target="_blank" href="/bookmakers/tobet/web/"><span class="BK b36"> </span></a>
And my full code is here:
public class AsyncTaskActivity extends Activity {
Button btn_start;
TextView state;
TextView output;
ProgressDialog dialog;
Document doc;
String test;
Element test2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
btn_start = (Button) findViewById(R.id.btn_start);
state = (TextView) findViewById(R.id.state);
output = (TextView) findViewById(R.id.output);
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_start.setEnabled(false);
new ShowDialogAsyncTask().execute();
}
});
}
private class ShowDialogAsyncTask extends AsyncTask<String, Void, ArrayList<String>> {
ArrayList<String> arr_linkText=new ArrayList<String>();
#Override
protected void onPreExecute() {
// update the UI immediately after the task is executed
super.onPreExecute();
Toast.makeText(AsyncTaskActivity.this, "Invoke onPreExecute()",
Toast.LENGTH_SHORT).show();
output.setText("Please Wait!");
}
#Override
protected ArrayList<String> doInBackground(String... String) {
// String linkText = "";
try {
doc = Jsoup.connect("http://www.bmbets.com/sure-bets/").get();
// linkText = el.attr("href");
// arr_linkText.add(linkText);
Elements widgets = doc.getElementsByClass("surebets-widget");
for (Element widget : widgets){
//Log.d("test", el.toString());
Elements items = widget.getElementsByClass("item"); //Dette giver dig ca 8 items.
for (Element item : items)
{
Elements matchtemp = item.getElementsByClass("odd");
String matchname = matchtemp.select("a[title]").first().text();
Log.d("test", matchname);
//Here is the problem
Elements bookietemp = item.getElementsByClass("name");
String bookie1 = bookietemp.select("a[title]").first().text();
Log.d("test", bookie1);
Elements tipvals = item.getElementsByClass("tip-val");
if (tipvals.size() == 2)
{
Log.d("test", "Head to Head kamp");
Element tipval1 = tipvals.get(0);
String oddshome = tipval1.text().trim();
Element tipval2 = tipvals.get(1);
String oddsaway = tipval2.text().trim();
Log.d("test", oddshome + " " + oddsaway);
}
else
{
Log.d("test", "3 way");
Element tipval1 = tipvals.get(0);
String oddshome = tipval1.text().trim();
Element tipval2 = tipvals.get(1);
String oddsdraw = tipval2.text().trim();
Element tipval3 = tipvals.get(2);
String oddsaway = tipval3.text().trim();
Log.d("test", oddshome + " " + oddsdraw + " " + oddsaway);
}
}
// arr_linkText.add(linkText);
}
// return test2;
} catch (IOException e) {
e.printStackTrace();
}
return arr_linkText;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// // progressBar.setProgress(values[0]);
// // txt_percentage.setText("downloading " +values[0]+"%");
}
#Override
protected void onPostExecute(ArrayList<String> result) {
// super.onPostExecute(result);
Toast.makeText(AsyncTaskActivity.this, "Invoke onPostExecute()",
Toast.LENGTH_SHORT).show();
state.setText("Done!");
//output.setText(result);
for (String temp_result : result){
output.append (temp_result +"\n");
}
btn_start.setEnabled(true);
}
}
Note i have something a bit similar to extract another text, which is working:
Elements matchtemp = item.getElementsByClass("odd");
String matchname = matchtemp.select("a[title]").first().text();
Log.d("test", matchname);
I finally figured it out myself using:
Elements bookietemp = item.getElementsByClass("name");
String bookie1 = bookietemp.attr("title"); //This gets the full line
String arr[] = bookie1.split(" ", 3); //This splits the word in 3
String theRest = arr[1]; //This selects the second word
EDit:
If anyone have a simplier way, or a way to combine these lines im still interrested

Categories

Resources