I have a query running to collect a youtube id from a database. The AsyncTask works and I get the piece of information but I can't pass it from onPostExecute to onCreate.
Here is what I have tried doing.
Make youtubeIdCode a global variable.
Run the query to get the id from the database.
Return the youtubeid in doInBackground.
Set youtubeIdCode = the result of doInBackground in onPostExecute.
Try calling the youtubeIdCode in onCreate to see if the result from onPostExecute passed to youtubeIdCode. This is where I have the issue. It is not passing from onPostExecute to onCreate. How can I pass it because in onCreate is where I will be needing the id to form a youtube url.
//Activity needs added to manifest.
public class DetailsActivity extends AppCompatActivity {
//LOG tag for debugging
private static final String TAG = "GalleryActivity";
String youtubeIdCode;
//Override on Create and set contentView to new activity_details layout.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
//Log for debugging so we can tell if activity started successfully.
Log.d(TAG, "onCreate: started.");
youtubeIdCode = "";
loadMovieData();
String test = "The value is" + youtubeIdCode;
Log.v("youtube code test", test);
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String image = movie.getMoviePoster();
String title = movie.getTitle();
String releaseDate = movie.getDate();
String voteAverage = movie.getVoteAverage();
String plot = movie.getPlot();
ImageView poster = findViewById(R.id.details_image);
Picasso.with(this).load(image).into(poster);
TextView name = findViewById(R.id.details_title);
name.setText((getResources().getString(R.string.movie_title)) + " " + title);
TextView dateRelease = findViewById(R.id.details_release_date);
dateRelease.setText((getResources().getString(R.string.release_date)) + " " + releaseDate);
TextView averageVote = findViewById(R.id.details_voter_average);
averageVote.setText((getResources().getString(R.string.vote_average)) + " " + voteAverage);
TextView moviePlot = findViewById(R.id.details_plot);
moviePlot.setText((getResources().getString(R.string.plot)) + " " + plot);
}
public class FetchTrailer extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
final String YOUTUBE_ID = "id";
final String RESULTS = "results";
String youtubeId = " ";
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String id = movie.getID();
final URL trailerUrl = NetworkUtils.buildUrlTrailer(id);
Log.v("Built trailer url", trailerUrl.toString());
try {
String jsonResponse = NetworkUtils.getReponseFromHttpUrl(trailerUrl);
JSONObject moviesObject = new JSONObject(jsonResponse);
JSONArray resultsArray = moviesObject.getJSONArray(RESULTS);
for(int i = 0; i < resultsArray.length(); i ++){
JSONObject movieObject = resultsArray.getJSONObject(i);
youtubeId = movieObject.getString(YOUTUBE_ID);
Log.v("youtubeid", youtubeId);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return youtubeId;
}
#Override
protected void onPostExecute(String s) {
youtubeIdCode = s;
Log.v("onposttest", s);
}
}
//Tell the new method to get the data based on the search term within the url.
private void loadMovieData() {
//If there is a network connection, fetch the data.
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
new FetchTrailer().execute();
} else {
Toast toast = Toast.makeText(this, getString(R.string.no_internet_toast), Toast.LENGTH_LONG);
toast.show();
}
}
}
I think you need to rethink the logic of the app. The main idea of using an AsyncTask is that the main thread would not block while the task is running.
This means onCreate() shouldn't wait for the AsyncTask to finish to continue it's execution, which is what you are implying that should happen.
The way to think your app, is that the URL setup you want to do with the youtube id, and any aditional processing should be trigged by onPostExecute() when the task is finished.
At a time of call asynTask you can do like that, may be it work i am not confident.
new FetchTrailer(){
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}.execute()
Just do a setter of the var you need to put te value, then onPostExecute just call that setter function and pass the value of the var in the AsyncTask, and after that use a method to fetch the text on your widgets, if you do it before you pass the value it will be null.
Also try to do AsyncTask in a separate class
AsyncTask OnPostExecute
#Override
protected void onPostExecute(List<ListaLineal> superlistItems) {
super.onPostExecute(superlistItems);
activity.setSuperListItems(superlistItems); -> this retrieve the value of a list that I was using (I got the value of the list in doInBackground)
activity.setupData(); -> method for setting up data
}
In your case setupData will look similar to this
public void setupData(){
String image = movie.getMoviePoster();
String title = movie.getTitle();
String releaseDate = movie.getDate();
String voteAverage = movie.getVoteAverage();
String plot = movie.getPlot();
ImageView poster = findViewById(R.id.details_image);
Picasso.with(this).load(image).into(poster);
TextView name = findViewById(R.id.details_title);
name.setText((getResources().getString(R.string.movie_title)) + " " + title);
TextView dateRelease = findViewById(R.id.details_release_date);
dateRelease.setText((getResources().getString(R.string.release_date)) + " " + releaseDate);
TextView averageVote = findViewById(R.id.details_voter_average);
averageVote.setText((getResources().getString(R.string.vote_average)) + " " + voteAverage);
TextView moviePlot = findViewById(R.id.details_plot);
moviePlot.setText((getResources().getString(R.string.plot)) + " " + plot);
}
Related
I am building an android app that displays the COVID19 statistics for India, I am getting the stats in JSON format from https://api.covid19india.org/data.json , this API contains data of individual states too,
Below is the snip of Json array(contains json objects representing each state) that i am requesting
as of Now i am displaying the entire data ( all states ) at a time on my screen, However i want to give the state name as the input and display the stats of only that state For eg. in the below image in place of sample i want to write a state name and the stats of that state must be displayed on click of the button.
Here is the code of mainActivity.java, I am using Volley Library for fetching data from API
public class MainActivity extends AppCompatActivity {
private TextView result;
private RequestQueue mq;
public String value;
int flag = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = findViewById(R.id.textView4);
Button parse = findViewById(R.id.button);
mq = Volley.newRequestQueue(this);
EditText text = (EditText)findViewById(R.id.state_ip);
value = text.getText().toString();
parse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
jsonParse(value);
**//How do i pass 'value' i.e the state name entered by user to jsonParse**
}
});
}
private void jsonParse(final String value) {
Log.d("val_state",value);
String url = "https://api.covid19india.org/data.json";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("statewise");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject st = jsonArray.getJSONObject(i);
String statename = st.getString("state");
String active = st.getString("active");
String confirmed = st.getString("confirmed");
String deaths = st.getString("deaths");
String recovered = st.getString("recovered");
if(statename.equals(value))
{
flag= 1;
}
statename = "State : " + statename;
active = "Active Cases : " + active;
confirmed = "Confirmed Cases : " + confirmed;
deaths = "Total Deaths : " + deaths;
recovered = "Total Recovered : " + recovered;
if(flag==1)
{
flag=0;
result.append(statename + "\n" + String.valueOf(active) + "\n" + String.valueOf(confirmed) + "\n" + String.valueOf(deaths) + "\n" + String.valueOf(recovered) + "\n\n\n");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mq.add(request);
}
}
Here , i want to pass the value of state entered by the user to the method jsonParse() so that i check the state name with the received JSON data and append it to the TextView, but when i do this , and try to log the value inside the jsonParse() method i get nothing, why is this happening , How do i implement the above ?
Your EditText value is update and has to be captured after the button is clicked.
parse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
value = text.getText().toString();
jsonParse(value);
}
});
I am trying to query JSON data on a background thread using AsyncTask and use one of the values from the query in onCreate of the same Activity. How should I do this? Should I use intents or is there a more intuitive and better way of doing it?
In my code below, I am trying to pull the youtube ID using an AsyncTask out of an online database. It works because when I log the value inside the AsyncTask, the correct youtube ID is shown. But I need to use this ID in onCreate so that I can use it to create the full youtube URL. How can I pass the youtube ID string from doInBackground to onCreate? The id is stored in the variable youtubeId
//Activity needs added to manifest.
public class DetailsActivity extends AppCompatActivity {
//LOG tag for debugging
private static final String TAG = "GalleryActivity";
String youtubeIdCode;
//Override on Create and set contentView to new activity_details layout.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
//Log for debugging so we can tell if activity started successfully.
Log.d(TAG, "onCreate: started.");
loadMovieData();
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String image = movie.getMoviePoster();
String title = movie.getTitle();
String releaseDate = movie.getDate();
String voteAverage = movie.getVoteAverage();
String plot = movie.getPlot();
ImageView poster = findViewById(R.id.details_image);
Picasso.with(this).load(image).into(poster);
TextView name = findViewById(R.id.details_title);
name.setText((getResources().getString(R.string.movie_title)) + " " + title);
TextView dateRelease = findViewById(R.id.details_release_date);
dateRelease.setText((getResources().getString(R.string.release_date)) + " " + releaseDate);
TextView averageVote = findViewById(R.id.details_voter_average);
averageVote.setText((getResources().getString(R.string.vote_average)) + " " + voteAverage);
TextView moviePlot = findViewById(R.id.details_plot);
moviePlot.setText((getResources().getString(R.string.plot)) + " " + plot);
ImageView watchTrailer = findViewById(R.id.imageView);
// watchTrailer.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl.toString()));
// Log.v("OnClick URL",trailerUrl.toString());
// startActivity(intent);
// }
// });
}
public class FetchTrailer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
final String YOUTUBE_ID = "id";
final String RESULTS = "results";
String youtubeId = " ";
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String id = movie.getID();
final URL trailerUrl = NetworkUtils.buildUrlTrailer(id);
Log.v("Built trailer url", trailerUrl.toString());
try {
String jsonResponse = NetworkUtils.getReponseFromHttpUrl(trailerUrl);
JSONObject moviesObject = new JSONObject(jsonResponse);
JSONArray resultsArray = moviesObject.getJSONArray(RESULTS);
for(int i = 0; i < resultsArray.length(); i ++){
JSONObject movieObject = resultsArray.getJSONObject(i);
youtubeId = movieObject.getString(YOUTUBE_ID);
Log.v("youtubeid", youtubeId);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
//Tell the new method to get the data based on the search term within the url.
private void loadMovieData() {
//If there is a network connection, fetch the data.
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
new FetchTrailer().execute();
} else {
Toast toast = Toast.makeText(this, getString(R.string.no_internet_toast), Toast.LENGTH_LONG);
toast.show();
}
}
}
Seems youtubeId is a pre-requisite for your DetailsActivity. So we would need youtubeId prior to DetailsActivity initialization.
In your previous activity from where user can be landed to DetailsActivity , before calling startActivity(intent) call your
loadMovieData()
method as is, you would have to declare method in prior activity. After that pass the youtubeId through intent to DetailsActivity, and you can retrieve value in oncreate():
Intent myIntent = new Intent(CurrentActivity.this,
NextActivity.class);
myIntent.putExtra("youtubeId", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("youtubeId"); //if it's a string you
stored.
}
You can use a Callback Listener to achieve this
public interface FetchTrailerListener {
public void onTrailerFetched(String youtubeId);
}
Make DetailsActivity to implement this. Pass this listener reference to asynctask when you are instantiating it.In this way from your postexecute notify the activity through this listener.
protected void onPostExecute( String youtubeId) {
fetchTrailerListenr.onTrailerFetched(youtubeId);
}
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
I have an app that in one of it's Activities uses AsyncTask to call a method from another class that hooks up to a database to varify a user's login credentials. The Activity EntryActivity Has three member variable that need to be updated with the result of the AsyncTask, carerID, firstName and surName . When I first run the App all three variables are null but if i press the login button a second time the variables are set correctly and the app behaves as it should.
Is there a reason why the three member variables are not set correctly from onPostxecute in the first run of the app?
.
public class EntryActivity extends NfcBaseActivity{
private LoginWebservice loginWebservice;
private static final String TAG = EntryActivity.class.getSimpleName();
private Button login;
private EditText userName;
private EditText passwordPin;
NfcScannerApplication nfcscannerapplication;
public static final String CUSTOM_QRCODE_ACTION = "com.carefreegroup.QRCODE_ACTION";
private String carerID;
private String firstName;
private String surName;
private boolean isValidated = false;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
nfcscannerapplication = (NfcScannerApplication) getApplication();
loginWebservice = new LoginWebservice(this);
carerID = null;
firstName = null;
surName = null;
userName = (EditText)findViewById(R.id.username);
passwordPin = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.buttonlogin);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
////////////get user's input///////////
String compId = "100";
String theUsername = userName.getText().toString();
String thePassword = passwordPin.getText().toString();
String loginType = "1";
String[] params = new String[]{compId, theUsername, thePassword, loginType};
//validate user Asynchonously on background thread
new AsyncValidateCarer().execute(params);
Log.e(TAG, "carerid =" + carerID + " firstname = " + firstName + " surnamee = " + surName);
DateTime now = new DateTime();
long loginTime = now.getMillis();
String fullName = firstName +" " + surName;
Log.e(TAG, "fullname = " + fullName);
if(carerID != null){
ContentValues loginValues = new ContentValues();
loginValues.putNull(LoginValidate.C_ID_INDEX);
loginValues.put(LoginValidate.C_CARER_ID, carerID);
loginValues.put(LoginValidate.C_COMP_ID, compId);
loginValues.put(LoginValidate.C_CARER_NAME, fullName);
loginValues.put(LoginValidate.C_PASSWORD, thePassword);
loginValues.put(LoginValidate.C_DATE_TIME, loginTime);
nfcscannerapplication.loginValidate.insertIntoCarer(loginValues);
Toast.makeText(
EntryActivity.this,
"Carer logged in to System",
Toast.LENGTH_LONG).show();
isValidated = true;
Intent intent = new Intent(EntryActivity.this,
NfcscannerActivity.class);
intent.setAction(CUSTOM_QRCODE_ACTION);
startActivity(intent);
}else{
Toast.makeText(
EntryActivity.this,
"Please check credentials",
Toast.LENGTH_LONG).show();
}
//////////////validate user/////////////////
}
});
Button changeUser = (Button)findViewById(R.id.buttonchangeuser);
changeUser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "change user button clicked");
nfcscannerapplication.loginValidate.deleteTableCarer();
Toast.makeText(
EntryActivity.this,
"Carer logged out",
Toast.LENGTH_LONG).show();
EntryActivity.this.onCreate(savedInstanceState);
}
});
}//end of onCreate
private void hideSoftKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(passwordPin.getWindowToken(), 0);
}
private class AsyncValidateCarer extends AsyncTask<String, Void, ContentValues> {
#Override
protected ContentValues doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside asynctask");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
if (cv != null){
Log.e(TAG, "cv = not null!");
}
} catch (Exception e) {
e.printStackTrace();
}
return cv;
}
#Override
protected void onPostExecute(ContentValues result) {
Log.e(TAG, "inside onpostexecute");
EntryActivity.this.carerID = (String) result.get("carerID");
EntryActivity.this.firstName = (String) result.get("firstname");
EntryActivity.this.surName = (String) result.get("surname");
}
}
}
[update]
private class AsyncValidateCarer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside doInBackground");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
carerID = (String) cv.get("carerID");
firstName = (String) cv.get("firstname");
surName = (String) cv.get("surname");
if (cv != null){
Log.e(TAG, "cv = not null! and exiting doInBackground");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
An AsyncTask will execute asynchronously so you have no guarantee that after the "execute" method call, the task is actually finished. My advice would be to move everything (or at least what is related to those fields) that are after "execute" call in "onPostExecute" method.
The reason why it seems the first click doesn't work and the second works, is that between the first "Login" click and the second one, you wait enough for the AsyncTask to finish. So when you click for the second time you see the results of the first execution. Please add some "Log" messeges in "onPostExecute" to understand what is going on.
Hope it helps:)
carerID = null;
firstName = null;
surName = null;
Remove the above there statements from the onCreate() method, as they have been initialized to their default values as they are in the Class Scope and are known as Instance Variables.
when my Async task is executed it completely crashes the app
Here is the code to the class. It sits inside of my main activity class.
I'm new to threading, so sorry if I've done something ridiculous lol, I don't fully understand it.
EDIT:
private class TeamSearchTask extends AsyncTask<String,Void,Void> {
CharSequence nfo;
String [] matches;
protected Void doInBackground(String... teamNumber)
{
//Team information ------------------------------------------------------------------------------------
//Array of team data
String [] data = APIconnection.getTeams(teamNumber[0], "");
//Display basic team info
nfo = ("\nFormal Team Name:\n" + data[1] +
"\n\nLocation:\n" + data [3] + ", " + data[4] + ", " + data[5] +
"\n\nRookie Year:\n" + data[6] +
"\n\nRobot Name:\n" + data[7] +
"\n\nWebsite:\n" + data[8] + "\n\n\n\n\n\n\n\n\n");
//Make match archive --------------------------------------------------------------------------------------
String [] events = APIconnection.getEventIdsByYear(year1);
String [] matches = new String [(events.length*11)];;
for (int i = 0; i<events.length; i++)
{
matches[(i*11) + i] = APIconnection.getMatches2(teamNumber[0], events[i] ,"","")[i];
}
return null;
}
protected void onProgressUpdate(Void...voids )
{}
protected void onPostExecute(Void result) {
info.setText(nfo);
matchArchive(matches);
}
}
titlets.setText(ttl.toString());
Don't touch UI elements in different thread then UI-thread. You can use Activity::runInUiThread(Runnable r) or Handler::post(Runnable r). In second case, handler should be paired with UI-thread.
private class TeamSearchTask extends AsyncTask<String,Void,Void> {
private String[] data;
protected Void doInBackground(String... teamNumber) {
// Do your background work! No UI-stuff here!!
data = APIconnection.getTeams(teamNumber[0], "");
return null;
}
protected void onPostExecute(Void result) {
// Do all UI related stuff here, it's executed when the doInBackground is finished
}
}
edit: My bad, fixed the error with onPostExecute. You need to use Void instead of Long as you use
extends AsyncTask<String,Void,Void>
which means input parameter is String, Progress parameter type (in onProgressUpdate) and the 3rd one is for the Result.