Below is the pictorial of the problem with my app.
THE APP ON STARTUP:
ON 100% PROGRESS:
NOW, IF I HIT BACK KEY AND AGAIN RETURN TO APP:
WHAT I ACTUALLY WANT: app should resume and not reload when the user returns after pressing back key.
I am sharing the code below. Kindly, suggest a solution.
package com.url.app;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;
import android.provider.Settings;
public class MainActivity extends Activity {
private WebView wv;
//make HTML upload button work in Webview
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
//Check if user is online
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
//if not online show alertdialog with settings button
public void showNoConnectionDialog(Context ctx1) {
final Context ctx = ctx1;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.setCancelable(false);
builder.show();
}
//supress lint coz it cries over javascript enabled
#SuppressLint("SetJavaScriptEnabled") #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//if not online then show NO CONNECTION Dialog
if(!isOnline()) {
showNoConnectionDialog(MainActivity.this);
}
//webview
wv = new WebView(this);
//loadurl
wv.loadUrl(getString(R.string.siteurl));
//Enable JavaScript
wv.getSettings().setJavaScriptEnabled(true);
//Zoom
wv.getSettings().setBuiltInZoomControls(true);
wv.getSettings().setSupportZoom(true);
//progressdialog
final ProgressDialog pd = ProgressDialog.show(this, "", getString(R.string.loading), true);
pd.setCanceledOnTouchOutside(false);
wv.setWebViewClient(new WebViewClient(){
//hide progressdialog when page loads completely
#Override
public void onPageFinished(WebView view, String url) {
if(pd.isShowing() && pd!=null)
{
pd.dismiss();
}
}
});
wv.setWebChromeClient(new WebChromeClient() {
// For Android 3.0+
public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
MainActivity.this.startActivityForResult( Intent.createChooser( i, getString(R.string.fileselect) ), MainActivity.FILECHOOSER_RESULTCODE );
}
// For Android < 3.0
public void openFileChooser( ValueCallback<Uri> uploadMsg ) {
openFileChooser( uploadMsg, "" );
}
// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
openFileChooser( uploadMsg, "" );
}
});
setContentView(wv);
}
}
PS: the upload button is working in my code, the problem is how do I keep WebView active in background, such that if user starts uploading and exits the app, uploading continues.
UPDATE: I think overriding the back button along with a notification may be useful in this case.
Catching the back button to behave like home key
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
Related
I saw so many similar questions, but none of them can helped me.
Here's the part of the mailto and tel handle:
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url_https = "https://somivill-flex.hu/";
String url_http = "http://somivill-flex.hu/";
if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
else if (url.startsWith("mailto:")) {
String mail_add = url.replace("mailto:", "");
MailTo mailto = MailTo.parse(mail_add);
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Kérdés");
mail.putExtra(Intent.EXTRA_EMAIL, new String[]{mailto.getTo()});
startActivity(mail);
return false;
}
else if (url.startsWith("tel://")) {
String dial_num = url.replace("tel://", "");
Intent dial = new Intent(Intent.ACTION_DIAL, Uri.parse(dial_num));
startActivity(dial);
return true;
}
return true;
}
}
Here's the AndroidManifest.xml file permission part:
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.somivillflexshop">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
Here's the full MainActivity.java code:
package com.example.somivillflexshop;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.net.MailTo;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.net.Uri;
import android.os.Environment;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.app.Activity;
import android.view.KeyEvent;
import android.webkit.WebResourceRequest;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private String url;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomWebViewClient client = new CustomWebViewClient(this);
checkDownloadPermission();
webView = findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("http://www.somivill-flex.hu");
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
request.setDescription("Letöltés...");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Letöltés...", Toast.LENGTH_SHORT).show();
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Letöltés befejezve", Toast.LENGTH_SHORT).show();
}
};
});
}
private void checkDownloadPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Egyes részeknék lehetősége van fájlokat letölteni. Ezek letöltéséhez kell engedélyt adni.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && this.webView.canGoBack()) {
this.webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(
WebView view, String url) {
return (false);
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Biztosan ki szeretnél lépni?");
alertDialogBuilder
.setMessage("Kattints az \"Igen\"-re a kilépéshez!")
.setCancelable(false)
.setPositiveButton("Igen",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
)
.setNegativeButton("Nem", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url_https = "https://somivill-flex.hu/";
String url_http = "http://somivill-flex.hu/";
if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
else if (url.startsWith("mailto:")) {
String mail_add = url.replace("mailto:", "");
MailTo mailto = MailTo.parse(mail_add);
Intent mail = new Intent(Intent.ACTION_SEND);
mail.setType("message/rfc822");
mail.putExtra(Intent.EXTRA_SUBJECT, "Kérdés");
mail.putExtra(Intent.EXTRA_EMAIL, new String[]{mailto.getTo()});
startActivity(mail);
return false;
}
else if (url.startsWith("tel://")) {
String dial_num = url.replace("tel://", "");
Intent dial = new Intent(Intent.ACTION_DIAL, Uri.parse(dial_num));
startActivity(dial);
return true;
}
return true;
}
}
}
class CustomWebViewClient extends WebViewClient {
private Activity activity;
public CustomWebViewClient(Activity activity) {
this.activity = activity;
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
return false;
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) {
return false;
}
}
My problema is that, if I click on one of the 2 links above, the app still stays in the WebView, and says that UNKNOWN_URL_SCHEME. My other idea is to let these two link formats out of the WebView and let open it in browser but I'm not professional in java.
I hope someone can help me. If you can, thanks a lot!
Have a nice day guys!
When the user captures the image, the device will automatically read aloud the text. for that i have implemented texttospeech method but when this activity stop i want to start another task. how will it can be done?
After reading the captured text, I want to implement another text-to-speech method how can i do this?
package com.example.software2.ocrhy;
import static android.Manifest.permission.CAMERA;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity2 extends AppCompatActivity {
private static final int REQUEST_SPEECH = 101;
private static final int REQ_CODE_SPEECH_INPUT = 100;
Button buttonCamera;
private Button button;
private TextView mVoiceInputTv;
private TextView textView;
private SurfaceView surfaceView;
private CameraSource cameraSource;
private TextRecognizer textRecognizer;
private static TextToSpeech textToSpeech;
private String stringResult = null;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mVoiceInputTv = (TextView) findViewById(R.id.textView);
textView = (TextView) findViewById(R.id.textView);
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, PackageManager.PERMISSION_GRANTED);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.CANADA);
textToSpeech.setSpeechRate(1f);
Toast.makeText(MainActivity2.this, "tap on the screen and say yes for read and no for return to the main menu", Toast.LENGTH_SHORT).show();
textToSpeech.speak("tap on the screen and say yes for read and no for return to the main menu", TextToSpeech.QUEUE_ADD, null);
}
}
});
}
private void textRecognizer() {
Toast.makeText(MainActivity2.this, "Tap on the screen and listen ", Toast.LENGTH_SHORT).show();
textToSpeech.speak(" Tap on the screen take a picture of any text with your device and listen", TextToSpeech.QUEUE_FLUSH, null);
textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer)
.setRequestedPreviewSize(1280, 1024)
.setAutoFocusEnabled(true)
.build();
surfaceView = findViewById(R.id.surfaceView);
Context context = this;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
cameraSource.start(surfaceView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
}
private void capture() {
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
SparseArray<TextBlock> sparseArray = detections.getDetectedItems();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < sparseArray.size(); ++i) {
TextBlock textBlock = sparseArray.valueAt(i);
if (textBlock != null && textBlock.getValue() != null) {
stringBuilder.append(textBlock.getValue() + " ");
}
}
final String stringText = stringBuilder.toString();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
stringResult = stringText;
resultObtained();
}
});
}
});
}
private void resultObtained() {
setContentView(R.layout.activity_main2);
textView = findViewById(R.id.textView);
textView.setText(stringResult);
textToSpeech.speak(stringResult, TextToSpeech.QUEUE_FLUSH, null, null);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startVoiceInput();
}
});
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, How can I help you?");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
if (mVoiceInputTv.getText().toString().contentEquals("time and date")) {
Intent intent = new Intent(getApplicationContext(), MainActivity4.class);
startActivity(intent);
}
if (mVoiceInputTv.getText().toString().contentEquals("battery")) {
Intent intent = new Intent(getApplicationContext(), MainActivity6.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("location")) {
Intent intent = new Intent(getApplicationContext(), MainActivity8.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
if (mVoiceInputTv.getText().toString().contentEquals("weather")) {
Intent intent = new Intent(getApplicationContext(), MainActivity5.class);
startActivity(intent);
mVoiceInputTv.setText(null);
} else {
textToSpeech.speak( "Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("calculator")) {
Intent intent = new Intent(getApplicationContext(), MainActivity3.class);
startActivity(intent);
mVoiceInputTv.setText(null);
}
else if(mVoiceInputTv.getText().toString().contentEquals("exit")) {
finish();
}
else {
textToSpeech.speak("Do not understand just tap on the screen Say again", TextToSpeech.QUEUE_FLUSH, null);
}
if (mVoiceInputTv.getText().toString().contentEquals("yes")) {
setContentView(R.layout.surface);
surfaceView = findViewById(R.id.surfaceView);
surfaceView.setOnClickListener((View v) -> {
capture();
});
textRecognizer();
mVoiceInputTv.setText(null);
} else if (mVoiceInputTv.getText().toString().contentEquals("no")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
break;
}
}
}
public boolean onKeyDown(int keyCode, #Nullable KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
textToSpeech.speak("You are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
textToSpeech.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
},1000);
}
return true;
}
public void buttonStart(View view) {
startVoiceInput();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
}
super.onPause();
}
}
just use the same mode on text to speech ADD and it will play when the first one is done, ADD = ADD, FLUSH = reset
textToSpeech.speak("this will play when first is done",
TextToSpeech.QUEUE_ADD, null);
You have to call startVoiceInput() again.
You are setting this call for an onClick() handler on a TextView already.
So I'm writing a voice assistant app for my final in Intro to Android, and I got most of it to work however I would like the intent for Instagram to open the app not the website. (That would be good enough for now)
I have tried several solutions from here to no avail.
Ideally, I would like for it to get a list of installed apps and throw those in an array that just responds to the apps name
I have the code is as follows, written in Java.
Any help will be appreciated.
package com.example.kako;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.text.format.DateUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import static android.text.format.DateUtils.FORMAT_SHOW_TIME;
import static android.text.format.DateUtils.formatDateTime;
public class MainActivity extends AppCompatActivity {
//Requesting run-time permissions
//Create placeholder for user's consent to record_audio permission.
//This will be used in handling callback
private final int MY_PERMISSIONS_RECORD_AUDIO = 1;
private void requestAudioPermissions() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED) {
//When permission is not granted by user, show them message why this permission is needed.
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(this, "Please grant permissions to record audio", Toast.LENGTH_LONG).show();
//Give user option to still opt-in the permissions
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_RECORD_AUDIO);
} else {
// Show user dialog to grant permission to record audio
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_RECORD_AUDIO);
}
}
//If permission is granted, then go ahead recording audio
else if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED) {
//Go ahead with recording audio now
recordAudio();
}
}
private TextToSpeech myTTS;
private SpeechRecognizer mySpeechRecognizer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
mySpeechRecognizer.startListening(intent);
}
});
initializeTextToSpeech();
initializeSpeechRecognizer();
}
private void initializeSpeechRecognizer() {
if(SpeechRecognizer.isRecognitionAvailable(this)){
mySpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mySpeechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle bundle) {
List<String> results = bundle.getStringArrayList(
SpeechRecognizer.RESULTS_RECOGNITION
);
processResult(Objects.requireNonNull(results).get(0));
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
}
}
private void processResult(String command) {
command = command.toLowerCase();
//what is your name?
//what is the time?
//open a browser
//private browser
//youtube
//applications
if(command.indexOf("what") != -1){
if(command.indexOf("your name") != -1) {
speak("Hi! I'm KayKo!");
}
if(command.indexOf("time") != -1) {
Date now = new Date();
String time = formatDateTime(this, now.getTime(),
FORMAT_SHOW_TIME);
speak("the time is " + time);
}
if(command.indexOf("date") != -1) {
Date now = new Date();
String date = formatDateTime(this, now.getTime(),
DateUtils.FORMAT_SHOW_DATE);
speak("the Date is " + date);
}
}
else if ( command.indexOf( "open" ) != -1 ) {
if ( command.indexOf( "browser" ) != -1 ) {
Intent intent;
intent = new Intent( Intent.ACTION_VIEW,
Uri.parse( "https://www.google.com/" ) );
startActivity( intent );
}
}
else if (command.indexOf("private") != -1) {
if (command.indexOf("browser") != -1) {
Intent intent;
intent = new Intent( Intent.ACTION_VIEW,
Uri.parse( "https://duckduckgo.com/" ) );
startActivity( intent );
}
}else if (command.indexOf("youtube") != -1) {
Intent intent;
intent = new Intent( Intent.ACTION_VIEW,
Uri.parse( "https://youtube.com/") );
startActivity( intent );
}else if (command.indexOf("instagram") != -1) {
Intent intent;
intent = new Intent( Intent.ACTION_VIEW,
Uri.parse( "https://www.instagram.com/artsyphotosllc/") );
startActivity( intent );
}
}
private void initializeTextToSpeech() {
myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if(myTTS.getEngines().size() ==0){
Toast.makeText(MainActivity.this,"There is no TTS engine installed on this device"
, Toast.LENGTH_LONG).show();
finish();
} else{
myTTS.setLanguage(Locale.getDefault());
speak("Ready");
}
}
});
}
private void speak(String message){
if(Build.VERSION.SDK_INT >= 21){
myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null, null);
}else {
myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
super.onPause();
myTTS.shutdown();
}
}
PackageManager pm = getPackageManager();
//apps package names
String instagram = "com.instagram.android",
youtube = "com.google.android.youtube",
facebook = "com.facebook.katana",
whatsapp = "com.whatsapp";
//other apps package names
// can be found in url of app in play store in the browser
//ex: https://play.google.com/store/apps/details?id=***com.whatsapp***&hl=en
//launch the app
Intent appIntent = pm.getLaunchIntentForPackage(instagram);//change app package name
if(appIntent != null)
startActivity(appIntent);
else {
//App not installed !
}
I'm trying to make a profile activity where user's data will be shown and also user can edit their data also. Everything works fine. There is no error showing in the code but when i'm trying to upload an image using camera or gallery. It's not uploading in the firebase storage. Also no "Toast" message shows. I'm fully stucked in this problem. How to solve this problem? The following code is given below:
package com.example.muthomap;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
public class Profile extends AppCompatActivity {
//views
ImageView profilephoto;
private TextView pname,pemail,pphone;
private FloatingActionButton medit;
//Instance of FirebaseAuth
private FirebaseAuth mAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//progress Dialog
ProgressDialog progressDialog;
//permissions constants
private static final int CAMERA_REQUEST_CODE=100;
private static final int STORAGE_REQUEST_CODE=200;
private static final int IMAGE_PICK_GALLERY_REQUEST_CODE=300;
private static final int IMAGE_PICK_CAMERA_REQUEST_CODE=400;
//arrays of permissions to be requested
String cameraPermissions[];
String storagePermissions[];
//uri of picked image
Uri image_uri;
//to check either profile or cover photo
String profileOrCoverPhoto;
//storage
StorageReference storageReference;
//path where imagees of profile and cover will be stored
String storagePath = "Users_Profile_Cover_Imgs/";
public Profile(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
profilephoto= findViewById(R.id.profile_photo);
pname= findViewById(R.id.profile_name);
pemail= findViewById(R.id.profile_email);
pphone= findViewById(R.id.profile_mobile);
medit= findViewById(R.id.edit);
//Initialize the FirebaseAuth instance
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference= firebaseDatabase.getReference("user").child("customers");
storageReference = FirebaseStorage.getInstance().getReference().child(storagePath);
//intitalize arrays of permissions
cameraPermissions= new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions= new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Updating User.....");
/*We need to get current signed in users email,name,phone etc. And we retrive user
detail using email.*/
/* by using OrderByChild query we will show the detail from a node whose
key named email has value equal to currently signed in email.
It will search all nodes, where the key matches it will get it's detail.
*/
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//check until getting required data
for (DataSnapshot ds : dataSnapshot.getChildren()) {
//get data
String name = "" + ds.child("name").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String image = "" + ds.child("image").getValue();
//set data
pname.setText(name);
pemail.setText(email);
pphone.setText(phone);
try {
Picasso.get().load(image).resize(50, 50)
.centerCrop().into(profilephoto);
} catch (Exception e) {
//if there is any exceptions while getting image then set defaults
Picasso.get().load(R.drawable.ic_default_face).into(profilephoto);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//handleing floating Button
medit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowEditProfileDialog();
}
});
}
private boolean checkStoragePermission(){
/*check if storage permission is enebled or not
return true if enebled
return false if not
*/
boolean result = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestStoragePermission(){
//request runtime storage permission
requestPermissions(storagePermissions,STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission(){
/*check if storage permission is enebled or not
return true if enebled
return false if not
*/
boolean result = ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission(){
//request runtime camera permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(cameraPermissions,CAMERA_REQUEST_CODE);
}
}
private void ShowEditProfileDialog() {
/*show dialog of options
*1. Upload Photo
*2. Edit Name
*3. Edit phone
*/
//options ro show in Dialog
String options[ ] = {"Upload Photo","Edit Name","Edit phone"};
//alert Dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//title
builder.setTitle("Choose Actions");
//set items
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if (which == 0){
//Edit Profile picture clicked
progressDialog.setMessage("Updating Profile Picture");
profileOrCoverPhoto = "image";
showImagePicDialog();
}
else if (which == 1){
//Edit Name clicked
progressDialog.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
}
else if (which == 2){
//Edit Phone clicked
progressDialog.setMessage("Updating Phone Number");
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(final String key) {
//custom dialog
AlertDialog.Builder builder= new AlertDialog.Builder(Profile.this);
builder.setTitle("Update "+ key);
//set layout of dialog
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//add edit text
final EditText editText = new EditText(Profile.this);
editText.setHint("Enter "+key);
linearLayout.addView(editText);
builder.setView(linearLayout);
//add button to update
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//input text
String val = editText.getText().toString().trim();
//validate if user has entered somethig or not
if ((!TextUtils.isEmpty(val))){
progressDialog.show();
HashMap<String, Object> results = new HashMap<>();
results.put(key, val);
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(Profile.this, "Please Enter ", Toast.LENGTH_SHORT).show();
}
}
});
//add button to cancel
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
//create and show dialog
builder.create().show();
}
private void showImagePicDialog() {
//options containing options Camera and Gallery
String options[ ] = {"Camera","Gallery"};
//alert Dialog
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//title
builder.setTitle("Pick Image From");
//set items
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
if (which == 0){
//Camera Clicked
if (!checkCameraPermission()){
requestCameraPermission();
}
else {
pickFromCamera();
}
}
else if (which == 1){
//Gallery Picked
if (!checkStoragePermission()){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestStoragePermission();
}
}
else{
pickFromGallery();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
/*This method called when user press Allow or Deny from permission request dialog
here we will handle permissions cases (allowed or denied)
*/
switch (requestCode){
case CAMERA_REQUEST_CODE:{
//picking from camera, first check if camera and storage permission allowed or not
if (grantResults.length>0){
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted= grantResults[1]==PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted){
//permission enebled
pickFromCamera();
}
else {
Toast.makeText(this, "Please eneble Camera and Storage permission",Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE:{
//picking from storage, first check if storage permission allowed or not
if (grantResults.length >0 ){
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted){
//permission enebled
pickFromGallery();
}
else {
Toast.makeText(this, "Please eneble Storage permission",Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//This method will be called after picking image from Camera or Gallery
if (resultCode == RESULT_OK){
if (resultCode == IMAGE_PICK_GALLERY_REQUEST_CODE){
//image is picked from gallery , get uri of image
image_uri = data.getData();
uploadProfilePhoto(image_uri);
}
if (resultCode == IMAGE_PICK_CAMERA_REQUEST_CODE){
//image is picked from Camera, get uri
uploadProfilePhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfilePhoto(Uri uri) {
//show progress
progressDialog.show();
/*The parameter "image_uri" contains the uri of image picked either from camera or gallery
*Will use UID of the currently signed in user as name of the image so ther will be only one image
* profile and one image for cover for each user */
//path and name of image to be stored in firebase storage
String filePathAndName = storagePath+ ""+ profileOrCoverPhoto +"_"+ user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask=taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
//check if uploading is successfull
if (uriTask.isSuccessful()){
//image uploaded
//add url in user's database
HashMap<String,Object> results = new HashMap<>();
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
//url in database of user is added successfully
//dismiss progress bar
progressDialog.dismiss();
Toast.makeText(Profile.this, "Image Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, "Error Updating Image", Toast.LENGTH_SHORT).show();
}
});
}
else {
//error
progressDialog.dismiss();
Toast.makeText(Profile.this, "Some Error Occurd", Toast.LENGTH_SHORT).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Profile.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//Intent of picking image from device camera
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
//put image uri
image_uri=Profile.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
//intent to open camera
Intent cameraIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_REQUEST_CODE);
}
private void pickFromGallery() {
//pick from gallery
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_REQUEST_CODE);
}
}
Logcat: Logcat log
https://i.stack.imgur.com/2NqTU.jpg
I have successfully integrated twitter in my app but now I want to open next activity upon successful login.
How do I implement a call back method? i use on Activity result for twitter but it does not gives any error but also its does not works kindly tell me the right way to solve it thanks in advance....
package com.example.android.accenturefeed;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
#SuppressWarnings("ALL")
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
public ProgressDialog pdialog;
public AlertDialog alertDialog;
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 1901;
private LinkedInOAuthService oAuthService;
private LinkedInApiClientFactory factory;
private LinkedInRequestToken liToken;
private LinkedInApiClient client;
static String TWITTER_CONSUMER_KEY = "my_consumer_key";
static String TWITTER_CONSUMER_SECRET = "my_consumer_secret";
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
// Login button
Button TwitterLoginButton;
// Twitter
private static Twitter twitter;
private static RequestToken requestToken;
// Shared Preferences
private static SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for facebook signin
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.login_activity);
final LoginActivity thisActivity = this;
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// for twitter login
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
TwitterLoginButton = (Button) findViewById(R.id.btnLoginTwitter);
TwitterLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
LoginActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(requestToken.getAuthenticationURL())));
} catch (TwitterException e) {
e.printStackTrace();
}
}
});
// for google signin
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// for logging out from facebook
LoginManager.getInstance().logOut();
// checks internet
if (isNetworkAvailable()==true){
//linkedin button
Button libutton=(Button)findViewById(R.id.btnLinkedin);
libutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//linkedin signin
LISessionManager.getInstance(getApplicationContext()).init(thisActivity, buildScope(), new AuthListener() {
#Override
public void onAuthSuccess() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
#Override
public void onAuthError(LIAuthError error) {
info.setText("Login attempt failed.");
}
}, true);
}
});
// google login button
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(this);
// shows error
info = (TextView)findViewById(R.id.info);
// facebook login button
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
// info.setText(
// "User ID: "
// + loginResult.getAccessToken().getUserId()
// + "\n" +
// "Auth Token: "
// + loginResult.getAccessToken().getToken()
// );
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException error) {
info.setText("Login attempt failed.");
}
});
Button b1=(Button)findViewById(R.id.loginbutton);
final EditText user =(EditText)findViewById(R.id.editTextentername);
final EditText pass =(EditText)findViewById(R.id.edittextenterpassword);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String givenUsername = user.getText().toString();
String givenPassword = pass.getText().toString();
if (givenUsername.isEmpty() || givenPassword.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setText("Username & password required!");
} else {
pdialog = ProgressDialog.show(LoginActivity.this, "Authenticating", "Please wait...");
sendLoginRequest(givenUsername, givenPassword);
}
}
private void sendLoginRequest(final String givenUsername, final String givenPassword) {
SendLoginRequestAsyncTask asyncTask = (SendLoginRequestAsyncTask) new SendLoginRequestAsyncTask(new SendLoginRequestAsyncTask.AsyncResponse() {
#Override
public void processFinish(String name) {
if (name.isEmpty()) {
TextView textView = (TextView) findViewById(R.id.error);
textView.setTextColor(Color.parseColor("#d41a14"));
textView.setText("Username or Password Is Incorrect!");
pdialog.dismiss();
} else {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
intent.putExtra("username", name);
pdialog.dismiss();
startActivity(intent);
}
}
}).execute(givenUsername, givenPassword);
}
}
);
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Check Your Internet Connection");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
private Scope buildScope() {
return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// for twitter result
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
// for google
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
// for facebook
else {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//forlinkedin
LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
}
// for google to open next activity or not
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivityForResult(intent, 1);
} else {
// Signed out, show unauthenticated UI.
info.setText("Login attempt failed.");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_logout) {
// Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
// #Override
// public void onResult(Status status) {
// mGoogleApiClient.disconnect();
// }
// });
return true;
}
return super.onOptionsItemSelected(item);
}
// checks Internet is available or not
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
// for google sign in button on click method
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
// ...
}
}
// google sign in method
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// google connection failed method
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
info.setText("Login attempt failed.");
}
}
remove all the intents from your code except the one from this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
final Uri uri = Uri.parse(data.getStringExtra("KEY_URI"));
new Thread(new Runnable() {
#Override
public void run() {
String verifier = uri.getQueryParameter(LoginActivity.URL_TWITTER_OAUTH_VERIFIER);
try {
AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
LoginActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(LoginActivity.this, CategoriesActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
Just keep the intent portion in order to go to the next activity in OnActivityResult itself, remove any other intent calls from your entire code and try running the app again.