Android Studio App | Firebase Database Reference not working - java

I'm working on this bit of code that should reference my Firebase Cloud Database. The idea that if there is no uID in the database, (from a user that has successfully authenticated), that it should send the person to a SetupActivity class. Right now, as this codes stands, it doesn't hit the database and goes straight to my MainActivity. Permissions on the database allows read/write. Anyone have a clue that might be the issue?
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.v4.view.GravityCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
String currentUserID;
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder().build(),
new AuthUI.IdpConfig.GoogleBuilder().build());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
//Navigation Drawer
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void onStart()
{
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null)
{
SendUserToLoginActivity();
}
else
{
CheckUserExistence();
}
}
private void CheckUserExistence()
{
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity()
{
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToLoginActivity()
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
if (id == R.id.nav_leader) {
} else if (id == R.id.nav_mypicks) {
} else if (id == R.id.nav_tribe) {
} else if (id == R.id.nav_results) {
} else if (id == R.id.nav_chat) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_donate) {
} else if (id == R.id.nav_logout) {
mAuth.signOut();
SendUserToLoginActivity();
} else if (id == R.id.nav_feedback) {
} else if (id == R.id.nav_profile) {
} else if (id == R.id.nav_home) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}

you are doing wrong,
here current_user_id is a uId which is available in Authentication of user
and you are trying to match it with the database key, which is not the same in any way, you must do a comparison with email or phone number which you are going to authenticate a user.
do something like this,
private void CheckUserExistence()
{
final String current_user_id = mAuth.getCurrentUser().getEmail();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
User user = dataSnapshot1.getValue(User.class);
if(user.getEmail().equels(current_user_id))
{
SendUserToSetupActivity();
break;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Related

How to check if user is new using GoogleSignInOptions in android studio using java?

I want my app to know if a user is new or not using GoogleSignInOptions. If the user is new I want them to show Navigation_Drawer as open else close the drawer.
How can I achieve that?
Below is the code that I used for the navigation drawer.
But my aim is to know if a user is the first time logging in or a new user and wants to do stuff as required.
Here's my code:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity {
NavigationView navigationView;
DrawerLayout drawerLayout;
GoogleSignInClient mGoogleSignInClient;
DatabaseReference databaseReference;
GoogleSignInAccount account;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewByIDS();
requiredByOtherMethods();
setUserProfileNavHeader();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
loadFragment(new MainViewFragment());
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_mainActivity){
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
else if (id == R.id.nav_chart) {
loadFragment(new PieChartFragment());
} else if (id == R.id.nav_connect_fb) {
Intent i =getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
openIntent(i);
} else if (id == R.id.nav_connect_insta) {
openIntent("https://www.instagram.com/prabinchand.007/");
} else if (id == R.id.nav_connect_linkedin) {
openIntent("https://www.linkedin.com/in/prabin-chand-42aa9b111/");
} else if (id == R.id.nav_connect_website) {
openIntent("https://www.prabinchand.com.np/");
} else if (id == R.id.nav_graph) {
loadFragment(new IncomeFragment());
} else if (id == R.id.nav_logout) {
showAlertBox();
} else if (id == R.id.nav_share) {
Toast.makeText(MainActivity.this, "GENERATE_LINK : SHARE MY APP", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "GOTO PLAY_STORE : FEEDBACK", Toast.LENGTH_SHORT).show();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
}
private void openIntent(String socialMediaLink) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(socialMediaLink));
startActivity(intent);
}
private void openIntent(Intent i){
Intent intent = new Intent(i);
startActivity(intent);
}
private void showAlertBox() {
new AlertDialog.Builder(this)
.setMessage("Do you want to log out ? ")
.setTitle("Alert !")
.setIcon(R.drawable.warning)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(getApplicationContext(), gso);
mGoogleSignInClient.signOut();
Toast.makeText(getApplicationContext(), "Logged out", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.show();
}
private void requiredByOtherMethods() {
account = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
databaseReference = FirebaseDatabase.getInstance().getReference().child("UsersExpense");
}
private void findViewByIDS() {
navigationView = findViewById(R.id.navigationView);
navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setItemIconTintList(null);
drawerLayout = findViewById(R.id.drawerLayout);
}
private void loadFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, fragment);
ft.commit();
}
private void setUserProfileNavHeader() {
//hook imageView of Navigation Header
View view = navigationView.getHeaderView(0);
CircleImageView imageView = (CircleImageView) view.findViewById(R.id.nav_header_imageView);
//hook textView of Navigation Header
TextView textView = (TextView) view.findViewById(R.id.nav_header_textView);
textView.setText(account.getDisplayName());
//get image URI from user's google account
Uri imagePic = account.getPhotoUrl();
Glide.with(this)
.load(imagePic)
.placeholder(R.drawable.google)
.error(R.drawable.google)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.priority(Priority.HIGH)
.into(imageView);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
When you need to authenticate your users in Firebase with Google, it means that you need to get Google credentials so you can further create a Firebase account. If you need to know if the user signs in for the first time, please note that a GoogleSignInOptions object doesn't contain such information. To solve this, you have to call AuthResult#getAdditionalUserInfo() function that returns an object of type AdditionalUserInfo. Having such an object, you can isNewUser() method which:
Returns whether the user is new or existing.
In Java, you can simply use the code in my answer from the following post:
How can I detect if user first time in Firebase

Converted Website into Android App and Youtube Videos From my Website Doesn't go in full screen mode

I converted a website into an app with WebView in Android Studio. Everything is fine but the youtube videos that was in my website does not go in full Screen. I am a beginner, so please help me in solving this.
Main Activity Code ---
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import java.net.URI;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//initializing WebView
private WebView mwebView;
private FrameLayout customViewContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
private View mCustomView;
private MyWebviewClient mWebChromeClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//WebView
mwebView = (WebView) findViewById(R.id.myWebView);
WebSettings webSettings = mwebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
mwebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mwebView.getSettings().setAppCacheEnabled(true);
mwebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mwebView.setWebChromeClient(new MyChromeBrowser());
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
mWebChromeClient = new myWebChromeClient();
         webView.setWebChromeClient(mWebChromeClient);
mwebView.loadUrl("https://laughonlyblog.wordpress.com");
//force links open in webview only
}
private class MyChromeBrowser extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
mwebView.loadUrl("http://www.newsweek.com/us");
} else if (id == R.id.nav_slideshow) {
mwebView.loadUrl("http://www.newsweek.com/world");
} else if (id == R.id.nav_manage) {
mwebView.loadUrl("http://www.newsweek.com/tech-science");
} else if (id == R.id.nav_gallery) {
mwebView.loadUrl("http://www.newsweek.com/sports");
} else if (id == R.id.nav_share) {
mwebView.loadUrl("http://www.newsweek.com/about-newsweek");
} else if (id == R.id.nav_send) {
mwebView.loadUrl("http://www.newsweek.com/contact");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class MyWebviewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/* if (Uri.parse(url).getHost().equals("www.laughonlyblog.wordpress.com/about/")) {
//open url contents in webview
return false;
} else {
//here open external links in external browser or app
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} */
view.loadUrl(url);
return true;
}
//ProgressDialogue
ProgressDialog pd = null;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd=new ProgressDialog(MainActivity.this);
pd.setTitle("Please Wait..");
pd.setMessage("Website is Loading..");
pd.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
super.onPageFinished(view, url);
}
}
//goto previous page when pressing back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mwebView.canGoBack()) {
mwebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
To achieve this follows these steps :
1) Set WebChromeClient to your webview.
Exmaple : WebView.setWebChromeClient(new MyChromeBrowser());
2) Implement method onShowCustomView() and onHideCustomView() inside your WebChromeClient.
Example : `
private class MyChromeBrowser extends WebChromeClient {
#Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
}
#Override
public void onHideCustomView() {
super.onHideCustomView();
}
}`
3) Give android:hardwareAccelerated="true" in manifest file for your activity.
Example : <activity android:name=".MainActivity"
android:hardwareAccelerated="true"
/>
Update :
To fix this try these :
change these lines : webView.setWebChromeClient(new MyWebChromeClient()); to
mWebChromeClient = new myWebChromeClient();
webView.setWebChromeClient(mWebChromeClient);
inside initWebView() method.
To let the system decide the best orientation in full-screen mode add this line to onShowCustomView(View view, CustomViewCallback callback) method:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
UPDATE : 09-07-2017
Or you can use a VideoEnabledWebView library for full screen viedo player in webview and much more .
Link : GitHub

Android studio - Button onclick in a fragment ERROR [duplicate]

This question already has answers here:
Start an activity from a fragment
(7 answers)
Closed 6 years ago.
SecondFragment.java
package com.hci.acer.heroesunite;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class SecondFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.trivia, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i;
i = new Intent(SecondFragment.this, jrizal_trivia.class);
startActivity(i);
}
});
return view;
}
}
jrizal_trivia.java
package com.hci.acer.heroesunite;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class jrizal_trivia extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jrizal_trivia);
}
}
MainActivity.java
package com.hci.acer.heroesunite;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.app.FragmentManager fragmentManager = getFragmentManager();
if (id == R.id.nav_home) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
,new FirstFragment())
.commit();
} else if (id == R.id.nav_dyk) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
,new SecondFragment())
.commit();
} else if (id == R.id.nav_about) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
,new ThirdFragment())
.commit();
} else if (id == R.id.nav_hero1) {
startActivity(new Intent(this, jose_rizal.class));
} else if (id == R.id.nav_hero2) {
startActivity(new Intent(this, andres_bonifacio.class));
} else if (id == R.id.nav_hero3) {
startActivity(new Intent(this, emilio_aguinaldo.class));
} else if (id == R.id.nav_hero4) {
startActivity(new Intent(this, apolinario_mabini.class));
} else if (id == R.id.nav_hero5) {
} else if (id == R.id.nav_hero6) {
startActivity(new Intent(this, juan_luna.class));
} else if (id == R.id.nav_hero7) {
} else if (id == R.id.nav_hero8) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
And this is the error
Error:(28, 31) error: no suitable constructor found for
Intent(,Class) constructor
Intent.Intent(String,Uri) is not applicable (argument mismatch;
cannot be converted to String) constructor
Intent.Intent(Context,Class) is not applicable (argument mismatch;
cannot be converted to Context)
under (SecondFragment.this, jrizal_trivia.class);
error says. "Cannot resolve constructor'intent(com.hci.acer.heroesunite.SecondFragment,java.lang.Class)'
Help anyone ? i want to call another activity in my button here in SecondFragment. Thanks
i = new Intent(SecondFragment.this, jrizal_trivia.class);
the first param need a Context, so you can get Context from fragment by getActivity()/getContext().
so should be like this:
i = new Intent(getActivity(), jrizal_trivia.class);

Call requires API level 23 (current min is 22) While making a call request from App

I am doing an app for making a call directly from an image button inside my app. I want the app to be worked with both API 22 and 22. But while making the minSDK as 22, I am getting an error.
How to make it work??
MainActivity.java
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=this.mContext;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
if (mContext.checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 4636));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
}
break;
}
}
}
The error is under checkSelfPermission
I had give the permission in Manifest...
You have to asked the runtime permission while compiling agaisnt 6.0
public static final int REQUEST_READ_PERMISSION =111;
// before on create as global variable
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton:
f (CheckPermission(this, Manifest.permission.CALL_PHONE)) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 4636));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else {
RequestPermission(YourActivityName.this, Manifest.permission.CALL_PHONE, REQUEST_READ_PERMISSION );
}
break;
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_READ_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 4636));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else {
ShowToast(getString(R.string.permission_needed_sms));
}
return;
}
}
}

EditText field gets an incorrect output

So, I have this testing app where I am trying to have two fragments communicate via MainActivity. After some research, I have managed to pass data from MainFragment to FragmentTwo. However, whenever I pass in string value from the MainFragment, I get a message saying
"android.support.v7.widget.AppCompatEditText{cce883f VFED .....
app:id/editText}"
I couldn't find what the problem was for this case. Please help.
BTW I know how to use intents and that they are much more flexible(sometimes) than fragments are but this is just so that I know how far I can go with Fragments.
Here's my MainActivity
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, MainFragment.OnHeadlineSelectedListener {
private String dataReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void sendInformations(String message) {
FragmentTwo fragmentTwo = new FragmentTwo();
Bundle args = new Bundle();
args.putString(fragmentTwo.DATA_RECEIVE, message);
fragmentTwo.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.container, fragmentTwo)
.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager = getFragmentManager();
int id = item.getItemId();
if (id == R.id.frag_one) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentOne()).commit();
} else if (id == R.id.frag_two) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentTwo()).commit();
} else if (id == R.id.frag_three) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentThree()).commit();
} else if (id == R.id.frag_four) {
fragmentManager.beginTransaction().replace(R.id.container, new FragmentFour()).commit();
} else if (id == R.id.main_frag) {
fragmentManager.beginTransaction().replace(R.id.container, new MainFragment()).commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
MainFragment class
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MainFragment extends Fragment {
OnHeadlineSelectedListener mCallback;
Button sendData;
public interface OnHeadlineSelectedListener {
public void sendInformations(String message);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
final EditText userInput = (EditText) rootView.findViewById(R.id.editText);
sendData = (Button) rootView.findViewById(R.id.button);
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button) {
mCallback.sendInformations(userInput.toString());
}
}
});
return rootView;
}
}
FragmentTwo class
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FragmentTwo extends Fragment {
final static String DATA_RECEIVE = "data_receive";
TextView textView;
String input;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
textView = (TextView) rootView.findViewById(R.id.data_receiver2);
savedInstanceState = getArguments();
if(savedInstanceState != null) {
input = savedInstanceState.getString(DATA_RECEIVE);
}
textView.setText(input);
return rootView;
}
}
Oh, and the message I get is when I run the app, type into the textfield, and press the button, I get the weird message. I would appreciate if anyone can tell me what is causing the weird output..
If this is a bug, which I had noticed in some cases that were relevant, is it because I deprecated the v7.Fragment & v7.FragmentManager?
You are basically passing the EditText as a string in place of the EditText value.
In your MainFragment change mCallback.sendInformations(userInput.toString()); to mCallback.sendInformations(userInput.getText().toString());
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button) {
mCallback.sendInformations(userInput.getText().toString());
}
}
});

Categories