REST POST API using with request Query Params in android Studio - java

I'm using the Retrofit2 Library to consume Rest API with a post request that delivers data in query parameters not in body. Now I want to integrate that api but retrofit stops us from providing data as a query parameters through a post request. It is possible to use a post request with retrofit to deliver data in query parameters?
Here is API Interface
#POST("calculation")
Call<QuestionResponse> calculation(
#Query("height") Double height,
#Query("age") Integer age,
#Query("gender") Boolean gender,
#Query("current_weight") Double current_weight,
#Query("activity_level") Double activity_level,
#Query("user_id") Integer user_id
Here is Question.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmiquestions);
getSupportActionBar().hide();
nextbtn = findViewById(R.id.Next);
date = findViewById(R.id.calender);
age = findViewById(R.id.age);
height = findViewById(R.id.currentHeight);
weight = findViewById(R.id.currentWeight);
rgGender = findViewById(R.id.gender_group);
rbMale = findViewById(R.id.male);
rbFemale = findViewById(R.id.female);
rgGender.clearCheck();
rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
rbMale = group.findViewById(R.id.male);
rbFemale = group.findViewById(R.id.female);
if (rbMale.isSelected()) {
gender= Boolean.valueOf("0");
}
if (rbFemale.isSelected()) {
gender= Boolean.valueOf("1");
}
}
});
findViewById(R.id.female).setOnClickListener(this);
findViewById(R.id.male).setOnClickListener(this);
findViewById(R.id.Next).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.Next:
openHomePage();
break;
}
}
public void openHomePage() {
Double userHeight = Double.valueOf(height.getText().toString());
Double userWeight = Double.valueOf(weight.getText().toString());
Integer userAge = Integer.valueOf(age.getText().toString());
if(rgGender.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please Select Gender", Toast.LENGTH_SHORT).show();
return;
}
Intent i=new Intent(BMIquestions.this,ActivityLevel.class);
i.putExtra("age",userAge);
i.putExtra("height",userHeight);
i.putExtra("weight",userWeight);
i.putExtra("gender",gender);
startActivity(i);
Here is Activity_level.java
public class ActivityLevel extends AppCompatActivity implements View.OnClickListener {
ImageButton next;
ImageButton previous;
CardView card1,card2,card3,card4;
SharedPreferenceManager sharedPreferenceManager;
SharedPreferences.Editor editor;
TextView l1,l2,l3,l4;
Double activity_level;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
getSupportActionBar().hide();
next = findViewById(R.id.NextButton);
previous = findViewById(R.id.PreviousButton);
card1 = (CardView) findViewById(R.id.level1);
card2 = (CardView) findViewById(R.id.level2);
card3 = (CardView) findViewById(R.id.level3);
card4 = (CardView) findViewById(R.id.level4);
card1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.55;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.725;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=1.75;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
card4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
activity_level=2.04;
Toast.makeText(ActivityLevel.this, activity_level.toString(), Toast.LENGTH_SHORT).show();
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openHomePage();
}
});
sharedPreferenceManager=new SharedPreferenceManager(getApplicationContext());
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.PreviousButton:
openBMIPage();
break;
}
}
public void openHomePage() {
Integer age= Integer.valueOf(getIntent().getStringExtra("age"));
Boolean gender= Boolean.valueOf(getIntent().getStringExtra("gender"));
Double height= Double.valueOf(getIntent().getStringExtra("height"));
Double weight= Double.valueOf(getIntent().getStringExtra("weight"));
Integer userId= sharedPreferenceManager.getUser().getUserId();
Call<QuestionResponse> call = RetrofitClient
.getInstance()
.getApi()
.calculation(height,age,gender,weight,activity_level,userId);
call.enqueue(new Callback<QuestionResponse>() {
#Override
public void onResponse(Call<QuestionResponse> call, Response<QuestionResponse> response) {
QuestionResponse questionResponse = response.body();
if (response.isSuccessful()) {
if (questionResponse.getStatus().equals("SUCCESS")) {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ActivityLevel.this, HomePage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(ActivityLevel.this, questionResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<QuestionResponse> call, Throwable t) {
Toast.makeText(ActivityLevel.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void openBMIPage() {
Intent intent1 = new Intent(this, BMIquestions.class);
startActivity(intent1);
}
}
After Debugging
Connected to the target VM, address: 'localhost:52230', transport: 'socket'
Disconnected from the target VM, address: 'localhost:52230', transport: 'socket'
How do I fix this?

Related

How do I make the terms and conditions appear only when I log in to Google for the first time?

I want to add terms and conditions when users use my app.
But I have to show terms and conditions only one time.
I'm using firebase google login. But I have a problem when I show terms and conditions and how code remembers users accept terms and conditions and shows only one time.
Here's a google login code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//새로운 코드다 마
signInButton = findViewById(R.id.signInButton);
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
auth = FirebaseAuth.getInstance(); //파이어 베이스 인증 객체 초기화
signInButton.setOnClickListener(new View.OnClickListener() { // 구글 로그인 버튼을 클릭했을때 이곳을 수행
#Override
public void onClick(View view) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent,REQ_SIGN_GOOGLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) { // 구글 로그인 인증을 요청했을때 결과 값을 되돌려 받는 곳
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_SIGN_GOOGLE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess() == true) { // true 생략 가능, 인증 결과가 성공적이면
GoogleSignInAccount account = result.getSignInAccount(); //account 라는 데이터는 구글 로그인 정보를 담고 있습니다. - 닉네임,프로필사진uri,이메일 주소등
resultLogin(account); // 로그인 결과 값 출력 수행하라는 메서드
}
}
}
private void resultLogin(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
long curTime=System.currentTimeMillis();
long gapTime=curTime-backBtnTime;
if(0<=gapTime && 2000>= gapTime){
moveTaskToBack(true);
finishAndRemoveTask();
android.os.Process.killProcess(android.os.Process.myPid());
}
else {
backBtnTime = curTime;
Toast.makeText(this,"뒤로 버튼을 한 번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Here is a code I want to show (terms and conditions)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terms);
CheckBox checkBox=findViewById(R.id.checkbox);
CheckBox checkBox2=findViewById(R.id.checkbox2);
CheckBox checkBox3=findViewById(R.id.checkbox3);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox2.setChecked(true);
checkBox3.setChecked(true);
}else {
checkBox2.setChecked(false);
checkBox3.setChecked(false);
}
}
});
checkBox2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
checkBox3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
Button btn_agr = findViewById(R.id.btn_agr1);
btn_agr.setText(R.string.app_name);
btn_agr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("서비스 이용약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_agr2 = findViewById(R.id.btn_agr2);
btn_agr2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("위치 정보 이용 약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_complete = findViewById(R.id.button_complete);
btn_complete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
I tried my self - transmit variables when the user accept terms and conditions but when the user reopens the app user has to open it again
Maybe there is a way to transmit certain variables to firebase and confirm it when the user clicks the login button??
There is a way to transmit certain variables to firebase and confirm it when the user clicks the login button?
The simplest solution would be to call AuthResult#getAdditionalUserInfo() method on the Task object, because it returns an object of type AdditionalUserInfo. In this class, you can find a very useful method called isNewUser(), which can help you check if the user signs in for the first time. In code should look like this:
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
//Display Terms & Conditions
}
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});

The email address is badly formatted Firebase/ android project

hi i am working on a android project where i am using firebase as back-end and i am building a signup and login form . When ever i sign up the code is working well and . When i try to retrieve it using "signInWithEmailAndPassword i am getting the fallowing error. The email address is badly formatted Firebase`
login Activity
public class login extends AppCompatActivity {
Button create_Account, login_btn;
EditText l_email, l_password;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
fAuth = FirebaseAuth.getInstance();
create_Account = findViewById(R.id.l_signup_btn);
create_Account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(login.this, MainActivity.class));
}
});
l_password = findViewById(R.id.et_lpassword);
l_email = findViewById(R.id.et_lpassword);
login_btn = findViewById(R.id.l_login_btn);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (l_email.getText().toString().isEmpty()) {
l_email.setError("Email is Missing");
return;
}
if (l_password.getText().toString().isEmpty()) {
l_password.setError("Password is Missing");
return;
}
fAuth.signInWithEmailAndPassword(l_email.getText().toString(), l_password.getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
startActivity(new Intent(getApplicationContext(), dashboard.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(login.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), dashboard.class));
finish();
}
}
}
Can you see what mistake you have
l_password = findViewById(R.id.et_lpassword);
l_email = findViewById(R.id.et_lpassword);

Pass username to another activity with RewardedAd

The problem is that I am trying to pass the name of the user when the adReward is complete to another activity. But I'm stuck in this activity, even though the video ad is loaded. (and it works well while there are no video ad to show). Here is my code:
My java.class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
Vibrator vibrator;
private RewardedVideoAd HDay1;
int currentActivity = 0;
boolean flag;
private EditText vname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_day1);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
MobileAds.initialize(this,
"ca-app-pub-3940256099942544/6300978111");
///ADD BAN
AdView mAdView = findViewById(R.id.banner1);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////
//VIDEO
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
loadRewardedVideoDAY1();
vname = findViewById(R.id.name);
final ImageView nm = findViewById(R.id.ID);
nm.setVisibility(View.INVISIBLE);
ColorMatrix matrix = new ColorMatrix();
matrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
nm.setColorFilter(filter);
final Button closeAd = findViewById(R.id.closeDay1);
closeAd.setVisibility(View.INVISIBLE);
///////////////////////////////////////////////////////////////////////////////////////////
closeAd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vibrator.vibrate(50);
loadRewardedVideoDAY1();
if (HDay1.isLoaded()) {
HDay1.show();
setCurrent(1);
}
String name = vname.getText().toString();
getusername(name);
}
});
}
////////////////////////////////////////////////////////////////
private void Day1() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
private void getusername(String name) {
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void loadRewardedVideoDAY1() {
if (!HDay1.isLoaded()) {
HDay1 = null;
HDay1 = MobileAds.getRewardedVideoAdInstance(this);
HDay1.setRewardedVideoAdListener(this);
///////////////TEST ID//////////////////
HDay1.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
Log.d("LOADED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdOpened() {
Log.d("OPENED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoStarted() {
Log.d("STARTED!", "onRewardedVideoAdLoaded");
}
#Override
public void onRewardedVideoAdClosed() {
loadRewardedVideoDAY1();
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewarded(RewardItem rewardItem) {
loadRewardedVideoDAY1();
flag = true;
if (currentActivity == 1) {
Day1();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
#Override
public void onRewardedVideoCompleted() {
}
#Override
protected void onPause() {
HDay1.pause(this);
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
public void setCurrent(int val){
currentActivity = val;
}
Any idea what the problem could be? Thanks in advance
Try below code. Update ProcessData with your intent logic and update oncreate with other data required in your class
public class TheDay1 extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private Boolean bRewardVideo = false;
#Override
public void onResume() {
super.onResume();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.resume(this);
}
}
#Override
public void onPause() {
super.onPause();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.pause(this);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mRewardedVideoAd != null) {
mRewardedVideoAd.destroy(this);
}
}
#Override
public void onRewardedVideoCompleted() {
//Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
//Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
//Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
//Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
//Toast.makeText(this, "Reward Video Closed", Toast.LENGTH_SHORT).show();
// Load the next rewarded video ad.
if (bRewardVideo) {
ProcessData();
} else {
Toast.makeText(this, "Please View Reward Video to get Reward Points", Toast.LENGTH_LONG).show();
}
loadRewardedVideoAd();
}
#Override
public void onRewarded(RewardItem rewardItem) {
Toast.makeText(this, "Now you can close Ad to Process", Toast.LENGTH_LONG).show();
bRewardVideo = true;
}
#Override
public void onRewardedVideoAdLeftApplication() {
//Toast.makeText(this, "onRewardedVideoAdLeftApplication",Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Toast.makeText(this, "Fail to Load Reward Video. Please try again!", Toast.LENGTH_SHORT).show();
}
private void loadRewardedVideoAd() {
bRewardVideo = false;
mRewardedVideoAd.loadAd(BuildConfig.REWARDVIDEOID,
new AdRequest.Builder().build());
}
private void ProcessData() {
Snackbar.make(findViewById(R.id.drawer_layout_law), "Please wait while we process the request... ", Snackbar.LENGTH_INDEFINITE).show();
//WRITE YOUR INTENT CODE HERE
Intent intent = new Intent(this, ActivityTwo.class);
Resources resources = getResources();
String key = resources.getString(R.string.key_name);
intent.putExtra(key, name);
startActivity(intent);
}
private void ShowRewardVideoDialog() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
} else {
loadRewardedVideoAd();
Toast.makeText(mctx, "Fail to Load Reward Video : Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
}
}

How to retrieve latest entry from the firebase realtime database?

I am trying to take inputs from one user and send the same data to another user. I am not sure what to put as an argument in child so that it refers to the same data and I can retrieve and show the data to another user for approval. I am able to send the image but for the data fields like visitor,mobile and flat not sure what to do.
My code is as follows.
Data entry File Code
public class Main4Activity extends AppCompatActivity {
private static final int PERMISSION_CODE = 1000;
private static final int IMAGE_CAPTURE_CODE = 1001;
Button btn;
ImageView imageView;
static Uri image_uri;
ImageView mImageView;
TextView mCaptureBtn;
Button uploadbtn;
static String downloadurl;
public static String Dvisitor;
public static String Dmobile;
static DatabaseReference reff;
//for upload
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
FirebaseStorage storage;
StorageReference storageReference;
//for upload
static String URL;
//Data store of Visitor
static EditText visitor;
static EditText mbnumber;
EditText bnmbr;
static EditText fnmbr;
EditText emal;
EditText pswrd;
HashMap<String,Object> map = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
//for upload
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();
//for upload
mImageView = (ImageView) findViewById(R.id.imageView2);
mCaptureBtn = (TextView) findViewById(R.id.textView4);
//Data for Visitor
visitor = (EditText) findViewById(R.id.vname);
mbnumber = (EditText) findViewById(R.id.mnumber);
bnmbr = (EditText) findViewById(R.id.blknmbr);
fnmbr = (EditText) findViewById(R.id.fltnmbr);
emal = (EditText) findViewById(R.id.emailId);
pswrd = (EditText) findViewById(R.id.passwordfield2);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
upload();
FirebaseDatabase.getInstance().getReference().child("Image").push().setValue(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
map.put("visitor",visitor.getText().toString());
map.put("mobile",mbnumber.getText().toString());
map.put("block",bnmbr.getText().toString());
map.put("flat",fnmbr.getText().toString());
map.put("email",emal.getText().toString());
map.put("password",pswrd.getText().toString());
Toast.makeText(Main4Activity.this, "Successful data registration", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main4Activity.this, "Failed data registration", Toast.LENGTH_SHORT).show();
}
});
}
});
//Camera functionality click and upload starts
mCaptureBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
String[] permission = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permission, PERMISSION_CODE);
} else {
openCamera();
}
} else {
openCamera();
}
}
});
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main4Activity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");
image_uri = 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_CAPTURE_CODE);
{
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
mImageView.setImageURI(image_uri);
}
}
private void upload(){
if(image_uri != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(image_uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Uploaded", Toast.LENGTH_SHORT).show();
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
DatabaseReference imagestore = FirebaseDatabase.getInstance().getReference().child("Image").push();
//HashMap<String, String> hasmap = new HashMap<>();
URL = uri.toString();
map.put("imgurl",URL);
//map.put("imageurl", String.valueOf(uri));
imagestore.setValue(map).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent= new Intent(Main4Activity.this,Main5Activity.class);
startActivity(intent);
}
});
//This is your image url do whatever you want with it.
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Main4Activity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
}
}
}
//Camera functionality click and upload starts
Code for another user to Approve
public class Main5Activity extends AppCompatActivity {
Button btnAllow, btnProhibit;
private String Dvisitor;
private String Dmobile;
private String Dflat;
DatabaseReference reff;
ImageView img;
private DatabaseReference Post;
static TextView textView;
String roadies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnAllow = (Button) findViewById(R.id.button);
btnProhibit = (Button) findViewById(R.id.button2);
textView = (TextView) findViewById(R.id.textView5);
img = (ImageView) findViewById(R.id.imageView3);
imageshow();
init();
readonetime();
}
private void readonetime() {
Query query = Post.orderByKey().limitToLast(1);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void init() {
Post = FirebaseDatabase.getInstance().getReference().child("Image");
}
private void imageshow() {
reff = FirebaseDatabase.getInstance().getReference().child("Image");
reff.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Picasso.get().load(Main4Activity.URL).fit().into(img);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Main5Activity.this, "OoooooLalalala", Toast.LENGTH_SHORT).show();
}
});
btnAllow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main8Activity.class);
startActivity(intent);
}
});
btnProhibit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main5Activity.this, Main9Activity.class);
startActivity(intent);
}
});
}
}
In your Main5Activity, I think:
This:
for(DataSnapshot child: dataSnapshot.getChildren()) {
String post = dataSnapshot.child("visitor").getValue(String.class);
String post1 = dataSnapshot.child("mobile").getValue(String.class);
String post2 = dataSnapshot.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}
Must be like this:
for(DataSnapshot ds: dataSnapshot.getChildren()) {
String post = ds.child("visitor").getValue(String.class);
String post1 = ds.child("mobile").getValue(String.class);
String post2 = ds.child("flat").getValue(String.class);
textView.setText("Mr. "+post+"with mobile number: " + post1+"wants to visit your flat: " + post2);
}

Retrieve contact from mobile's phone directory

This code can open a built-in contacts directory on a mobile device. However, when I select a contact, the app reports "done", but doesn't retrieve the contact number -- the user can't send a message.
How do I retrieve the contact number? List View is not a solution: I need to return just the one number, not extra information.
Here's my code:
public EditText no;
public EditText msg;
public Button cancel;
public Button snd;
public String Number,name,Message;
public int run=0;
public static final int PICK_CONTACT=1;
public void callContacts(View v)
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent,PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode,int resultCode,Intent data)
{
super.onActivityResult(reqCode,resultCode,data);
if(reqCode==PICK_CONTACT)
{
if(resultCode== ActionBarActivity.RESULT_OK)
{
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData,null,null,null,null);
if(c.moveToFirst())
{
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.CONTENT_URI.toString()));
Toast.makeText(this,"done",Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
no = (EditText)findViewById(R.id.num);
msg = (EditText)findViewById(R.id.sms);
cancel = (Button)findViewById(R.id.cancel);
snd = (Button)findViewById(R.id.snd);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg.setText("");
no.setText("");
callContacts(null);
}
});
snd.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Number = no.toString();
Message = msg.getText().toString();
SmsManager manager = SmsManager.getDefault();
ArrayList<String>long_sms = manager.divideMessage(Message);
manager.sendMultipartTextMessage(Number,null,long_sms,null,null);
Toast.makeText(getApplicationContext(),"Sent Successfully",Toast.LENGTH_SHORT).show();
}
});
}
Here is the code just for selecting one phone number from contact list. i found this code simplest. let me know if there is any problem.
start activity with pick intent on phone data type:
findViewById(R.id.choose_contact_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(pickContact, PICK_CONTACT_REQUEST);
}
});
Now set onAcitivityResult();
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
switch (requestCode){
case PICK_CONTACT_REQUEST:
if (resultCode == RESULT_OK){
Uri contactUri = intent.getData();
Cursor nameCursor = getContentResolver().query(contactUri, null, null, null, null);
if (nameCursor.moveToFirst()){
String name = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = nameCursor.getString(nameCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
((EditText)findViewById(R.id.person_name)).setText(name);
((EditText)findViewById(R.id.enter_mobile)).setText(number);
nameCursor.close();
}
}
break;
}
}

Categories

Resources