I got some errors in DrawerLayout and Google appindex API!!
I'm going to crazy with this IntelliJ Android Studio :(
here is DrawerLayout :
DL
here is error messages :
EM
and here is my HomaActivity (MainActivity) code:
package ir.homa;
import android.net.Uri;
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;
import java.util.HashMap;
import ir.homa.SQLiteHandler;
import ir.homa.SessionManager;
import android.content.Intent;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class HomaActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homa);
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();
}
});
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
*/
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(HomaActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
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.homa, 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;
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Homa Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://ir.homa/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Homa Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://ir.homa/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
I have some errors about Google Play AppIndex in middle of those errors!
help..!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homa);
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();
}
});
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
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);
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
*/
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(HomaActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
Related
My application crashes after trying to login.
i created navigationActivity as CHome which i want my user to be directed to. But it keeps crashing :
Unfortnately your app has stopped working.
But when i disabled this lines below it shows the Toast and no crash.
Help please
Toast.makeText(LoginActivity.this, "CUSTOMER",Toast.LENGTH_SHORT).show();
Intent cHome = new Intent(LoginActivity.this, CHome.class);
Common.currentUser = user;
startActivity(cHome);
finish();
and i have my manifest here
my CHome is as follows
package com.example.oracle.eliteafro;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.TextView;
//import com.example.oracle.eliteafro.Common.Common;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;
public class CHome extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//Init Firebase
//FirebaseDatabase database;
// DatabaseReference salons;
TextView loginName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chome);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Menu");
setSupportActionBar(toolbar);
//Init Firebase
// database = FirebaseDatabase.getInstance();
//salons = database.getReference("el_af_salon");
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);
//set name for user
View headerView = navigationView.getHeaderView(0);
loginName = (TextView) findViewById(R.id.loginName);
loginName.setText("Beedy");
//loginName.setText(Common.currentUser.getFullname());
}
#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.chome, 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;
}
}
Declare CHome as activity in your AndroidManifest.xml
UPDATE
I saw your updated question, so the problem is on your CHome activity, you are not getting the reference of your TextView before set the text.
TextView yourTextView = findViewById(R.id.your_text_view_id);
yourTextView.setText("your text");
UPDATE 2
Ok, I think that you need to pass parameters, you could pass parameters using extras.
Intent cHome = new Intent(LoginActivity.this, CHome.class);
cHome.putExtra("user", user);
startActivity(cHome);
finish();
Then on your CHome activity class you need to receive the extra :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
User user = (User) getIntent().getSerializableExtra("user");
//now you can use your user object
TextView yourTextView = findViewById(R.id.your_text_view_id);
yourTextView.setText(user.getName()); // for example
}
Don't forget your User class has to implements Serializable
The problem is inside of your onCreate method for CHome, you are references a null TextView. So either, you forgot to call
TextView textView = findViewById(R.id.your_text_view_id);
Or, maybe you did call that method but you passed in a id to a view that doensn't exist in your layout because findViewById will fail silently and return null instead of throughing an exception. So when you call setText() on the TextView you get a NullPointerexception.
I have a simple project with a navigation drawer that loads the users name, email and profile picture when they log in using a google account, This all gets set in the navigation drawer. The issue I'm facing is that it does not load the users picture, name or email when they first launch the app and log in, if you close the app and reopen it will then show the users information. My code is below:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
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.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.mts2792.swissarmytools.R;
import com.squareup.picasso.Picasso;
import model.CircleTransform;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#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);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("User logged in", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("User logged out", "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#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);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = user.getUid();
TextView nameTextView = (TextView) findViewById(R.id.currentUser);
TextView emailTextView = (TextView) findViewById(R.id.currentEmail);
ImageView currentPic = (ImageView) findViewById(R.id.currentPic);
nameTextView.setText(name);
emailTextView.setText(email);
Picasso.with(this)
.load(photoUrl)
.resize(175, 175)
.placeholder(R.drawable.ic_account)
.error(R.drawable.ic_account)
.centerCrop()
.transform(new CircleTransform())
.into(currentPic);
// Picasso.with(this).load(photoUrl).into(currentPic);
Log.v("Logged in", name);
Log.v("Email: ", email);
}
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_home) {
// Handle the camera action
} else if (id == R.id.nav_compass) {
} 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;
}
}
Heres some screenshots to show what I'm talking about:
First load:
After the second load:
Using Drawer state change listener might help you out, here is a stripped down version of your code, I have kept the ActionBarDrawerToggle as is., you might want to update that
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth mAuth;
FirebaseUser FBuser;
private FirebaseAuth.AuthStateListener mAuthListener;
#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);
mAuth = FirebaseAuth.getInstance();
FBuser = FirebaseAuth.getInstance().getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FBuser = firebaseAuth.getCurrentUser();
fetchUpdateUserData();
if (FBuser != null) {
// User is signed in
Log.d("User logged in", "onAuthStateChanged:signed_in:" + FBuser.getUid());
} else {
// User is signed out
Log.d("User logged out", "onAuthStateChanged:signed_out");
}
// ...
}
};
mAuth.addAuthStateListener(mAuthListener)
}
#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);
// Fetch Data if FBuser is not null
fetchUpdateUserData();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {}
#Override
public void onDrawerOpened(View drawerView) {}
#Override
public void onDrawerClosed(View drawerView) {}
#Override
public void onDrawerStateChanged(int newState) {
// STATE_IDLE, STATE_DRAGGING or STATE_SETTLING.
if (newState == STATE_DRAGGING || newState == STATE_SETTLING)
// Fetch Data if FBuser is not null
fetchUpdateUserData();
}
});
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void fetchUpdateUserData() {
if (FBuser != null) {
// Name, email address, and profile photo Url
String name = FBuser.getDisplayName();
String email = FBuser.getEmail();
Uri photoUrl = FBuser.getPhotoUrl();
// The FBuser's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getToken() instead.
String uid = FBuser.getUid();
TextView nameTextView = (TextView) findViewById(R.id.currentUser);
TextView emailTextView = (TextView) findViewById(R.id.currentEmail);
ImageView currentPic = (ImageView) findViewById(R.id.currentPic);
nameTextView.setText(name);
emailTextView.setText(email);
Picasso.with(this)
.load(photoUrl)
.resize(175, 175)
.placeholder(R.drawable.ic_account)
.error(R.drawable.ic_account)
.centerCrop()
.transform(new CircleTransform())
.into(currentPic);
// Picasso.with(this).load(photoUrl).into(currentPic);
} else {
nameTextView.setText("");
emailTextView.setText("");
Picasso.with(this)
.load(R.drawable.ic_account)
.resize(175, 175)
.placeholder(R.drawable.ic_account)
.error(R.drawable.ic_account)
.centerCrop()
.transform(new CircleTransform())
.into(currentPic);
}
}
}
PS: please refactor the code before posting and use Fields rather than localVariables for DRY (don't repeat yourself) coding
Hello Davis try this in your code if it helps
When your activity first loads onCrate method will work and while coming from background to foreground onResume will work
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getUserDetails();
TextView nameTextView = (TextView) findViewById(R.id.currentUser);
TextView emailTextView = (TextView) findViewById(R.id.currentEmail);
ImageView currentPic = (ImageView) findViewById(R.id.currentPic);
nameTextView.setText(name);
emailTextView.setText(email);
Picasso.with(this)
.load(photoUrl)
.resize(175, 175)
.placeholder(R.drawable.ic_account)
.error(R.drawable.ic_account)
.centerCrop()
.transform(new CircleTransform())
.into(currentPic);
}
#Override
protected void onResume() {
super.onResume();
getUserDetails();
}
public void getUserDetails(){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
name = user.getDisplayName();
email = user.getEmail();
photoUrl = user.getPhotoUrl();
uid = user.getUid();
}
}
I am pretty new to the Google Maps API v2 and would like to integrate a map available via this base link: https://tiles.guildwars2.com/{continent_id}/{floor}/{zoom}/{x}/{y}.jpg. My problem is, well everything, but let's get started with the following:
1) How can I set the map sizes that there is no grey space at any side?
2) How can I move the map correctly because I have obviously 4 parameters while I can change only 3 at a time with getTileUrl?
3) Why are the tiles mixed and not shown in their correct order?
The map documentation is available here:
http://wiki.guildwars2.com/wiki/API:2/maps
http://wiki.guildwars2.com/wiki/API:Maps
Working example link: 0.jpg
My current code is:
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
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;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
import java.net.MalformedURLException;
import java.net.URL;
public class mapsContainer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback {
SupportMapFragment mapFragment;
private DrawerLayout drawer;
private Toolbar toolbar;
private ActionBarDrawerToggle toggle;
private NavigationView navigationView;
private GoogleMap mMap;
private TileOverlay mSelectedTileOverlay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mapFragment = SupportMapFragment.newInstance();
setContentView(R.layout.activity_maps_container);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
setSupportActionBar(toolbar);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawer.addDrawerListener(toggle);
navigationView.setNavigationItemSelectedListener(this);
ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
View navHeader = navigationView.getHeaderView(0);
if (networkInfo != null && networkInfo.isConnected()) {
TextView connectionStatus = (TextView) navHeader.findViewById(R.id.connection_status);
connectionStatus.setText(R.string.common_online);
} else {
TextView connectionStatus = (TextView) navHeader.findViewById(R.id.connection_status);
connectionStatus.setText(R.string.common_offline);
}
toggle.syncState();
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.mapsFragement, mapFragment).commit();
mapFragment.getMapAsync(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
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 onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = drawer.isDrawerOpen(GravityCompat.START);
return super.onPrepareOptionsMenu(menu);
}
#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.syncProfile) {
//String res = gwApiAccess.apiQueryAuthorized("https://api.guildwars2.com/v2/account/dyes");
//Log.d(DEBUG_TAG,"res: " + res);
}
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_home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.nav_profile) {
Intent intent = new Intent(this, profile.class);
startActivity(intent);
} else if (id == R.id.nav_itemDB) {
Intent intent = new Intent(this, items.class);
startActivity(intent);
} else if (id == R.id.nav_guilds) {
Intent intent = new Intent(this, guilds.class);
startActivity(intent);
} else if (id == R.id.nav_maps) {
//Do nothing
} else if (id == R.id.settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
CustomUrlTileProvider mTileProvider = new CustomUrlTileProvider(256, 256, "https://tiles.guildwars2.com/{continent_id}/{floor}/{zoom}/{x}/{y}.jpg");
mSelectedTileOverlay = mMap.addTileOverlay(new TileOverlayOptions().tileProvider(mTileProvider).zIndex(-1));
mMap.getUiSettings().setTiltGesturesEnabled(false);
mMap.getUiSettings().setRotateGesturesEnabled(false);
}
private static class CustomUrlTileProvider extends UrlTileProvider {
private String baseUrl;
CustomUrlTileProvider(int width, int height, String url) {
super(width, height);
this.baseUrl = url;
}
#Override
public URL getTileUrl(int zoom, int x, int y) {
try {
return new URL(baseUrl.replace("{continent_id}", "" + 1).replace("{floor}", "" + 0).replace("{zoom}", "" + zoom).replace("{x}", "" + x).replace("{y}", "" + y));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
private boolean checkTileExists(int x, int y, int zoom) {
int minZoom = 0;
int maxZoom = 0;
return !(zoom < minZoom || zoom > maxZoom);
}
}
}
Ok, after having a looooong break because of school I figured everything out except the first thing.
My fault with the wrong tiles was that I did not have the correct order of params.
The other thing with the to much params, I will program myself a workaround in the near future.
So I will close the thread and open a new one just before I smash the display because sth doesn't work.
This question already has answers here:
Can not find a View with findViewById()
(4 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am currently trying to program a small app, now I am trying to use a Navigation Drawer in my app. This does not work with the reason that I get a NPE at drawer.addDrawerListener(toggle);. Everything else seems to be fine as far as I can say and the app worked correctly till adding the drawer. Thx in advance.
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
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.TextView;
import de.nocompany.gotthold.gw2companion.Tools.GwApiAccess;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private Toolbar toolbar;
private ActionBarDrawerToggle toggle;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_main);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
drawer.addDrawerListener(toggle);
navigationView.setNavigationItemSelectedListener(this);
ConnectivityManager connMgr = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
View navHeader = navigationView.getHeaderView(0);
if (networkInfo != null && networkInfo.isConnected()) {
TextView connectionStatus = (TextView) navHeader.findViewById(R.id.connection_status);
connectionStatus.setText(R.string.common_online);
} else {
TextView connectionStatus = (TextView) navHeader.findViewById(R.id.connection_status);
connectionStatus.setText(R.string.common_offline);
}
toggle.syncState();
GwApiAccess gwApiAccess = new GwApiAccess(this,"https://api.guildwars2.com/v2/items/30704?lang=de");
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
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 onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = drawer.isDrawerOpen(GravityCompat.START);
return super.onPrepareOptionsMenu(menu);
}
#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_profile) {
Intent intent = new Intent(this,profile.class);
startActivity(intent);
} else if (id == R.id.nav_itemDB) {
Intent intent = new Intent(this,items.class);
startActivity(intent);
} else if (id == R.id.nav_guilds) {
Intent intent = new Intent(this,guilds.class);
startActivity(intent);
} else if (id == R.id.nav_maps) {
Intent intent = new Intent(this,map.class);
startActivity (intent);
} else if (id == R.id.settings) {
Intent intent = new Intent(this,SettingsActivity.class);
startActivity (intent);
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
First change this part
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
setSupportActionBar(toolbar);
setContentView(R.layout.activity_main);
to this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
setSupportActionBar(toolbar);
Because you are not set layout to Actiivty before that you have to access it inner element so that the Studio can't find it and it give you NullpointerExeception.
I have a navigation drawer and a fragment listview that uses ArrayAdapter. The app crashes at the current build. The part that I'm not sure is MyListAdapter, where super(getActivity(), R.Layout...). Can someone please help me with this? I've spent much time in trying to fix this.
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class FavouritesFragment extends ListFragment {
private List<Food> foodList = new ArrayList<Food>();
public FavouritesFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
populateFoodList();
populateListView();
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_favourites, container, false);
}
private void populateFoodList() {
foodList.add(new Food("Large Fries", 4.50, R.drawable.fries));
foodList.add(new Food("Small Fries", 4.50, R.drawable.fries));
foodList.add(new Food("Hamburger", 4.50, R.drawable.hamb));
foodList.add(new Food("Cheese Burger", 4.50, R.drawable.hamb));
foodList.add(new Food("Cheese Bacon Burger", 4.50, R.drawable.hamb));
foodList.add(new Food("Crispy Chicken Burger", 4.50, R.drawable.hamb));
foodList.add(new Food("Large Poutine", 4.50, R.drawable.poutine));
foodList.add(new Food("Small Poutine", 4.50, R.drawable.poutine));
}
private void populateListView() {
ArrayAdapter<Food> adapter = new MyListAdapter();
ListView list = (ListView) getActivity().findViewById(R.id.favouritesListView);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Food> {
public MyListAdapter() {
super(getActivity(), R.layout.item_view, foodList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getActivity().getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Food selectedFood = foodList.get(position);
ImageView imageView = (ImageView) getActivity().findViewById(R.id.item_imgFood);
imageView.setImageResource(selectedFood.getIconID());
return itemView;
// return super.getView(position, convertView, parent);
}
}
}
This is my MainActivity
import android.net.Uri;
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;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setting fragment
MainMenu fragment = new MainMenu();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#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) {
MainMenu fragment = new MainMenu();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
FavouritesFragment fragment = new FavouritesFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} 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;
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.hrak109.happytimescafe/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.hrak109.happytimescafe/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}