i searched every directory and i dont see problem, please help me.
BlockquoteProcess:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
at com.example.projectmanagement.wallet.CreateCashActivity.setViewOrUpdateWallet(CreateCashActivity.java:58)
at com.example.projectmanagement.wallet.CreateCashActivity.onCreate(CreateCashActivity.java:46)
And my code:
public class CreateCashActivity extends AppCompatActivity {
private EditText inputWalletTitle, inputWalletSubtitle, inputWalletText;
private Wallet alreadyAvailableWallet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_wallet);
ImageView imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(v -> onBackPressed());
inputWalletTitle = findViewById(R.id.inputWalletTitle);
inputWalletSubtitle = findViewById(R.id.inputWalletSubtitle);
inputWalletText = findViewById(R.id.inputWalletText);
Button save_btn = findViewById(R.id.save_btn);
save_btn.setOnClickListener(v -> saveWallet());
ImageView imageSave = findViewById(R.id.imageSave);
imageSave.setOnClickListener(v -> saveWallet());
if (getIntent().getBooleanExtra("isViewOrUpdate", false)) {
alreadyAvailableWallet = (Wallet) getIntent().getSerializableExtra("wallet");
setViewOrUpdateWallet();
}
}
private void setViewOrUpdateWallet() {
inputWalletTitle.setText(alreadyAvailableWallet.getTitle());
inputWalletSubtitle.setText(alreadyAvailableWallet.getSubtitle());
inputWalletText.setText(alreadyAvailableWallet.getWalletText());
if (alreadyAvailableWallet != null) {
this.findViewById(R.id.layoutDeleteWallet).setVisibility(View.VISIBLE);
}
}
private void saveWallet() {
if (inputWalletTitle.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Uzupełnij kwotę oraz walutę!", Toast.LENGTH_SHORT).show();
return;
}
if (inputWalletSubtitle.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Brak zlecenia!", Toast.LENGTH_SHORT).show();
return;
}
if (inputWalletText.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Brak opisu wydatku!", Toast.LENGTH_SHORT).show();
return;
}
final Wallet wallet = new Wallet();
wallet.setTitle(inputWalletTitle.getText().toString());
wallet.setSubtitle(inputWalletSubtitle.getText().toString());
wallet.setWalletText(inputWalletText.getText().toString());
if (alreadyAvailableWallet != null) {
wallet.setId(alreadyAvailableWallet.getId());
}
#SuppressLint("StaticFieldLeak")
class SaveWalletTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
WalletDatabase.getDatebase(getApplicationContext()).walletDao().insertWallet(wallet);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
}
new SaveWalletTask().execute();
}
public void deleteText(View view) {
final LinearLayout layoutMiscellcash = findViewById(R.id.layoutDeleteWallet);
layoutMiscellcash.findViewById(R.id.layoutDeleteWallet).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
#SuppressLint("StaticFieldLeak")
class DeleteWalletTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
WalletDatabase.getDatebase(getApplicationContext()).walletDao()
.deleteWallet(alreadyAvailableWallet);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent();
intent.putExtra("isWalletDeleted", true);
setResult(RESULT_OK, intent);
finish();
}
}
new DeleteWalletTask().execute();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
}
}
}
}
Logcat show line 58 and 46, this is:
this.findViewById(R.id.layoutDeleteWallet).setVisibility(View.VISIBLE);
and:
if (getIntent().getBooleanExtra("isViewOrUpdate", false)) { alreadyAvailableWallet = (Wallet) getIntent().getSerializableExtra("wallet"); setViewOrUpdateWallet(); }
I dont see problem in this. Please help.
Related
at the beginning I would like to point out that I am a beginner in java and android.
I'm coding an application, which I can use to send a image of test result to database. For that moment I've got possibility to upload picture to Firebase Storage and I have no clue what should I do next, to import(?) image from storage to a database of specific user.
public class BloodTestActivity extends AppCompatActivity {
ImageView imageSelected;
Button btn_uploadImage, btn_sendImage;
Uri uri;
StorageReference storageReference;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blood_test);
imageSelected = findViewById(R.id.viewSelectedImage);
btn_uploadImage = findViewById(R.id.btn_uploadImage);
btn_sendImage = findViewById(R.id.btn_sendImage);
btn_uploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UploadImage();
}
});
btn_sendImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendImage();
}
});
}
private void sendImage() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Sending test result...");
progressDialog.show();
SimpleDateFormat format = new SimpleDateFormat("yyy_MM_dd_HH_mm_ss", Locale.CANADA);
Date now = new Date();
String fileName = format.format(now);
storageReference = FirebaseStorage.getInstance().getReference("images/" + fileName);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageSelected.setImageURI(null);
Toast.makeText(BloodTestActivity.this, "Success!", Toast.LENGTH_SHORT).show();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (progressDialog.isShowing())
progressDialog.dismiss();
Toast.makeText(BloodTestActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
});
}
private void UploadImage() {
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 101);
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(BloodTestActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.cancelPermissionRequest();
}
}).check();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101 && resultCode == RESULT_OK){
uri = data.getData();
imageSelected.setImageURI(uri);
}
}
}
I'm trying to display a Toast when I call the AsyncTask class with new saveWithStickers(BaseActivity.this).execute(); to notify the user that the save process being started, when I run the code below the onPreExecute() method for some logical reason is not called so the Toast does not appear as well,is runOnUiThread the reason for this behavior?
#SuppressLint("StaticFieldLeak")
public class saveWithStickers extends AsyncTask<Void, File, File> {
File fileSaved;
Context mContext;
saveWithStickers(Context context) {
mContext = context;
}
#Override
protected File doInBackground(Void... voids) {
fileSaved = FileUtil.getNewFile(BaseActivity.this, "VAPOGRAM");
if (fileSaved != null)
runOnUiThread(() -> {
stickerView.save(fileSaved, true);
});
return fileSaved;
}
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
content.setVisibility(View.GONE);
Toast.makeText(mContext, "saving ...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckPermissionUtil checkPermissionUtil = new CheckPermissionUtil(BaseActivity.this);
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermissionUtil.checkPermission(1812)) {
new saveWithStickers(BaseActivity.this).execute();
} else
checkPermissionUtil.requestPermission(1812);
} else {
new saveWithStickers(BaseActivity.this).execute();
}
}
});
Replace your code with this
#SuppressLint("StaticFieldLeak")
public class saveWithStickers extends AsyncTask<Void, File, File> {
File fileSaved;
Context mContext;
saveWithStickers(Context context) {
mContext = context;
}
#Override
protected File doInBackground(Void... voids) {
fileSaved = FileUtil.getNewFile(BaseActivity.this, "PHOTO EDITOR");
if (fileSaved != null)
runOnUiThread(() -> stickerView.save(fileSaved, true));
return fileSaved;
}
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(mContext, "Saving ...", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
}
}
To access to the context you need to pass it or use WeakRerefence to your parent activity
I am using a Sinch tutorial(https://github.com/sinch/android-app-app-calling-headers) as a framework for an app I am trying to develop. The following is the login class from the tutorial which I have updated and been successful in initializing the sinch client.
public class LoginActivity extends BaseActivity implements SinchService.StartFailedListener {
private Button mLoginButton;
private EditText mLoginName;
private static final int REQUEST_PERMISSION = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mLoginName = (EditText) findViewById(R.id.loginName);
mLoginButton = (Button) findViewById(R.id.loginButton);
mLoginButton.setEnabled(false);
requestAppPermissions(new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION}, R.string.msg, REQUEST_PERMISSION);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
loginClicked();
}
});
}
#Override
public void onPermissionGranted(int requestCode) {
}
#Override
protected void onServiceConnected() {
mLoginButton.setEnabled(true);
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onStarted() {
openPlaceCallActivity();
}
private void loginClicked() {
String userName = mLoginName.getText().toString();
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
return;
}
if (!getSinchServiceInterface().isStarted()) {
getSinchServiceInterface().startClient(userName);
} else {
openPlaceCallActivity();
}
}
private void openPlaceCallActivity() {
Intent mainActivity = new Intent(this, PlaceCallActivity.class);
startActivity(mainActivity);
}
}
The instantiation of the client occurs in the SinchService Class which is as follows:
private static final String APP_KEY = "";
private static final String APP_SECRET = "";
private static final String ENVIRONMENT = "sandbox.sinch.com";
public static final String LOCATION = "LOCATION";
public static final String CALL_ID = "CALL_ID";
static final String TAG = SinchService.class.getSimpleName();
private SinchServiceInterface mSinchServiceInterface = new SinchServiceInterface();
private SinchClient mSinchClient;
private String mUserId;
private StartFailedListener mListener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
if (mSinchClient != null && mSinchClient.isStarted()) {
mSinchClient.terminate();
}
super.onDestroy();
}
private void start(String userName) {
if (mSinchClient == null) {
mUserId = userName;
mSinchClient = Sinch.getSinchClientBuilder().context(getApplicationContext()).userId(userName)
.applicationKey(APP_KEY)
.applicationSecret(APP_SECRET)
.environmentHost(ENVIRONMENT).build();
mSinchClient.setSupportCalling(true);
mSinchClient.startListeningOnActiveConnection();
mSinchClient.addSinchClientListener(new MySinchClientListener());
mSinchClient.getCallClient().addCallClientListener(new SinchCallClientListener());
mSinchClient.start();
}
}
private void stop() {
if (mSinchClient != null) {
mSinchClient.terminate();
mSinchClient = null;
}
}
private boolean isStarted() {
return (mSinchClient != null && mSinchClient.isStarted());
}
#Override
public IBinder onBind(Intent intent) {
return mSinchServiceInterface;
}
public class SinchServiceInterface extends Binder {
public Call callPhoneNumber(String phoneNumber) {
return mSinchClient.getCallClient().callPhoneNumber(phoneNumber);
}
public Call callUser(String userId) {
return mSinchClient.getCallClient().callUser(userId);
}
public Call callUser(String userId, Map<String, String> headers) {
return mSinchClient.getCallClient().callUser(userId, headers);
}
public String getUserName() {
return mUserId;
}
public boolean isStarted() {
return SinchService.this.isStarted();
}
public void startClient(String userName) {
start(userName);
}
public void stopClient() {
stop();
}
public void setStartListener(StartFailedListener listener) {
mListener = listener;
}
public Call getCall(String callId) {
return mSinchClient.getCallClient().getCall(callId);
}
}
public interface StartFailedListener {
void onStartFailed(SinchError error);
void onStarted();
}
private class MySinchClientListener implements SinchClientListener {
#Override
public void onClientFailed(SinchClient client, SinchError error) {
if (mListener != null) {
mListener.onStartFailed(error);
}
mSinchClient.terminate();
mSinchClient = null;
}
#Override
public void onClientStarted(SinchClient client) {
Log.d(TAG, "SinchClient started");
if (mListener != null) {
mListener.onStarted();
}
}
#Override
public void onClientStopped(SinchClient client) {
Log.d(TAG, "SinchClient stopped");
}
#Override
public void onLogMessage(int level, String area, String message) {
switch (level) {
case Log.DEBUG:
Log.d(area, message);
break;
case Log.ERROR:
Log.e(area, message);
break;
case Log.INFO:
Log.i(area, message);
break;
case Log.VERBOSE:
Log.v(area, message);
break;
case Log.WARN:
Log.w(area, message);
break;
}
}
#Override
public void onRegistrationCredentialsRequired(SinchClient client,
ClientRegistration clientRegistration) {
}
}
private class SinchCallClientListener implements CallClientListener {
#Override
public void onIncomingCall(CallClient callClient, Call call) {
Log.d(TAG, "Incoming call");
Intent intent = new Intent(SinchService.this, IncomingCallScreenActivity.class);
intent.putExtra(CALL_ID, call.getCallId());
intent.putExtra(LOCATION, call.getHeaders().get("location"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
SinchService.this.startActivity(intent);
}
}
}
For my purposes, I need to derive the username for the client from my shared preferences folder. I made a dummy app that uses the same framework above with the addition of shared preferences but I always get a NullPointerException error. The following is my login class from my dummy app.
public class LoginActivity extends BaseActivity implements SinchService.StartFailedListener {
private EditText mLoginName, recipientName, coordinateA, coordinateB;
private Button loginButton;
private static final int REQUEST_PERMISSION = 10;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.userInput);
recipientName = (EditText) findViewById(R.id.recipientInput);
loginButton = (Button) findViewById(R.id.loginButton);
requestAppPermissions(new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_FINE_LOCATION}, R.string.msg, REQUEST_PERMISSION);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("user_name", mLoginName.getText().toString());
editor.putString("recipient_name", recipientName.getText().toString());
editor.commit();
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginClicked();
}
});
}
#Override
public void onPermissionGranted(int requestCode) {
}
#Override
protected void onServiceConnected() {
getSinchServiceInterface().setStartListener(this);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onStartFailed(SinchError error) {
Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onStarted() {
openPlaceCallActivity();
}
private void loginClicked() {
SharedPreferences sharedPreferences = getSharedPreferences("MyData", MODE_PRIVATE);
String userName = sharedPreferences.getString("user_name", DEFAULT);
if (userName.isEmpty()) {
Toast.makeText(this, "Please enter a name",
Toast.LENGTH_LONG).show();
return;
}
if (!getSinchServiceInterface().isStarted()) {
getSinchServiceInterface().startClient(userName);
} else {
openPlaceCallActivity();
}
}
private void openPlaceCallActivity() {
Intent mainActivity = new Intent(LoginActivity.this, PlaceCallActivity.class);
startActivity(mainActivity);
}
}
When comparing my login class with the tutorial's login class-- the only difference is where the variable "userName" is derived. We both have a value attached to the username; however, only one client is able to establish while the other throws a NullPointerException Error. Anyone know why?
EDIT: The error message is as follows:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dejon_000.sinchtest2, PID: 32470
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.example.dejon_000.sinchtest2.SinchService$SinchServiceInterface.isStarted()' on a null object reference
at com.example.dejon_000.sinchtest2.LoginActivity.loginClicked(LoginActivity.java:83)
at com.example.dejon_000.sinchtest2.LoginActivity.access$000(LoginActivity.java:17)
at com.example.dejon_000.sinchtest2.LoginActivity$1.onClick(LoginActivity.java:47)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20059)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
SECOND EDIT: The getSinchServiceInterface() method is found in the BaseActivity class. It is as follows:
public abstract class BaseActivity extends Activity implements ServiceConnection {
private SparseIntArray mErrorString;
public static final String DEFAULT = "N/A";
private SinchService.SinchServiceInterface mSinchServiceInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getApplicationContext().bindService(new Intent(this, SinchService.class), this,
BIND_AUTO_CREATE);
mErrorString = new SparseIntArray();
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
onServiceConnected();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = null;
onServiceDisconnected();
}
}
protected void onServiceConnected() {
// for subclasses
}
protected void onServiceDisconnected() {
// for subclasses
}
protected SinchService.SinchServiceInterface getSinchServiceInterface() {
return mSinchServiceInterface;
}
public abstract void onPermissionGranted(int requestCode);
public void requestAppPermissions(final String[] requestedPermissions, final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean showRequestPermissions = false;
for (String permission : requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (showRequestPermissions) {
Snackbar.make(findViewById(android.R.id.content), stringId, Snackbar.LENGTH_INDEFINITE).setAction("GRANT", new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(BaseActivity.this, requestedPermissions, requestCode);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionGranted(requestCode);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for(int permission : grantResults){
permissionCheck = permissionCheck + permission;
}
if((grantResults.length > 0)&& PackageManager.PERMISSION_GRANTED == permissionCheck ){
onPermissionGranted(requestCode);
}else{
Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode), Snackbar.LENGTH_INDEFINITE).setAction("ENABLE", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:"+ getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
}).show();
}
}
}
Try this :
on your BaseActivity.java
instead of
protected void onServiceConnected() {
// for subclasses
}
put
protected void onServiceConnected(IBinder iBinder) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
}
and in your LoginActivity.java
Override the function onServiceConnected(IBinder iBinder)
#Override
protected void onServiceConnected(IBinder iBinder) {
super.onServiceConnected(iBinder);
getSinchServiceInterface().setStartListener(this);
}
My code is as follows
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runBtn = (Button)findViewById(R.id.button_run_demo);
ttobj = new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
ttobj.setLanguage(Locale.UK);
}
}
});
runBtn.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
}
public void onPause() {
if (ttobj != null) {
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
public void speakText(String text) {
String toSpeak = text;
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
//do my stuff
speakText("Hello");
}
}
Although I am able to do my stuff I am not able to run speech.
Am I missing something ??
Thanks All
When onActivityResult() is called the TextToSpeech is already shutdown since you shut it down in onPause(). You have to either set a flag to speak "Hello" when TextToSpeech is reinitialize or put your code in onPause() in onDestroy().
i have a problem to send fbid to my server after logged out once. and if i want to login again it always send twice request and start the activity twice.
MainActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TheGaffer", "ONCREATE");
mFacebook = new Facebook(APP_ID);
SessionStore.restore(mFacebook, this);
setContentView(R.layout.login_view);
mLoginButton = (LoginButton) findViewById(R.id.login);
SessionEvents.addAuthListener(new SampleAuthListener());
mLoginButton.init(this, mFacebook);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleAuthListener implements AuthListener {
public void onAuthSucceed() {
new fbRequest().execute("/user_profiles/registerUser");
}
private class fbRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TheGaffer.this , null,
"Loading...");
}
protected String doInBackground(String... urls) {
String fbid = null;
Bundle params = new Bundle();
params.putString("fields", "id,name");
try {
JSONObject jsonObjSend = new JSONObject();
JSONObject fbData = new JSONObject(mFacebook.request("me", params));
fbid = fbData.getString("id");
jsonObjSend.put("fbid", fbData.getString("id"));
jsonObjSend.put("username", fbData.getString("name"));
jsonObjSend.put("playerPhoto", "http://graph.facebook.com/"+ fbData.getString("id") +"/picture");
HttpClient.SendHttpPost(urls[0], jsonObjSend);
} catch (Exception e) {
Log.e("FACEBOOK", "Error parsing data " + e.toString());
}
return fbid;
}
#Override
protected void onPostExecute(String fbid) {
Toast.makeText(getApplicationContext(), "Login successful", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent = new Intent(TheGaffer.this, TeamActivity.class);
intent.putExtra("fbid", fbid);
startActivity(intent);
}
}
TeamActivity.java:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_create_team:
intent = new Intent(TeamActivity.this, CreateTeam.class);
return true;
case R.id.menu_logout:
Log.i("Logout", "Logged out");
Intent intent = new Intent(TeamActivity.this, TheGaffer.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Once I was trapped in similar situation where Activity call twice one after another.
To avoid this after lots of research I find a very easy solution.
May be solution is not perfect but works for me
in manifest.xml file
in your activity just add
android:launchMode="singleTask"