Can anyone help me out that why is the function getInBackground is not running i want to fetch the data from parse in android.
This is my class which calls the function of fetchData(String themeId) in parseManipulate class
public class selectTheme extends Activity implements OnClickListener{
Button gBtn;
Button rBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.themeselection);
String themeid = "ECGo4oSKgU";
ParseManipulate pm = new ParseManipulate();
pm.fetchData(themeid);
/* gBtn = (Button)findViewById(R.id.greentheme);
rBtn = (Button)findViewById(R.id.redtheme);
gBtn.setOnClickListener(this);
rBtn.setOnClickListener(this);
*/
}
And this is my fetchData() function in ParseManipulate class.compiler does not run the function getInBackground() function and jumps at the end of function closing bracket
public class ParseManipulate {
public void fetchData(String ThemeId)
{
ParseQuery<ParseObject> pq = ParseQuery.getQuery("testThemes");
pq.getInBackground(ThemeId, new GetCallback<ParseObject>(){
#Override
public void done(ParseObject object, ParseException e) {
// TODO Auto-generated method stub
if(e == null)
{
// value = object.getString("ThemeName");
Log.d("ParseObject", ""+object.getString("ThemeName"));
}
else
{
// Toast.makeText(getApplicationContext(), "error in data fetching", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Instead of
Log.d("ParseObject", ""+object.getString("ThemeName"));
Use it like this
Log.d("ParseObject", ""+object.fetchIfNeeded().getString("ThemeName"));
Related
I want to display this textview "txtCalculate" which comes from the class CustomerMapActivity which is displayed in the activity_map_customer layout in another layout which is activity_bon_de_commande, of the class BonDeCommande.
the problem is I don't know how to do it
I'm new to java programming
thank you
public void readValues(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query lastQuery = ref.child("ride_info").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
double value0_float = ds.child("pickup").child("lat").getValue(Double.class);
double value1_float = ds.child("pickup").child("lng").getValue(Double.class);
double value2_float = ds.child("destination").child("lat").getValue(Double.class);
double value3_float = ds.child("destination").child("lng").getValue(Double.class);
String pickupLat = String.valueOf(value0_float);
String pickupLng = String.valueOf(value1_float);
String destiLat = String.valueOf(value2_float);
String destiLng = String.valueOf(value3_float);
String requestUrl=null;
try {
requestUrl = "https://maps.googleapis.com/maps/api/directions/json?"+
"mode=driving&"
+"transit_routing_preference=less_driving&"
+"origin="+pickupLat+","+pickupLng+"&"
+"destination="+destiLat+","+destiLng+"&"
+"key="+getResources().getString(R.string.google_maps_key);
Log.e("LINK",requestUrl);
mService.getPath(requestUrl).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject object = routes.getJSONObject(0);
JSONArray legs = object.getJSONArray("legs");
JSONObject legsObject = legs.getJSONObject(0);
//Get distance
JSONObject distance = legsObject.getJSONObject("distance");
String distance_text = distance.getString("text");
//use regex to extract double from string
//This regex will remove all text not digit
Double distance_value= Double.parseDouble(distance_text.replaceAll("[^0-9\\\\.]+",""));
//Get Time
JSONObject time = legsObject.getJSONObject("duration");
String time_text = time.getString("text");
Integer time_value = Integer.parseInt(time_text.replaceAll("\\D+",""));
String final_calculate = String.format("%.2f €",
TypeObject.getPrice(distance_value,time_value));
HERE -----> txtCalculate.setText(final_calculate);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
mCurrentRide.cancelRide();
endRide();
}
});
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
mCurrentRide.cancelRide();
endRide();
}
});
}
screenshot of my screen
You need to Create an Interface with an update method, declare in your Activity and after, pass as parameter to your handler object that gets the data.
Don't forget If you're getting the data in a different Thread, you need to update your views always in an UI Thread or in the Main Thread.
Here Follow some example code:
Your Activity or Fragment
public class MainActivity extends AppCompatActivity
implements UpdateViewCallback { // implement the interface here
private TextView textView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = findViewById(R.id.textView);
// Pass the interface in your Object that makes the async work
final AsyncWork asyncWork = new AsyncWork(this);
// Running
Thread thread = new Thread(asyncWork);
thread.start();
}
/**
* UpdateViewCallback
* #param result
*/
#Override
public void updateView(final String result) {
// Always update View on MainThread or an UI Thread, or else issues will start to happening
this.runOnUiThread(new Runnable() {
public void run() {
// Check if View is null since you're updating in a thread async
if (textView != null) {
textView.setText(result);
}
}
});
}
}
Your Interface:
public interface UpdateViewCallback {
void updateView(String result);
}
Your Object to handle the Async Work:
public class AsyncWork implements Runnable {
private UpdateViewCallback updateViewCallback;
public AsyncWork(UpdateViewCallback updateViewCallback) {
this.updateViewCallback = updateViewCallback;
}
/**
* Async Work here
*/
#Override
public void run() {
// Do some Work and after update using the interface you passed in the constructor
updateViewCallback.updateView("This is a test");
}
}
EDITED:
The real purpose of that is to have one activity and on class who fetch data and render it to the activity.
The problem is I have dropdown menu. When I clicked on an item of the menu it change my url but it does not load or fetch my data to the activity but when i clicked again it works but with the paramaters selected just before and if I clicked again it still works but still with the previous elements selected.
My "teacher" said I have to call build into my callback method.
But it doesen't work at all. And I still didn't find any solution :/.
As you recommended I changed everything for non-static method
I thought why not saving an history of the dropdown, compare the current value with the saved value and if it's diffrent it means it was changed so reload the app to make new fetch and displyed new data.
But I got :
Here my all code
PhotosActivity
public class PhotosActivity extends AppCompatActivity {
// Local variable
private OkHttpClient httpClient;
private ImageButton home_btn;
private ImageButton favorites_btn;
private ImageButton search_btn;
private ImageButton profil_btn;
// Constante variable
private static final String TAG = "PhotoActivity";
private static final String clientId = "bb0c749c6403fd2";
// Private shared variable
private static List<Photo> mPhotos;
private static JSONArray mItems;
private static String mAccessToken;
private static String userID;
static Activity activity;
// Shared variable
private static String selectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
this.home_btn = findViewById(R.id.home_button);
this.favorites_btn = findViewById(R.id.favorites_button);
this.search_btn = findViewById(R.id.search_button);
this.profil_btn = findViewById(R.id.profil_button);
final HttpHandler httpHandler = new HttpHandler();
httpHandler.fetchData();
build();
activity = this;
Spinner spinner=(Spinner)findViewById(R.id.spinner);
String[] filters=getResources().getStringArray(R.array.filters);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner,R.id.text, filters);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
selectedItem = parent.getItemAtPosition(position).toString();
// httpHandler.fetchData();
// build();
}
public void onNothingSelected(AdapterView<?> parent)
{
Log.d("TAG", "Error");
}
});
home_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), PhotosActivity.class);
finish();
startActivity(next_activity);
}
});
favorites_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
finish();
startActivity(next_activity);
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), SearchActivity.class);
finish();
startActivity(next_activity);
}
});
profil_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), ProfileActivity.class);
finish();
startActivity(next_activity);
}
});
}
public void Filters() {
String hSection;
String hSort;
String hShowV;
hSection = HttpHandler.section ;
hSort = HttpHandler.sort;
hShowV = HttpHandler.showV;
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
if(selectedItem != null) {
if (selectedItem.equals("Most Viral")) {
HttpHandler.sort = "viral/";
HttpHandler.section = "hot/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "most: "+HttpHandler.section);
Log.d("TAG", "H most: "+hSection);
// activity.recreate();
// onRestart();
finish();
startActivity(next_activity);
}
} else if (selectedItem.equals("Newest")) {
HttpHandler.section = "top/";
HttpHandler.sort = "time/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "new: "+HttpHandler.section);
Log.d("TAG", "H new: "+hSection);
finish();
startActivity(next_activity);
// activity.recreate();
// onRestart();
}
} else if (selectedItem.equals("Rising")) {
HttpHandler.section = "user/";
HttpHandler.sort = "rising/";
HttpHandler.showV = "?showViral=false";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "rising: "+HttpHandler.section);
Log.d("TAG", "H rising: "+hSection);
// onRestart();
// activity.recreate();
finish();
startActivity(next_activity);
}
} else {
Log.d(TAG, "Might be a problem");
}
} else {
activity.recreate();
}
}
public void build () {
try {
for(int i = 0; i < mItems.length(); i++) {
JSONObject item = mItems.getJSONObject(i);
Photo photo = new Photo();
if(item.getBoolean("is_album")) {
photo.id = item.getString("cover");
} else {
photo.id = item.getString("id");
}
photo.title = item.getString("title");
mPhotos.add(photo);
runOnUiThread(new Runnable() {
#Override
public void run() {
render(mPhotos);
}
});
}
} catch (Exception e) {
Log.e("JSONerr" , "Something went wrong.");
}
}
private static class PhotoVH extends RecyclerView.ViewHolder {
ImageView photo;
TextView title;
public PhotoVH(View itemView) {
super(itemView);
}
}
private void render(final List<Photo> photos) {
RecyclerView rv = (RecyclerView)findViewById(R.id.rv_of_photos);
rv.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.Adapter<PhotoVH> adapter = new RecyclerView.Adapter<PhotoVH>() {
#NonNull
#Override
public PhotoVH onCreateViewHolder(ViewGroup parent, int viewType) {
PhotoVH vh = new PhotoVH(getLayoutInflater().inflate(R.layout.item, null));
vh.photo = (ImageView) vh.itemView.findViewById(R.id.photo);
vh.title = (TextView) vh.itemView.findViewById(R.id.title);
return vh;
}
#Override
public void onBindViewHolder(PhotoVH holder, int position) {
Picasso.with(PhotosActivity.this).load("https://i.imgur.com/" +
photos.get(position).id + ".jpg").into(holder.photo);
holder.title.setText(photos.get(position).title);
}
#Override
public int getItemCount() {
return photos.size();
}
};
rv.setAdapter(adapter);
}
public static void getUserID(String UserID) {
Log.d("TAG", UserID);
userID = UserID;
}
public void callBackPhoto( List<Photo> photos, JSONArray items)
{
mPhotos = photos;
mItems = items;
// build();
}
}
HttpHandler
public class HttpHandler {
private static final String TAG = "HttpHandler";
private static String clientId = "bb0c749c6403fd2";
private static OkHttpClient httpClient;
private static String mAccessToken;
// URL BUILDER VARIABLES
public static String section = "hot/";
public static String sort = "viral/";
public static String page;
public static String showV;
public static String mUrl;
public void fetchData() {
httpClient = new OkHttpClient.Builder().build();
photosActivity.Filters();
mUrl = "https://api.imgur.com/3/gallery/" + section + sort;
// Log.d("TAG", "Sort: " + sort + ": URl is" + mUrl);
Request request = new Request.Builder()
.url(mUrl + "0.json" + showV)
.addHeader("Authorization", "Client-ID " + clientId)
.header("User-Agent", "epicture")
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "An error has occurred " + e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject data = new JSONObject(response.body().string());
JSONArray items = data.getJSONArray("data");
final List<Photo> photos = new ArrayList<Photo>();
photosActivity.callBackPhoto(photos, items);
} catch (Exception e) {
Log.e("JSONerr", "Something went wrong.");
}
}
});
}
public static void getLoginData(String accessToken) {
mAccessToken = accessToken;
}
}
It doesn't look like making sense to declare callBackPhoto as a static method. If you have put static keyword accidentally in its declaration, simply remove it to solve your problem i.e. replace
public static void callBackPhoto( List<Photo> photos, JSONArray items)
with
public void callBackPhoto( List<Photo> photos, JSONArray items)
Note that there is no way to call a non-static method from a static one directly (i.e. without calling it on an object/instance). Thus, if for any reason, you can't remove static keyword from the declaration of callBackPhoto, you are left with only two options:
Declare build too as static
Call build on an object/instance e.g. new PhotosActivity().build()
Though any of these two options will solve your problem, I don't think this is how you intend to design your class.
In java, a static method belongs to EVERY object of the class that defines it. Therefore, you can call it from the parent class without creating an object like so:
ParentClass.myMethod;
However, this is not the case the case with instance (non-static) methods. To call this type of method, you need to define it in a class, create an object from that class, and then call it from that object, like this:
//inside ParentClass definition
public void myMethod(){bla bla;}
//In some other class
ParentClass obj = new ParentClass;
obj.myMethod;
Suppose you have code calling a static member of a class without creating an instance of that class. If that method contained a non-static method, there would be no object in memory to call it on. This is why it isn't possible.
Static
The static methods are alive all the time. They live from the class is loaded. They don't need objects to live. I think of them as not really belonging to the class, but the class is just a nice way to organize those methods (the same for variables). The methods could be put in any other class definition and it would still work. But organizing them in classes where they will be used make it easy to prevent access from other parts of the program, like other objects or other static methods. They are called class methods or class variables.
Instance
The non-static "stuff" does not live unless there is an object. That's why you cannot call below methodOne or methodTwo from the static methods. You have to create an object first. They are called instance methods or instance variables, because you need an instance of an object to call them.
Error
error: non-static method <methodname> cannot be referenced from a static context basically means "There's no object"
Example
public class StackOverflowTest {
public static void main(String[] args) { // this is just another static method
// methodOne(); // error. There's no object
StackOverflowTest test = new StackOverflowTest();
test.methodOne(); // method called on object.
}
// methods live outside objects
static void staticMethodOne() {
System.out.println("staticMethodOne");
staticMethodTwo(); // no object required.
}
static void staticMethodTwo() {
System.out.println("staticMethodTwo");
// methodTwo(); // error. There's no object
}
// methods that only live inside objects
void methodOne() { // method can only be invoked if there's an object.
System.out.println("methodOne");
methodTwo(); // no problem. Already inside the object.
}
void methodTwo() {
System.out.println("methodTwo");
staticMethodTwo(); // no problem. Objects can access static methods.
}
}
Your case
So you either have to create a PhotosActivity object inside your build(), or you have to make callBackPhoto a static method. I can't see what your render does, but it's the same principle.
I'm stuck, I try to get an Array in Parse. I succeed to get it however I can't return it to use it in another method.
Do someone know what should I do ?
Retrieved ["international","entrepreneurship"]
public class CardsActivity extends AppCompatActivity {
ParseUser currentUser = ParseUser.getCurrentUser();
String test = currentUser.getObjectId();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cards);
// Specify which class to query
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.selectKeys(Arrays.asList("tastes"));
// Specify the object id
query.getInBackground(test, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
ArrayList<String> userTastesGot = (ArrayList<String>) object.get("tastes");
Log.d("User", "Retrieved " + userTastesGot);
} else {
Toast.makeText(CardsActivity.this, "Nous n'avons pas trouvés vos goûts", Toast.LENGTH_SHORT).show();
}
}
});
You can't return it from onCreate, no. I wouldn't even retrieve it in onCreate unless you can be certain that it won't be needed until it has been retrieved. I would do something like this:
interface Callback<T> {
void success(T result);
void failure(Exception error);
}
void getUserTastes(Callback<ArrayList<String>> callback){
// Note the special way to get a query for the user table
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.selectKeys(Arrays.asList("tastes"));
// TODO: Specify the object id
query.getInBackground(test, new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
ArrayList<String> userTastesGot = (ArrayList<String>) object.get("tastes");
Log.d("User", "Retrieved " + userTastesGot);
callback.success(userTastesGot);
} else {
callback.failure(e);
}
}
});
}
Use whatever protection levels are appropriate.
I'm Using inner AsyncTask to Calculate the Average from remote DB,
I get the result but
The problem is : The value of Average available only in "onPostExecute" , I want this value to be accessible in "On Create ()" so I can send it to another AsyncTask in the same Activity
public class Place_details extends Activity {
RatingBar PlaceRatingBar;
UserSessionManager session;
String ID;
Double [] Place_rates;
int Total_place_rates;
float Average_place_rates;
// JSON
JSONParser jsonparser;
JSONObject JSONObject;
ProgressDialog ProgressDialog;
JSONArray jsonArray1;
int value;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_details);
PlaceRatingBar = (RatingBar) findViewById (R.id.Place_rating);
jsonparser = new JSONParser();
//Session
session = new UserSessionManager(Place_details.this);
new getPlaceRating().execute() ;
// Here I get 0.0 and not the correct Average
Toast.makeText(Place_details.this, ""+Average_place_rates, Toast.LENGTH_SHORT).show();
} // End Of OnCreate
public class getPlaceRating extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
ProgressDialog = new ProgressDialog(Place_details.this);
ProgressDialog.setTitle("Wait....");
ProgressDialog.setIndeterminate(false);
ProgressDialog.setCancelable(true);
ProgressDialog.show();
}
#Override
protected String doInBackground(String...parma) {
// TODO Auto-generated method stub
List<NameValuePair> list = new ArrayList<NameValuePair>();
// passing place_id value
list.add(new BasicNameValuePair("id",String_Place_id));
try {
JSONObject = jsonparser.makeHttpRequest("http://192.168.1.2/Yourguideapplication/Place_rating2.php", "POST", list);
Log.e("pass 1", "connection success ");
}
catch (Exception e) {
Log.e("Fail 1", "Fail connection");
}
try {
value = JSONObject.getInt("value");
if (value==1){
//Place Rating
jsonArray1 = JSONObject.getJSONArray("Place_rating");
Place_rates = new Double[jsonArray1.length()];
Total_place_rates =0;
for (int i = 0 ; i < jsonArray1.length() ; i++)
{
JSONObject object = jsonArray1.getJSONObject(i);
Place_rates[i] = object.getDouble("Rating_box");
Total_place_rates+= Place_rates[i];
}
} else {
value = 0;
}
} catch (Exception e){
Log.d("ERORR",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (value == 1){
//Place Rating
Average_place_rates = (float) (Total_place_rates/jsonArray1.length());
PlaceRatingBar.setRating((float) Average_place_rates);
} else {
Toast.makeText(Place_details.this, "Error", Toast.LENGTH_LONG).show();
}
ProgressDialog.dismiss();
}
}
}
Thank you
You can create something like
private interface CallbackListener<T> {
void onComputingFinished(T arg);
}
Make your activity implement this interface.
public class Place_details extends Activity implements CallbackListener<String> {
#Override
public void onComputingFinished(String arg) {
//do your stuff here
}
And register it as listener in your AsynTask class (create field and constructor in you AsyncTask class):
public class GetPlaceRating extends AsyncTask<String,String,String>{
private CallbackListener<String> mListener;
public GetPlaceRating(CallbackListener<String> listener) {
mListener = listener;
}
And when starting task
new GetPlaceRating(this).execute() ;
And in onPostExecute call
if (mListener != null) mListener.onComputingFinished(*your arg*);
I used String to replace generic T in this example, hope you understand you can use whatever you want.
EDITED:
If arguments are of the same type you can change signature of interface to:
private interface CallbackListener<T> {
void onComputingFinished(T ...args);
}
And access them as an array: args[0], args[1].
Or just specify what concrete arguments you want to pass, for example String, int and SomeClass:
private interface CallbackListener {
void onComputingFinished(String str, int value, SomeClass obj);
}
I am making an android game. I am using RelativeLayout, which hosts a FrameLayout, which hosts a SurfaceView. However, i have added a textview onto the RelativeLayout to show how many health points the player has left. I have a method which sets the int value of how many health points he has left into the text view. The int value is located in the SurfaceView, which is another class. But the textview and the method which updates the textview, is inside the other class. I want the method in the other class to be constantly updated, so that the textview will always display the health value. How can i do this? The method is called updateHealthPointsTextView(). Please help me and thanks so much! My code:
package com.mysoftwaremobileapps.alien.attack;
import java.util.ArrayList;
public class GameScreenActivity extends Activity {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
RadioButton radioEasy, radioMedium, radioHard;
private ExampleView eView;
public int ParachuterIndex;
TextView healthPoints;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dropParachuters();
}
private void dropParachuters() {
// TODO Auto-generated method stub
}
#Override
protected void onStart()
{
FrameLayout fl = new FrameLayout(this);
eView = new ExampleView(this);
fl.addView(eView);
healthPoints = new TextView(this);
healthPoints.setText("Health Points: " + eView.getThread().healthPoints);
RelativeLayout relativeLayout= new RelativeLayout(this);
relativeLayout.addView(fl);
relativeLayout.addView(healthPoints);
setContentView(relativeLayout);
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().drawAlien();
eView.getThread().publicFloatX = 750;
eView.getThread().gettingAttacked();
updateHealthPointsTextView();
super.onStart();
try {
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("KEY");
}
} catch (Exception e) {
// TODO: handle exception
}
}
private void updateHealthPointsTextView() {
// TODO Auto-generated method stub
//Updating textview with health points value
healthPoints.setText(Integer.toString(eView.getThread().healthPoints));
}
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent Event) {
if ((KeyCode == KeyEvent.KEYCODE_MENU)) {
//Call performSpecialAttack()
Log.d("Parachute Hunter", "calling performSpecialAttack()");
eView.getThread().performSpecialAttack();
return true;
}
return super.onKeyDown(KeyCode, Event);
}
#Override
protected void onStop()
{
try {
eView.getThread().setRunning(false);
eView = null;
}
catch (NullPointerException e) {}
super.onStop();
}
}
How about having a method like this:
public void setHealthPoints(int points) {
eView.getThread().healthPoints = points;
//Updating textview with health points value
healthPoints.setText("Health Points: " + Integer.toString(points));
}
}
call it from everywhere, it should not block the GUI-Thread
just pass the reference of textview in constructor of that class and use handler to update it frequently.
public final class MethodUtil {
TextView mTextView;
public MethodUtil(TextView mTextView) {
//this.mTextView =(TextView)mTextView.findViewById(R.id.textview);
this.mTextView=mTextView;
}
public void updateHealthPointsTextView(){
mTextView.post(new Runnable() {
#Override
public void run() {
mTextView.setText("Health Points: " + eView.getThread().healthPoints);
}
});
}
}
I fixed it by simply making a countdown timer counting down from 1 second and then restarting itself and updating the textview when it's fininished. It works
public void updateHealthPointsTextView() {
//The aliens are firing and throwing rocks, make the defender lose health
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//Updating textview
healthPoints.setText("Health points: " + Integer.toString(eView.getThread().healthPoints));
updateHealthPointsTextView();
}
}.start();
}