We come across the following code or something similar in Android or Java many times. This code seems like containing repetitions and this is not a good practice at all. There must be some better way to do this. is there any shorter code to achieve this?
Intent intent=null;
switch (v.getId()) {
case R.id.details:
intent = new Intent(this, DetailsActivity.class);
break;
case R.id.apply:
intent = new Intent(this, ApplyActivity.class);
break;
case R.id.edit:
intent = new Intent(this, EditActivity.class);
break;
case R.id.upload:
intent = new Intent(this, UploadActivity.class);
break;
case R.id.call:
intent = new Intent(this, CallActivity.class);
break;
}
startActivity(intent);
Make a table of ids to activity classes in a static initializer or constructor:
HashMap<Integer, Class<?>> map = new HashMap<>();
map.put(R.id.foo, Foo.class); // repeat for each id/class pair
Then use the map instead of a switch:
startActivity(new Intent(this), map.get(v.getId()));
As I commented use setClass method instead. Do like this.
Set your Activity classname to button tag and get this tag on button click.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="YourActivityName"
/>
Java Code
String classname = (String) textView.getTag();
intent.setClassName(getPackageName().toString(), classname)
startActivity(intent);
Yes Ofcourse. This is not a good practise at all. Try to achieve generalization.
Below is what I put into practice.
Just a think, Why I would write the code again, when it is already written..!!
Thinking that way,
Put all the common code in to a common class
Extend that class
Use its members
Create a class, say BaseAppCompatActivity.java as below:
public abstract class BaseAppCompatActivity extends AppCompatActivity {
private ProgressDialog mProgressDialog;
private Toolbar mToolbar;
private TabLayout mTabLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResourceId());
initiateViews();
}
protected abstract int getLayoutResourceId();
protected abstract void initiateViews();
public void setHasToolBar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
}
public Toolbar getToolBar() {
return mToolbar;
}
public void setHasTabLayout() {
mTabLayout = (TabLayout) findViewById(R.id.tabLayout);
}
public TabLayout getTabLayout() {
return mTabLayout;
}
public void showProgressDialog() {
showProgressDialog("Please Wait ...");
}
public void showProgressDialog(String message) {
// progress bar not null and is visible, so set the title
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.setMessage(message);
}
// create new progress bar
else {
mProgressDialog = ProgressDialog.show(this, "Loading", message, true, false);
}
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
public void showAlertDialog(String message) {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
})
.create();
alertDialog.setMessage(message);
alertDialog.show();
}
public void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
public void logInformation(Class tag, String description) {
Log.i(tag.getName(), description);
}
public void logError(Class tag, String description) {
Log.e(tag.getName(), description);
}
public void logDebug(Class tag, String description) {
Log.d(tag.getName(), description);
}
public void launchActivity(Class<? extends Activity> cls, Bundle bundle, int code) {
Intent intent = new Intent();
if (bundle != null)
intent.putExtras(bundle);
intent.setClass(activity, cls);
if (code == -1)
startActivity(intent);
else
startActivityForResult(intent, code);
}
public void loadFragment(Class fragmentClass, boolean addToBackStack) {
Fragment fragment = null;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
if (fragment != null) {
if (addToBackStack) {
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(fragmentClass.getSimpleName())
.replace(R.id.frameLayout, fragment, fragmentClass.getSimpleName())
.commit();
} else {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout, fragment, fragmentClass.getSimpleName())
.commit();
}
}
}
}
And after that, extend all your activities to this BaseAppCompatActivity class.
Then, in your code in activity is cut down to just
launchActivity(Activity2.class, null, -1);
You can set tag equal your activity :
<Button
android:id="#+id/btn1"
android:tag="DetailsActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn2"
android:tag="ApplyActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn3"
android:tag="EditActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn4"
android:tag="EditActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn5"
android:tag="DetailsActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
<Button
android:id="#+id/btn6"
android:tag="CallActivity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dnt want this text" />
Java code this : Your package name :com.example.pkg1
Intent intent = new Intent();
intent.setClassName("com.example.pkg1", "com.example.pkg1."+v.getTag() );
startActivity(intent);
Related
I have an audiobook app that I'm currently working on. If the book has audio, the controller will be shown. If not, it'll only show the text. I want to switch the chapters just by swiping at the text. I'm currently using a RelativeLayout and the text is wrapped in a ScrollView. I read that I should use ViewPager. But I was wondering if I could just keep using the RelativeLayout and ScrollView.
player.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/mainbg">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/m_tab_color"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<LinearLayout
android:id="#+id/player_footer_bg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#FFFFFF"
android:gravity="center"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/linearButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<ImageButton
android:id="#+id/btnRepeat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:background="#null"
android:src="#drawable/btn_repeat"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnShuffle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:background="#null"
android:src="#drawable/btn_shuffle"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/btnPlay"
android:background="#null"
android:src="#drawable/btn_next"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="5dp"
android:background="#drawable/btn_play"
android:src="#drawable/pause"
tools:ignore="ContentDescription" />
<ImageButton
android:id="#+id/btnPrevious"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/btnPlay"
android:background="#null"
android:src="#drawable/btn_prev"
tools:ignore="ContentDescription" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:id="#+id/ad_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/ads_startapp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone">
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:id="#+id/sec_ssekbar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/player_footer_bg"
android:layout_centerVertical="true"
android:background="#00ffffff"
android:paddingLeft="7dp"
android:paddingRight="7dp">
<SeekBar
android:id="#+id/songProgressBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:progressTint="#E94C3D"
android:thumb="#drawable/pointer"
android:thumbTint="#E94C3D"
android:thumbOffset="8dp"/>
<TextView
android:id="#+id/songCurrentDurationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/songProgressBar"
android:gravity="start"
android:text="#string/current_duration"
android:textColor="#color/black"
android:textStyle="bold" />
<TextView
android:id="#+id/songTotalDurationLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_below="#+id/songProgressBar"
android:gravity="end"
android:text="#string/total_duration"
android:textColor="#color/black"
android:textStyle="bold" />
</RelativeLayout>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/sec_ssekbar"
android:layout_below="#+id/toolbar"
android:layout_centerInParent="true"
android:layout_marginStart="3dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:layout_marginBottom="3dp"
android:background="#B3FFFFFF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/text_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="3dp"
android:gravity="center"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black"
android:textStyle="bold" />
<TextView
android:id="#+id/text_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginBottom="5dp"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/black" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
MusicPlayActivity.java
public class MusicPlayActivity extends AppCompatActivity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {
Toolbar toolbar;
private ImageButton btnPlay;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private MediaPlayer mp;
ImageView img_song;
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
String[] allArrayImage, allArrayMusicCatName, allArrayMusicShare;
String[] allArrayMusicId, allArrayMusicCatId, allArrayMusicurl, allArrayMusicName, allArrayMusicDuration, allArrayMusicDesc;
int position = currentSongIndex;
int music_id;
private SeekBar songProgressBar;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private Utilities utils;
private Handler mHandler = new Handler();
private Menu menu;
DatabaseHandler db;
String mp3id, mp3catid, mp3name, mp3url, mp3duration, mp3desc, mp3shareurl, mp3image, mp3catname;
private ActionClickItem actionClickItem;
private InterstitialAd mInterstitialAd;
private int btNextClicked = 1;
private AdsObj adsObj;
private StartAppAd startAppAd;
private boolean runClickExecuted;
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
btnPlay = findViewById(R.id.btnPlay);
ImageButton btnNext = findViewById(R.id.btnNext);
ImageButton btnPrevious = findViewById(R.id.btnPrevious);
btnRepeat = findViewById(R.id.btnRepeat);
btnShuffle = findViewById(R.id.btnShuffle);
TextView songTitleLabel = findViewById(R.id.text_title);
TextView songDesc = findViewById(R.id.text_description);
img_song = findViewById(R.id.image);
songProgressBar = findViewById(R.id.songProgressBar);
songCurrentDurationLabel = findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = findViewById(R.id.songTotalDurationLabel);
//imageView = (ImageView)findViewById(R.id.full_image);
// imageLoader=new ImageLoader(this);
db = new DatabaseHandler(this);
toolbar = this.findViewById(R.id.toolbar);
toolbar.setTitle(Constant.MUSIC_NAME);
this.setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
utils = new Utilities();
mp = new MediaPlayer();
Intent i = getIntent();
music_id = i.getIntExtra("POSITION", 0);
allArrayImage = i.getStringArrayExtra("MP3_IMAGE");
allArrayMusicCatName = i.getStringArrayExtra("MP3_CATNAME");
allArrayMusicShare = i.getStringArrayExtra("MP3_SHARE");
allArrayMusicId = i.getStringArrayExtra("MP3_CID");
allArrayMusicCatId = i.getStringArrayExtra("MP3_CATID");
allArrayMusicurl = i.getStringArrayExtra("MP3_URL");
allArrayMusicName = i.getStringArrayExtra("MP3_NAME");
allArrayMusicDuration = i.getStringArrayExtra("MP3_DURATION");
allArrayMusicDesc = i.getStringArrayExtra("MP3_DISCRIPTION");
position = getPositionFromArray(String.valueOf(music_id));
Log.e("POSITIO", "" + position);
playSong(position);
songProgressBar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check for already playing
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_paush);
}
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
btNextClicked++;
if ((btNextClicked % 3 == 0)) {
actionItemClicked(new ActionClickItem() {
#Override
public void runClick() {
// check if next song is there or not
if (position < (allArrayMusicurl.length - 1)) {
playSong(position + 1);
position = position + 1;
} else {
// play first song
playSong(0);
position = 0;
}
}
});
} else {
// check if next song is there or not
if (position < (allArrayMusicurl.length - 1)) {
position = position + 1;
playSong(position + 1);
} else {
// play first song
playSong(0);
position = 0;
}
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (position > 0) {
playSong(position - 1);
position = position - 1;
} else {
// play last song
playSong(allArrayMusicurl.length - 1);
position = allArrayMusicurl.length - 1;
}
}
});
btnRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isRepeat) {
isRepeat = false;
Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
} else {
// make repeat to true
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isShuffle = false;
btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});
btnShuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
} else {
// make repeat to true
isShuffle = true;
Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});
//int songIndex = i.getIntExtra("songIndex", 0);
// Displaying Song title
String songTitle = allArrayMusicName[position];
songTitleLabel.setText(songTitle);
toolbar.setTitle(songTitle);
String musicUrl = allArrayMusicurl[position];
if(musicUrl.equals(".")){
songProgressBar.setVisibility(View.GONE);
songCurrentDurationLabel.setVisibility(View.GONE);
songTotalDurationLabel.setVisibility(View.GONE);
RelativeLayout linearButton = findViewById(R.id.linearButton);
linearButton.setVisibility(View.GONE);
}
#SuppressLint("CutPasteId") FrameLayout frameAds1 = findViewById(R.id.ad_view_container);
AdsAssistants adsAssistants = new AdsAssistants(this);
adsObj = adsAssistants.getSessionAdsObj();
if (adsObj != null) {
if (adsObj.getCurrentActivatedAds().equals(AdsConfig.ADS_ADMOB)) {
frameAds1.setVisibility(View.VISIBLE);
adsAssistants.createAdmobBanner(frameAds1, adsObj.getADS_ADMOB_BANNER());
} else {
startAppAd = new StartAppAd(this);
#SuppressLint("CutPasteId") FrameLayout frameAds = findViewById(R.id.ad_view_container);
frameAds.setVisibility(View.VISIBLE);
adsAssistants.createStartAppBanner(frameAds);
}
}
}
public void actionItemClicked(ActionClickItem actionClickItemParam) {
actionClickItem = actionClickItemParam;
if (adsObj == null) {
actionClickItem.runClick();
} else {
if (adsObj.getCurrentActivatedAds().equals(AdsConfig.ADS_ADMOB)) {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
actionClickItem.runClick();
generateInterstitialAd();
}
} else {
startAppAd.loadAd(new AdEventListener() {
#Override
public void onReceiveAd(Ad ad) {
}
#Override
public void onFailedToReceiveAd(Ad ad) {
// actionClickItem.runClick();
}
});
StartAppAd.disableAutoInterstitial();
startAppAd.showAd(new AdDisplayListener() {
#Override
public void adHidden(Ad ad) {
if(!runClickExecuted){
runClickExecuted = true;
actionClickItem.runClick();
}
Log.d("YWV", "Action clicked");
}
#Override
public void adDisplayed(Ad ad) {
}
#Override
public void adClicked(Ad ad) {
}
#Override
public void adNotDisplayed(Ad ad) {
}
});
}
}
}
private void generateInterstitialAd() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(adsObj.getADS_ADMOB_INTERSTITIALS());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// mNextLevelButton.setEnabled(true);
}
#Override
public void onAdFailedToLoad(int errorCode) {
// mNextLevelButton.setEnabled(true);
}
#Override
public void onAdClosed() {
// Proceed to the next level.
//finish();
//showDialogApp();
actionClickItem.runClick();
generateInterstitialAd();
}
});
AdRequest adRequestIn = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequestIn);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
position = Objects.requireNonNull(data.getExtras()).getInt("songIndex");
// play selected song
playSong(position);
}else if(resultCode == 11){
runClickExecuted = false;
}
}
public void playSong(int songIndex) {
// Play song
try {
// if(needResetFirst){
mp.reset();
// }
mp.setDataSource(allArrayMusicurl[songIndex]);
mp.prepare();
mp.start();
// // Displaying Song title
TextView songTitleLabel = findViewById(R.id.text_title);
String songTitle = allArrayMusicName[songIndex];
songTitleLabel.setText(songTitle);
toolbar.setTitle(songTitle);
TextView songDesc = findViewById(R.id.text_description);
String songDescd = allArrayMusicDesc[songIndex];
songDesc.setText(songDescd);
// Toast.makeText(getApplicationContext(), img_name,Toast.LENGTH_SHORT).show();
// imageLoader.DisplayImage(Constant.SERVER_IMAGE_UPFOLDER1+img_name, imageView);
// Log.e("IMAGEPATH", ""+Constant.SERVER_IMAGE_UPFOLDER1+img_name);
// Toast.makeText(getApplicationContext(), Constant.SERVER_IMAGE_UPFOLDER1+img_name,Toast.LENGTH_SHORT).show();
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_paush);
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
// set Progress bar values
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
if (isRepeat) {
// repeat is on play same song again
playSong(position);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
position = rand.nextInt((allArrayMusicurl.length - 1) + 1);
playSong(position);
} else {
// no repeat or shuffle ON - play next song
if (position < (allArrayMusicurl.length - 1)) {
playSong(position + 1);
position = position + 1;
} else {
// play first song
playSong(0);
position = 0;
}
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
if (mp != null) {
mp.reset();
mp.release();
mp = null;
mHandler.removeCallbacks(mUpdateTimeTask);
}
setResult(RESULT_OK);
finish();
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
songTotalDurationLabel.setText(utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel.setText(utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = utils.getProgressPercentage(currentDuration, totalDuration);
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
public void AddtoFav(int position) {
mp3id = allArrayMusicId[position];
// mp3catid=allArrayMusicCatId[position];
mp3catname = allArrayMusicCatName[position];
mp3url = allArrayMusicurl[position];
mp3image = allArrayImage[position];
mp3name = allArrayMusicName[position];
mp3duration = allArrayMusicDuration[position];
mp3desc = allArrayMusicDesc[position];
// mp3shareurl=allArrayMusicShare[position];
db.AddtoFavorite(new Pojo(mp3id, mp3catid, mp3catname, mp3url, mp3image, mp3name, mp3duration, mp3desc, mp3shareurl));
Toast.makeText(getApplicationContext(), "Added to Favorite", Toast.LENGTH_SHORT).show();
// fabfav.setImageDrawable(getResources().getDrawable(R.drawable.fav_hover));
}
//remove from favorite
public void RemoveFav(int position) {
mp3id = allArrayMusicId[position];
db.RemoveFav(new Pojo(mp3id));
Toast.makeText(getApplicationContext(), "Removed from Favorite", Toast.LENGTH_SHORT).show();
// fabfav.setImageDrawable(getResources().getDrawable(R.drawable.fav_hover));
}
public void FirstFav() {
mp3id = allArrayMusicId[position];
List<Pojo> pojolist = db.getFavRow(mp3id);
if (pojolist.size() == 0) {
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav));
} else {
if (pojolist.get(0).getMp3Id().equals(mp3id)) {
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_mp3, menu);
this.menu = menu;
//for when 1st item of view pager is favorite mode
FirstFav();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.menu_fav:
mp3id = allArrayMusicId[position];
List<Pojo> pojolist = db.getFavRow(mp3id);
if (pojolist.size() == 0) {
AddtoFav(position);//if size is zero i.e means that record not in database show add to favorite
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav_hover));
} else {
if (pojolist.get(0).getMp3Id().equals(mp3id)) {
RemoveFav(position);
}
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.fav));
}
return true;
case R.id.menu_share:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_TEXT, "Listen to this verse from " + Constant.APP_NAME + "\n" + "http://play.google.com/store/apps/details?id=" + getPackageName());
sharingIntent.setType("text/plain");
startActivity(Intent.createChooser(sharingIntent, "Share Link"));
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
public int getPositionFromArray(String id) {
return Arrays.asList(allArrayMusicId).indexOf(id);
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
/** Called when leaving the activity */
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed */
#Override
public void onDestroy() {
super.onDestroy();
if (mp != null) {
mp.reset();
mp.release();
mHandler.removeCallbacks(mUpdateTimeTask);
mp = null;
}
finish();
if (adView != null) {
adView.destroy();
}
}
}
Thank you in advance !
You can detect gestures on any View by attaching an onTouchListener to it.
In your case however, you are trying to detect swiping gestures, therefore the best solution is to create a gesture detector class by extending an onTouchListener like in this tutorial (step 4):
https://www.tutorialspoint.com/how-to-handle-right-to-left-and-left-to-right-swipe-gestures-on-android
After doing this, you can easily attach the swipe-detector class to any of your views as:
textView.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
#Override
public void onSwipeLeft() {
super.onSwipeLeft();
// do something
}
#Override
public void onSwipeRight() {
super.onSwipeRight();
// do something
}
});
Have you tried to add and OnSwipeTouchListener like here https://stackoverflow.com/a/12938787/4330467?
Relativelayout should not be the issue
I am using this library - https://github.com/stepstone-tech/android-material-stepper to build a step by step registration system where users will fill each field one by one before finally saving users data into the database using a php script via JSON.
I have 2 problems.
1. After filling the data, I dont kow how to save the data that has been inputed into the database.
2 How to validate each data been inputed individually onClick of 'NEXT' button. (Although, number 1 is much more important for now, but if someome could help me out with both, GREAT!.)
I have done this with the use of just one activity and it works fine.
One of the fragment. 6 of them (They are all similar)
public class EmailRegisterFragment extends Fragment implements Step {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_email_register, container, false);
//initialize your UI
return v;
}
#Override
public VerificationError verifyStep() {
//return null if the user can go to the next step, create a new VerificationError instance otherwise
return null;
}
#Override
public void onSelected() {
//update UI when selected
}
#Override
public void onError(#NonNull VerificationError error) {
//handle error inside of the fragment, e.g. show error on EditText
}
}
One of the fragementLayout (They are all similar)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".UsernameRegisterFragment"
android:orientation="vertical">
<!-- TODO: Update blank fragment layout -->
<ImageView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:src="#drawable/back_left_light"
android:layout_marginLeft="10dp"
android:clickable="true"
android:focusable="true"
android:onClick="goToWelcomePage"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Email Address"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:padding="20dp"
/>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextTheme"
>
<EditText
android:layout_width="match_parent"
android:inputType="textEmailAddress"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:hint="Input Your Email"
android:textColor="#android:color/black"
android:id="#+id/email"
app:backgroundTint="#color/edit_text"
android:theme="#style/EditTextTheme"
android:textCursorDrawable="#null"
/>
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="20dp"
android:onClick="goToRegisterWithPhone"
android:clickable="true"
android:text="You dont have an email? Click here"/>
</LinearLayout>
Activity layout (That shows the NEXT, BACK COMPLETE Button and progress bar)
<?xml version="1.0" encoding="utf-8"?>
<com.stepstone.stepper.StepperLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/stepperLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:ms_stepperType="progress_bar"
app:ms_nextButtonColor="#color/white"
app:ms_completeButtonColor="#color/white"
app:ms_backButtonColor="#color/white"
/>
ActivityJava file
public class IntroActivity extends AppCompatActivity implements StepperLayout.StepperListener{
private StepperLayout mStepperLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
//remove action and status bar
if (getSupportActionBar() != null)
getSupportActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intro);
mStepperLayout = (StepperLayout) findViewById(R.id.stepperLayout);
mStepperLayout.setAdapter(new MyStepperAdapter(getSupportFragmentManager(), this));
mStepperLayout.setListener(this);
}
#Override
public void onCompleted(View completeButton) {
Toast.makeText(this, "onCompleted!", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(VerificationError verificationError) {
Toast.makeText(this, "onError! -> " + verificationError.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
#Override
public void onStepSelected(int newStepPosition) {
}
#Override
public void onReturn() {
finish();
}
public void goToWelcomePage(View view){
Intent intent = new Intent(this, WelcomeActivity.class);
startActivity(intent);
}
public void goToRegisterWithPhone(View view){
Intent intent = new Intent(this, IntroActivity.class);
startActivity(intent);
}
}
Like I said I have done this with the use of just one Activity using the Volley library. Check it out.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText username, email, password;
private Button btn_register_final;
private ProgressBar loading;
private TextView login_text;
private static String URL_REGISTER = "http://78d24f21.ngrok.io/misnap/register.php";
SessionManager sessionManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sessionManager = new SessionManager(this);
username = findViewById(R.id.etUsername);
email = findViewById(R.id.etEmail);
password = findViewById(R.id.etPassword);
btn_register_final = findViewById(R.id.btnRegisterFinal);
loading = findViewById(R.id.loading);
login_text = findViewById(R.id.btnLoginText);
btn_register_final.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something here after clicking register
Register();
}
});
login_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
v.getContext().startActivity(intent);
}
});
}
public void Register(){
loading.setVisibility(View.VISIBLE);
btn_register_final.setVisibility(View.GONE);
final String username = this.username.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
sessionManager.createSession(username, email);
Intent intent = new Intent(RegisterActivity.this, HomeActivity.class);
intent.putExtra("username", username);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
} catch (JSONException e){
e.printStackTrace();
Toast.makeText(RegisterActivity.this, "Unable to register" + e.toString(),
Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Unable to register" + error.toString(),
Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_register_final.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Register.php
<?php
require_once("connect.php");
if ($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password)
VALUES ('$username', '$email', '$password')";
if(mysqli_query($conn, $sql)){
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($conn);
}
else{
$result["success"] = "0";
$result["message"] = "An error occured";
echo json_encode($result);
mysqli_close($conn);
}
}
?>
How do use this same logic for the fragments??
this might be late but i think it would help to others. So for sure you can validate/Insert or whatever you want to do with your inputs on Next button click before going to next step, This is how you can do it in Kotlin
// To be somewhere inside your Step
override fun verifyStep(): VerificationError? {
if (validateStep()){
return null
}
else
VerificationError("Any error message")
}
Now here validateStep will be a function that returns True or false depending upon your needs. Here is a simple example of a validateStep() function. Here you can do anything like insertion or validation etc.
private fun validateStep(): Boolean {
var isValid = true
val name = binding.etCustomerName.text.toString()
val email = binding.etCustomerEmail.text.toString()
if (name.isEmpty()) {
isValid = false
}
if (email.isEmpty()) {
isValid = false
} else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
isValid = false
}
return isValid
}
Do let me know if it helps anyone. Happy coding :)
I have this code
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
else
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
String activityTitle = cellsList.get(position).getTitle();
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, activityTitle);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.setType("image/*");
sharingIntent.setPackage("com.whatsapp");
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sharingIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Intent chooser = Intent.createChooser(sharingIntent,getResources().getString(R.string.share_using));
getActivity().startActivity(chooser);
And I want to share another message that contain text and image to the same chooser app.
Do u have any idea on how to solve the problem?
You can use a ShareActionProvider. In the following sample, I'm using one tied to a MenuItem in the Toolbar, but it's also possible to use them with e.g. a Button.
main_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_item_share"
app:showAsAction="ifRoom"
android:title="Share"
app:actionProviderClass=
"android.support.v7.widget.ShareActionProvider" />
</menu>
activity_main.xml
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.sharing.datasender.MainActivity">
<TextView
android:id="#+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="Send data once more"
/>
</FrameLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity
{
private ShareActionProvider shareActionProvider;
private Intent shareIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.view2);
view.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
sendDataOnceMore();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
shareActionProvider = (ShareActionProvider)MenuItemCompat.getActionProvider(item);
setShareIntent(getShareIntent());
shareActionProvider.setOnShareTargetSelectedListener(new ShareActionProvider.OnShareTargetSelectedListener()
{
#Override
public boolean onShareTargetSelected(ShareActionProvider shareActionProvider, Intent intent)
{
ComponentName component = intent.getComponent();
shareIntent = intent;
String className = null;
if (component != null)
{
className = component.getClassName();
}
Log.d("TEST", "onShareTargetSelected: *" + className + "*");
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
switch (id)
{
case R.id.menu_item_share:
Intent intent = getShareIntent();
setShareIntent(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
private Intent getShareIntent()
{
Intent sharingIntent = new Intent();
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "This is my text to send.");
Uri uri = Uri.parse(IMAGE_PATH);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
sharingIntent.setType("image/*");
sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sharingIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
return sharingIntent;
}
private void sendDataOnceMore()
{
if (shareIntent != null)
{
Intent sendIntent = new Intent();
try
{
sendIntent.fillIn(shareIntent, Intent.FILL_IN_COMPONENT + Intent.FILL_IN_ACTION + Intent.FILL_IN_CATEGORIES + Intent.FILL_IN_PACKAGE);
sendIntent.putExtra(Intent.EXTRA_TEXT, "And another thing...");
sendIntent.setType("text/plain");
sendIntent.setAction(Intent.ACTION_SEND);
startActivity(sendIntent);
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "Boooom!", Toast.LENGTH_LONG).show();
return;
}
}
else
{
Toast.makeText(this, "No Go :(", Toast.LENGTH_LONG).show();
return;
}
}
// Call in onCreateOptionsMenu() or the MenuItem will not be clickable!
// Call later to update the share Intent
private void setShareIntent(Intent shareIntent)
{
if (shareActionProvider != null)
{
shareActionProvider.setShareIntent(shareIntent);
}
}
}
Remember to make sure that sendIntent.resolveActivity() != null if you're using this much later - the other app may have been uninstalled in the meantime!
Login Activity
Please Help I just wanted to Remember Login in App in background, so that when he reopen the app automatically next activity open rather than sign in activity.
package xxx.xxxxx.xxxxxx;
/**
* Created by Yoyo on 12/21/2015.
*/
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
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.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
public class Login extends AppCompatActivity implements OnConnectionFailedListener, View.OnClickListener, ConnectionCallbacks {
GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso;
SignInButton signIn_btn;
private static final int RC_SIGN_IN = 0;
ProgressDialog progress_dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buidNewGoogleApiClient();
setContentView(R.layout.login);
customizeSignBtn();
setBtnClickListeners();
progress_dialog = new ProgressDialog(this);
progress_dialog.setMessage("Signing in....");
}
/*
Configure sign-in to request the user's ID, email address, and basic profile.
User's ID and basic profile are included in DEFAULT_SIGN_IN.
create and initialize GoogleApiClient object to use Google Sign-In API and the options specified by gso..
*/
private void buidNewGoogleApiClient(){
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
/*
Customize sign-in button. The sign-in button can be displayed in
multiple sizes and color schemes. It can also be contextually
rendered based on the requested scopes. For example. a red button may
be displayed when Google+ scopes are requested, but a white button
may be displayed when only basic profile is requested. Try adding the
Plus.SCOPE_PLUS_LOGIN scope to see the difference.
*/
private void customizeSignBtn(){
signIn_btn = (SignInButton) findViewById(R.id.sign_in_button);
signIn_btn.setSize(SignInButton.SIZE_STANDARD);
signIn_btn.setScopes(gso.getScopeArray());
}
/*
Set on click Listeners on the sign-in sign-out and disconnect buttons
*/
private void setBtnClickListeners(){
// Button listeners
signIn_btn.setOnClickListener(this);
findViewById(R.id.sign_out_button).setOnClickListener(this);
findViewById(R.id.disconnect_button).setOnClickListener(this);
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#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
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
progress_dialog.dismiss();
}
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
getSignInResult(result);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
Toast.makeText(this, "start sign process", Toast.LENGTH_SHORT).show();
gSignIn();
break;
case R.id.sign_out_button:
Toast.makeText(this, "Google Sign Out", Toast.LENGTH_SHORT).show();
gSignOut();
break;
case R.id.disconnect_button:
Toast.makeText(this, "Google Access Revoked", Toast.LENGTH_SHORT).show();
gRevokeAccess();
break;
}
}
private void gSignIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
progress_dialog.show();
}
private void gSignOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void gRevokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
updateUI(false);
}
});
}
private void getSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
TextView user_name= (TextView)findViewById(R.id.userName);
TextView email_id= (TextView)findViewById(R.id.emailId);
user_name.setText("UserName: "+ acct.getDisplayName());
email_id.setText("Email Id: " + acct.getEmail());
updateUI(true);
SharedPreferences sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLogin", true);
editor.putString("name", //Name),
editor.putString("e_mail",
editor.putString("ID", //ID);
editor.commit());
progress_dialog.dismiss();
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
private void updateUI(boolean signedIn) {
if (signedIn) {
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Login xml file for the Activity login xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="num.app.xxx.xxxx.xxxx.Login"
tools:showIn="#layout/Login">
<com.google.android.gms.common.SignInButton
android:id="#+id/sign_in_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/sign_out_and_disconnect"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone"
tools:visibility="visible"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true">
<TextView
android:id="#+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" user name:"
android:layout_marginTop="15dp"
android:layout_marginLeft="10dp"
android:textColor="#android:color/black"
android:textSize="14sp"
/>
<TextView
android:id="#+id/emailId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email id:"
android:textColor="#android:color/black"
android:layout_below="#+id/userName"
android:layout_marginTop="15dp"
android:layout_marginLeft="10dp"
android:textSize="14sp"
/>
<Button
android:id="#+id/sign_out_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Google Sign out"/>
<Button
android:id="#+id/disconnect_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="revoke Google Access"/>
</LinearLayout>
</RelativeLayout>
//Splash activity before the above activity
Thread timer = new Thread(){
public void run(){
try{
sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openStartingPoint = new Intent("android.intent.action.Login");
startActivity(openStartingPoint);
finish();
}
}
};
timer.start();
I would avoid saving the token in the shared preferences and rather try to perform a Silent Sign In as described here: http://android-developers.blogspot.de/2015/12/api-updates-for-sign-in-with-google.html
This has the advantage to let you verify if the user is still logged in and eventually let you prompt him to request to re-login.
here some code (basically adapted from the example in the link):
public void silentLogin() {
OptionalPendingResult<GoogleSignInResult> pendingResult = Auth.GoogleSignInApi.silentSignIn(googleApiClient);
if (pendingResult != null) {
handleGooglePendingResult(pendingResult);
} else {
//no result from silent login. Possibly display the login page again
}
}
private void handleGooglePendingResult(OptionalPendingResult<GoogleSignInResult> pendingResult) {
if (pendingResult.isDone()) {
// There's immediate result available.
GoogleSignInResult signInResult = pendingResult.get();
onSilentSignInCompleted(signInResult);
} else {
// There's no immediate result ready, waits for the async callback.
pendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
#Override
public void onResult(#NonNull GoogleSignInResult signInResult) {
onSilentSignInCompleted(signInResult, callback);
}
});
}
}
private void onSilentSignInCompleted(GoogleSignInResult signInResult) {
GoogleSignInAccount signInAccount = signInResult.getSignInAccount();
if (signInAccount != null) {
// you have a valid sign in account. Skip the login.
} else {
// you don't have a valid sign in account. Eventually display the login page again
}
}
You can try this:
After user login success then you can save id token to SharedPreferences by call method getIdToken() of GoogleSignInAccount. And when user reopen you can check id token is exiting then ignore login screen.
private void getSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
String id_token = acct.getIdToken(); //add this code here to save it by use SharedPreferences
TextView user_name= (TextView)findViewById(R.id.userName);
TextView email_id= (TextView)findViewById(R.id.emailId);
user_name.setText("UserName: "+ acct.getDisplayName());
email_id.setText("Email Id: " + acct.getEmail());
updateUI(true);
progress_dialog.dismiss();
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
//save user login state id_token
private void saveLoginState(String id_token){
SharedPreferences sharedpreferences = getSharedPreferences("YOUR_PREFERENCE_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("GG_LOGED", id_token);
editor.commit();
}
After the user login you can use this code to store the data in SharedPreference
SharedPreferences sharedPreferences = getSharedPreferences("APP", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLogin", true);
editor.putString("name", //Name);
editor.putString("e_mail",//Email);
editor.putString("ID", //ID);
editor.commit();
And in the splash screen you can do like this
boolean isLoggedIn = sharedPreferences.getBoolean("isLogin", false);
Here isLoggedIn is the value whether the user is logged in or not status. You need to handle this in SplashScreen and proceed according to that.
I'm new to Android development. I have used ;
I type the number in the EditText, Now i want to get the contact number from my contact list. can someone pls help me to fix this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText pnumber= (EditText) findViewById(R.id.editTextPnumber);
final EditText gsms= (EditText) findViewById(R.id.editTextSMS);
Button sendsms= (Button) findViewById(R.id.buttonSend);
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String gPhone= pnumber.getText().toString();
String gSMS= gsms.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(gPhone, null, gSMS, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent ! ", Toast.LENGTH_LONG).show();
finish();
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "PLS Enter Again ! ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
This is a simple trick. I hope you would be able to fix this to your code easily.
You can put a button (SMS) to its setOnClickListener you can use this.
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),
"PLS Enter Again ! ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
If you means that you want wrap input number with matched contact name from your contacts on the device?
For that you want
1) ContactProvider http://developer.android.com/guide/topics/providers/contacts-provider.html
2) AutoComplete http://developer.android.com/guide/topics/ui/controls/text.html#AutoComplete
3) If you want no one number, you could youse some chips. (EditText, Spanned) https://github.com/nichtemna/ChipsEditText#mychipsedittext, https://github.com/kpbird/chips-edittext-library
// try this way here i gave sample or demo code you modify as per your requirement.
1.activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/edtNumber"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="phone number"
android:layout_weight="1"/>
<ImageView
android:id="#+id/imgPickUpContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_marginLeft="5dp"/>
</LinearLayout>
<EditText
android:id="#+id/edtMessage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="message"/>
<Button
android:id="#+id/btnSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send"/>
</LinearLayout>
2.MyActivity
public class MyActivity extends Activity {
private EditText edtNumber;
private EditText edtMessage;
private Button btnSend;
private ImageView imgPickUpContact;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtNumber=(EditText)findViewById(R.id.edtNumber);
edtMessage=(EditText)findViewById(R.id.edtMessage);
btnSend=(Button)findViewById(R.id.btnSend);
imgPickUpContact=(ImageView)findViewById(R.id.imgPickUpContact);
imgPickUpContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent localIntent = new Intent("android.intent.action.PICK", ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(localIntent, 1);
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendSMS(edtNumber.getText().toString(), edtMessage.getText().toString());
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent paramIntent) {
super.onActivityResult(requestCode, resultCode, paramIntent);
if (resultCode == RESULT_OK) {
String str = getPhoneNumber(paramIntent.getData());
if (str.trim().length() > 0) {
edtNumber.setText(str);
edtNumber.setSelection(edtNumber.getText().length());
}
} else {
Toast.makeText(this,"Phone Number Not Founded ...",Toast.LENGTH_SHORT).show();
}
}
private String getPhoneNumber(Uri paramUri) {
String id = "";
String no="";
Cursor cursor = getContentResolver().query(paramUri, null, null, null, null);
while(cursor.moveToNext()){
id = cursor.getString(cursor.getColumnIndex("_id"));
if("1".equalsIgnoreCase(cursor.getString(cursor.getColumnIndex("has_phone_number")))){
Cursor cursorNo = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = " + id, null, null);
while (cursorNo.moveToNext()) {
if (cursorNo.getInt(cursorNo.getColumnIndex("data2")) == 2){
no = no.concat(cursorNo.getString(cursorNo.getColumnIndex("data1")));
break;
}
}
cursorNo.close();
}
}
cursor.close();
return no;
}
private void sendSMS(String paramString1, String paramString2) {
Intent localIntent = new Intent("android.intent.action.SENDTO", Uri.parse("smsto:" + paramString1));
localIntent.putExtra("sms_body", paramString2);
startActivity(localIntent);
}
}
3.please define this permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.SEND_SMS" />