NavigationDrawer blocks/stops other buttons on the activity - java

I'm creating an app where once you log in, you can click a button and it leads you to a quiz, however, the Profile activity (activity when you first log in) has a navigation drawer and for some reason, the navigation drawer is blocking the use of the buttons on the Profile that leads to the Quiz activity. Does anyone know how to fix this? If there's anything I can do please let me know. I'm sorry if this is a stupid question this is my first time coding an app.
Profile Java:
package com.example.civis;
import android.content.Intent;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.net.Uri;
import android.widget.Button;
public class Profile extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private Button quizbutton;
private Button enrolbutton1;
//Menu Drawer Set Up
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
quizbutton = (Button) findViewById(R.id.quizbutton);
quizbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openQuiz();
}
});
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
// Menu Drawer Navigation
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_profile: // Profile Page Link
Intent i = new Intent(Profile.this, Profile.class);
startActivity(i);
break;
case R.id.nav_current_mps: // Current MP's Link
Intent mpi = new Intent(Profile.this, CurrentMps.class);
startActivity(mpi);
break;
case R.id.nav_local_board: // Local Board Link
Intent locali = new Intent(Profile.this, LocalBoard.class);
startActivity(locali);
break;
case R.id.nav_referendums: // Referendums Link
Intent referendumi = new Intent(Profile.this, Referendums.class);
startActivity(referendumi);
break;
case R.id.nav_elections: // Elections Link
Intent electioni = new Intent(Profile.this, Election.class);
startActivity(electioni);
break;
case R.id.nav_about_us: // About Us Link
Intent aboutusi = new Intent(Profile.this, AboutUs.class);
startActivity(aboutusi);
break;
case R.id.nav_settings: // Settings Link
Intent settingsi = new Intent(Profile.this, Settings.class);
startActivity(settingsi);
break;
case R.id.nav_signout: // Sign Out Link (Links to Sign In Page)
Intent signouti = new Intent(Profile.this, SignIn.class);
startActivity(signouti);
break;
}
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void openQuiz() {
Intent intent = new Intent(this, quiz1.class);
startActivity(intent);
}
}
Profile XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
android:orientation="vertical"
tools:context=".Profile"
tools:openDrawer="start">
<!-- White Card Style Backing -->
<ImageView
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginTop="195dp"
android:background="#drawable/rounded_rectangle_white" />
<!-- Profile Person Image -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_marginTop="90dp"
android:src="#drawable/dp_civis"
tools:ignore="MissingConstraints" />
<!-- Name Area -->
<TextView
android:id="#+id/textView3"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:background="#drawable/edit_text_style"
android:text="Name"
android:textAlignment="center"
android:textSize="24sp" />
<!-- Political Compass Quiz Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/quizbutton"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="160dp"
android:background="#drawable/edit_purple_button_style"
android:gravity="center"
android:text="Political Compass Quiz"
android:textColor="#FFF"
tools:ignore="MissingConstraints" />
</LinearLayout>
<!-- Enrol to Vote Button -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="visible">
<Button
android:id="#+id/enrolbutton1"
android:layout_width="280dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_marginTop="320dp"
android:background="#drawable/edit_purple_button_style"
android:gravity="center"
android:text="Enrol to Vote"
android:textColor="#FFF"
tools:ignore="MissingConstraints" />
</LinearLayout>
<!-- Menu Drawer-->
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#00000000"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>
Quiz Java:
package com.example.civis;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class quiz1 extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtnAgree;
private Button answerBtnDisagree;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT =5;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {Question, Choice 1, Choice 2}
{"All firearms should be registered and it should be tougher to get a licence.", "Agree", "Disagree"},
{"16-year-olds are mature enough to make informed decisions so they should be allowed to vote.", "Agree", "Disagree"},
{"It should be compulsory for everyone in New Zealand to be vaccinated against communicable diseases.", "Agree", "Disagree"},
{"We expect too much of NZ’s Police, and some of their work should be done by communities, mental health experts, and social services.", "Agree", "Disagree"},
{"New Zealand’s borders should remain closed to non-citizens until a COVID-19 vaccine is found, even if that takes years.", "Agree", "Disagree"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz1);
countLabel = (TextView)findViewById(R.id.countLabel);
questionLabel = (TextView)findViewById(R.id.questionLabel);
answerBtnAgree = (Button)findViewById(R.id.answerBtnAgree);
answerBtnDisagree = (Button)findViewById(R.id.answerBtnDisagree);
// Create quizArray from quizDara
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Question
tmpArray.add(quizData[i][1]); // Agree
tmpArray.add(quizData[i][2]); // Disagree
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Q" + quizCount);
// Generate random number between 0 and 1 (quizArray's size -1 )
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set question and right answer.
// Array format: // {Question, Choice 1, Choice 2,}
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Question" from quiz and Shuffle choices
quiz.remove(0);
// Set Choices.
answerBtnAgree.setText(quiz.get(0));
answerBtnDisagree.setText(quiz.get(1));
// Remove this quiz from quizArray.
quizArray.remove(randomNum);
}
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if(btnText.equals(rightAnswer)) {
alertTitle = "Thank you for responding";
rightAnswerCount++;
} else {
alertTitle = "Thank you for responding";
}
// Create Dialogue
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Your response has been recorded");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (quizCount == QUIZ_COUNT) {
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
} else {
quizCount++;
showNextQuiz();;
}
}
});
builder.setCancelable(false);
builder.show();
}
}
Quiz XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".quiz1"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#drawable/gradient_background">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/countLabel"
android:text="Q1"
android:textSize="28dp"
android:textColor="#android:color/background_light"
android:layout_marginTop="120dp"/>
<TextView
android:id="#+id/questionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question"
android:textSize="20dp"
android:layout_gravity="center_horizontal"
android:textColor="#android:color/background_light"
android:layout_marginTop="15dp"/>
<Button
android:id="#+id/answerBtnAgree"
android:layout_width="320dp"
android:layout_height="60dp"
android:layout_marginTop="90dp"
android:text="Agree"
android:background="#drawable/rounded_button"
android:onClick="checkAnswer"/>
<Button
android:id="#+id/answerBtnDisagree"
android:layout_width="320dp"
android:layout_height="60dp"
android:layout_marginTop="40dp"
android:text="Disagree"
android:background="#drawable/rounded_button"
android:onClick="checkAnswer"/>

DrawerLayout should be the parent if you're using NavigationView.
Put the RelativeLayout inside the DrawerLayout.
Your xml should look something like this:
<!-- Menu Drawer-->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!-- OTHER VIEWS -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>

Related

android.widget.RelativeLayout cannot be cast to android.widget.EditText

I'm attempting to create a note taker using Firebase and I'm falling at the first hurdle as I'm getting the error as per the title of this question.
My XML file is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.frapp.NoteTakerActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:id="#+id/appBarLayout2">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark" />
</android.support.design.widget.AppBarLayout>
<include
android:id="#+id/noteTitleTxt"
layout="#layout/content_note_taker" />
<EditText
android:id="#+id/noteTitleTxt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/appBarLayout2"
android:ems="10"
android:hint="Enter Title"
android:inputType="text" />
<Spinner
android:id="#+id/spinnerNoteType"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/noteTitleTxt"
android:layout_marginTop="13dp"
android:entries="#array/type" />
<Button
android:id="#+id/addNoteBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/spinnerNoteType"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Add Note" />
</RelativeLayout>
The java class in question is:
package com.example.android.frapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class NoteTakerActivity extends AppCompatActivity {
EditText editNoteTitle; // It's this causing the issue
Button addButton;
Spinner spinnerType;
DatabaseReference databaseNotes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_taker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
databaseNotes = FirebaseDatabase.getInstance().getReference("notes");
editNoteTitle = (EditText) findViewById(R.id.noteTitleTxt);
addButton = (Button) findViewById(R.id.addNoteBtn);
spinnerType = (Spinner) findViewById(R.id.spinnerNoteType);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNote();
}
});
}
private void addNote() {
String title = editNoteTitle.getText().toString().trim();
String type = spinnerType.getSelectedItem().toString();
if (!TextUtils.isEmpty(title)) {
String id = databaseNotes.push().getKey(); // id being created is unique every time
Notes notes = new Notes(id, title, type);
databaseNotes.child(id).setValue(notes); // to send data to database
Toast.makeText(this, "Title added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "You must give the note a title", Toast.LENGTH_SHORT).show();
}
}
}
I've made sure I don't have any duplicate edit text names and got rid of any classes and xml files that are no longer needed just to be sure.
I've cleaned and rebuilt I don't know how many times but can't get past this issue. Does anyone have any other ideas I can use/try?
Thanks
Here you have it twice!
<include
android:id="#+id/noteTitleTxt" // <-----------------
layout="#layout/content_note_taker" />
<EditText
android:id="#+id/noteTitleTxt" // <-----------------
Just remove the one id in your include tag. While not shown in your post, I bet its top container is RelativeLayout.

I am Currently developing an app for final year. No errors appear, but when i select my searchScreen the app crashes

I started to develop an app for my final year project. I created all the navigation drawers with no issue and they worked fine when I had run the program. When I added a search-page that would link in with the mapsAcivity I added. No errors are appearing however the app will run fine but when I click on the navigation drawer to access the search page and mapsActivity page the app crashes. Any ideas what the issue is?Screengrab of the app failing
04-26 23:48:25.311: E/AndroidRuntime(13703): Caused by: android.view.InflateException: Binary XML file line #285: ScrollView can host only one direct child
04-26 23:48:25.311: E/AndroidRuntime(13703): Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child
Below is the code for my search screen
package com.example.mcdai.derrytourism;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
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.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SearchScreen extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Spinner restaurantSpinner, accommidationSpinner;
ArrayAdapter<CharSequence> adapter;
Button btnSearch;
TextView buttonLogout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_screen);
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);
final EditText freeTextEntry = (EditText)findViewById(R.id.editFreeTextSearch);
//final EditText editMinDestination = (EditText)findViewById(R.id.editMinDestination);
final EditText editMaxDestination = (EditText)findViewById(R.id.editMaxDestination);
final EditText editMinPrice = (EditText)findViewById(R.id.editMinPrice);
final EditText editMaxPrice = (EditText)findViewById(R.id.editMaxPrice);
final Spinner spinnerRestautantType = (Spinner)findViewById(R.id.spinnerRestaurantType);
final Spinner spinnerAccommidationType = (Spinner)findViewById(R.id. spinnerAccommidationType);
buttonLogout = (TextView)findViewById(R.id.buttonLogout);
editMinPrice.setEnabled(false);
editMaxPrice.setEnabled(false);
spinnerRestautantType.setEnabled(false);
spinnerAccommidationType.setEnabled(false);
//restaurant drop down menu
restaurantSpinner = (Spinner)findViewById(R.id.spinnerRestaurantType);
adapter = ArrayAdapter.createFromResource(this,R.array.restaurant_type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
restaurantSpinner.setAdapter(adapter);
restaurantSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
TextView defaultPleaseSelect = (TextView) view;
if(position == 0)
{
// Set hint size and colour
defaultPleaseSelect.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
defaultPleaseSelect.setTextColor(Color.GRAY);
}
else
{
// Set dropdown selection and display an onscreen message
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+" selected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
//Accommidation drop down menu
accommidationSpinner = (Spinner)findViewById(R.id.spinnerAccommidationType );
adapter = ArrayAdapter.createFromResource(this,R.array.accommidation, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
accommidationSpinner.setAdapter(adapter);
accommidationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
TextView defaultPleaseSelect = (TextView) view;
if(position == 0)
{
// Set hint size and colour
defaultPleaseSelect.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
defaultPleaseSelect.setTextColor(Color.GRAY);
}
else
{
// Set dropdown selection and display an onscreen message
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+" selected", Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
btnSearch = (Button)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intentMapsActivity = new Intent(SearchScreen.this, MapsActivity.class);
//code to get min desitance for destination
//String minDestination = editMinDestination.getText().toString().trim();
//code to get max distance for destination
if(editMaxDestination.getText().toString().equals(""))
{
Toast.makeText(SearchScreen.this, "Please Populate Distance Field", Toast.LENGTH_LONG).show();
}
else
{
Double maxDestination = Double.parseDouble(editMaxDestination.getText().toString());
//code to get from editTextFreeSearch
String freeTextSearchParam = freeTextEntry.getText().toString();
//code to get restaurant type spinner
String restaurantTypeSpinner = spinnerRestautantType.getSelectedItem().toString();
//code to get accommidation type spinner
String accommidationSpinner = spinnerAccommidationType .getSelectedItem().toString();
if(freeTextSearchParam.equals("") && restaurantTypeSpinner.equals("Select") && accommidationSpinner.equals("Select"))
{
Toast.makeText(SearchScreen.this, "Please Populate Free Text, Price or Restaurant Type", Toast.LENGTH_LONG).show();
}
else
{
freeTextSearchParam = freeTextSearchParam.replaceAll("\\s", "\\+");
intentMapsActivity.putExtra("freeTextSearch", freeTextSearchParam);
intentMapsActivity.putExtra("maxDestination", maxDestination);
restaurantTypeSpinner = restaurantTypeSpinner.replaceAll("\\s", "\\+");
intentMapsActivity.putExtra("restaurantType", restaurantTypeSpinner);
accommidationSpinner = accommidationSpinner.replaceAll("\\s", "\\+");
intentMapsActivity.putExtra("accommidation", accommidationSpinner);
startActivity(intentMapsActivity);
}
}
}
});
buttonLogout = (TextView)findViewById(R.id.buttonLogout);
buttonLogout.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), SearchScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}
public void onRadioButtonClicked(View view)
{
//EditText editMinDestination = (EditText)findViewById(R.id.editMinDestination);
EditText editMaxDestination = (EditText)findViewById(R.id.editMaxDestination);
EditText editMinPrice = (EditText)findViewById(R.id.editMinPrice);
EditText editMaxPrice = (EditText)findViewById(R.id.editMaxPrice);
Spinner spinnerRestautantType = (Spinner)findViewById(R.id.spinnerRestaurantType);
Spinner spinnerAccommidationType = (Spinner)findViewById(R.id.spinnerAccommidationType );
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
boolean unchecked = !((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.radioPrice:
if (checked)
{
editMinPrice.setEnabled(true);
editMaxPrice.setEnabled(true);
}break;
case R.id.radioRestuarantType:
if (checked)
{
spinnerRestautantType.setEnabled(true);
} break;
case R.id.radioAccommidationType:
if (checked)
{
spinnerAccommidationType.setEnabled(true);
}break;
}
}
#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.search_screen, 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_MainActivity) {
Intent intentMainActivity = new Intent(SearchScreen.this, MainActivity.class);
startActivity(intentMainActivity);
finish();
} else if (id == R.id.nav_SearchScreen) {
Intent intentSearchScreen = new Intent(SearchScreen.this,SearchScreen.class);
startActivity(intentSearchScreen);
finish();
} else if (id == R.id.nav_Attractions) {
Intent intentAttractions = new Intent(SearchScreen.this, Attractions.class);
startActivity(intentAttractions);
finish();
} else if (id == R.id.nav_Food) {
Intent intentFood = new Intent(SearchScreen.this, Food.class);
startActivity(intentFood);
finish();
} else if (id == R.id.nav_Accommidation) {
Intent intentAccommidation = new Intent(SearchScreen.this,Accommidation.class);
startActivity(intentAccommidation);
finish();
} else if (id == R.id.nav_Entertainment) {
Intent intentEntertainment = new Intent(SearchScreen.this,Entertainment.class);
startActivity(intentEntertainment);
finish();
} else if (id == R.id.nav_MapsActivity) {
Intent intentMapsActivity = new Intent(SearchScreen.this,MapsActivity.class);
startActivity(intentMapsActivity);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Code below was taken from activity_search_screen.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mcdai.derrytourism.SearchScreen">
<TextView
android:id="#+id/txtSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:paddingBottom="50sp"
android:textAlignment="center"
android:textSize="20sp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/txtFreeTextSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Free-Text Search"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="20sp"
android:paddingBottom="20sp"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_below="#+id/txtSearch"
android:layout_alignParentLeft="true" />
<Button
android:id="#+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_alignTop="#+id/txtAccommidationType"
android:layout_toRightOf="#+id/txtDestination"
android:layout_centerHorizontal="true"
android:layout_marginTop="50sp" />
<TextView
android:id="#+id/txtAccommidationType"
android:text="AccommidationType"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_marginLeft="40dp"
android:layout_alignBottom="#+id/radioGroup"
android:layout_toRightOf="#+id/radioGroup"
android:paddingBottom="10sp" />
<EditText
android:id="#+id/editFreeTextSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:ems="10"
android:inputType="text"
android:layout_below="#+id/txtFreeTextSearch"
android:layout_centerHorizontal="true" />
<Spinner
android:id="#+id/spinnerAccommidationType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/txtAccommidationType"
android:layout_alignParentRight="true" />
<Spinner
android:id="#+id/spinnerRestaurantType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txtRestuarantType"
android:layout_alignParentRight="true"
android:layout_alignLeft="#+id/spinnerAccommidationType" />
<TextView
android:id = "#+id/buttonLogout"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:text = "Logout"
android:textSize="15sp"
android:textAlignment="center"
android:clickable="false"
android:textColor="#android:color/holo_blue_dark"
android:onClick="onClick"
android:paddingBottom="50sp"
android:layout_alignBaseline="#+id/txtSearch"
android:layout_alignBottom="#+id/txtSearch"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/txtMaxPrice"
android:text="Max(£)"
android:textSize="10sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textAlignment="center"
android:layout_above="#+id/editMinPrice"
android:layout_alignParentRight="true"
android:layout_alignLeft="#+id/editMaxPrice"
android:layout_marginBottom="-4sp" />
<EditText
android:id="#+id/editMaxPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:hint="10"
android:textSize="15sp"
android:textAlignment="center"
android:background="#android:color/transparent"
android:inputType="numberDecimal"
android:layout_marginBottom="21dp"
android:layout_above="#+id/spinnerRestaurantType"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/txtMinPrice"
android:text="Min(£)"
android:textSize="10sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:textAlignment="center"
android:layout_above="#+id/editMinPrice"
android:layout_alignLeft="#+id/editMinPrice"
android:layout_toLeftOf="#+id/txtMaxPrice"
android:layout_marginBottom="-4sp"
android:paddingRight="55sp" />
<EditText
android:id="#+id/editMaxDestination"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:hint="10"
android:textSize="15sp"
android:background="#android:color/transparent"
android:textAlignment="center"
android:inputType="number"
android:layout_below="#+id/txtDestination"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/txtCriteriaSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Criteria Search"
android:textStyle="bold"
android:textAlignment="center"
android:textSize="20sp"
android:paddingTop="20sp"
android:textAppearance="#style/TextAppearance.AppCompat"
android:paddingBottom="10sp"
android:layout_marginTop="41dp"
android:layout_below="#+id/editFreeTextSearch"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/txtDestination"
android:text="Max Distance (km)"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_below="#+id/editFreeTextSearch"
android:layout_centerHorizontal="true"
android:paddingTop="10sp" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="14sp"
android:paddingBottom="6sp"
android:layout_below="#+id/txtCriteriaSearch"
android:layout_alignParentLeft="true">
<RadioButton
android:id="#+id/radioPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:layout_marginTop="10sp"
android:layout_marginBottom="3sp" />
<RadioButton
android:id="#+id/radioRestuarantType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onRadioButtonClicked"
android:layout_marginTop="10sp"/>
<RadioButton
android:id="#+id/radioAccommidationType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioRestuarantType"
android:onClick="onRadioButtonClicked"
android:layout_marginTop="15sp" />
</RadioGroup>
<EditText
android:id="#+id/editMinPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:hint="0"
android:textSize="15sp"
android:textAlignment="center"
android:background="#android:color/transparent"
android:inputType="numberDecimal"
android:layout_alignBaseline="#+id/editMaxPrice"
android:layout_alignBottom="#+id/editMaxPrice"
android:layout_toLeftOf="#+id/buttonLogout"
android:paddingRight="55sp" />
<TextView
android:id="#+id/txtPrice"
android:text="Price"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:paddingTop="7sp"
android:layout_alignTop="#+id/txtMaxPrice"
android:layout_alignLeft="#+id/txtRestuarantType" />
<TextView
android:id="#+id/txtRestuarantType"
android:text="Restuarant Type"
android:textSize="15sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.AppCompat"
android:layout_marginBottom="26dp"
android:paddingBottom="2sp"
android:layout_above="#+id/txtAccommidationType"
android:layout_alignLeft="#+id/txtAccommidationType"
android:layout_alignStart="#+id/txtAccommidationType" />
</RelativeLayout>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_search_screen"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_search_screen"
app:menu="#menu/activity_search_screen_drawer" />
</android.support.v4.widget.DrawerLayout>
</ScrollView>
The reason you're crashing is your ScrollView has more than one child element in it. You'll need to either wrap them both in a parent view sitting inside the ScrollView or move your DrawerLayout outside of the ScrollView.
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mcdai.derrytourism.SearchScreen">
<!-- RelativeLayout Children go here -->
</RelativeLayout>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_search_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_search_screen"
app:menu="#menu/activity_search_screen_drawer"/>
</android.support.v4.widget.DrawerLayout>
</FrameLayout>
</ScrollView>
I'm not sure exactly what you want your layout to look like but if you follow the above you shouldn't be crashing. Make sure you are using Code > Reformat Code to keep your indentations consistent. Good luck!

Sliding Menu Like Facebook in Material Design theme in Android

I have made a sliding menu like that of facebook by following the tutorial which is available in the following site:
http://www.devexchanges.info/2016/05/creating-your-own-sliding-menu-like.html?m=1
Now in the main layout I have added a long paragraph of text so in order to view everything I used ScrollView. But when I use ScrollView I cannot pull the menu out, I can only open the drawer by clicking on the button. Please help me on how to scroll through the para and also be able to pull the menu drawer.
The MainActivity XML file:
<info.devexchanges.slidingmenu.SlidingLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This holds our menu -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbars="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarmenu"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#102961"
android:orientation="horizontal"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<ListView
android:id="#+id/activity_main_menu_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbarmenu"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<!-- This holds our content-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#drawable/toolbar"
android:orientation="horizontal"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<ImageView
android:id="#+id/menu_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:onClick="toggleMenu"
android:src="#drawable/menu" />
<TextView
android:id="#+id/title"
style="#style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:gravity="center"
android:textColor="#android:color/white" />
</android.support.v7.widget.Toolbar>
<!-- Fragments container layout -->
<FrameLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</LinearLayout>
the_fiesta Fragment (the home Fragment) XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/white">
<ScrollView
android:layout_width="800dp"
android:layout_height="fill_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="75dp"
android:src="#drawable/fiesta_title"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:layout_alignParentTop="true"
android:id="#+id/imageView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/the_fiesta"
android:id="#+id/textView"
android:textSize="17sp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_below="#+id/imageView"
android:layout_marginTop="15dp"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</ScrollView>
Java file of MainActivity:
package info.devexchanges.slidingmenu;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// The SlidingLayout which will hold both the sliding menu and our main content
// Main content will holds our Fragment respectively
SlidingLayout slidingLayout;
// ListView menu
private ListView listMenu;
private String[] listMenuItems;
private Toolbar toolbar;
private TextView title; //page title
private ImageView btMenu; // Menu button
private Fragment currentFragment;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the mainLayout
setContentView(R.layout.activity_main);
slidingLayout = (SlidingLayout) findViewById(R.id.sliding_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
title = (TextView) findViewById(R.id.title);
setSupportActionBar(toolbar);
// Init menu
listMenuItems = getResources().getStringArray(R.array.menu_items);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listMenu = (ListView) findViewById(R.id.activity_main_menu_listview);
listMenu.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listMenuItems));
listMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onMenuItemClick(parent, view, position, id);
}
});
// handling menu button event
btMenu = (ImageView) findViewById(R.id.menu_icon);
btMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show/hide the menu
toggleMenu(v);
}
});
// Replace fragment main when activity start
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
TheFiesta fragment = new TheFiesta();
ft.add(R.id.activity_main_content_fragment, fragment);
ft.commit();
currentFragment = fragment;
title.setText("The Fiesta");
}
public void toggleMenu(View v) {
slidingLayout.toggleMenu();
}
// Perform action when a menu item is clicked
private void onMenuItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment;
if (position == 0) {
fragment = new TheFiesta();
title.setText("The Fiesta");
} else if (position == 1) {
fragment = new ListViewFragment();
title.setText("Events");
} else if (position == 2) {
fragment = new TextViewFragment();
Bundle args = new Bundle();
args.putString("KEY_STRING", "This is a TextView in the Fragment");
fragment.setArguments(args);
title.setText("Schedule");
} else if (position == 3) {
fragment = new ListViewFragment();
title.setText("Schools");
} else if (position == 4) {
fragment = new ListViewFragment();
title.setText("Updates");
} else if (position == 5) {
fragment = new ListViewFragment();
title.setText("Our Team");
} /*else if (position == 6) {
fragment = new ListViewFragment();
title.setText("About Us");
}*/ else {
fragment = new DummyFragment();
title.setText("About Us");
}
if(!fragment.getClass().equals(currentFragment.getClass())) {
// Replace current fragment by this new one
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
currentFragment = fragment;
}
// Hide menu anyway
slidingLayout.toggleMenu();
}
#Override
public void onBackPressed() {
if (slidingLayout.isMenuShown()) {
slidingLayout.toggleMenu();
} else {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
getSupportActionBar().setTitle("");
}
}
try this instead of Fragments container. add this code below
</android.support.v7.widget.Toolbar> this may work.
<LinearLayout
android:id="#+id/activity_main_content_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:id="#+id/scrollView" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView1" />
</LinearLayout>
</ScrollView>
</LinearLayout>

ViewStub is Not Inflating and Layout Remains Blank - Android

I am working through the sample code that is generated when you start a Navigation Drawer Activity in Android Studio. What I am trying to do is change an included view programatically and my research has shown that ViewStub is the best way to do this. However I cannot get it working. For the main layout in question there are 3 files involved:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.MY_APP.android.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ViewStub
android:id="#+id/main_content"
android:inflatedId="#id/main_content"
android:layout="#layout/content_main"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main"
tools:context="com.MY_APP.android.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/content_textview"
android:text="//TODO Main Feed"/>
</RelativeLayout>
Following is my MainActivity.java. Nothing seems to be happening and content_main never seems to show up. Could it be a visibility issue?
package com.myapp.android;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
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.MenuItem;
import android.view.ViewStub;
import android.widget.Toast;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity
extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NetworkHelpers NetworkHelper = new NetworkHelpers();
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if user is connected
if(!NetworkHelper.checkConnectivity(this)){
NetworkHelper.showNotConnectedAlert(this);
}
//Check for Google Play Services
checkGooglePlayServicesAvailable();
//Get User Info From Database
sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE);
String login_token = sharedpreferences.getString("login_token", "");
String first_name = sharedpreferences.getString("first_name", "");
String last_name = sharedpreferences.getString("last_name", "");
String email = sharedpreferences.getString("email", "");
if (login_token.isEmpty()){
//Start LoginActivity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);
}else{
//Update user info
ArrayList<String> params = new ArrayList<String>();
params.add(login_token);
new getUserInfo().execute(params);
}
//Create View
super.onCreate(savedInstanceState);
setContentView(com.myapp.android.R.layout.activity_main);
//Set Toolbar and Navigation Drawer
Toolbar toolbar = (Toolbar) findViewById(com.myapp.android.R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, com.myapp.android.R.string.navigation_drawer_open, com.myapp.android.R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(com.myapp.android.R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ViewStub stub = (ViewStub) findViewById(R.id.main_content);
stub.setLayoutResource(R.layout.content_main);
stub.inflate();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_home) {
// Start Home Screen
} else if (id == R.id.nav_videos) {
// Start Videos Screen
} else if (id == R.id.nav_photos) {
// Start Photos Screen
} else if (id == R.id.nav_galleries) {
// Start Galleries Screen
} else if (id == R.id.nav_map) {
// Start Map Screen
} else if (id == com.myapp.android.R.id.nav_share) {
//Open share app dialog
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "My App");
intent.putExtra(Intent.EXTRA_TEXT, "Check out My App: http://myapp.com/app");
Intent chooser = Intent.createChooser(intent, "Tell a friend about My App");
startActivity(chooser);
} else if (id == com.myapp.android.R.id.nav_logout){
logout();
}
DrawerLayout drawer = (DrawerLayout) findViewById(com.myapp.android.R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//AsyncTask to get user info from api
class getUserInfo extends AsyncTask<ArrayList<String>, Void, String> {
#Override
protected String doInBackground(ArrayList<String>... params) {
String token = params[0].get(0);
String response = HttpRequest.post("http://api.myapp.com/users/get-info/").send("api_key=API_KEY&token="+token).body();
return response;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
try {
// Do JSON Stuff
JSONObject jsonobject = new JSONObject(result);
String status = jsonobject.get("status").toString();
String message = jsonobject.get("message").toString();
JSONObject userinfo = jsonobject.getJSONObject("user_info");
//Set up user variables
String first_name = userinfo.get("first_name").toString();
String last_name = userinfo.get("last_name").toString();
String email = userinfo.get("email").toString();
String display_name = userinfo.get("display_name").toString();
String about = userinfo.get("about").toString();
String newsletter = userinfo.get("newsletter").toString();
if (status.equals("success")){
updateSharedPreferences(first_name, last_name, email, display_name, about, newsletter);
}else if (status.equals("error")){
logout();
} else{
logout();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(),"An unknown error occurred.", Toast.LENGTH_SHORT).show();
logout();
}
}
}
private boolean checkGooglePlayServicesAvailable() {
final int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (status == ConnectionResult.SUCCESS) {
return true;
}
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(status, this, 1);
if (errorDialog != null)
{
errorDialog.show();
}
}
return false;
}
private void updateSharedPreferences(String first_name, String last_name, String email, String display_name, String about, String newsletter){
//Put user info into sharedpreferences
SharedPreferences sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("first_name", first_name);
editor.putString("last_name", last_name);
editor.putString("email", email);
editor.putString("display_name", display_name);
editor.putString("about", about);
editor.putString("newsletter", newsletter);
editor.commit();
}
private void logout(){
//Logout of Facebook
FacebookSdk.sdkInitialize(this);
LoginManager.getInstance().logOut();
//Unset shared preferences login token
SharedPreferences sharedpreferences = getSharedPreferences("com.myapp.android.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("login_token", "");
editor.putString("facebook_token", "");
editor.putString("google_token", "");
editor.commit();
//Open login screen
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
finish();
startActivity(intent);
}
}
I have come across the same issue. It seems that when you are dynamically inflating the StubView, the behaviour is different than when you just use the <include> tag to include another xml layout. In this case, after being inflated the content that replaces the StubView is not positioned below the AppBar layout, but is positioned exactly behind it.
One way to solve this issue, is to move the RelativeLayout so that it wraps the StubView. So, the below changes are needed:
app_bar_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.MY_APP.android.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!-- Changed Content -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main"
tools:context="com.MY_APP.android.MainActivity">
<ViewStub
android:id="#+id/main_content"
android:inflatedId="#id/main_content"
android:layout="#layout/content_main"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</RelativeLayout>
<!-- Changed Content -->
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/content_textview"
android:text="//TODO Main Feed"/>

Cannot get a reference to EditText using 'findViewById()' after 'setContentView()'

In an activity where the user is supposed to enter his credentials, in the 'onCreate(...)' of activity, after setContentView(layout) I am doing this:
nameView = (EditText) findViewById(R.id.profileNameTextBox);
Where nameView is an EditText. When I try to get the text from this variable on a button click, my application crashes. The reason behind it is that nameView holds a null object reference. I can't really understand the reason behind because the function 'findViewById(...)' returns a valid reference to every other View object like Button, Spinner, Image but returns null when called for EditText. I have rechecked the ids multiple times and cross checked almost every little dependency, googled a lot but can't really find the solution, or the cause of the problem.
Bottom line is that the function findViewById is returning null to an object which clearly exists in the layout file with the same id used for the search.
Any help regarding this is appreciated.
This is my Activity
package theappman.speedcontacts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddContact extends AppCompatActivity {
Contact currentContact;
private EditText nameView;
private EditText numberView;
private ImageView imageView;
private Spinner dayView;
private Spinner monthView;
private Spinner yearView;
private Button saveView;
private void loadViews(){
numberView = (EditText) findViewById(R.id.profileNumberTextBox);
imageView = (ImageView) findViewById(R.id.profileImage);
dayView = (Spinner) findViewById(R.id.dateSpinner);
monthView = (Spinner) findViewById(R.id.monthSpinner);
yearView = (Spinner) findViewById(R.id.yearSpinner);
saveView = (Button) findViewById(R.id.saveButton);
nameView = (EditText) findViewById(R.id.profileNameTextBox);
}
private void populateSpinners(){
String[] days = new String[32];
String[] months = new String[13];
String[] years = new String[71];
days[0] = "Day";
months[0] = "Month";
years[0] = "Year";
for (int i=1; i<32; i++){
days[i] = String.valueOf(i+1);
}
for (int i=1,j=69; i<71; i++,j--){
years[i] = String.valueOf(1947+j);
}
months[1] = "January";
months[2] = "February";
months[3] = "March";
months[4] = "April";
months[5] = "May";
months[6] = "June";
months[7] = "July";
months[8] = "August";
months[9] = "September";
months[10] = "October";
months[11] = "November";
months[12] = "December";
ArrayAdapter<String> dayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, days);
dayView.setAdapter(dayAdapter);
ArrayAdapter<String> monthAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, months);
monthView.setAdapter(monthAdapter);
ArrayAdapter<String> yearAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, years);
yearView.setAdapter(yearAdapter );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contact);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
currentContact = new Contact();
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();
}
});
loadViews();
populateSpinners();
saveView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (nameView != null) {
String nnn = nameView.getText().toString();
Toast.makeText(AddContact.this, nnn,Toast.LENGTH_LONG).show();
}
Toast.makeText(AddContact.this, "not.",Toast.LENGTH_LONG).show();
}
});
}
public void saveContact(View view){
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
String NAME = t.getText().toString();
//String NUMBER = view.findViewById(R.id.profileNumber).toString();
Toast.makeText(AddContact.this, "Ok.",Toast.LENGTH_LONG).show();
/*String DATE = day.getSelectedItem().toString() + "-" + month.getSelectedItem().toString() + "-" + year.getSelectedItem().toString();
if (NAME.equals("") || NUMBER.equals("") ){//|| day.getSelectedItem().toString().equals("Day") || month.getSelectedItem().toString().equals("Month") || year.getSelectedItem().toString().equals("Year")){
Toast.makeText(this, "Please fill all fields.",Toast.LENGTH_LONG).show();
return;
}*/
//currentContact.setName(NAME);
//currentContact.setNumber(NUMBER);
//currentContact.setDateOfBirth(DATE );
//save currentContact in database
/*Intent intent = getIntent();
intent.putExtra("key", "Contact Saved");
setResult(RESULT_OK, intent);
finish();*/
}
#Override
public void onBackPressed() {
nameView = (EditText) findViewById(R.id.profileNameTextBox);
Intent intent = getIntent();
intent.putExtra("key", nameView.getText().toString());
setResult(RESULT_OK, intent);
finish();
super.onBackPressed();
}
}
These are my layout files
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="theappman.speedcontacts.AddContact">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_add_contact" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
The above file includes the code given below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="theappman.speedcontacts.AddContact"
tools:showIn="#layout/activity_add_contact">
<ImageView
android:id="#+id/profileImage"
android:src="#drawable/ic_person_black_48dp"
android:layout_width="match_parent"
android:layout_height="200dp" />
<Button
android:id="#+id/selectImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Select Picture"
/>
<EditText
android:name="#+id/profileNameTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Full Name"/>
<EditText
android:name="#+id/profileNumberTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="phone"
android:hint="Enter Phone Number"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:orientation="horizontal"
android:weightSum="3"
>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/dateSpinner"
/>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/monthSpinner"/>
<Spinner
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:id="#+id/yearSpinner"/>
</LinearLayout>
<Button
android:id="#+id/saveButton"
android:layout_width="96dp"
android:layout_height="wrap_content"
android:text="Save"
android:layout_gravity="right"
/>
</LinearLayout>
You are initializing the profileNameTextBox at multiple places .
At one place you are using -
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
to initialize profileNameTextBox.
Remove the initialization from saveContact(), onBackPressed() and from anywhere else.You should initialize it only once in loadViews(). That's it. And when you want to access it you can use nameView.
public void saveContact(View view){
EditText t = (EditText) view.findViewById(R.id.profileNameTextBox);
view is the button clicked. Something tells me that the text box you're looking for is not inside the button.
You created your view variables so you don't have to findViewById all the time. Use them:
EditText t = nameView;

Categories