Repeat AsyncTask on the next code - android

I have a code that only takes information from a web vía Jsoup and I want to refresh this information every second. I tried with all the code that I've found in Google and stackoverflow with no luck. Thank you very much in advance. [SOLVED]
Now I'm trying to send an array from MainActivity to another Activity called "Activity_allday" with Bundle and Intent when viewallday() function is called pressing the "btviewallday" button but with no luck. Any suggestions?
LogCat error: Could not find a method viewallday(View) in the activity class com.example.Chispa.MainActivity for onClick handler on view class android.widget.Button with id 'btviewallday'.
I've noticed that the error comes from receiving two values at viewallday(View view, Pair p). How can I receive the "Pair p" value in my viewallday function?
Here is the new app code:
[MainActivity]
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, Pair p) {
Intent intent = new Intent(this, Activity_allday.class);
Bundle bundle =new Bundle();
bundle.putStringArray("bar", p.bar);
intent.putExtras(bundle);
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;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
try {
URL url= new URL("http://www.myweb.com");
Document doc = Jsoup.connect(url.toString()).get();
p.bar = getValuesGraph(doc);
p.values = getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
return p;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
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_allday]
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_prices);
tvall = (TextView) findViewById(R.id.tvall);
Bundle bundle = this.getIntent().getExtras();
String[] bar=bundle.getStringArray("bar");
/*tvall.setText(bar[0]);*/
}
public void back (View view) {
finish();
}
}

Related

How to update recyclerView from web service periodically without leaking memory

My application makes a webservice call using volley, in order to update recyclerView every 10 seconds. Besides memory usage increase in 10 seconds constantly until it hits the max heap size. Then GC starts doing its job, but the memory usage does not come back down like at the beginning.
Using Eclipse MAT or Android Studio analyzer tasks, I could'nt find a single leak in my code.
I want to know that if there are suspects of leaking in my code. Any help will be appreciated.
Below I have 3 classes:
EventService send a message to MainActivity using sendBroadcast() in every 10 seconds.
MainActiviy will get message from EventService using BroadcastReceiver and calls update operation within its Fragment
EventListFragment, which is inside the MainActivity, contains a RecyclerView, that needs to be updated.
Here is my EventService:
public class EventService extends Service {
private volatile boolean isCanceled = false;
public static final String KEY_MESSAGE = "connection";
public EventService() {}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Runnable r = new Runnable() {
#Override
public void run() {
while (!isCanceled) {
try {
Intent i = new Intent("android.intent.action.MAIN");
AppController.getInstance().cancelPendingRequests("json_obj_req");
i.putExtra(KEY_MESSAGE, MESSAGE);
sendBroadcast(i);
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread eventThread = new Thread(r);
eventThread.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
isCanceled = true;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Here is my MainActivity:
public class MainActivity extends AppCompatActivity {
private Intent intent;
private BroadcastReceiver mReceiver;
private EventListFragment eventListFragment;
private IntentFilter intentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void setView() {
eventListFragment = (EventListFragment) getSupportFragmentManager().findFragmentById(R.id.frgEventList);
}
#Override
protected void onResume() {
intent = new Intent(this, EventService.class);
mReceiver = new MyReceiver(eventListFragment);
this.registerReceiver(mReceiver, intentFilter);
intent = new Intent(this, EventService.class);
startService(intent);
}
#Override
protected void onPause() {
super.onPause();
stopService(intent);
unregisterReceiver(mReceiver);
}
private static class MyReceiver extends BroadcastReceiver {
private WeakReference<EventListFragment> eventListFragment = null;
public MyReceiver(EventListFragment eventFragment) {
this.eventListFragment = new WeakReference<>(eventFragment);
}
#Override
public void onReceive(Context context, Intent intent) {
String mssg = intent.getStringExtra(KEY_MESSAGE);
EventListFragment eventFragment = eventListFragment.get();
if (mssg.equals(MESSAGE) && eventFragment != null) {
//Update recyclerView
eventFragment.eventToList();
}
}
}
}
And here is my EventListFragment:
public class EventListFragment extends Fragment {
private View view;
private RecyclerView recyclerView;
private LinearLayoutManager mLayoutManager;
private EventAdapter eventAdapter;
private RequestData requestData;
private ArrayList<EventModel> eventList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_event_list, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
setView();
setControl();
}
private void setView() {
recyclerView = (RecyclerView) view.findViewById(R.id.frg_recycler_view);
}
private void setControl() {
if (eventAdapter == null && mLayoutManager == null) {
eventList = new ArrayList<>();
eventAdapter = new EventAdapter(getActivity().getApplicationContext(), eventList);
mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(eventAdapter);
}
recyclerView.addOnItemTouchListener(new RecyclerItemListener(getActivity().getApplicationContext(), recyclerView, new RecyclerItemListener.RecyclerTouchListener() {
#Override
public void onClickItem(View v, int position) {
EventModel model = eventList.get(position);
SQLiteHandler db = SQLiteHandler.getInstance(getActivity().getApplicationContext());
//some instances
}
#Override
public void onLongClickItem(View v, int position) {
}
}));
}
//make service call
public void eventToList() {
if (requestData == null) {
requestData = new RequestData(getActivity());
}
final ArrayList<EventModel> newList = new ArrayList<>(); //are you leaking?
requestData.getEventToday(new RequestData.VolleyCallback() {
#Override
public void onSuccess(JSONObject result) {
for (int i = 0; i < result.length(); i++) {
try {
JSONObject item = result.getJSONObject(Integer.toString(i));
EventModel eventModel = new EventModel();
String title = item.getString("title");
String start = item.getString("start");
String end = item.getString("end");
String date = item.getString("date");
eventModel.setDate(date);
eventModel.setStartTime(start);
eventModel.setEndTime(end);
eventModel.setTitle(title);
newList.add(eventModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
eventAdapter.update(newList);
}
});
}
}
Many thanks!
First of all, a design consideration: is it necessary to call web service every 10 seconds? Do you know when/how often server data changes?
Every time you read data from web server, application have to do a lot of work: you create many object, update the adapter etc. Moreover, think about network traffic, you use network every 10 seconds.
There are somethings you can do:
Increment wait time: in this way, you reduce the number of created object/per seconds.
Reduce local reference for temporary objects (see following code)
Check if recycler view's adapter, before add new values, the old ones was correctly deferred.
Evaluate if it is possible to use technology to push data, you to avoid data polling. You can see GCM.
For consideration #2, i try rewrite eventToList method:
public void eventToList() {
if (requestData == null) {
requestData = new RequestData(getActivity());
}
requestData.getEventToday(new RequestData.VolleyCallback() {
#Override
public void onSuccess(JSONObject result) {
ArrayList<EventModel> newList = new ArrayList<>();
JSONObject item;
EventModel eventModel;
String title;
String start;
String end;
String date;
for (int i = 0; i < result.length(); i++) {
try {
item = result.getJSONObject(Integer.toString(i));
eventModel = new EventModel();
title = item.getString("title");
start = item.getString("start");
end = item.getString("end");
date = item.getString("date");
eventModel.setDate(date);
eventModel.setStartTime(start);
eventModel.setEndTime(end);
eventModel.setTitle(title);
newList.add(eventModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
eventAdapter.update(newList);
}
});
}

Single button multiple action

I am using a single button to do two task.
Watson Conversation.
Watson Text to Speech.
My code is executing only if my TextView has some Text name (string), but the Text to Speech is playing the last conversation response even though the new conversation response is updated at TextView display on my phone UI.. Continuation of this here Race condition with UI thread issue.
Also I found out, if I keep my TextView empty i get error this:
Code here:
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
reply.setText(textResponse);
System.out.println(textResponse);
}
#Override
public void onFailure(Exception e) {
}
});
return textResponse;
}
}
//
private class WatsonTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(final String... textToSpeak) {
/* runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(" ");
}
});*/
TextToSpeech textToSpeech = initTextToSpeechService();
streamPlayer = new StreamPlayer();
streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute());
return "Text to Speech Done";
}
/*#Override protected void onPostExecute(String result) {
textView.setText("");
}*/
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register the UI controls.
input = (EditText) findViewById(R.id.input);
send = (ImageButton) findViewById(R.id.send);
textView = (TextView) findViewById(R.id.textView);
reply = (TextView) findViewById(R.id.reply);
play = (ImageButton) findViewById(R.id.play);
new ConversationTask().execute("");
//Button function
send.setOnClickListener(action3);
}
//five actions on button click
public void action5() {
String textResponse = new String();
System.out.println("Text to Speech:" + reply.getText());
//textView.setText("");
WatsonTask task = new WatsonTask();
task.execute(String.valueOf(reply.getText()));
//new WatsonTask().execute(reply.getText().toString());
}
View.OnClickListener action3 = new View.OnClickListener() {
public void onClick(View v) {
//action here//
new ConversationTask().execute(input.getText().toString());
action5();
}
};
}
Please help.
Action 3
View.OnClickListener action3 = new View.OnClickListener() {
public void onClick(View v) {
//action here//
new ConversationTask().execute(input.getText().toString());
}
};
Action 5
public void action5(String replyString) {
WatsonTask task = new WatsonTask();
task.execute(replyString);
}
Conversation Task
private class ConversationTask extends AsyncTask<String, Void, String> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
reply.setText(textResponse);
action5(textResponse);
}
#Override
public void onFailure(Exception e) {
}
});
return textResponse;
}
}
WatsonTask
private class WatsonTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(final String... textToSpeak) {
reply.setText(textToSpeak[0]);
TextToSpeech textToSpeech = initTextToSpeechService();
streamPlayer = new StreamPlayer();
streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute());
return textToSpeak[0];
}
}
And for the sake of completeness address to the comment by Marcin Jedynak
I think your program scenario will follow next sequences:
Enter text to conversation task.
Get conversation result from GLS_service.message().
Input the result from sequence 2, for make the voice.
So try to change your code like this.
// There is no need to return String. Just send result to TextToSpeech.
//private class ConversationTask extends AsyncTask<String, Void, String> {
private class ConversationTask extends AsyncTask<String, Void, Void> {
String textResponse = new String();
#Override
protected String doInBackground(String... params) {
System.out.println("in doInBackground");
MessageRequest newMessage = new MessageRequest.Builder().inputText(params[0]).context(context).build();
// async
GLS_service.message("xxxxxxx", newMessage).enqueue(new ServiceCallback<MessageResponse>() {
#Override
public void onResponse(MessageResponse response) {
context = response.getContext();
textResponse = response.getText().get(0);
reply.setText(textResponse);
System.out.println(textResponse);
action5(textResponse); // It is real result that you want.
}
#Override
public void onFailure(Exception e) {
}
});
//return textResponse; // Not necessary.
}
}
//
private class WatsonTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(final String... textToSpeak) {
/* runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(" ");
}
});*/
TextToSpeech textToSpeech = initTextToSpeechService();
streamPlayer = new StreamPlayer();
streamPlayer.playStream(textToSpeech.synthesize(textToSpeak[0], Voice.EN_LISA).execute());
return "Text to Speech Done";
}
/*#Override protected void onPostExecute(String result) {
textView.setText("");
}*/
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Register the UI controls.
input = (EditText) findViewById(R.id.input);
send = (ImageButton) findViewById(R.id.send);
textView = (TextView) findViewById(R.id.textView);
reply = (TextView) findViewById(R.id.reply);
play = (ImageButton) findViewById(R.id.play);
new ConversationTask().execute("");
//Button function
send.setOnClickListener(action3);
}
//five actions on button click
// Need a parameter to get String.
//public void action5() {
public void action5(String text) {
// String textResponse = new String(); // Replace to parameter as "text".
//System.out.println("Text to Speech:" + reply.getText());
System.out.println("Text to Speech:" + text);
//textView.setText("");
WatsonTask task = new WatsonTask();
//task.execute(String.valueOf(reply.getText()));
task.execute(text); // Replace to parameter as "text".
//new WatsonTask().execute(reply.getText().toString());
}
View.OnClickListener action3 = new View.OnClickListener() {
public void onClick(View v) {
//action here//
new ConversationTask().execute(input.getText().toString());
// action5(); // This invoking is not necessary at this point.
// Try to invoke this method after you get conversation result.
}
};
If it is not working even you changed, I want to know how you implement initTextToSpeechService() method.
Hope this helps you.

How to get updated value of EditText in Android

I'm new to android and working on a basic screen to use a web-service with android application.
I am posting values using AsyncTask and fetching the result from the webservice. It works fine until displaying the returned value. While displaying the Toast Message on click, I get old value of TextView resultReturned
public class TestPost extends Activity{
private TextView result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_screen);
result = (TextView)findViewById(R.id.resultReturned);
Button submit = (Button)findViewById(R.id.btnSubmit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] strPost = new String[]{"value1", "value2"};
SendAsyncRequest asyncSend = new SendAsyncRequest();
asyncSend.execute(strPost);
// ResultView retains old value and gets correct value on second click
String returned = result.getText().toString();
Toast.makeText(getApplicationContext(), returned, Toast.LENGTH_LONG).show();
}
});
}
public class SendAsyncRequest extends AsyncTask<String, Void, String>{
private String fetchedData = "";
#Override
protected String doInBackground(String... params ) {
// perform async task
return fetchedData;
}
#Override
protected void onPostExecute(String result) {
setReturedValue(result);
}
}
private void setReturedValue(String data){
result.setText(data);
}
So, how do I get the updated text value of the TextView?
AsyncTask takes time to get response from request, Show toast message in postExecute() method, like this, and remove from onclick.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
Try this
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] strPost = new String[]{"value1", "value2"};
SendAsyncRequest asyncSend = new SendAsyncRequest();
asyncSend.execute(strPost);
// ResultView retains old value and gets correct value on second click
String jsonResult;
try {
jsonResult=asyncSend.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), jsonResult, Toast.LENGTH_LONG).show();
}
});
And return your Json String in doInBackground().

public function in class doesn't work properly

I have a "movie" class and a public function getName(), but the function doesn't return anything, and the logcat is just blank.
public class movie {
public String name45;
int dvd_no ;
public void addData( String name1 , int dvd_no1)
{
this.name45=name1 ;
this.dvd_no = dvd_no1 ;
Log.d("constructor name1", name1);
Log.d("constructor name45", name45);
}
public String getName()
{
return name45 ;
}
}
This is an activity which uses this method - the list always has blank entries.
public class MoviesList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.movieslist);
ListView lvAllMoviesList = (ListView)findViewById(R.id.allmovieslist);
ArrayList<String> moviesNames = new ArrayList<String>();
// go through list of members and compare name with given name
for(movie movie : MovieReg_activity.movies) {
String name = movie.getName();
Log.d("Movie Name list", movie.getName());
moviesNames.add(name);
}
ArrayAdapter<String> AllMovieList = new ArrayAdapter<String>(MoviesList.this,android.R.layout.simple_list_item_1, moviesNames);
lvAllMoviesList.setAdapter(AllMovieList);
}
}
the code which generate objects and add values to it
public class MovieReg_activity extends Activity {
public static List<movie> movies = new ArrayList<movie>();
String movName ;
int dvdNo ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mov_reg_layout);
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
EditText etdvd_no = (EditText)findViewById(R.id.etdvds);
Button btMovie_submit = (Button)findViewById(R.id.btmovsubmit);
movName= etmovie_name.getText().toString();
// dvdNo = Integer.parseInt(etdvd_no.getText().toString()); // to string then to int :)
btMovie_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int x=0 ;
movie movie = new movie() ;
movie.addData(movName, dvdNo);
movies.add(x,movie );
x++ ;
int size =movies.size() ;
Toast.makeText(MovieReg_activity.this, "no of movies added :"+size , Toast.LENGTH_SHORT).show();
}
});
}
}
You are setting the TAG parameter for the logs to the first string, try:
Log.d("DEBUG", "constructor name1 " + name1);
Log.d("DEBUG", "constructor name45 " + name45);
And then set your logcat filter to DEBUG
The problem was in taking the data from the user in the MovieReg_activity
and its solved by putting those two lines
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
movName= etmovie_name.getText().toString();
inside the button listener to be like this
public void onClick(View v) {
int x=0 ;
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
movName= etmovie_name.getText().toString();
movies.add(new movie(movName , dvdNo) );
String name3= movie.getName() ;
x++ ;
int size =movies.size() ;
Toast.makeText(MovieReg_activity.this, "no of movies added :"+size , Toast.LENGTH_SHORT).show();
}
});

AsynkTask within Fragment within a ViewPager

First of all, I am relatively new to android programming.
I am creating a ViewPager application with two Fragments. One of the Fragments requests data from a server and return a result to the main FragmentActivity. My problem is that this request to the server can take sometime, and I have been trying to get a ProgressDialog to appear with AsyncTask while the user waits for the data to be retrieved. Once I create the background thread to retrieve the data, I successfully execute some code in the onPostExecute() method and set some variables. However, the return statement that sends information back to the FragmentActivity is being executed before the background thread actually ends. I can't seem to figure out a way for the main thread to wait on the background thread. Using Asyctask's get() method results in the ProgressDialog from appearing. I have looked through a lot of posts in here, but can't seem to find an answer.
Anything helps.
Code below:
SplashScreen.java
public class SplashScreen extends FragmentActivity {
MainMenu mainMenu;
MapScreen mapScreen;
PagerAdapter pagerAdapter;
ViewPager viewPager;
List<LatLng> geoPoints;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
context = this;
initializePaging();
}
private void initializePaging()
{
mainMenu = new MainMenu();
mapScreen = new MapScreen();
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(mainMenu);
pagerAdapter.addFragment(mapScreen);
viewPager = (ViewPager) super.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageScrollStateChanged(int postion){}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2){}
#Override
public void onPageSelected(int position)
{
switch(position){
case 0: findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
break;
case 1: findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
break;
}
}
});
}
//Called from onClick in main_mainu.xml
public void getDirections(View view)
{
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
try
{
geoPoints = mainMenu.getDirections(context);
mapScreen.plotPoints(geoPoints);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error! Invalid address entered.", Toast.LENGTH_LONG).show();
mainMenu.clear();
}
}
}
MainMenu.java
public class MainMenu extends Fragment {
String testString;
int testInt;
TextView testTV;
private TextView tvDisplay;
private EditText departure;
private EditText destination;
private Geocoder geocoder;
private List<Address> departAddress;
private List<Address> destinationAddress;
private List<LatLng> geoPoints;
private String departString;
private String destinationString;
private Address departLocation;
private Address destinationLocation;
private LatLng departurePoint;
private LatLng destinationPoint;
private Context contextMain;
private GetData task;
public MainMenu()
{
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View root = (View) inflater.inflate(R.layout.main_menu, null);
geoPoints = new ArrayList<LatLng>(2);
return root;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
departure = (EditText) getView().findViewById(R.id.depart_field);
destination = (EditText) getView().findViewById(R.id.destination_field);
tvDisplay = (TextView) getView().findViewById(R.id.textView1);
}
public List<LatLng> getDirections(Context context)
{
contextMain = context;
geocoder = new Geocoder(getActivity());
departString = departure.getText().toString();
destinationString = destination.getText().toString();
try
{
task = new GetData(new Callback(){
public void run(Object result)
{
//return geoPoints;
}
});
task.execute((Void[])null);
}catch(Exception e)
{
e.printStackTrace();
}
return geoPoints;
}
public void clear()
{
departure.setText("");
destination.setText("");
tvDisplay.setText("Enter departure point, and destination point");
}
private class GetData extends AsyncTask<Void, Void, List<List<Address>>>
{
Callback callback;
private ProgressDialog processing;
public GetData(Callback callback)
{
this.callback = callback;
}
#Override
protected void onPreExecute()
{
processing = new ProgressDialog(contextMain);
processing.setTitle("Processing...");
processing.setMessage("Please wait.");
processing.setCancelable(false);
processing.setIndeterminate(true);
processing.show();
}
#Override
protected List<List<Address>> doInBackground(Void...arg0)
{
List<List<Address>> list = new ArrayList<List<Address>>(2);
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
list.add(departAddress);
list.add(destinationAddress);
}catch(IOException e)
{
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(List<List<Address>> list)
{
departLocation = list.get(0).get(0);
destinationLocation = list.get(1).get(0);
departurePoint = new LatLng(departLocation.getLatitude(), departLocation.getLongitude());
destinationPoint = new LatLng(destinationLocation.getLatitude(), destinationLocation.getLongitude());
if(geoPoints.size() >= 2)
{
geoPoints.clear();
}
geoPoints.add(departurePoint);
geoPoints.add(destinationPoint);
callback.run(list);
processing.dismiss();
}
}
}
#Override
protected Object doInBackground(Void...arg0)
{
Object result = null;
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
You never set the value of result...

Categories

Resources