I'm new to android studio and Java. My app uses jsoup to pass the contents of a website into an array where each element gets displayed on swipable flashcards (like tinder)
I've got a problem where my app crashes when I try to pass the result of the variable 'words' from onPostExecute() (line 123) to String num on line 49. I want to take the output of the function in onPostExcecute and set it as String num but I'm not sure how to do it.
public class AppHome extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
TextView texx;
private ArrayList<String> al;
private ArrayAdapter<String> arrayAdapter;
private int i;
String words;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_home);
texx= findViewById(R.id.text1);
new doit().execute();
String num = words;
String str[] = num.split(",");
final ArrayList al = new ArrayList<String>(Arrays.asList(str));
arrayAdapter = new ArrayAdapter<>(this, R.layout.item, R.id.helloText, al );
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
registerForContextMenu(flingContainer);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
al.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
Toast.makeText(AppHome.this, "left", Toast.LENGTH_SHORT).show();
}
#Override
public void onRightCardExit(Object dataObject) {
Toast.makeText(AppHome.this, "right", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
al.add("XML ".concat(String.valueOf(i)));
arrayAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
}
public class doit extends AsyncTask<Void,Void,Void> {
//String words;
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words=doc.text();
}catch(Exception e){e.printStackTrace();}
return null;
}
#Override
public void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
}
public class doit extends AsyncTask<Void, Void, String> {
#Override
protected Void doInBackground(Void... voids) {
String words = "";
try {
Document doc = Jsoup.connect("https://screenscrape4top40.000webhostapp.com/").get();
words = doc.text();
} catch(Exception e) {
e.printStackTrace();
}
return words;
}
#Override
public void onPostExecute(String words) {
super.onPostExecute(aVoid);
texx.setText(words);
//String str = (words);
//List<String> elephantList = Arrays.asList(str.split(","));
//texx.setText(elephantList.toString());
// texx.setText(elephantList);
}
}
It should be fine now.
The problem is, you are not returning anything from the doInBackground method and hence you are not getting anything in the onPostExecute function.
You might consider checking the documentation for AsyncTask here.
In doInBackgroud() return the string(make sure it never beacome null) you want to use it on PostExecute()
also changed the data type of Parameter in onPostExecute method
onPostExecute(String Strs)
Then pass it to supper.OnPostExecute().
then u can use it.
Related
So I am trying to call notifyDataSetChanged() to update the ArrayList on completion of OnPostExecute However I am finding it quite hard to do with the AsyncTask being in another class. I also cannot call it in setpagecontent as it is a static method.
I appreciate all the help provided :)
PostListActivity.java
public class PostListActivity extends AppCompatActivity {
ArrayList<String> Posts_Array_List = new ArrayList<String>();
// private RequestQueue mQueue;
ArrayAdapter<String> PostsAdaptor;
ListView lv;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_list);
mContext=PostListActivity.this;
lv = (ListView) findViewById(R.id.LV_Post_list);
PostsAdaptor = new ArrayAdapter<String>(PostListActivity.this, android.R.layout.simple_list_item_1, Posts_Array_List);
PostsAdaptor.notifyDataSetChanged();
lv.setAdapter(PostsAdaptor);
String stringUrl = "https://www.reddit.com/r/cars/hot.json?limit=1";
new DownloadAsyncTask(mContext,stringUrl).execute();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String myParam = extras.getString("paramPosition");
// Get the URL from the UI's text field.
}
}
public void setPageContent(String thePageContent) {
System.out.println("Got: " + thePageContent);
String jsonFromReddit = thePageContent;
//ArrayList<String> posts = RedditPostHelper.getRedditPostsFromJSON(jsonFromReddit);
// Posts_Array_List.addAll(posts);
Posts_Array_List.add(thePageContent);
System.out.println("result==="+thePageContent);
PostsAdaptor.notifyDataSetChanged();
}
}
DownloadAsyncTask.java
public class DownloadAsyncTask extends AsyncTask<Void,Void,String>{
private Context context;
private String url;
DownloadAsyncTask(Context mContext, String stringUrl)
{
super();
this.context=mContext;
this.url=stringUrl;
}
#Override
protected String doInBackground(Void... voids) {
String result="testing";
return result;
}
#Override
protected void onPostExecute(String result) {
if (!result.isEmpty() && result !=null){
PostListActivity pla = (PostListActivity) context;
pla.setPageContent(result);
}
}
Output:
}
There would be some changes to be made to the code but for inter class communication you can use an interface and use its functions as callbacks
I need help. I have two methods of shared preference. They are getList and setList.
This is setList()
public static void setList(Application activity, List<tcmb> mValuesList) {
StringBuilder valuesBuilder = new StringBuilder();
/*Log.d(TAG, "List Size ------ \t: " + mValuesList.size());*/
for (tcmb s : mValuesList) {
valuesBuilder.append(s);
valuesBuilder.append(",");
Log.d(TAG, "setValuestcmb: " + valuesBuilder.toString());
}
SharedPreferences values = activity.getSharedPreferences("dd", MODE_PRIVATE);
SharedPreferences.Editor editor = values.edit();
editor.putString("ss", valuesBuilder.toString());
editor.apply();
}
This is getList()
public static List<tcmb> getList(Activity a) {
SharedPreferences values = a.getSharedPreferences("dd", MODE_PRIVATE);
String wordsString = values.getString("ss", "");
/* Log.d(TAG, "wordsString \t:" + wordsString);*/
String[] itemWords = wordsString.split(",");
List<String> itemList = new ArrayList<String>();
itemList.addAll(Arrays.asList(itemWords));
dovizList = (List)itemsList;
Log.d(TAG, "getValuestcmb: " + dovizList.size());
return dovizList;
}
For the values I got, I run the setList method in the asyncTask class of Main Activity that assigns to shared preference.
Then for I get to values, I run the getList method in the asyncTask class of Fragment.
And I get the object values.namely, I can see the values I get from the logcat.
[com.example.lscodex.ddddd.Model.tcmb#4ff695, com.example.lscodex.ddddd.Model.tcmb#b6b93aa, com.example.lscodex.ddddd.Model.tcmb#347db9b, com.example.lscodex.ddddd.Model.tcmb#f63eb38, com.example.lscodex.ddddd.Model.tcmb#4866711, com.example.lscodex.ddddd.Model.tcmb#8c74076, com.example.lscodex.ddddd.Model.tcmb#3be9677, com.example.lscodex.ddddd.Model.tcmb#10882e4, com.example.lscodex.ddddd.Model.tcmb#8d9634d, com.example.lscodex.ddddd.Model.tcmb#b5eee02, com.example.lscodex.ddddd.Model.tcmb#b7c2313, com.example.lscodex.ddddd.Model.tcmb#a3ce950, com.example.lscodex.ddddd.Model.tcmb#ee5e749, com.example.lscodex.ddddd.Model.tcmb#fd1e84e, com.example.lscodex.ddddd.Model.tcmb#b7bdd6f, com.example.lscodex.ddddd.Model.tcmb#40f4a7c, com.example.lscodex.ddddd.Model.tcmb#b1caf05, com.example.lscodex.ddddd.Model.tcmb#b683b5a, com.example.lscodex.ddddd.Model.tcmb#f12e18b]
totally 19 values.
But when I cast values to recylerView's bindHolder in the fragment class, I get an error is that
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.lscodex.ddddd.Model.tcmb
This is asyncTask from fragment
private class DownloadXmlTask extends AsyncTask<Void, Integer, List<tcmb>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected List<tcmb> doInBackground(Void... voids) {
return SharedPreferenceValues.getList(getActivity());
}
#Override
protected void onPostExecute(List<tcmb> tcmb) {
if (tcmb.size() == 0) {
mtcmbList = tcmb;
setupAdapter();
mRecyclerViewAnim.runLayoutAnimation(getContext(), mRecyclerView);
mProgressBar.setVisibility(View.INVISIBLE);
} else if (mRecyclerView != null) {
mtcmbList.addAll(tcmb);
Log.d(TAG, "onPostExecute: " + mtcmbList.size());
mRecyclerView.getAdapter().notifyDataSetChanged();
dateUpdate();
mRecyclerViewAnim.runLayoutAnimation(getContext(), mRecyclerView);
mProgressBar.setVisibility(View.INVISIBLE);
mSwipeRefreshLayout.setRefreshing(false);
}
}
}
and the place where I got the error.
#Override
public void onBindViewHolder(tcmbHolder holder, int position) {
tcmb tcmb= mtcmbList.get(position); ---- the error here
holder.bindTcmb(tcmb);
I don't know why?
EDIT
I try it with the shared preferences, I get XML list data from splash screen and import it into other activity.
private class splashTask extends AsyncTask<Void, Integer, List<tcmb>> {
private Activity mContext;
public splashTask(Activity c){
this.mContext = c;
}
#Override
protected void onPreExecute() {
mSplashProgressBar.setProgress(0);
}
#Override
protected List<tcmbDoviz> doInBackground(Void... voids) {
List<tcmb> tcmbList = new ConnectionXmlParser().getXmlFile(getApplicationContext());
try {
int getvalues = ConnectionXmlParser.howLong();
Log.d(TAG, "doInBackground: " +getvalues);
for (int i=0;i<getvalues;i++){
Log.d(TAG, "doInBackground: " +i);
publishProgress(((int)i*100)/getvalues);
Log.d(TAG, "Publishing " + ((int)i*100/getvalues));
}
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
return tcmbList;
}
#Override
protected void onPostExecute(List<tcmbDoviz> list) {
mtcmbList.addAll(list);
SharedPreferenceValues.setValuesList(getApplication(),mtcmbList);
splashScreen();
mSplashProgressBar.setVisibility(View.GONE);
}
#Override
protected void onProgressUpdate(Integer... values) {
mSplashProgressBar.setProgress(values[0]);
super.onProgressUpdate(values);
}
You are trying to change List<String> to List<tcmb> and problem lies here
public static List<tcmb> getList(Activity a){
// your code
//
List<String> itemList = new ArrayList<String>();
itemList.addAll(Arrays.asList(itemWords));
dovizList = (List)itemsList;
Log.d(TAG, "getValuestcmb: " + dovizList.size());
return dovizList;
Also, I don't understand, what exactly you are trying to achieve here.
List<String> itemsList = new ArrayList<String>();
dovizList = (List)itemsList;
But, as per code shared, you need to change
List<String> itemsList = new ArrayList<String>();
to
List<tcmb> itemsList = new ArrayList<tcmb>();
And, you don't need
dovizList = (List)itemsList;
I found how to do it.
to save XML List object with Shared Preferences in splashscreen.activity
public static void setValues(Context context, List<tcmb> curProduct){
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(curProduct);
SharedPreferences sharedPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("dd", jsonCurProduct);
editor.apply();
Log.d(TAG, "setValues: " + jsonCurProduct);
}
then, to get the List object with Shared Preferences in the fragment
public static List<tcmb> getValuesAltın(Context context){
Gson gson = new Gson();
List<tcmbDoviz> productFromShared = new ArrayList<>();
SharedPreferences sharedPref = context.getSharedPreferences("Prefs", Context.MODE_PRIVATE);
String jsonPreferences = sharedPref.getString("dd", "");
Type type = new TypeToken<List<tcmb>>() {}.getType();
productFromShared = gson.fromJson(jsonPreferences, type);
return productFromShared;
}
finally, Thanks, Ravi.
I need to call a new activity from onPostExecute() method of ASyncTask but the context is returning null.
public class ImageDownloadTask extends AsyncTask<String,Void,ArrayList<String>> {
public final String search = "https://www.google.co.in/search?&tbm=isch&q=";
public final String searchAlbum = "album+art";
ArrayList<String> arrayList=new ArrayList<String>();
ArrayList<String> urlList=new ArrayList<String>();
Context context;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<String> doInBackground(String... urls) {
System.out.println(urls.length);
arrayList.clear();
urlList.clear();
for(int i=0;i<urls.length;i++) {
String url = urls[i];
String finalUrl = search + url + searchAlbum;
try {
//Log.i("URL", finalUrl);
urlList.add(finalUrl);
Document document = Jsoup.connect(finalUrl).get();
String result = document.toString();
//Pattern pattern = Pattern.compile("<img class=\"rg_ic rg_i\" data-src=\"(.*?)\" data-sz");
Pattern newPattern = Pattern.compile("\"ou\":\"(.*?)\",\"ow\"");
//Matcher m = pattern.matcher(result);
Matcher newMatcher = newPattern.matcher(result);
if(newMatcher.find())
arrayList.add(newMatcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Printing Images");
System.out.println(urlList);
System.out.println(arrayList);
return arrayList;
}
#Override
protected void onPostExecute(ArrayList<String> strings) {
if(context!=null) {
Intent i = new Intent(context,MusicPlayerActivity.class).putExtra("arrayImages",arrayList);
context.startActivity(i);}
else
Log.i("Context","NULL"); //Check why it is null*****
super.onPostExecute(strings);
}
}
The Output is Context:NULL.
Why is it null, i have tried making a variable of type MainActivity and Activity, but both doesn't solve the problem.
Thank you for your time.
You declare your context variable but never set it:
Context context;
So yes, it is null when you try and use it.
You should populate it before you try to use it - perhaps pass a reference to to the calling Activity or similar.
Put this ImageDownloadTask inside your Activity, then you can call it using below code
new MyTask().execute(urls);
and on you ImageDownloadTask change onPostExecute function to this one
#Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
Intent i = new Intent(YourActivityName.this, MusicPlayerActivity.class).putExtra("arrayImages", strings);
startActivity(i);
}
}
}
I am having some problem when trying to pass a String and object to AsyncTask class. So when my button on click, it should pass in a String and an EventReview object into the AsyncTask class:
viewDtlEventBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
new GetEventDetailAsyncTask(new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
//Get the values returned from AsyncTask and pass it to another activity
}
}).execute(String.valueOf(eventIDTV.getText()));
}
});
And inside my AsyncTask class, I am getting String as the parameter:
public static class GetEventDetailAsyncTask extends AsyncTask<String, Integer, Double> {
EventController eventCtrl = new EventController();
Context context;
public interface OnRoutineFinished { // interface
void onFinish();
}
private OnRoutineFinished mCallbacks;
public GetEventDetailAsyncTask(OnRoutineFinished callback) {
mCallbacks = callback;
}
public GetEventDetailAsyncTask() {
} // empty constructor to maintain compatibility
public GetEventDetailAsyncTask(Context context){
this.context = context;
}
#Override
protected Double doInBackground(String... params) {
try {
eventCommentModel = eventCtrl.getEventCommentByID(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
if (mCallbacks != null)
mCallbacks.onFinish(); // call interface on finish
}
protected void onProgressUpdate(Integer... progress) {
}
}
So I wonder is there any possible way to pass in a String and EventReview object to the execute() and then when doInBackground(), each execute each method. Any guides?
Thanks in advance.
You can pass String and your custom class' object in Object[] in asynctask.
Object[] obj = new Object[2];
obj[0] = "my data";
obj[1] = myEventReviewObj;
new GetEventDetailAsyncTask().execute(obj);
AsyncTask:
public static class GetEventDetailAsyncTask extends AsyncTask<Object, Integer, Double> {
#Override
protected Double doInBackground(Object... params) {
String paramStr = "";
EventReview eventReview = null;
if(params[0] instanceof String && params[1] instanceof EventReview) {
paramStr = (String) params[0];
eventReview = (EventReview) params[1];
}
else {
eventReview = params[0];
paramStr = params[1];
}
try {
//perform operation using String and Object as per your need
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Hope this helps.
You can change the class to accept Objects as input:
public static class GetEventDetailAsyncTask extends AsyncTask<Object, Integer, Double>
and check if the object is an instance of String or of EventReview
#Override
protected Double doInBackground(Object... params) {
if(params[0] instanceof String) // it is String
else if(params[0] instanceof EventReview) // it is EventReview
}
Create custom constructor and save the passed variables in your AsyncTask:
public static class GetEventDetailAsyncTask extends AsyncTask<String, Integer, Double> {
EventReview eventReview;
private OnRoutineFinished mCallbacks;
String string;
Context context;
public GetEventDetailAsyncTask(OnRoutineFinished callback, String str, EventReview review) {
mCallbacks = callback;
string = str;
eventReview = review;
}
...
}
And then call the AsyncTask by passing your vars:
public void onClick(View v){
new GetEventDetailAsyncTask(
new GetEventDetailAsyncTask.OnRoutineFinished() {
public void onFinish() {
// Get the values returned from AsyncTask and pass it to another activity
}
},
String.valueOf(eventIDTV.getText(),
eventReview).execute());
}
I'm newbie in Java/ADT and I'm trying to get an array from "Activity A" to "Activity B". The app takes information from a webpage, and then saves it in a pair of arrays and show the information. I want to click a "go to graph" button (calls to viewallday()) to redirect to Activity B who will show a graphic with all this information.
The problem is that they're a self refresh array (1sec refresh) and don't want to loose this feature when the app It's on graphic mode (Activity B). Any ideas about how to do that?
Thank all of you in advance, I'm learning a lot from this site.
UPDATE: I'm trying to do this with a Singleton pattern. But LogCat says:
02-26 22:21:59.300: E/AndroidRuntime(2677): FATAL EXCEPTION: main
02-26 22:21:59.300: E/AndroidRuntime(2677): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.Chispa/com.example.Chispa.Activity_allday}: android.os.NetworkOnMainThreadException
02-26 22:21:59.300: E/AndroidRuntime(2677): Caused by: android.os.NetworkOnMainThreadException
UPDATE 2: Finally got it!! Here's the code I used:
Here's the code for Activity A:
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view) {
Intent intent = new Intent(MainActivity.this, Activity_allday.class);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
public Document getUrl(){
try {
URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?FECHA=20140226");
/*URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?lang=es&frameId=4064&segmento=1&promocion=");*/
Document doc = Jsoup.connect(url.toString()).get();
return doc;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
GlobalVariables gs = (GlobalVariables) getApplication();
gs.setBar(getValuesGraph(getUrl()));
p.bar = getValuesGraph(getUrl());
p.values = getValuesFooter(getUrl());
return p;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
And here's the code for Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
And here's a GlobalVariable class who captures the array I want to send to Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
That's all! hope It'll help to future users.
Thanks all for your help.
Here is something you could try:
Inside your AsyncTask, define an interface and a method inside it that will pass back the data to the calling activity and inside that method, call the next activity and set the data as an extra.
This is the simplest way.
In your AsyncTask, inside onPostExecute(result), use a try block to call the method which belongs to the above mentioned interface which must be implemented by the calling activity.
HomeActivity.java
/public class SampleActivity extends Activity implements SampleAsyncTask.OnUpdateListener{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
executeAsync();
}
public void executeAsync(){
new SampleAsyncTask(this).execute("someFlagToCheck");
}
#Override
public void onDataProcessed(String result){
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("data", result);
startActivity(intent);
}
}
SampleAsyncTask.java
public class SampleAsyncTask extends AsyncTask<Void, Void, String>{
Context context;
//constructor
SampleAsyncTask(Context context){
this.context = context;
}
#Override
public void doInBackground(String... params){
//do something depending on the arguments in params
return "data";
}
#Override
public void onPostExecute(String result){
try{
((OnUpdateListener) context).onDataProcessed(result);
}catch(Exception e){
e.printStackTrace();
}
}
public interface OnUpdateListener{
public void onDataProcessed(String data);
}
}
Follow this example. The calling activity implements the AsyncTask's interface and overrides its method which will be called when the async task is done with the result.
I hope this helped.
SOLUTION:
Here's the code for Activity A:
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view) {
Intent intent = new Intent(MainActivity.this, Activity_allday.class);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
public Document getUrl(){
try {
URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?FECHA=20140226");
/*URL url= new URL("http://www.endesaonline.com/canal/precios/Canal_Preciosdelpool.asp?lang=es&frameId=4064&segmento=1&promocion=");*/
Document doc = Jsoup.connect(url.toString()).get();
return doc;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
GlobalVariables gs = (GlobalVariables) getApplication();
gs.setBar(getValuesGraph(getUrl()));
p.bar = getValuesGraph(getUrl());
p.values = getValuesFooter(getUrl());
return p;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
Global variable class who captures the array I want to send to Activity B:
public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_price);
TextView tvall=(TextView)findViewById(R.id.tvall);
GlobalVariables gs = (GlobalVariables) getApplication();
String[] s = gs.getBar();
tvall.setText(s[0]);
}
}
Thanks all for your help!!