get TextView from another class - java

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");
}
}

Related

Call non-static method in Static method JAVA

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.

Android: String array becomes null when I pass it back to MapsActivity from a class which uses an async task

I am fairly new to Android development and am creating an application which uses a Google map fragment. I am querying the Google Directions Api and retrieving JSON data using an AsyncTask method. I then decode the polyline and in turn gain a string array of LatLon pairs. I now would now like to use this string array back in my MainActivity. I have tried many ways to do this, however every single way has made the string array null.
Method tried = 1) using a static field 2) using Intent objects to transfer data 3) creating an interface.
Could someone please tell me as to how I should go around this and why it keeps becoming null in my MainActivity? Snippets of my code are below, thanks.
public class GetDirectionsData extends AsyncTask<Object, String,
String>
{
private GoogleMap mMap;
private Context context;
private String url , googleDirectionsData;
private String distance,duration;
private LatLng destinationLatLng;
private String[] directionsList;
public GetDirectionsData(Context context)
{
this.context = context;
}
#Override
protected String doInBackground(Object... objects)
{
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
destinationLatLng = (LatLng)objects[2];
DownloadUrl downloadURL = new DownloadUrl();
try
{
googleDirectionsData = downloadURL.readUrl(url);
}
catch (IOException e)
{
e.printStackTrace();
}
return googleDirectionsData;
}
#Override
protected void onPostExecute(String s)
{
// uses other class DataParser to extract relevant JSONdata and
// displays polyline
DataParser directionParser = new DataParser();
directionsList = directionParser.parseDirections(s);
displayDirection(directionsList);
}
public void displayDirection(String[] directionsList)
{
int count = directionsList.length;
for(int i = 0; i < count; i++)
{
PolylineOptions options = new PolylineOptions();
options.color(Color.BLUE);
options.width(10);
options.addAll(PolyUtil.decode(directionsList[i])); // decode polylines
mMap.addPolyline(options);
}
}
I now want to pass directionsList string array back to MapsActivity Below
public class MapsActivity extends FragmentActivity
{
public void onClick(View v)
{
Object directionDataTransfer[];
// DIRECTIONS BUTTON
switch(v.getId())
{
case R.id.IB_search:
directionDataTransfer = new Object[3];
GetDirectionsData getDirectionsData = new GetDirectionsData(this);
String directionsUrl = getDirectionsUrl();
directionDataTransfer[0] = mMap;
directionDataTransfer[1] = directionsUrl;
directionDataTransfer[2] = new LatLng(//destination LatLon)
getDirectionsData.execute(directionDataTransfer);
Toast.makeText(MapsActivity.this, "Fetching directions", Toast.LENGTH_LONG).show();
}
}
private String getDirectionsUrl()
{
StringBuilder googleDirectionsUrl = new StringBuilder("https://maps.googleapis.com/maps/api/directions/json?");
googleDirectionsUrl.append("origin=" + originLat + "," + originLon);
googleDirectionsUrl.append("&destination=" + destinationLat + "," + destinationLon);
googleDirectionsUrl.append("&mode=" + modeOfTransport);
googleDirectionsUrl.append("&waypoints=via:" + waypointsLat + "," + waypointsLon);
googleDirectionsUrl.append("&key=" + googleApiKey);
return( googleDirectionsUrl.toString() );
}
}
Here is one of the example using Interface - hope this helps.
DummyAsyncTask.java
import android.os.AsyncTask;
public class DummyAsyncTask extends AsyncTask<Void, Void, String> {
private DummyInterface mListener = null;
DummyAsyncTask(DummyInterface listener) {
mListener = listener;
}
#Override
protected String doInBackground(Void... voids) {
return s; // return your string from doInBackground(it will be available as a parameter in onPostExecute())
}
#Override
protected void onPostExecute(String s) {
if(mListener != null) {
mListener.onCallback(s); // sending string s back to activity which registered for callback
}
}
}
DummyInterface.java
public interface DummyInterface {
void onCallback(String s); // callback API
}
DummyActivity.java
import android.app.Activity;
import android.os.Bundle;
public class DummyActivity extends Activity implements DummyInterface{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new DummyAsyncTask(this).execute();
}
#Override
public void onCallback(String s) {
System.out.println("String s = " + s);
}
}

Not able to fetch data from Wear Data layer

I'm trying to sync a list from the handheld to the wearable. On the phone side, I have a listview and you can add items to it and on the wear side I am just displaying the same list. I'm adding items to /card/id path and adding the array size on /counter. OnDataChanged method does gets called when I add items to the list on phoneside, but when I try to read the items on wearside, it's not working. It gives nullpointer exception when I'm trying to get the connected nodes and therefor I'm not able to read the data. Here's the code and the log snapshot:
Error
04-15 12:41:38.075: E/AndroidRuntime(13791): Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.os.Looper com.google.android.gms.common.api.GoogleApiClient.getLooper()' on a null object reference
Wear side:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDefaultCircleRadius = getResources().getDimension(R.dimen.default_settings_circle_radius);
mSelectedCircleRadius = getResources().getDimension(R.dimen.selected_settings_circle_radius);
cards = new ArrayList<GiftCard>();
new LoadCards().execute();
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
//mTextView = (TextView) stub.findViewById(R.id.count_text);
mListView = (WearableListView) stub.findViewById(R.id.card_list_view);
}
});
mHandler = new Handler();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
DataItem item = event.getDataItem();
if (item.getUri().getPath().compareTo(COUNT_PATH) == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
final String counter = dataMap.getString(CardUtil.CARD_COUNT);
new LoadCards().execute();
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(c,"Card count: "+ counter,Toast.LENGTH_LONG).show();
//mTextView.setText("COUNTER FROM DATACHANGE METHOD: " + counter);
}
});
}
else if(item.getUri().getPath().compareTo(CARD_PATH) == 0){
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
}
}
}
public GiftCard loadCardData(int id){
//Uri uri = getIntent().getData().buildUpon().encodedPath("/card").appendPath(String.valueOf(id)).build();
Uri uri = getUriForDataItem("/counter");
Log.d("URI", uri.getPath());
DataApi.DataItemResult result = Wearable.DataApi.getDataItem(mGoogleApiClient,uri).await();
DataMapItem item = DataMapItem.fromDataItem(result.getDataItem());
Asset cardImageAsset = item.getDataMap().getAsset(CardUtil.CARD_IMAGE);
//Asset barcodeImageAsset = item.getDataMap().getAsset(CardUtil.BARCODE_IMAGE);
String card_type = item.getDataMap().getString(CardUtil.CARD_TYPE);
Bitmap cardImage = BitmapFactory.decodeStream(Wearable.DataApi.getFdForAsset(mGoogleApiClient, cardImageAsset).await().getInputStream());
// Bitmap barcodeImage = BitmapFactory.decodeStream(Wearable.DataApi.getFdForAsset(mGoogleApiClient,barcodeImageAsset).await().getInputStream());
GiftCard card = new GiftCard();
card.setCardImage(cardImage);
card.setCardName(card_type);
card.setCardID(id);
return card;
}
public class LoadCards extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... arg0) {
// Uri uri = getIntent().getData().buildUpon().encodedPath("/counter").build();
Uri uri = getUriForDataItem("/counter");
Toast.makeText(c,uri.toString(),Toast.LENGTH_LONG).show();
DataApi.DataItemResult result = Wearable.DataApi.getDataItem(mGoogleApiClient,uri).await();
DataMapItem item = DataMapItem.fromDataItem(result.getDataItem());
int card_count = Integer.parseInt(item.getDataMap().getString(CardUtil.CARD_COUNT));
// int card_count = Integer.parseInt(loadCardCounter());
if(card_count <= 0){
Toast.makeText(c,"No cards available to show!",Toast.LENGTH_LONG).show();
} else {
for (int i = 1; i <= card_count; i++) {
GiftCard c = loadCardData(i);
cards.add(c);
}
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//update the card list
mAdapter = new CardListAdapter(c,cards);
mListView.setAdapter(mAdapter);
// mListView.setClickListener();
}
}
private Uri getUriForDataItem(String path) {
String nodeId = getNodeId();
return new Uri.Builder().scheme(PutDataRequest.WEAR_URI_SCHEME).authority(nodeId).path(path).build();
}
private String getNodeId() {
NodeApi.GetConnectedNodesResult nodesResult = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
List<Node> nodes = nodesResult.getNodes();
if (nodes.size() > 0) {
return nodes.get(0).getId();
} else {
Toast.makeText(c,"NO NODES AVAILABLE",Toast.LENGTH_LONG).show();
}
return null;
}}
From the stacktrace it's pretty obvious that you are trying to use Wearable DataAPI from the thread without Looper - in doInBackground() method I believe. That is why it crashes.
Move this code directly into onDataChanged() method and it should solve the issue.

Get Result from onPostExecute inner AsyncTask to OnCreate

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);
}

parse in android getInBackground function is not running

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"));

Categories

Resources