Accessing TextView from other class in android - android

Hello i am new to android.i was creating a simple google cloud appengine app with endpoint.i was using using this tutorial https://github.com/GoogleCloudPlatform/gradle-appengine-templates/tree/master/HelloEndpoints .but the thing is i want to show the result in a textview not in a toast.
Layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/lay1">
<EditText
android:id="#+id/edt1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Enter Number"
android:inputType="number"
android:textSize="24sp" />
<EditText
android:id="#+id/edt2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Enter Number"
android:inputType="number"
android:textSize="24sp" />
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:hint="Result Will be Here"
android:textSize="24sp" />
<Button
android:id="#+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="Add" />
</LinearLayout>
GoogleAppEngActivity.java (main activity)
package com.ontech.googleappengine;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GoogleAppEngActivity extends AppCompatActivity {
Button btnAdd;
TextView tv1;
//String val1,val2;
EditText edt1,edt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_app_eng);
edt1=(EditText)findViewById(R.id.edt1);
edt2=(EditText)findViewById(R.id.edt2);
tv1=(TextView)findViewById(R.id.tv1);
btnAdd =(Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = "";
temp = edt1.getText().toString();
temp += "+";
temp += edt2.getText().toString();
new EndpointsAsyncTask().execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
// tv1.setText( new EndpointsAsyncTask().);
}
});
// new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Manfred"));
}
public TextView getTextView(){
TextView txtView=(TextView)findViewById(R.id.tv1);
return txtView;
}
}
EndpointsAsyncTask.java
package com.ontech.googleappengine;
//package com.ontech.googleappengine;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Layout;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.ontech.myapplication.backend.myApi.MyApi;
import java.io.IOException;
/**
* Created by on 05-11-2015.
*/
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
My endpoint.java
package com.ontech.myapplication.backend;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import javax.inject.Named;
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.ontech.com",
ownerName = "backend.myapplication.ontech.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) {
MyBean response = new MyBean();
String val1, val2;
val1 = name.substring(0, name.indexOf("+"));
val2 = name.substring(name.indexOf("+") + 1);
int res = Integer.parseInt(val1) + Integer.parseInt(val2);
// response.setData("Hi, " + name);
response.setData(Integer.toString(res));
return response;
}
}
MyBean.java
package com.ontech.myapplication.backend;
/**
* The object model for the data we are sending through endpoints
*/
public class MyBean {
private String myData;
public String getData() {
return myData;
}
public void setData(String data) {
myData = data;
}
}

Pass TextView as parameter to Constructor of EndpointsAsyncTask in which you want to show result as done below.
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
private TextView textView
public EndpointsAsyncTask(Context context,TextView mtextView) {
// TODO Auto-generated constructor stub
this.context=context;
this.textView=mtextView;
}
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
textView.setText(result);
}
}
call AsyncTask from you Activity or Fragment
new EndpointsAsyncTask(context,yourTextView).execute(yourParams);

In EndpointsAsyncTask.java replace
#Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
With
#Override
protected void onPostExecute(String result) {
GoogleAppEngActivity.getTextView().setText(result);
}

change to:new EndpointsAsyncTask(tv1) in GoogleAppEngActivity class
and add next code to EndpointsAsyncTask class
TextView view;
public EndpointsAsyncTask(TextView tv) {
view = tv;
}
and replace Toast.makeText(context, result, Toast.LENGTH_LONG).show();
to view.setText(result);

I'll suggest making EndpointsAsyncTask an inner class of your activity. Get a reference to textView in postExecute and update it there. Something like this

Ideally, the UI elements belonging to an activity should be changed in the activity itself, and no where else. Try following the presentation pattern.
A small example:
1. Create an interface - ActivityPresenter with methods signifying events with parameters as the input data required for the views to change. An example would be:
void onServerResponse(ServerResponse resp);
Make the activity implement this interface. That is, you define what UI changes to make in the activity when the server response arrives.
When you call a service / asynctask from the activity to do some task asynchronously for you, send the activity presenter reference. Call the presenter.onServerResponse(response) from your service / asynctask.

For this purpose you can use callback interface:
Create a public interface:
public interface AsyncTaskResponse {
void asyncTaskFinish(String output);
}
Now override the method of callback interface and define the action need to do i.e set the TextView value. After that pass it to async task class:
package com.ontech.googleappengine;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class GoogleAppEngActivity extends AppCompatActivity {
Button btnAdd;
final TextView tv1;
//String val1,val2;
EditText edt1,edt2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_app_eng);
edt1=(EditText)findViewById(R.id.edt1);
edt2=(EditText)findViewById(R.id.edt2);
tv1=(TextView)findViewById(R.id.tv1);
btnAdd =(Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String temp = "";
temp = edt1.getText().toString();
temp += "+";
temp += edt2.getText().toString();
new EndpointsAsyncTask(new AsyncTaskResponse() {
#Override
public void asyncTaskFinish(String response) {
tv1.setText(response);
}
};).execute(new Pair<Context, String>(GoogleAppEngActivity.this, temp));
// tv1.setText( new EndpointsAsyncTask().);
}
});
// new EndpointsAsyncTask(new AsyncTaskResponse().execute(new Pair<Context, String>(this, "Manfred"));
}
public TextView getTextView(){
TextView txtView=(TextView)findViewById(R.id.tv1);
return txtView;
}
}
Now in async task class call the Callback interface method and pass response String to set edit text value:
package com.ontech.googleappengine;
//package com.ontech.googleappengine;
import android.content.Context;
import android.os.AsyncTask;
import android.text.Layout;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.ontech.myapplication.backend.myApi.MyApi;
import java.io.IOException;
/**
* Created by on 05-11-2015.
*/
public class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private static MyApi myApiService = null;
private Context context;
private AsyncTaskResponse asyncCallback;
public EndpointsAsyncTask(AsyncTaskResponse asyncTaskResponse){
asyncCallback = asyncTaskResponse;
}
#Override
protected String doInBackground(Pair<Context, String>... params) {
if (myApiService == null) { // Only do this once
/* MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});*/
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("https://leafy-display-112017.appspot.com/_ah/api/");
// end options for devappserver
myApiService = builder.build();
}
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(context, result, Toast.LENGTH_LONG).show();
asyncCallback.asyncTaskFinish(result); // call the method of callback interface
}
}

Related

"SinchClient not started" The main problem in android studio

I am facing this problem for the last two weeks. Can you help me why this problem occurs?
Error occur at this line allClient.callPhoneNumber("+16315192247");
Please check it. Every time it crashes.
package com.eureka.voicecallinapk;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.sinch.android.rtc.PushPair;
import com.sinch.android.rtc.Sinch;
import com.sinch.android.rtc.SinchClient;
import com.sinch.android.rtc.SinchError;
import com.sinch.android.rtc.calling.Call;
import com.sinch.android.rtc.calling.CallClient;
import com.sinch.android.rtc.calling.CallClientListener;
import com.sinch.android.rtc.calling.CallListener;
import java.util.List;
public class MainActivity extends AppCompatActivity {
public static final String APP_KEY = "b7258284-f0dnd-4734-afec-210d387d****";
//i do it for security because i am posting here
public static final String APP_SECRET = "k76tOLgz+kSdKL7ULYsH**==";
public static final String ENVIRONMENT = "clientapi.sinch.com";
public Call call;
private TextView callState;
public SinchClient sinchClient;
private Button button;
private String callerId;
private String recipientId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
callerId = intent.getStringExtra("callerId");
recipientId = intent.getStringExtra("recipientId");
sinchClient = Sinch.getSinchClientBuilder()
.context(MainActivity.this)
.userId("172976")
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT)
.build();
sinchClient.setSupportCalling(true);
sinchClient.startListeningOnActiveConnection();
sinchClient.start();
// sinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
button = findViewById(R.id.button);
callState = findViewById(R.id.callState);
button.setOnClickListener(view -> {
if (call == null) {
try {
boolean s=isStarted();
Log.d("checksinch", String.valueOf(s));
CallClient callClient = sinchClient.getCallClient();
callClient.callPhoneNumber("+16315192247"); // Error occur at this line "SinchClient not started"
//callClient.callPhoneNumber("+16315192247");
// call = sinchClient.getCallClient().callPhoneNumber("+46000000000.");
// call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}catch (Exception e){
Log.d("checksinch", e.getMessage());
}
} else {
call.hangup();
button.setText("Call");
}
});
}
private boolean isStarted() {
return (sinchClient != null && sinchClient.isStarted());
}
private class SinchCallListener implements CallListener {
#Override
public void onCallEnded(Call endedCall) {
call = null;
SinchError a = endedCall.getDetails().getError();
button.setText("Call");
callState.setText("");
setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
}
#Override
public void onCallEstablished(Call establishedCall) {
callState.setText("connected");
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
}
#Override
public void onCallProgressing(Call progressingCall) {
callState.setText("ringing");
}
#Override
public void onShouldSendPushNotification(Call call, List<PushPair> pushPairs) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call incomingCall) {
call = incomingCall;
Toast.makeText(MainActivity.this, "incoming call", Toast.LENGTH_SHORT).show();
call.answer();
call.addCallListener(new SinchCallListener());
button.setText("Hang Up");
}
}
}

I don't understand why 'onResponse()' is not triggered after successful response?

From the log I can see that the web service correctly returns the JSON to me. But for some reason it never enters the onResponse method.
MainActivity.java
OnResponse() method in getaccesstoken() not triggered after successful response
package com.example.alexandra.instagramlogin;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.alexandra.instagramlogin.models.AuthToken;
import com.example.alexandra.instagramlogin.rest.RestClient;
import com.example.alexandra.instagramlogin.rest.services.Auth;
import com.squareup.picasso.Picasso;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity
implements AuthenticationListener {
private static final String TAG = "MainActivity";
private String token = null;
private String code = null;
private AppPreferences appPreferences = null;
private AuthenticationDialog authenticationDialog = null;
private Button button = null;
private View info = null;
AuthToken authToken = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.btn_login);
info = findViewById(R.id.info);
appPreferences = new AppPreferences(this);
//check already have access token
}
public void login() {
button.setText("LOGOUT");
info.setVisibility(View.VISIBLE);
ImageView pic = findViewById(R.id.pic);
Picasso.with(this).load(appPreferences.getString(AppPreferences.PROFILE_PIC)).into(pic);
TextView id = findViewById(R.id.id);
id.setText(appPreferences.getString(AppPreferences.USER_ID));
TextView name = findViewById(R.id.name);
name.setText(appPreferences.getString(AppPreferences.USER_NAME));
}
public void logout() {
button.setText("INSTAGRAM LOGIN");
token = null;
info.setVisibility(View.GONE);
appPreferences.clear();
}
#Override
public void onTokenReceived(String auth_code) {
Log.d(TAG, auth_code);
appPreferences.putString(AppPreferences.CODE, auth_code);
code = auth_code;
getAccessToken(code);
}
//getting access token
private void getAccessToken(final String code) {
Auth auth = RestClient.getInstance();
Call<AuthToken>authTokenCall = auth.getAuthToken(getString(R.string.client_id),getString(R.string.client_secret),"authorization_code",getString(R.string.redirect_url),
code);
authTokenCall.enqueue(new Callback<AuthToken>() {
#Override
public void onResponse(Call<AuthToken> call, Response<AuthToken> response) {
Log.d(TAG, "onResponse: ");
}
#Override
public void onFailure(Call<AuthToken> call, Throwable t) {
}
});
}
public void onClick(View view) {
if(token!=null)
{
logout();
}
else {
authenticationDialog = new AuthenticationDialog(this, this);
authenticationDialog.setCancelable(true);
authenticationDialog.show();
}
}
}
pojo(AuthToken)
package com.example.alexandra.instagramlogin.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AuthToken {
#SerializedName("access_token")
#Expose
private String access_token;
#SerializedName("user_id")
#Expose
private Integer user_id;
public String getAccessToken() {
return access_token;
}
public void setAccessToken(String accessToken) {
this.access_token = accessToken;
}
public Integer getUserId() {
return user_id;
}
public void setUserId(Integer userId) {
this.user_id = userId;
}
}
Auth.java
package com.example.alexandra.instagramlogin.rest.services;
import com.example.alexandra.instagramlogin.Classes.AuthorizationToken;
import com.example.alexandra.instagramlogin.models.AuthToken;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Auth {
#FormUrlEncoded
#POST("oauth/access_token")
Call<AuthToken>getAuthToken(#Field("client_id")String clientid,#Field("client_secret")String client_secret,#Field("grant_type")String grant_type
,#Field("redirect_uri")String redirect_uri,#Field("code")String code);
}
Response
D/OkHttp: {"access_token": "IGQVJXWTcyNVBZANmFfeWNSQXUwQmdZAYlUtSHYxc1Q1dUlZAWTVPaTVTZA3dqYU00dC1ocjc4WDJwS2ZA2cVJjMTA3Rkx5QkN4alBlVjFNWjBndkJMcm45ZA0s3dk5HbXBFNnU5empGVGI0WXdrb1ZARZADktVlFjeVJIQUxGRnpv", "user_id": 17841401561947636}
I think you are not handling all case correctly like what if onFailure trigger for error.
I am not debugging you project so exact error i can tell you but i suggest you some links where you can find how to debug your code properly.
How to debug android apps

Not annotated parameter overrides #NonNull parameter

#nonnull error at inflater , any one can solve this error?
im new to android i don't know how to solve this error any solution ?
is it the error of due theme or something else ,do my code have some major issue ?? can you solve this error please. due to this error my code is not working. your help will be highly appreciated
my import in the code is listed below
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.app.DownloadManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.support.v7.widget.DividerItemDecoration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import static android.content.Context.DOWNLOAD_SERVICE;
import java.lang.reflect.Type;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class FilesListingFragment extends android.support.v4.app.Fragment {
private static final String TAG = "FilesListingFragment";
public static final String PATH_FILES = "http://%s:%s/files";
public static final String PATH_STATUS = "http://%s:%s/status";
public static final String PATH_FILE_DOWNLOAD = "http://%s:%s/file/%s";
private String mSenderIp = null, mSenderSSID;
private ContactSenderAPITask mUrlsTask;
private ContactSenderAPITask mStatusCheckTask;
private String mPort, mSenderName;
static final int CHECK_SENDER_STATUS = 100;
static final int SENDER_DATA_FETCH = 101;
RecyclerView file;
ProgressBar progressBar;
TextView mTextView;
private SenderFilesListingAdapter mFilesAdapter;
private UiUpdateHandler uiUpdateHandler;
private static final int SENDER_DATA_FETCH_RETRY_LIMIT = 3;
private int senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT, senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_files_listing, null);
file = (RecyclerView) v.findViewById(R.id.files_list);
progressBar = (ProgressBar) v.findViewById(R.id.loading);
mTextView = (TextView) v.findViewById(R.id.empty_listing_text);
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTextView.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
fetchSenderFiles();
}
});
file.setLayoutManager(new LinearLayoutManager(getActivity()));
file.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.lidivider)));/**here is the error */
mFilesAdapter = new SenderFilesListingAdapter(new ArrayList<String>());
file.setAdapter(mFilesAdapter);
uiUpdateHandler = new UiUpdateHandler(this);
return v;
}
public static FilesListingFragment getInstance(String senderIp, String ssid, String senderName, String port) {
FilesListingFragment fragment = new FilesListingFragment();
Bundle data = new Bundle();
data.putString("senderIp", senderIp);
data.putString("ssid", ssid);
data.putString("name", senderName);
data.putString("port", port);
fragment.setArguments(data);
return fragment;
}
#Override
public void onAttach(Context activity) {
super.onAttach(activity);
if (null != getArguments()) {
mSenderIp = getArguments().getString("senderIp");
mSenderSSID = getArguments().getString("ssid");
mPort = getArguments().getString("port");
mSenderName = getArguments().getString("name");
Log.d(TAG, "sender ip: " + mSenderIp);
}
}
#Override
public void onResume() {
super.onResume();
fetchSenderFiles();
checkSenderAPIAvailablity();
}
private void fetchSenderFiles() {
progressBar.setVisibility(View.VISIBLE);
if (null != mUrlsTask)
mUrlsTask.cancel(true);
mUrlsTask = new ContactSenderAPITask(SENDER_DATA_FETCH);
mUrlsTask.execute(String.format(PATH_FILES, mSenderIp, mPort));
}
private void checkSenderAPIAvailablity() {
if (null != mStatusCheckTask)
mStatusCheckTask.cancel(true);
mStatusCheckTask = new ContactSenderAPITask(CHECK_SENDER_STATUS);
mStatusCheckTask.execute(String.format(PATH_STATUS, mSenderIp, mPort));
}
#Override
public void onPause() {
super.onPause();
if (null != mUrlsTask)
mUrlsTask.cancel(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (null != uiUpdateHandler)
uiUpdateHandler.removeCallbacksAndMessages(null);
if (null != mStatusCheckTask)
mStatusCheckTask.cancel(true);
}
public String getSenderSSID() {
return mSenderSSID;
}
public String getSenderIp() {
return mSenderIp;
}
private void loadListing(String contentAsString) {
Type collectionType = new TypeToken<List<String>>() {
}.getType();
ArrayList<String> files = new Gson().fromJson(contentAsString, collectionType);
progressBar.setVisibility(View.GONE);
if (null == files || files.size() == 0) {
mTextView.setText("No Downloads found.\n Tap to Retry");
mTextView.setVisibility(View.VISIBLE);
} else {
mTextView.setVisibility(View.GONE);
mFilesAdapter.updateData(files);
}
}
private void onDataFetchError() {
progressBar.setVisibility(View.GONE);
mTextView.setVisibility(View.VISIBLE);
mTextView.setText("Error occurred while fetching data.\n Tap to Retry");
}
private long postDownloadRequestToDM(Uri uri, String fileName) {
// Create request for android download manager
DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setDescription("ShareThem");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(getActivity(),
Environment.DIRECTORY_DOWNLOADS, fileName);
return downloadManager.enqueue(request);
}
private class SenderFilesListingAdapter extends RecyclerViewArrayAdapter<String, SenderFilesListItemHolder> {
SenderFilesListingAdapter(List<String> objects) {
super(objects);
}
void updateData(List<String> objects) {
clear();
mObjects = objects;
notifyDataSetChanged();
}
#Override
public SenderFilesListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.listitem_file, parent, false);
return new SenderFilesListItemHolder(itemView);
}
#Override
public void onBindViewHolder(SenderFilesListItemHolder holder, int position) {
final String senderFile = mObjects.get(position);
holder.itemView.setTag(senderFile);
final String fileName = senderFile.substring(senderFile.lastIndexOf('/') + 1, senderFile.length());
holder.title.setText(fileName);
holder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
postDownloadRequestToDM(Uri.parse(String.format(PATH_FILE_DOWNLOAD, mSenderIp, mPort, mObjects.indexOf(senderFile))), fileName);
Toast.makeText(getActivity(), "Downloading " + fileName + "...", Toast.LENGTH_SHORT).show();
}
});
}
}
static class SenderFilesListItemHolder extends RecyclerView.ViewHolder {
TextView title;
ImageButton download;
SenderFilesListItemHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.sender_list_item_name);
download = (ImageButton) itemView.findViewById(R.id.sender_list_start_download);
}
}
/**
* Performs network calls to fetch data/status from Sender.
* Retries on error for times bases on values of {#link FilesListingFragment#senderDownloadsFetchRetry}
*/
private class ContactSenderAPITask extends AsyncTask<String, Void, String> {
int mode;
boolean error;
ContactSenderAPITask(int mode) {
this.mode = mode;
}
#Override
protected String doInBackground(String... urls) {
error = false;
try {
return downloadDataFromSender(urls[0]);
} catch (IOException e) {
e.printStackTrace();
error = true;
Log.e(TAG, "Exception: " + e.getMessage());
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
switch (mode) {
case SENDER_DATA_FETCH:
if (error) {
if (senderDownloadsFetchRetry >= 0) {
--senderDownloadsFetchRetry;
if (getView() == null || getActivity() == null || null == uiUpdateHandler)
return;
uiUpdateHandler.removeMessages(SENDER_DATA_FETCH);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(mode), 800);
return;
} else senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT;
if (null != getView())
onDataFetchError();
} else if (null != getView())
loadListing(result);
else Log.e(TAG, "fragment may have been removed, File fetch");
break;
case CHECK_SENDER_STATUS:
if (error) {
if (senderStatusCheckRetryLimit > 1) {
--senderStatusCheckRetryLimit;
uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 800);
} else if (getActivity() instanceof ReceiverActivity) {
senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
((ReceiverActivity) getActivity()).resetSenderSearch();
Toast.makeText(getActivity(), getString(R.string.p2p_receiver_error_sender_disconnected), Toast.LENGTH_SHORT).show();
} else
Log.e(TAG, "Activity is not instance of ReceiverActivity");
} else if (null != getView()) {
senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 1000);
} else
Log.e(TAG, "fragment may have been removed: Sender api check");
break;
}
}
private String downloadDataFromSender(String apiUrl) throws IOException {
InputStream is = null;
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response =
conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
return readIt(is);
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream) throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(stream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
stream.close();
}
return writer.toString();
}
}
private static class UiUpdateHandler extends Handler {
WeakReference<FilesListingFragment> mFragment;
UiUpdateHandler(FilesListingFragment fragment) {
mFragment = new WeakReference<>(fragment);
}
#Override
public void handleMessage(Message msg) {
FilesListingFragment fragment = mFragment.get();
if (null == mFragment)
return;
switch (msg.what) {
case CHECK_SENDER_STATUS:
fragment.checkSenderAPIAvailablity();
break;
case SENDER_DATA_FETCH:
fragment.fetchSenderFiles();
break;
}
}
}
fragment_files_listing
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".receiver.FilesListingFragment"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/files_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
style="#android:style/Widget.Holo.ProgressBar"
android:layout_width="wrap_content"
android:id="#+id/loading"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center" />
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/empty_listing_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:clickable="true"
android:gravity="center"
android:text="No Downloads found.\n Tap to Retry"
android:visibility="gone" />
</RelativeLayout>
Not annotated parameter overrides #NonNull parameter
This is just a warning. You have
#Override
public View onCreateView(LayoutInflater inflater...
while the base class you're extending has nullity annotation on the inflater parameter.
public View onCreateView(#NonNull LayoutInflater inflater...
You can just alt-enter in Android Studio to get a quick fix menu that has the option to add the missing annotation there.
due to this error my code is not working.
Missing an annotation like that just causes a warning. The reason for "not working" is something else. Please start by updating your question and specifying what "not working" means to you here.
Try to change this line
View v = inflater.inflate(R.layout.fragment_files_listing, null);
to
View v = inflater.inflate(R.layout.fragment_files_listing, container, false);
This will inflate your layout with your fragment container.
You have to change this line
View v = inflater.inflate(R.layout.fragment_files_listing, null);
to
View v = inflater.inflate(R.layout.fragment_files_listing, container, false);
and then clean your project and invalidate cache restart you android studio.

Unable to get data from query results from Twitter API

I am new to Android. I can't get my ListView to populate. I am aware that this question has been asked on SO multiple times before and I have tried the things suggested in other questions (e.g. making sure my orientation is set to vertical, calling notifyDataSetChanged etc) and it still won't work. My activity class is as follows:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
and my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/search"
android:textSize="25dp"/>
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/queryEditText"
android:ems="20"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/query"
android:id="#+id/queryButton"
android:textSize="15dp"/>
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchListView">
</ListView>
</LinearLayout>
Here is my API client class also:
package com.michaelnares.twitterclient;
import android.util.Log;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class APIClient
{
ArrayList<String> statusArrayList = new ArrayList<String>();
ArrayList<String> searchArrayList = new ArrayList<String>();
public ArrayList<String> getHomeTimeline() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
try {
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statuses = twitter.getHomeTimeline();
statusArrayList.clear();
for (Status status : statuses)
{
statusArrayList.add(status.toString());
}
}
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to get home timeline tweets: " + e.getErrorMessage());
}
return statusArrayList;
} // ends getHomeTimeline() method
public ArrayList<String> getQueryResults(String userQuery)
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
searchArrayList.clear();
try {
Query query = new Query(userQuery);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
int count = 0;
searchArrayList.clear();
for (Iterator<Status> i = tweets.iterator(); i.hasNext();)
{
Status tweet = i.next();
count++;
if (count == 10)
{
break;
}
searchArrayList.add("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
} // ends for loop
} // ends try block
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to search tweets: " + e.getErrorMessage());
}
return searchArrayList;
} // ends getQueryResults() method
} // ends class
I'm really struggling to work out what the issue is.

Error await must not be called on the UI Thread in Android project

I am currently trying to read data from google drive, using a query then transferring the gson to a fragment so I can set the edit text values of said fragment to the gson being read in (Kudos if you followed that!)
Every time I move to open the fragment I am getting the following error message:
05-03 16:12:39.311 12594-12594/com.example.fitness_first.fitnessfirst E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.fitness_first.fitnessfirst, PID: 12594
java.lang.IllegalStateException: await must not be called on the UI thread
at com.google.android.gms.common.internal.zzx.zza(Unknown Source)
at com.google.android.gms.common.api.internal.zzb.await(Unknown Source)
at com.example.fitness_first.fitnessfirst.ReadFileInAppFolder$1.onResult(ReadFileInAppFolder.java:63)
at com.example.fitness_first.fitnessfirst.ReadFileInAppFolder$1.onResult(ReadFileInAppFolder.java:50)
at com.google.android.gms.common.api.internal.zzb$zza.zzb(Unknown Source)
at com.google.android.gms.common.api.internal.zzb$zza.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I thought by setting a new thread to handle the data thread itself it would negate this problem but alas this was not the case. Any pointers would be kindly appreciated
The load details activity:
package com.example.fitness_first.fitnessfirst;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.ProgressBar;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.MetadataBuffer;
import com.google.android.gms.drive.query.Filter;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.Query;
import com.google.android.gms.drive.query.SearchableField;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReadFileInAppFolder extends MainActivity {
UserDetails result1;
Gson gson = new Gson();
Bundle connectionHint;
#Override
protected void onCreate(Bundle b) {
super.onCreate(b);
}
public void retrieveUserDetails() {
DataThread runner = new DataThread();
runner.start();
}
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
Filter starredFilter = Filters.eq(SearchableField.STARRED, true);
Filter mimeTypeFilter = Filters.eq(SearchableField.MIME_TYPE, "application/json");
Filter titleFilter = Filters.contains(SearchableField.TITLE, "appconfig.json");
Query query = new Query.Builder().addFilter(starredFilter).addFilter(mimeTypeFilter).addFilter(titleFilter).build();
Drive.DriveApi.getAppFolder(mGoogleApiClient).queryChildren(mGoogleApiClient, query)
.setResultCallback(new ResultCallback<DriveApi.MetadataBufferResult>() {
#Override
public void onResult(DriveApi.MetadataBufferResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Problem while retrieving results");
return;
}
MetadataBuffer metadataBuffer = result.getMetadataBuffer();
DriveId driveId = metadataBuffer.get(0).getDriveId();
DriveFile file = driveId.asDriveFile();
DriveApi.DriveContentsResult driveContentsResult =
file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).await();
if (!driveContentsResult.getStatus().isSuccess()) {
driveContentsResult = null;
}
InputStream inputStream = driveContentsResult.getDriveContents().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
result1 = gson.fromJson(reader, UserDetails.class);
Bundle bundle = new Bundle();
android.os.Message message = AccountFragment.dataHandler.obtainMessage();
try {
Thread.sleep(1000);
bundle.putString("NAME", result1.toString());
message.setData(bundle);
AccountFragment.dataHandler.sendMessage(message);
} catch (InterruptedException e) {
Log.i(TAG, "Data thread interrupted");
}
}
});
}
private class DataThread extends Thread implements Runnable {
#Override
public void run()
{
Log.i("Data Thread", "Starting");
onConnected(connectionHint);
Log.i("Data Thread", "Finshed");
}
}
And the fragment I want to pass the data too:
package com.example.fitness_first.fitnessfirst;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.nearby.messages.Message;
public class AccountFragment extends Fragment implements View.OnClickListener{
public static GoogleApiClient getInstance() {
return null;
}
private String activityName = "Account management";
private Button saveDetailsButton;
private static EditText accountName;
private EditText accountUserName;
private EditText accountHeight;
private EditText accountWeight;
private Spinner spinnerGender = null;
private Bundle name = new Bundle();
private String nameKey = "NAME";
private Bundle userName = new Bundle();
private String usernameKey = "USERNAME";
private Bundle gender = new Bundle();
private String genderKey = "GENDER";
private Bundle height = new Bundle();
private String heightKey = "HEIGHT";
private Bundle weight = new Bundle();
private String weightKey = "WEIGHT";
public static Intent detailsIntent = new Intent();
private final int spinnerPosMALE = 0;
private final int spinnerPosFEMALE = 1;
public AccountFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_account, container, false);
saveDetailsButton = (Button) rootView.findViewById(R.id.buttonSaveDetails);
saveDetailsButton.setOnClickListener(this);
accountName = (EditText) rootView.findViewById(R.id.editTextName);
accountUserName = (EditText) rootView.findViewById(R.id.editTextUsername);
spinnerGender = (Spinner) rootView.findViewById(R.id.spinnerGender);
accountHeight = (EditText) rootView.findViewById(R.id.editTextHeight);
accountWeight = (EditText) rootView.findViewById(R.id.editTextWeight);
super.onCreateView(inflater, container, savedInstanceState);
return rootView;
}
#Override
public void onClick(View v) {
name.putString("NAME", accountName.getText().toString());
userName.putString("USERNAME", accountUserName.getText().toString());
gender.putString("GENDER", spinnerGender.getSelectedItem().toString());
height.putString("HEIGHT", accountHeight.getText().toString());
weight.putString("WEIGHT", accountWeight.getText().toString());
detailsIntent.putExtras(name);
detailsIntent.putExtras(userName);
detailsIntent.putExtras(gender);
detailsIntent.putExtras(height);
detailsIntent.putExtras(weight);
CreateFileInAppFolderActivity saveDetails = new CreateFileInAppFolderActivity();
saveDetails.saveDetails(detailsIntent);
}
#Override
public void onPause() {
super.onPause();
Log.i(activityName, "Paused");
}
#Override
public void onResume() {
super.onResume();
ReadFileInAppFolder dataIn = new ReadFileInAppFolder();
dataIn.retrieveUserDetails();
Log.i(activityName, "Resumed");
}
#Override
public void onStop() {
super.onStop();
Log.i(activityName, "Stopped");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(activityName, "Destroyed");
}
public static Handler dataHandler = new Handler()
{
#Override
public void handleMessage(android.os.Message message){
String s = message.getData().getString("NAME");
accountName.setText(s);
}
};
}
As stated in the Exception message, you shouldn't use await on the UI thread.
Setting a new thread to handle the data should fix it.
[EDIT 1]
The "onResult" function is called on the UI Thread as mentioned in https://developers.google.com/android/reference/com/google/android/gms/common/api/ResultCallback#public-method-summary
public abstract void onResult (R result)
Called when the Result is ready.
It is the responsibility of the callback to release any resources
associated with the result. Some result types may implement
Releasable, in which case release() should be used to free the
associated resources.
This method is called on the main thread, unless overridden by
setHandler(Handler).

Categories

Resources