launch another application from my own app - java

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 !
}

Related

I am working on OCR reader application. below is my java code. My question is how to start another method if one is completed?

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.

speech recognition intent not opening on button click

I am working on a simple assistant app intially by hardcoding what it replies. It has a button which on clicked shows up the voice recognizer intent. but it is not showing up now on button click. I have attached my code here please help me to find the mistake causing the error.
also please help me how to invoke the speech recognizer without tapping on the button, by just saying some specified word as in 'Ok google'.
MainActivity.java
package com.example.rv00485448.neha1;
import android.content.Intent;
import android.os.Build;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.Locale;
import static android.speech.RecognizerIntent.ACTION_RECOGNIZE_SPEECH;
public class MainActivity extends Activity{
private TextToSpeech tts;
private ArrayList<String> questions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.microphoneButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listen();
}
});
loadQuestions();
tts = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
speak("Hello");
} else {
Log.e("TTS", "Initilization Failed!");
}
}
});
}
private void loadQuestions(){
questions = new ArrayList<>();
questions.clear();
questions.add("hi how are you");
questions.add("I am good. how are you feeling today?");
questions.add("Do you have vitals readings?");
questions.add("you seem to have fever. Do you want me to book an appointment with doctor nandan ");
questions.add("I have booked an appointment with doctor nandan at 5 PM");
questions.add("Thank you too");
}
private void listen(){
Intent i = new Intent(ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something");
// speak("I am listening to you");
// try {
// startActivityForResult(i, 100);
// } catch (ActivityNotFoundException a) {
// Toast.makeText(MainActivity.this, "Your device doesn't support Speech Recognition", Toast.LENGTH_SHORT).show();
// }
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
private void speak(String text){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}else{
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100){
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> res = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String inSpeech = res.get(0);
recognition(inSpeech);
}
}
}
private void recognition(String text){
switch (text)
{
case "hello":
{
speak(questions.get(0));
break;
}
case "fine how about you":
{
speak(questions.get(1));
break;
}
case "feeling dizzy":
{
speak(questions.get(2));
break;
}
case "yeah":
{
speak(questions.get(3));
break;
}
case "yes":
{
speak(questions.get(4));
break;
}
case "thank you":
{
speak(questions.get(5));
break;
}
}
}
}
you are not triggering that activity.
use startActivityForResult(i) inside listen method.
You need to add INTERNET permission in your manifest file

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 Android musicplayer [duplicate]

This question already has answers here:
Why does ArrayIndexOutOfBoundsException occur and how to avoid it in Android? [closed]
(4 answers)
Closed 6 years ago.
I'm developing a music application but i keep geting this error, i don't understand it and dont know how to solve. I'm stuck for 2 day trying to re-write the code but still the error pops-up.My logcat comes up as java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0. And please elaborate the main problem.
This MainActivity.java
package com.developer.bunamay.player;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements MusicService.MediaFileListener {
public static final PlayerUtils PlayerController = PlayerUtils.getInstance();
public static final int PICK_FOLDER_REQUEST = 8;
private MediaFileAdapter mediaFileAdapter = null;
private TextView playingSong;
private Button btnPause, btnPlay, btnNext, btnPrevious;
private Button btnStop;
private LinearLayout linearLayoutPlayingSong;
private ListView mediaListView;
private SeekBar seekbar;
private TextView textBufferDuration, textDuration;
private ImageView imageViewAlbumArt;
private Context context;
MusicService mService;
boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
if (!PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext())) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
startService(i);
}
}
private void init() {
initViews();
setListeners();
playingSong.setSelected(true);
seekbar.getProgressDrawable().setColorFilter(ContextCompat.getColor(context, R.color.colorText), PorterDuff.Mode.SRC_IN);
if (PlayerController.SONGS_LIST.size() <= 0) {
PlayerController.SONGS_LIST = PlayerController.listOfSongs(getApplicationContext());
}
initAdapter();
}
private void initAdapter() {
mediaFileAdapter = new MediaFileAdapter(this, R.layout.custom_list, PlayerController.SONGS_LIST);
mediaListView.setAdapter(mediaFileAdapter);
mediaListView.setTextFilterEnabled(true);
mediaListView.setFastScrollEnabled(true);
}
private void initViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
seekbar = (SeekBar) findViewById(R.id.seekBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private Animation setButtonAnimation() {
return AnimationUtils.loadAnimation(this, R.anim.button_anim);
}
// defines callbacks for service binding, passed to bindService()
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
mService = binder.getService();
mService.setListener(MainActivity.this);
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
mService = null;
}
};
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
PlayerController.SONG_PAUSED = false;
PlayerController.SONG_NUMBER = position;
boolean isServiceRunning = PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
startService(i);
} else {
PlayerController.SONG_CHANGE_HANDLER.sendMessage(
PlayerController.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerController.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PlayerController.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(setButtonAnimation());
PlayerController.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(setButtonAnimation());
PlayerController.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext())) {
PlayerController.pauseControl(getApplicationContext());
}
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
// clicked position on the seekBar
int currentSeekBarPosition = seekBar.getProgress();
// 1% of song duration = song duration / 100%
int onePercentOfSongDuration = (mService.getDuration() / 100);
// associate song duration with clicked position on the seekBar
int changedPosition = currentSeekBarPosition * onePercentOfSongDuration;
// seek to selected position
PlayerController.seekToAnyControl(getApplicationContext(), changedPosition);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
protected void onPause() {
if (mBound) {
unbindService(mConnection);
}
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
Intent i = new Intent(getApplicationContext(), MusicService.class);
bindService(i, mConnection, Context.BIND_AUTO_CREATE);
handleAudioFromOpenWithPopup();
boolean isServiceRunning = PlayerUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
} else {
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerController.SEEKBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(PlayerUtils.getDuration(i[0]));
textDuration.setText(PlayerUtils.getDuration(i[1]));
seekbar.setProgress(i[2]);
}
};
}
public void updateUI() {
MediaFile mediaFile = PlayerController.SONGS_LIST.get(PlayerController.SONG_NUMBER);
String nowPlayingTitleText = mediaFile.getTitle() + " " + mediaFile.getArtist() + "-" + mediaFile.getAlbum();
playingSong.setText(nowPlayingTitleText);
Bitmap albumArt = PlayerController.getAlbumart(context, mediaFile.getAlbumId());
if (albumArt != null) {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(Resources.getSystem(), albumArt));
} else {
Bitmap defaultAlbumArt = PlayerController.getDefaultAlbumArt(context);
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(Resources.getSystem(), defaultAlbumArt));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
}
public void changeButton() {
if (PlayerController.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public void changeUI() {
updateUI();
changeButton();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// init menu items for search
MenuItem itemSearchTitle = menu.findItem(R.id.action_search_title);
MenuItem itemSearchAlbum = menu.findItem(R.id.action_search_album);
MenuItem itemSearchArtist = menu.findItem(R.id.action_search_artist);
SearchView searchViewTitle = (SearchView) itemSearchTitle.getActionView();
SearchView searchViewAlbum = (SearchView) itemSearchAlbum.getActionView();
SearchView searchViewArtist = (SearchView) itemSearchArtist.getActionView();
searchViewTitle.setFocusable(true);
searchViewAlbum.setFocusable(true);
searchViewArtist.setFocusable(true);
// init searchable info for each menu item
searchViewTitle.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewTitle.setQueryHint("title...");
searchViewTitle.setIconified(true);
searchViewAlbum.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewAlbum.setQueryHint("album...");
searchViewAlbum.setIconified(true);
searchViewArtist.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewArtist.setQueryHint("artist...");
searchViewArtist.setIconified(true);
// set textChangeListeners for each type of search
final SearchView.OnQueryTextListener textChangeListenerTitle = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerAlbum = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerArtist = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
// apply listeners to searchViews
searchViewTitle.setOnQueryTextListener(textChangeListenerTitle);
searchViewAlbum.setOnQueryTextListener(textChangeListenerAlbum);
searchViewArtist.setOnQueryTextListener(textChangeListenerArtist);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// get music from specific folder
if (id == R.id.folder_music) {
Intent intent = new Intent(this, FolderPickerActivity.class);
startActivityForResult(intent, PICK_FOLDER_REQUEST);
return true;
}
// fetch all music from device
if (id == R.id.all_music) {
PlayerController.SONGS_LIST = PlayerController.listOfSongs(getApplicationContext());
initAdapter();
return true;
}
// search songs by title
if (id == R.id.action_search_title) {
PlayerController.SEARCH_TYPE = "TITLE";
return true;
}
// search songs by artist
if (id == R.id.action_search_artist) {
PlayerController.SEARCH_TYPE = "ARTIST";
return true;
}
// search songs by album
if (id == R.id.action_search_album) {
PlayerController.SEARCH_TYPE = "ALBUM";
return true;
}
if (id == R.id.action_sort_title) {
MediaFileComparator.sortByTitle(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_album) {
MediaFileComparator.sortByAlbum(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_artist) {
MediaFileComparator.sortByArtist(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_duration) {
MediaFileComparator.sortByDuration(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_FOLDER_REQUEST) {
String pickedFolder = data.getStringExtra("pickedFolder");
Log.i("PICKER_FOLDER_TAG", pickedFolder);
// get last subfolder from path as WHERE arg
pickedFolder = getSelectionArg(pickedFolder);
Log.i("PICKER_FOLDER_WHERE_TAG", pickedFolder);
// reinit music list and adapter with data from specific folder
List<MediaFile> songsFromSpecificFolder = PlayerController.getSongsFromSpecificFolder(
getApplicationContext(), new String[]{pickedFolder}
);
if (songsFromSpecificFolder.size() != 0) {
PlayerController.SONGS_LIST = songsFromSpecificFolder;
PlayerController.SONG_NUMBER = 0;
initAdapter();
}
}
}
}
// receive audio action from 'Complete action with' pop-up
private void handleAudioFromOpenWithPopup() {
// receive Intent
Intent intent = getIntent();
// check action
String action = intent.getAction();
// if it's audio action view
if (action != null && action.equals("android.intent.action.VIEW")) {
// play song
PlayerController.playMusicFromActionPicker(this, intent.getData());
}
}
// get last subfolder from path as WHERE arg
private String getSelectionArg(String path) {
String sTag = "%";
// substring last directory in path
String lastSubfolder = path.substring(path.lastIndexOf("/") + 1);
return sTag + lastSubfolder + sTag;
}
#Override
public void onMediaFileChanged() {
changeUI();
}
#Override
public void onPlayPauseActionChanged() {
changeButton();
}
}
I've tried searching online varios times but i still dont understand.
Thanks
The root cause of the problem is that somewhere, either your code or some code that your code uses is doing something that is equivalent to this:
Object[] array = new Object[0];
...
System.out.println(array[0]);
Something created an array (of some type) with size ZERO, and it (or maybe something else) is trying to access the first element (index zero) of that array. That is beyond the end of the array ... and that results in an exception.
I can't see where you are creating a zero-length array in your code.
Could you have a look at the method protected void onResume()?
I think, you may have a problem in following lines:
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(PlayerUtils.getDuration(i[0]));
textDuration.setText(PlayerUtils.getDuration(i[1]));
seekbar.setProgress(i[2]);
First try running the program by commenting out those lines. It may happen that, on some occasions, your msg.obj is actually an array whose length is 0. Then you will get java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0. Hope it helps you.

Issue with Twitter 4j callback on Android

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.

Google Sign-In Button Null Pointer Exception

I am trying to implement a Google Sign-In button to my app and although it initially runs, I am getting this error:
09-16 19:44:38.679 26125-26125/com.hudsoncorp.zahudson.caravan E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.hudsoncorp.zahudson.caravan, PID: 26125
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference
at com.hudsoncorp.zahudson.caravan.HomeActivity.onSignInClicked(HomeActivity.java:189)
at com.hudsoncorp.zahudson.caravan.HomeActivity.onClick(HomeActivity.java:177)
at com.google.android.gms.common.SignInButton.onClick(Unknown Source)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
I just fixed some implementing methods with the Google Sign-In and ran into this problem. I am fairly new to Android, especially with implementing GoogleApiClients. I'm wondering if my error has anything to do with the order of my methods. Then again, I could have no idea what I'm talking about. My HomeActivity code is:
import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; import static android.view.View.*;
public class HomeActivity extends Activity implements
ConnectionCallbacks,
OnConnectionFailedListener,
OnClickListener {
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
private Button mLoginButton;
private TextView mSignUpLabel;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
public static final String TAG = HomeActivity.class.getSimpleName();
private TextView mStatusTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mLoginButton = (Button) findViewById(R.id.btnLogin);
mLoginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomeActivity.this, "Button Pressed", Toast.LENGTH_SHORT).show();
}
});
mSignUpLabel = (TextView) findViewById(R.id.lblAboutUs);
mSignUpLabel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(HomeActivity.this, "WAY TO SIGN UP MAN", Toast.LENGTH_SHORT).show();
}
});
findViewById(R.id.sign_in_button).setOnClickListener(this);
// Build GoogleApiClient with access to basic profile
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.build();
}
#Override
public void onConnected(Bundle bundle) {
// onConnected indicates that an account was selected on the device, that the selected
// account has granted any requested permissions to our app and that we were able to
// establish a service connection to Google Play services.
Log.d(TAG, "onConnected:" + bundle);
mShouldResolve = false;
//Show the signed-in UI
showSignedInUI();
}
#Override
public void onConnectionSuspended(int arg0) {
// what should i do here ? should i call mGoogleApiClient.connect() again ? ?
}
#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_home, 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
public void onConnectionFailed(ConnectionResult connectionResult) {
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
} else { // // Could not resolve the connection result, show the user an // // error dialog. // showErrorDialog(connectionResult);
}
} else { // // Show the signed-out UI // showSignedOutUI();
}
}
// private void showErrorDialog(ConnectionResult connectionResult) { // // } // // private void showSignedOutUI() { // // }
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private void onSignInClicked() {
// User clicked the sing-in button, so begin the sign-in process and automatically
// attempt to resolve any errors that occur.
mShouldResolve = true;
mGoogleApiClient.connect();
// Show a message to the user that we are signing in.
mStatusTextView.setText(R.string.signing_in);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.sign_in_button) {
onSignInClicked();
}
}
private void showSignedInUI() {
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve it further.
if (resultCode != RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
}
}
}
You have not set up mStatusTextView with a findViewByID call yet, so it is bound to NULL.
In this method:
protected void onCreate(Bundle savedInstanceState) {
You need to do what you did with the other widgets:
mStatusTextView = (TextView) findViewById(R.id.TEXTVIEW_ID_HERE);

Categories

Resources