Why is my AsyncTask running on the main thread? - java

I have a tab fragment inside of a container activity.
I would like to download some data to display in the tab. In the tab, I have made an asynctask that I execute just after inflating the fragment layout in onCreateView. When I do it this way, the AsyncTask's doInBackground... work occurs on the main thread and the view does not load until it is done. All of my progress... logs show up at the same time as soon as the task is done.
However, if I put a button in the fragment layout and start the asynctask work as a response to the button click, it works as expected, I get my normally spaced progress updates.
So, why does AsyncTask run on the main thread if it is the first thing to happen when my fragment starts? And, how can I prevent this? My ultimate goal is to show a progress wheel while the data is downloading.
Edit. Here is where I call my AsyncTask.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.temp_my_moments, container, false);
getMyClips(getActivity(), rootView, p_session, p_person,progressBar);
//If I use this button, it works fine:
// test = (Button) rootView.findViewById(R.id.testbutton);
// test.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// progressBar =(ProgressBar) rootView.findViewById(R.id.myMomentsProgress);
// getMyClips(getActivity(), rootView, p_session, p_person, progressBar);
// }
// });
return rootView;
}
And here is getMyClips():
public void getMyClips(Context context,View view,String thisSession,String thisPerson,ProgressBar progressBar) {
Log.d("Currently running", "getMyClips");
JSONObject params = new JSONObject();
try {
params.put("Function", clipsMine_apiCall);
params.put("p_session", thisSession);
params.put("p_person", thisPerson);
} catch (JSONException e1) {
e1.printStackTrace();
}
ApiClipCaller webServiceTask = new ApiClipCaller(context,view,progressBar);
if (webServiceTask.hasConnection()) {
webServiceTask.execute(params);
} else {
//TODO no internet connection
}
}
Edit Here is my AsyncTask. This is inside the Fragment:
public class ApiClipCaller extends AsyncTask<JSONObject, Integer, ApiResponse> {
public Context context;
public String clipID;
public String sessionID;
public String personID;
public String functionName;
public View view;
public ProgressBar progressBar;
public final String apiURL = "...."; //need to keep private
LinearLayout loading;
public ApiClipCaller(Context c, View v,ProgressBar progressBar) {
this.context = c;
this.view = v;
this.progressBar = progressBar;
loading = (LinearLayout) view.findViewById(R.id.loadingMyMoments);
}
#Override
protected ApiResponse doInBackground(JSONObject... params) {
JSONObject realParams = params[0];
try {
functionName = realParams.getString("Function");
} catch (JSONException e) {
e.printStackTrace();
}
ApiResponse responseObject = masterFunction(realParams);
//making some work to see if it is running correctly
for (int i=10;i<=100;i += 10)
{
try {
Thread.sleep(1000);
publishProgress(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return responseObject;
}
#Override
protected void onProgressUpdate(Integer... progress) {
loading.setVisibility(View.VISIBLE);
progressBar.setProgress(progress[0]);
Log.d("progress",Integer.toString(progress[0]));
}
#Override
protected void onPostExecute(ApiResponse responseObject) {
loading.setVisibility(View.GONE);
if (functionName.equals(clipsMine_apiCall)) {
JSONObject clipObject = responseObject.getResponseJSONObject();
//just testing here to see if I can get data back in the fragment view when it is done.
///This works as expected.
String responseString = responseObject.getResponseString();
TextView showAsyncResults = (TextView) view.findViewById(R.id.testAsyncTask);
showAsyncResults.setText(responseString);
}
super.onPostExecute(responseObject);
}
}

So, it seems like the answer is that I was going about this all wrong. It it is not possible to launch asynctask when the first activity or fragment loads, because the onCreate etc. methods are not actually on the UI thread. So, AsyncTask cannot be executed directly from there, as Ordous pointed out.
Instead, it seems like the solution is to load information when the application first starts by creating a class which extends Application and doing the loading work from there, because this will necessarily be on the main thread. The methods in there can be called from the activity to access the layouts and make a progress bar or similar.
Reference: http://developer.android.com/reference/android/app/Application.html
A good example: http://www.intertech.com/Blog/androids-application-class/

Related

AsyncTask operation with return type

I am new to android developing, as a part of my learning, I am making a multilingual news reader application, where the application is fetching rss feeds from google news and parses.
for this, I am using tabbed view for showing multiple languages, user can swipe through different language. application contains Hindi,Malayalam,English, and Tamil tabs, all lists particular news items.
each language view page is separate fragment. and there are totally four fragments is there in the application and main activity holds all these.
for all these fragments I have one AsyncTask extended class, which loads and parses news from the server.and returns an array list on its doInBackground method, but the problem with this is when I swiping from one tab to another it works very slow. I am pasting my code down. I think my AsyncTask usage is not correct, because I am showing a progress bar in onPreExecute method, but it also not showing in proper.
please anyone look on to my code and help me to correct
EnglishNewsFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<HashMap<String, String>> newsWrapper;
context = getActivity();
View rootView = inflater.inflate(R.layout.english_news_fragment, container, false);
NewsLoader newsLoader = new NewsLoader(context, language);
newsLoader.execute();
try {
newsWrapper = newsLoader.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
showNews(newsWrapper);
}
return rootView;
}
NewsLoader
public class NewsLoader extends AsyncTask{
public NewsLoader(Context context, String language) {
this.context = context;
this.language = language;
}
#Override
protected void onPreExecute() {
startDialogue();
initAll(language);
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
getNews();
news = processXML();
} catch (Exception e) {
e.printStackTrace();
}
return news;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> aVoid) {
super.onPostExecute(aVoid);
stopDialogue();
}
}
UPDATE
AsyncTask.get() blocks the UI. so that I have to implement a call back interface, can anyone help me to do it I have read a little from here but how will be its calling and how do I pass the result to MainActivity ?
Screen shot
The Asynctask.get() method blocks the UI until doInBackground() finished. You can use instead the onPostExecute() to deliver result back on the UI.
The slowdown or bottleneck in the UI is probably coming from onPreExecute() or onPostExecute(). Add code like Log.d() and print the timing difference to see which code causes the bottleneck. For example, code initAll(language) may be moved to the non-UI thread of doInBackground(). Perhaps that method is slow. Basically with onPreExecute and onPostExecute, be quick in whatever needs to be done.
I think you don't need to call super.onPreExecute() or super.onPostExecute(aVoid). Google's sample does not do so or suggest to # AsyncTask. Maybe that causes the bottleneck also.
Hope that helps...
I have got the answer.
I have made a callback interface for passing the result to Fragment
public interface CallBackReciever {
public void recieveData(ArrayList<HashMap<String,String>> result);
}
and implemented this interface with fragment.
then passed a context of this interface to AsyncTask. and in its onPostExecute() method invoked recieveData() method
Fragment
#Override
public void recieveData(ArrayList<HashMap<String, String>> result) {
newsWrapper = result;
showNewsOnUI();
}
AsyncTask
public class NewsLoader extends AsyncTask<Void, Void, ArrayList<HashMap<String, String>>>{
public NewsLoader(CallBackReciever callBackReciever) {
this.callBackReciever = callBackReciever;
}
#Override
protected void onPreExecute() {
startDialogue();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
initAll(language);
result = processNews()
return result;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
stopDialogue();
callBackReciever.recieveData(result);
}
}

Dynamic UI Progress Updates using Interface + ExecutorService Issue

So I have a music application. I am trying to update the UI with the progress of the media player (like current time, current song, album cover) everytime the song changes. I found that using interfaces was a awesome magical way of communication between activity and fragments so I implemented an interface in my MusicManger class. My code will show what and how did it.
Two problems
1) Commented look below, ExecutorService seems to stop after one loop. No Errors in catch block (this is why I tagged with java)
2) Commented please look, All the System.out methods print but the UI doesn't update. I do believe I called the method from mainThread so it should update.
I'll show code in logical order will add titles in bold before code segment to tell you basic idea of code.
Passing UI references from fragment to MusicManager class, code below in Fragment class
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_songlist, container, false);
// Set the adapter
TextView musicManagerSongName, musicManagerCurrent, musicManagerTotal;
ProgressBar musicManagerProgress;
ImageView musicManagerImageView;
mListView = (AbsListView) view.findViewById(R.id.slist);
musicManagerSongName = (TextView)view.findViewById(R.id.textView12);
musicManagerCurrent = (TextView)view.findViewById(R.id.textView10);
musicManagerTotal = (TextView)view.findViewById(R.id.textView11);
musicManagerProgress = (ProgressBar)view.findViewById(R.id.progressBar);
musicManagerImageView = (ImageView)view.findViewById(R.id.imageView2);
MainActivity.mediaPlayer.passUIReferences(musicManagerSongName, musicManagerCurrent, musicManagerTotal, musicManagerProgress, musicManagerImageView, view);
// line above is a method within MusicManager that takes the references will show code next!
ImageButton playbutton = (ImageButton)view.findViewById(R.id.playbuttonbar);
ImageButton nextButton = (ImageButton)view.findViewById(R.id.nextbuttonbar);
ImageButton backButton = (ImageButton)view.findViewById(R.id.backbuttonbar);
ImageButton toggleButton = (ImageButton)view.findViewById(R.id.shufflebuttonbar);
ImageButton pausebutton = (ImageButton)view.findViewById(R.id.pausebuttonbar);
playbutton.setBackgroundResource(R.drawable.playbuttonbar);
playbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
MainActivity.mediaPlayer.stateChange(1);
}catch(Exception e) {
}
}
});
backButton.setBackgroundResource(R.drawable.backbutton1);
nextButton.setBackgroundResource(R.drawable.nextbutton1);
toggleButton.setBackgroundResource(R.drawable.shufflebuttonselected);
pausebutton.setBackgroundResource(R.drawable.pausebutton1);
pausebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
MainActivity.mediaPlayer.stateChange(0);
} catch (Exception e){
}
}
});
mListView.setAdapter(mAdapter);
((MainActivity) mListener).restoreActionBar();
return view;
}
As Commended above the code that is located in MusicManager class that takes references and stores them. Also shows interface implementation with MusicManager class. And the Executor service
public void passUIReferences(View... views) {
this.uiElements = views;
}
private ExecutorService executorService = Executors.newSingleThreadExecutor();
private MediaplayerUpdateInterface uiUpdateInterface;
public MediaPlayerManager(MediaplayerUpdateInterface inter) {
this.player = new MediaPlayer();
this.uiUpdateInterface = inter;
// The below line starts the single thread while loop for excutorservice and only loops and prints "this" once after I start one song then it never loops again
executorService.submit(new Runnable() {
#Override
public void run() {
while(true) {
if (player.isPlaying() && uiElements != null) {
System.out.println("this");
uiUpdateInterface.updateUI(uiElements, 0);
}
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
public interface MediaplayerUpdateInterface {
public void updateUI(View[] views, int type);
}
Finally some code from MainActivity class that actually is suppose to update the UI note that both println's work as expected but only once as stated above because of the executorservice issue
public static MediaPlayerManager mediaPlayer = new MediaPlayerManager(new MediaPlayerManager.MediaplayerUpdateInterface() {
#Override
public void updateUI(View[] views, int type) {
System.out.println("check1 " + type);
updateMediaplayerViews(views, type);
}
});
private static void updateMediaplayerViews(View[] views, int type)
{
switch(type) {
case 0:
System.out.println("that?");
((TextView)views[0]).setText(mediaPlayer.getCurrentSongInfo().getName().length() > 22? mediaPlayer.getCurrentSongInfo().getName().substring(0, 19)+"..." : mediaPlayer.getCurrentSongInfo().getName());
break;
}
views[views.length - 1].invalidate();
}
The view array is shown perviously! Also the last view in the array is shown as the main view for songlist fragment.
I am sorry for all the code I've tried to debug it as you can see from my println's there is just something I am unaware of going on here.
Ok so there was an error that I needed to catch to see within the following code:
private static void updateMediaplayerViews(View[] views, int type)
{
switch(type) {
case 0:
System.out.println("that?");
((TextView)views[0]).setText(mediaPlayer.getCurrentSongInfo().getName().length() > 22? mediaPlayer.getCurrentSongInfo().getName().substring(0, 19)+"..." : mediaPlayer.getCurrentSongInfo().getName());
break;
}
views[views.length - 1].invalidate();
}
The issue is I was trying to change the view from a different thread then the one which created it. Solving it was pretty long and painful but basically I made it nonstactic used more interfaces then used the famous
Mainactivity.runOnUiThread(new Runnable(....));

Android communication between main thread and other thread

I want to change dynamically the text of a textview, but I will need the same logic if I want to make a game thread, so I need to make the communication between the main one and the second one.
I have the files :
MainActivity
public class MainActivity extends ActionBarActivity {
public static Handler mHandler;
Runnable thread = new SampleThread();
TextView txt1 = (TextView) findViewById(R.id.txt1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
//hiding status bar
if (Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
setContentView(R.layout.activity_main);
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
// i want to change the text of txt1 here
}
};
new Thread(thread).start();
}
}
SampleThread
package com.example.katsar0v.myapplication;
import android.util.Log;
/**
* Created by Katsar0v on 1/21/2015.
*/
public class SampleThread implements Runnable {
#Override
public void run() {
int two = 0;
while(two<10) {
two++;
try {
Thread.sleep(1000);
//instead of logging, i want to send the text to main UI
Log.d("MSG", String.valueOf(two + "sec"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The problem I see is, how do I change the text with the handler, when my thread is in another file? Or should I make the second class static within the first one (and what should I do when the code gets really long, it can't be all in one file)?
You could implement a custom Interface in order to handle it from your main activity.
On your SampleThread:
public interface TextViewChangeListener
{
public void onTextViewChanged(String newName);
}
TextViewChangeListener mListener;
Then call mListener.onTextViewChanged(String newName) wherever you want to have the new name in your TextView. Remember to initialize mListener with an instance of your MainActivity first, otherwise you will get a null pointer exception. You can do that either in the constructor of SampleThread or by creating a method for the purpose.
In your activity you should implement SampleThread.TextViewChangeListener and override the onTextViewChanged.
#Override
public void onTextViewChanged(String newName)
{
//MyTextView.setText(newName);
}
Edit: untested code:
MainActivity:
public class MainActivity extends ActionBarActivity implements SampleThread.TextViewChangeListener {
#Override
public void onTextViewChanged(Message msg)
{
// process incoming messages here
// i want to change the text of txt1 here
}
public static Handler mHandler;
Runnable thread = new SampleThread(this);
TextView txt1 = (TextView) findViewById(R.id.txt1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
//hiding status bar
if (Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
setContentView(R.layout.activity_main);
new Thread(thread).start();
}
}
SampleThread:
package com.example.katsar0v.myapplication;
import android.util.Log;
/**
* Created by Katsar0v on 1/21/2015.
*/
public class SampleThread implements Runnable
{
public interface TextViewChangeListener
{
public void onTextViewChanged(Message msg);
}
public SampleThread(TextViewChangeListener mListener)
{
this.mListener = mListener;
}
TextViewChangeListener mListener;
#Override
public void run() {
int two = 0;
while(two<10) {
two++;
try {
Thread.sleep(1000);
mListener.onTextViewChanged(String.valueOf(two + "sec"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Let me know if that helped.
You can find some examples in Grafika, which does a lot of work off the UI thread. For example, TextureFromCameraActivity has a pair of handlers, one for the UI thread, one for the renderer thread. In onResume() you can see the main thread passing its handler to the renderer through a constructor, then retrieving the renderer thread's handler with a method call.
ContinuousCaptureActivity has a slightly different approach, using a Handler that also implements a callback interface. The handler object is passed to the CircularEncoder constructor as an interface instance. The public callback methods use the Handler internally.
The only tricky bit is if you're passing a Handler out of the non-UI thread. You either need to do it before the thread starts, or use appropriate thread synchronization operations to avoid data races.
You don't need to have your classes in the same file (and you really shouldn't unless one is nested inside the other). If they're in the same package then the default (package) scope will let them see each other. The first example from Grafika uses nested / private classes, the second example is more spread out.
Of course, if all you're trying to do is submit UI events from a non-UI thread, you can just use Activity.runOnUiThread().

Errors in fragment class

So I am converting my application, after loads of research I decided to convert my Activities into Fragments. That was a success, but now the slightly harder part comes in, to implement the code from my Activity to the fragments. So I used getView(). and getActivity(). to fix the issues, and all was fine. As you can see below...
public class HomeFragment extends Fragment {
public static HomeFragment newInstance(String title) {
HomeFragment homeFragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
homeFragment.setArguments(bundle);
return homeFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_activity_home, container, false);
// Time function - Displays timeview on Card
final boolean keepRunning = true;
Thread thread = new Thread(){
#Override
public void run(){
while(keepRunning){
// Make the thread wait half a second (if you're only showing time up to seconds, it doesn't need to be updating constantly)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
TextView time = (TextView) getView().findViewById(R.id.time);
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
}
});
}
}
};
thread.start();
// Date function - Displays dateview on Card
final boolean keepRunning1 = true;
Thread thread_two = new Thread(){
#Override
public void run(){
while(keepRunning1){
// Make the thread wait half a second. If you want...
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable(){
#Override
public void run(){
TextView date = (TextView) getView().findViewById(R.id.date);
date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
}
});
}
}
};
thread_two.start();
return view;
}
}
When running the application, it displays the app for approx 2 secs and then force closes, so I checked the logs for any errors. And this came up --
05-20 16:54:17.213: E/AndroidRuntime(26473): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
05-20 16:54:17.213: E/AndroidRuntime(26473): at com.activelauncher.fragments.HomeFragment$1$1.run(HomeFragment.java:54)
I'm fairly new to Fragments I have had more experience working with Activities so I don't know what the issue is here. So I check line 54 and it was this line --
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
However I don't see any issues or errors there? Is there something I am missing?
Thanks for reading this.
Change this
TextView time = (TextView) getView().findViewById(R.id.time);
to
TextView time = (TextView) view.findViewById(R.id.time);
And make this final
final View view;
Simailarly
TextView date = (TextView) view.findViewById(R.id.date);
Try this..
Change this..
TextView time = (TextView) getView().findViewById(R.id.time);
time.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
to
TextView time = (TextView) view.findViewById(R.id.time);
time.setText(""+DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
and also
TextView date = (TextView) view.findViewById(R.id.date);
date.setText(""+DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));

Android: Updating gridview multiple times after x seconds

I am having a problem updating the view in android every x seconds.
To get to know how android works I am writing a small game.
It has a GameController which holds the game loop. Inside the loop, the logic is executed and afterwards the gui will be informed about the changes.
The problem is that the changes cannot be seen in the view. The view stays the same until the game loop finishes and updates then only once.
Here is my code (the important parts):
GameController.java:
IGui gui;
public void play() {
while (playing) {
getAndProcessInput();
updateGui();
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
}
}
}
private void updateGui() {
gui.setPlayer(x, y);
// ...
}
GameActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.GridView1);
TextAdapter = new TextAdapter(this);
gridview.setAdapter(textAdapter);
GameController c = new GameController();
// here, the game loop shoud start.
// what i tried:
// new Thread(c).start(); <-- causes crash
// c.play(); <-- causes view to frease until game loop is done
this.runOnUiThread(c); <-- causes view to frease until game loop is done
}
TextAdapter.java:
public class TextAdapter extends BaseAdapter implements IGui {
private final Context context;
private final String[] texts;
public TextAdapter(Context context) {
this.context = context;
texts = new String[height * width];
for (int i = 0; i < texts.length; i++) {
texts[i] = " ";
}
}
public int getCount() {
return height * width;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(context);
tv.setLayoutParams(new GridView.LayoutParams(25, 25));
} else {
tv = (TextView) convertView;
}
tv.setText(texts[position]);
return tv; // <-- this happens only when game loop is done, not everytime something changed
}
#Override
public void setPlayer(int x, int y) {
texts[width * y + x] = "X";
// this.notifyDataSetChanged(); <-- this does not help (view still freases)
// gridview.invalidateViews(); does not help either
}
}
I googled a lot and tried a lot as well (and I do know that similar questions where asked here already, but they did not help me either), but somehow it just does not work.
I cannot get it do work that the view and logic run on different theads in android, and if they run on the same thread the logic blocks the view.
Any help would be greatly appreciated.
// edit:
If I try new Thread(c).start(); LogCat sais:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
And if I add Looper.prepare(); :
java.lang.RuntimeException: Unable to start activity ComponentInfo{GameActivity}: java.lang.RuntimeException: Only one Looper may be created per thread
If I try this.runOnUiThread(c); there are no errors.
First, this doesn't seems like the way to crate a game, you will need to use SurfaceView, or GLSurfaceView to better do what you want.
You can also look for Cocos2d for android, it's a 2D platform (that was ported from iPhone) that makes you life easier:
http://code.google.com/p/cocos2d-android/
I muse warn you though, I tried it a couple months back, and it was not production grade yet, it did crash from time to time.
Anyway, if you still want to continue heading your way I'll try answering your question:
I think you are messing too much with the way these stuff should work. try understanding first how handlers work with threads.
Do anything you want on your thread:
new Thread(new Runnable()
{
#Override
public void run()
{
try
{
calculateGameChangesHere();
handler.sendEmptyMessage(SUCCESS);
}
catch (Exception e)
{
handler.sendEmptyMessage(FAILURE);
}
}
}).start();
When your data is ready, tell the handler to put it in a view and show it:
protected Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == SUCCESS)
{
setCalculatedDataToaView(); // the data you calculated from your thread can now be shown in one of your views.
}
else if (msg.what == FAILURE)
{
errorHandlerHere();//could be your toasts or any other error handling...
}
}
};
This goes to everything that requires heavy processing/networking that shouldn't block your UI thread.
Hope this helps.
Not sure what you are trying to achieve by refreshing a listView every few seconds. Anyways if you are writing some 2d games, you have to use SurfaceView , which is especially meant for continuous refreshing.
Had the same problem and solved it using a pretty simple code.
Tips:
GridView must be refreshed by the UI thread
To display every change you must keep the loop and the Sleep method away from the UI thread
Solution:
Method to update the grid (put on your Activity that you build your GridView at the first place or wherever)
public void UpdateGrid(){
//your logic
//your way to change grid values (there are tones of other ways)
CustomGridAdapter cga = new CustomGridAdapter(this, values);
gridView.setAdapter(cga);
gridView.invalidateViews();
}
Build the non UI Thread that does the work
public class DataReceiver implements Runnable {
private MainActivity mainActivity;
public DataReceiver(MainActivity ma) {
mainActivity = ma;
}
#Override
public void run() {
for (int i = 0; i < 100; i++) {
mainActivity.runOnUiThread(new Runnable() {
public void run() {
//update the grid here
mainActivity.UpdateGrid();
}
});
//sleep here
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Categories

Resources