(EditText)Android Contact list getting phone number - java

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" />

Related

How can I change the TextView's content by swiping horizontally?

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

User does not have permission to access this object . with storage firebase

I am making an android application which is sort of a social media app
but when I am trying to put image from gallery or from camera for profile or cover this problem occurs.
I want the user to select a photo from his gallery or take a new picture using camera and then upload the image to Firebase Storage.
User does not have permission to access this object using Firebase Storage.
There are my permissions ..
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
My Java Code:
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
String storagePath = "Uers_Profile_Cover_Imgs/";
ImageView avatartv, coverTv;
TextView nameTv, emailTv, phoneTv;
FloatingActionButton fab;
ProgressDialog pd;
private static final int CAMERA_REQUEST_CODE = 100;
private static final int STORAGE_REQUEST_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
String cameraPermissions[];
String storagePermission[];
Uri image_uri;
String profileOrCoverPhoto;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference = getInstance().getReference();
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
avatartv = view.findViewById(R.id.avatarTv);
coverTv = view.findViewById(R.id.coverTv);
nameTv = view.findViewById(R.id.name);
emailTv = view.findViewById(R.id.category);
phoneTv = view.findViewById(R.id.location);
fab = view.findViewById(R.id.fab);
pd = new ProgressDialog(getActivity());
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = "" + ds.child("name").getValue();
String image = "" + ds.child("image").getValue();
String email = "" + ds.child("email").getValue();
String phone = "" + ds.child("phone").getValue();
String cover = "" + ds.child("cover").getValue();
nameTv.setText(name);
emailTv.setText(email);
phoneTv.setText(phone);
try {
Picasso.get().load(image).into(avatartv);
} catch (Exception e) {
Picasso.get().load(R.drawable.ic_add_a_photo_black_24dp).into(avatartv);
}
try {
Picasso.get().load(cover).into(coverTv);
} catch (Exception e) {
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showEditProfileDialog();
}
});
return view;
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestStoragePermission() {
requestPermissions(storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkCameraPermission() {
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
private void requestCameraPermission() {
requestPermissions(cameraPermissions, CAMERA_REQUEST_CODE);
}
private void showEditProfileDialog() {
String options[] = {"Edit Profile Picture", "Edit Cover Photo", "Edit Name", "Edit Phone"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Action");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
pd.setMessage("Updating Profile Picture");
profileOrCoverPhoto = "image";
showImagePicDialog();
} else if (which == 1) {
pd.setMessage("Updating Cover Picture");
profileOrCoverPhoto = "cover";
showImagePicDialog();
} else if (which == 2) {
pd.setMessage("Updating Name");
showNamePhoneUpdateDialog("name");
} else if (which == 3) {
pd.setMessage("Updating Phone");
showNamePhoneUpdateDialog("phone");
}
}
});
builder.create().show();
}
private void showNamePhoneUpdateDialog(String Key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Updated " + Key);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10, 10, 10, 10);
EditText editText = new EditText(getActivity());
editText.setHint("Enter " + Key);
linearLayout.addView(editText);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString().trim();
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(Key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
private void showImagePicDialog() {
String options[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Pick Image From");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
if (!checkCameraPermission()) {
requestCameraPermission();
} else {
pickFromCamera();
}
} else if (which == 1) {
if (!checkStoragePermission()) {
requestStoragePermission();
} else {
pickFromGallery();
}
}
}
});
builder.create().show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickFromCamera();
} else {
Toast.makeText(getActivity(), "Please Enable Camera & Storage Permission", Toast.LENGTH_SHORT).show();
}
}
}
break;
case STORAGE_REQUEST_CODE: {
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickFromGallery();
} else {
Toast.makeText(getActivity(), "Please Enable Storage Permission", Toast.LENGTH_SHORT).show();
}break;
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE) {
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void uploadProfileCoverPhoto(Uri uri) {
String filePathAndName = storagePath + "" + profileOrCoverPhoto + "_" + user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
Uri downloadUri = uriTask.getResult();
if (uriTask.isSuccessful()) {
HashMap<String, Object> results = new HashMap<>();
results.put(profileOrCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Image Updated ...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "Error Updating Image ...", Toast.LENGTH_SHORT).show();
}
});
} else {
pd.dismiss();
Toast.makeText(getActivity(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
XML Codes:
<?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"
tools:context=".ProfileFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/coverTv"
android:layout_width="match_parent"
android:layout_height="180dp"
android:background="#FFA117">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout_marginTop="90dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/avatarTv"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:background="#color/colorPrimaryDark"
android:scaleType="fitXY"
app:srcCompat="#drawable/face" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#B67310"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="25sp" />
<TextView
android:id="#+id/category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#fff"
android:textSize="15dp" />
<TextView
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginLeft="5dp"
android:textColor="#fff"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:src="#drawable/editpen"
app:backgroundTint="#FFA117" />
</RelativeLayout>
FIrebase Security Rules:
service firebase.storage {
match /b/learno-fc8fc.appspot.com/o {
// Allow access by all users
allow read, write;
}
Screenshot of the issue.
Can you please cross check your bucket name if it correct.
After searching i found solution ..
My rules in Firebase was not right ..
we should make it like that ..
service firebase.storage
{ match /b/learno-fc8fc.appspot.com/o
{ match /{allPaths=**}
{ // Allow access by all users
allow read, write; }

How to save all data inputed in fragments into database on click of completed using material stepper library

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 :)

What is the better way to handle mutiple intents in android?

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);

Buttons not being shown when TextureView is implemented

So I implemented a TextureView through code. Now the buttons however are not being shown, and the onclick listener is giving me a null pointer exception. What am I doing wrong
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mTextureView = new TextureView(this);
mTextureView.setSurfaceTextureListener(this);
setContentView(mTextureView);
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
Toast.makeText(this, "No camera on device", Toast.LENGTH_LONG).show();
}else {
cameraId = findFrontFacingCamera();
if (cameraId<0){
Toast.makeText(this, "no front camera", Toast.LENGTH_LONG).show();
}else{
camera = Camera.open(cameraId);
Toast.makeText(this, "We have camera", Toast.LENGTH_LONG).show();
}
}
findViewById(R.id.buttonMenu).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// No account, load new account view
Intent intent = new Intent(CameraActivity.this,
MenuActivity.class);
startActivityForResult(intent, 0);
}
});
}
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width,
int height) {
camera = Camera.open();
Camera.Size previewSize = camera.getParameters().getPreviewSize();
mTextureView.setLayoutParams(new FrameLayout.LayoutParams(
30, 30, Gravity.CENTER));
try {
camera.setPreviewTexture(surface);
} catch (IOException t) {
}
camera.startPreview();
mTextureView.setAlpha(0.8f);
mTextureView.setRotation(45.0f);
}
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width,
int height) {
// Ignored, the Camera does all the work for us
}
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
camera.stopPreview();
camera.release();
return true;
}
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// Called whenever a new frame is available and displayed in the
rotation += 1.0f;
if (rotation > 360) {
rotation = 0;
}
mTextureView.setRotation(rotation);
}
#Override
protected void onPause() {
if (camera != null) {
camera.release();
camera = null;
}
super.onPause();
}
public void onClick(View view) {
if (camera == null){
Toast.makeText(this, "Camera is null", Toast.LENGTH_LONG).show();
}else{
camera.takePicture(null, null,
new PhotoHandler(getApplicationContext(), mPreferences ));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.camera, menu);
return true;
}
}
xml file:
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".CameraActivity" >
<Button
android:id="#+id/buttonMenu"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/capture"
android:layout_alignBottom="#+id/capture"
android:layout_alignParentLeft="true"
android:layout_marginLeft="22dp"
android:text="menu" />
<Button
android:id="#+id/capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="24dp"
android:onClick="onClick"
android:text="Take pic" />
</RelativeLayout>
you should add the TextureView you created through code in the activity_camera.xml. You should retrieve the root for activity_camera.xml (RelativeLayout) with findViewById and call addView(mTextureView) on the RelativeLayout instance you get. Calling setContentView(mTextureView) will simply replace the views hierarchy.

Categories

Resources