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();
}
}
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'm creating a Navigation Drawer like this
MainActivity.java
import android.support.v4.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;
import com.paperwrrk.videos.FragmentVideo;
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);
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();
FragmentManager fragmentManager = getSupportFragmentManager();
if (id == R.id.nav_home) {
// Handle the camera action
} else if (id == R.id.nav_articles) {
} else if (id == R.id.nav_videos) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new FragmentVideo())
.addToBackStack(null)
.commit();
} else if (id == R.id.fb_posts) {
} 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;
}
}
My FragmentVideo
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.paperwrrk.R;
public class FragmentVideo extends Fragment {
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
myView = inflater.inflate(R.layout.fragment_video, container, false);
return myView;
}
}
But when I click on the item from Navigation Drawer second fragment doesn't replace or hide the first one, it is overlapping like this
Please see the screenshot
Use a container instead of using fragment tag
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!" />
Now in activity
if(condition)
getSupportFragmentManager().beginTransaction().replace(R.id.container,new FirstFragment()).commit();
else
getSupportFragmentManager().beginTransaction().replace(R.id.container, new SecondFragment()).commit();
if this not works try to get the fragment container view ID..Here's the code:
transaction.replace(((ViewGroup)(getView().getParent())).getId(), fragment);
It works for me...
int id = item.getItemId();
android.app.Fragment fragment = null;
if (id == R.id.nav_profile) {
fragment = new ProfileActivity();
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}
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();
}
I want to call another fragment from the current fragment on the click of the button in the current fragment.
Here is my Mainactivity :
import android.app.FragmentManager;
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 com.asd.fragments.RecommendationsFragment;
import com.asd.ibitz4college.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.TrendingFragment;
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);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
if (id == R.id.search_colleges) {
// Handle the Search Colleges action
fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();
}
else if (id == R.id.search_consultancies) {
fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();
}
else if (id == R.id.search_coaching) {
fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();
}
else if (id == R.id.my_recommendations) {
fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();
}
else if (id == R.id.trending) {
fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();
} else if (id == R.id.profile) {
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is one of my fragment :
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.asd.k4c.R;
public class SearchCoachingFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_search_coaching,container,false);
return rootview;
}
} //Update code formatting
Suppose I want to call resultsfragment from the above fragment on the click
of a button whose id is btn_search, then what should I do?
I tried some already existing answers here, no luck!
P.S: I'm a starter to the world of android dev.
For doing a fragment transaction.Please do the following.
Eg..
A and B are fragments.
Currently A is visible to the User. If you want to do a transaction.
Just create as like below
B b = new B();
((YourActivity)getActivity).setnewFragment(b,true);
public void setNewFragment(Fragment fragment,boolean addbackstack) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_content, fragment);
if (addbackstack)
transaction.addToBackStack(title);
transaction.commit();
}
Use an interface to communicate between fragments. For example
public YourFirstFragment extends Fragment {
public interface FragmentCallBack {
void callBack();
}
private FragmentCallBack fragmentCallBack;
public void setFragmentCallBack(FragmentCallBack fragmentCallBack) {
this.fragmentCallBack = fragmentCallBack;
}
private void callThisWhenYouWantToCallTheOtherFragment(){
fragmentCallBack.callBack();
}
}
Then in You activity
private void setCallToFragment{
yourFirstFragment.setFragmentCallBack(new FragmentCallBack(){
void callBack(){
yourSecondFragment.doWhatEver();
}})
}
First you need to create an interface which defines methods that will be used by your fragment to invoke code from the respective activity it is attached to
public interface OnFragmentInteractionlistener {
// the method that you call from your fragment,
// add whatever parameter you need in the implementation of this
// method.
void onClickOfMyView();
}
once you have created the interface, implement it any and all activities that use this fragment.
public class MainActivity extends AppCompatActivity
implements OnMyFragmentInteractionListener {
#Override
public void onClickOfMyView() {
// DO your on click logic here, like starting the transaction
// to add/replace another fragment.
}
}
Then in the onAttach of your fragment to an activity be sure to check if the attaching activity implements this interface, else throw a RunTimeException like so
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMyFragmentInteractionListener) {
mListener = (OnMyFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnMyFragmentInteractionListener");
}
}
Here mListener is a interface reference you hold in your fragment class through which you invoke the onClickOfMyView() method when actually the click happens
Your fragment class where the view's click code is there.
myView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mListener.onClickOfMyview();
}
});
You should create some method in your activity. Supposedly it will look like this :
public void startFragment(Fragment fragment) {
fm.beginTransaction().replace(R.id.content_frame,new fragment).commit();
}
As you already done in youronNavigationItemSelected
Then, from your fragment, you can call
((MainActivity)getActivity()).startFragment(new SearchConsultanciesFragment())
for example
Create a method switchFragment in your MainActivity
FragmentTransaction ft;
public void switchFrag() {
try {
ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, new Your_Fragment.class);
ft.commit();
} else {
Log.e("test", "else part fragment ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Now from your current Fragment you can call this MainActivity's funciton throught the below code:
((MainActivity)getActivity()).switchFrag();
Let me know if this works for you! :)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I want to call another fragment from the current fragment on the click of the button in the current fragment.Based on answers I got here, calling a fragment from fragment.
My revised code is as follows :
Here is my Mainactivity :
package com.kibitz4college.k4c;
import android.app.FragmentManager;
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 com.asd.fragments.RecommendationsFragment;
import com.asd.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.SearchResultsFragment;
import com.asd.fragments.TrendingFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SearchCoachingFragment.searchbtnclickedlistner {
#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);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
if (id == R.id.search_colleges) {
// Handle the Search Colleges action
fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();
}
else if (id == R.id.search_consultancies) {
fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();
}
else if (id == R.id.search_coaching) {
fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();
}
else if (id == R.id.my_recommendations) {
fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();
}
else if (id == R.id.trending) {
fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();
} else if (id == R.id.profile) {
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void showresults() {
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new SearchResultsFragment()).commit();
}
}
Here is one of my fragment from which I'm trying to call another :
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
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.TextView;
import android.widget.Toast;
import com.kibitz4college.k4c.R;
public class SearchCoachingFragment extends Fragment {
Button search_coll_btn;
searchbtnclickedlistner searchbtnclickedlistner_var;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.fragment_search_coaching, container, false);
search_coll_btn = (Button) rootview.findViewById(R.id.Search_coaching_btn );
search_coll_btn.setOnClickListener(new View.OnClickListener() {
TextView lite=(TextView) rootview.findViewById(R.id.textView3);
#Override
public void onClick(View v) {
searchbtnclickedlistner_var.showresults();
}
});
return rootview;
}
public interface searchbtnclickedlistner
{
public void showresults();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
searchbtnclickedlistner_var=(searchbtnclickedlistner)context;
}
catch(Exception e){
throw new RuntimeException(context.toString()+ " must implement OnMyFragmentInteractionListener");
}
}
}
I've implemented interface & Overridden in the mainactivity, now I get a nullpointer exception as follows:
java.lang.NullPointerException: Attempt to invoke interface method
void com.asd.fragments.SearchCoachingFragment$searchbtnclickedlistner.showresults() on a null object reference.
can someone please tell me what I'm doing wrong?
You are calling a method from the interface and that interface is null. You should implement that interface in another class for the callback. Also you should create the interface outside the fragment for a better structure.
The problem could be caused from the fact, you don't put replaced/removed Fragment in the backstack, calling the method addToBackStack().
If you do not call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and will be resumed if the user navigates back.
So when you try to use a method of a replaced/removed Fragment you have NullPointerException. This is the link.