Navigation Drawer menu items aren't clickable [duplicate] - android

This question already has answers here:
NavigationView OnNavigationItemSelectedListener not being called
(3 answers)
setNavigationItemSelectedListener Not Working
(3 answers)
Closed 2 years ago.
Nothing is happening when I'm selecting any option from the navigation drawer. As soon as I click on the navigation drawer the drawer closes. I'll add my GitHub repository link also if you want to try correcting from there you are very much welcome:
https://github.com/tanmay380/andorid-studio-
This is my alphabetBaseShow class which shows the Navigation Drawer (I'll delete some of the lines so that it uses less space)
package com.example.myapplication.background;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
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.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
import com.example.myapplication.infront.CharacterSelection;
import com.example.myapplication.infront.SplashScreen;
import com.software.shell.fab.ActionButton;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
public class alphabetBaseShow extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
protected String mPracticeString;
protected DrawingView mDrawView;
public SeekBar seekBar;
Button button;
public boolean draw = true;
AudioManager audio;
protected TextView mScoreTimerView;
protected TextView mBestScoreView;
protected boolean mDone;
public AlertDialog.Builder alertDialog;
private static final int STORAGE_PERMISSION_CODE = 101;
public TextView colorset;
public NavigationView navigationView;
//private TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
System.gc();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alphabet_show);
Toolbar toolbar = findViewById(R.id.PracticeToolbar);
setSupportActionBar(toolbar);
// textToSpeech=new TextToSpeech(this,LanguageSelection);
drawerLayout = findViewById(R.id.drawerLayout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.close, R.string.open);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawView = new DrawingView(this);
seekBar = findViewById(R.id.size1);
mDrawView = findViewById(R.id.DrawingView);
mBestScoreView = (TextView) findViewById(R.id.best_score_View);
mScoreTimerView = (TextView) findViewById(R.id.score_and_timer_View);
mPracticeString = getIntent().getStringExtra(getResources().getString(R.string.practice_string));
mDone = false;
mScoreTimerView.bringToFront();
mDrawView.canVibrate(true);
mDrawView.setBitmapFromText(mPracticeString);
audio = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
/*switch (audio.getStreamVolume(AudioManager.STREAM_MUSIC)) {
case AudioManager.RINGER_MODE_SILENT:
Toast.makeText(getApplicationContext(), "TURN UP THE VOLUME", Toast.LENGTH_SHORT).show();
}*/
if ((audio.getStreamVolume(AudioManager.STREAM_MUSIC) > 1)) {
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
}
else if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
audio.setStreamVolume(AudioManager.STREAM_MUSIC, 10, 1);
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
catch (Exception e) {
showErrorDialog(e);
}
}
private void toggleSeekbar() {
if (seekBar.getVisibility() == View.INVISIBLE) {
seekBar.setVisibility(View.VISIBLE);
seekBar.bringToFront();
mDrawView.candraw(false);
}
else {
seekBar.setVisibility(View.INVISIBLE);
mDrawView.candraw(true);
}
}
public void clickit() {
toggleSeekbar();
setSize();
}
public void setSize() {
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mDrawView.setCurrentWidth(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
toggleSeekbar();
}
});
return;
}
public void practiceOnClick(View v) {
switch (v.getId()) {
case R.id.reset:
if (mDone) {
mDrawView.init();
}
mDrawView.setBitmapFromText(mPracticeString);
mBestScoreView.setAnimation(Animator.createFadeOutAnimation());
mDrawView.startAnimation(Animator.createScaleUpAnimation());
mScoreTimerView.setAnimation(Animator.createFadeOutAnimation());
Animator.createYFlipForwardAnimation(findViewById(R.id.done));
((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_done);
Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
mDone = false; //implies that the user isn't done
mDrawView.candraw(true);
break;
case R.id.done:
String result = mDrawView.saveBitmap(mPracticeString, "");
if (result.charAt(0) == '/')
result = "Trace Saved";
Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); // Toast displayed with the status of saving the trace
if (!mDone) {
float best = SplashScreen.mDbHelper.getScore(mPracticeString);
if (best < mDrawView.score()) {
best = mDrawView.score();
SplashScreen.mDbHelper.writeScore(mPracticeString, best);
}
//Animations for when the user is done with the trace
mDrawView.startAnimation(Animator.createScaleDownAnimation());
findViewById(R.id.best_score_View).bringToFront();
((TextView) findViewById(R.id.best_score_View)).setText("Best: " + String.valueOf(best));
mScoreTimerView.setText("Score: " + String.valueOf(mDrawView.score()));
mScoreTimerView.setAnimation(Animator.createFadeInAnimation());
mBestScoreView.setAnimation(Animator.createFadeInAnimation());
Animator.createYFlipForwardAnimation(findViewById(R.id.done));
((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_save);
Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
mDrawView.candraw(false);
mDone = true;
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (!mDone) {
int next = Arrays.asList(SplashScreen.CHARACTER_LIST).indexOf(mPracticeString);
switch (item.getItemId()) {
case R.id.action_next:
next = (next + 1) % SplashScreen.CHARACTER_LIST.length;
break;
case R.id.action_previous:
next = (next + SplashScreen.CHARACTER_LIST.length - 1) % SplashScreen.CHARACTER_LIST.length;
break;
case R.id.setting:
clickit();
break;
}
if (item.getItemId() == R.id.action_next || item.getItemId() == R.id.action_previous) {
mPracticeString = SplashScreen.CHARACTER_LIST[next];
mDrawView.setBitmapFromText(mPracticeString);
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
return super.onOptionsItemSelected(item);
}
protected void showErrorDialog(final Exception e) {
new AlertDialog.Builder(this)
.setTitle("ERROR")
.setMessage(Log.getStackTraceString(e))
.setPositiveButton("Save to File", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.app_name));
File file = new File(mediaStorageDir.getPath() + File.separator + "error.txt");
if (file.exists() || file.createNewFile()) {
FileOutputStream fOut = new FileOutputStream(file, true);
fOut.write(("\n\n" + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date()) + "\n\n").getBytes());
fOut.write(Log.getStackTraceString(e).getBytes());
fOut.flush();
fOut.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.green:
SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
break;
case R.id.red:
Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
break;
case R.id.black:
Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
break;
case R.id.blue:
Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
This is my XML file (deleted some Textview lines as they were not important hence less space will be required):
<?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/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".background.alphabetBaseShow">
<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:layout_marginTop="55dp"
app:headerLayout="#layout/header"
app:menu="#menu/colors"
android:clickable="true">
</android.support.design.widget.NavigationView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/PracticeToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ActionbarBg"
app:title="PRACTICE " />
<com.example.myapplication.background.DrawingView
android:id="#+id/DrawingView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp" />
<com.software.shell.fab.ActionButton
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="0dp"
android:layout_marginRight="0dp"
android:layout_marginBottom="0dp"
android:onClick="practiceOnClick"
app:button_color="#color/ButtonBg"
app:image="#drawable/ic_done" />
<com.software.shell.fab.ActionButton
android:id="#+id/reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:onClick="practiceOnClick"
app:button_color="#color/ButtonBg"
app:image="#drawable/ic_reset" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
This is my colors.xml (menu file). I've even tried to add onClick inside item, but it didn't work:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/green"
android:icon="#drawable/ic_save"
android:title="GREEN" />
<item
android:id="#+id/black"
android:icon="#drawable/ic_save"
android:title="BLACK" />
<item
android:id="#+id/blue"
android:icon="#drawable/ic_save"
android:title="BLUE" />
<item
android:id="#+id/red"
android:icon="#drawable/ic_save"
android:title="RED"
android:onClick="toast"/>
</group>
</menu>

Created a pull request to your repository. Check out.
P.S.:
You should have used the same version of support and design libraries
Do not use System.gs (!)
The main reason why your navigation item click listener did not work was - you did not assign your interface implementation,
navigationView.setNavigationItemSelectedListener(this);
instead of
navigationView.setNavigationItemSelectedListener(new OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Some stuff here
}
});
as you have implemented the interface NavigationView.OnNavigationItemSelectedListener.

I just need to put the NAVIGATIONDRAWER part at the end.

Related

Toolbar overlaps the PreferenceFragment

As you see in the title, The toolbar appears, but it overlaps my preferenceFragment content.
I fixed the issue on the Settings Screen by adding a padding to the listview.
But the problem persists in all the other preferenceFragments. Here is my code.
Activity
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ClassFragment()).commit();
PreferenceManager.setDefaultValues(this,
R.xml.pref_students, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_information, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_security, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_notifications, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_logout, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_addStudent:
displayToast(getString(R.string.action_addStudent_message));
return true;
case R.id.action_settings:
Intent settingsIntent = new Intent(this,
SettingsActivity.class);
startActivity(settingsIntent);
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_class:
selectedFragment = new ClassFragment();
break;
case R.id.navigation_due:
selectedFragment = new DueFragment();
break;
case R.id.navigation_messages:
selectedFragment = new MessagesFragment();
break;
case R.id.navigation_class_updates:
selectedFragment = new ClassUpdatesFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}
SettingsActivity
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NavUtils;
import androidx.recyclerview.widget.RecyclerView;
import com.example.schooltest.Settings.AppCompatPreferenceActivity;
import java.util.List;
public class SettingsActivity extends AppCompatPreferenceActivity {
private static Preference.OnPreferenceChangeListener
sBindPreferenceSummaryToValueListener =
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
// For ringtone preferences, look up the correct display value
// using RingtoneManager.
if (TextUtils.isEmpty(stringValue)) {
// Empty values correspond to 'silent' (no ringtone).
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
// Clear the summary if there was a lookup error.
preference.setSummary(null);
} else {
// Set the summary to reflect the new ringtone display
// name.
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
private static boolean isXLargeTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(
sBindPreferenceSummaryToValueListener);
sBindPreferenceSummaryToValueListener
.onPreferenceChange(preference, PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
int horizontalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int verticalMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (int) getResources().getDimension(R.dimen.activity_vertical_margin) + 30, getResources().getDisplayMetrics());
getListView().setPadding(horizontalMargin, topMargin, horizontalMargin, verticalMargin);
}
private void setupActionBar() {
getLayoutInflater().inflate(R.layout.settings_toolbar, (ViewGroup)findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public boolean onIsMultiPane() {
return isXLargeTablet(this);
}
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| StudentsPreferenceFragment
.class.getName().equals(fragmentName)
|| InformationPreferenceFragment
.class.getName().equals(fragmentName)
|| SecurityPreferenceFragment
.class.getName().equals(fragmentName)
|| NotificationsPreferenceFragment
.class.getName().equals(fragmentName)
|| LogoutPreferenceFragment
.class.getName().equals(fragmentName);
}
/**
* This fragment shows student preferences only.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class StudentsPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_students);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
/**
* This fragment shows information preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class InformationPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_information);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("first_name"));
bindPreferenceSummaryToValue(findPreference("last_name"));
bindPreferenceSummaryToValue(findPreference("example_text"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows security preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class SecurityPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_security);
setHasOptionsMenu(true);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows notifications preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationsPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notifications);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(
findPreference("notifications_new_message_ringtone"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
/**
* This fragment shows logout preferences.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class LogoutPreferenceFragment
extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_logout);
setHasOptionsMenu(true);
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(
new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#FFFFFF"
app:popupTheme="#style/AppTheme.PopupOverlay">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
</RelativeLayout>
As you see in this photo, the "First Name" EditTextPreference is hidden by the toolbar:
I think, maybe it has something to do with the preference ressource files under xml/. so here a link to the files : https://github.com/waeljomni/apptest.git
The problem here is that you are inflating the activity_main.xml layout in android.R.id.content and the preference fragments into com.android.internal.R.id.headers (if you see the implementation of PreferenceActivity).
The default XML layout of PreferenceActivity is preference_list_content.
You should define in your team your custom preference layout in which you reproduce your main Activity layout.
See headerLayout in R.attr.preferenceActivityStyle.
I suggest to use ConstraintLayout for performance reason and simplicity
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
app:popupTheme="#style/AppTheme.PopupOverlay">
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottom_navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>

android.view.InflateException: Binary XML file line #6: Error inflating class EditText

I am trying to inflate a layout into a fragment and have a very frustrating error
WHY ONLY EDITTEXT causing error
My fragment layout Code usb_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Begin"
android:id="#+id/buttonStart"
android:layout_below="#+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="onClickStart"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="#+id/buttonSend"
android:onClick="onClickSend"
android:layout_below="#+id/editText"
android:layout_toRightOf="#+id/buttonStart"
android:layout_toEndOf="#+id/buttonStart" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_below="#+id/buttonSend"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/editText"
android:layout_alignEnd="#+id/editText"
android:layout_alignParentBottom="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop"
android:id="#+id/buttonStop"
android:layout_below="#+id/editText"
android:layout_toRightOf="#+id/buttonSend"
android:layout_toEndOf="#+id/buttonSend"
android:onClick="onClickStop"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"
android:id="#+id/buttonClear"
android:layout_below="#+id/editText"
android:layout_toRightOf="#+id/buttonStop"
android:layout_toEndOf="#+id/buttonStop"
android:onClick="onClickClear"/>
</LinearLayout>
My fragment code Usb.java
package com.example.rajat.blueusb
import android.app.Fragment;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class Usb extends Fragment {
public Usb(){}
public final String ACTION_USB_PERMISSION = "com.example.rajat.blueusb.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
tvAppend(textView,"Serial Connection Opened!\n");
} else {
Log.d("SERIAL", "PORT NOT OPEN");
}
} else {
Log.d("SERIAL", "PORT IS NULL");
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.usb_view, container, false);
usbManager = (UsbManager) getActivity(). getSystemService(Context.USB_SERVICE);
startButton = (Button)getView(). findViewById(R.id.buttonStart);
sendButton = (Button)getView(). findViewById(R.id.buttonSend);
clearButton = (Button)getView(). findViewById(R.id.buttonClear);
stopButton = (Button)getView(). findViewById(R.id.buttonStop);
editText = (EditText)getView().findViewById(R.id.editText);
textView = (TextView)getView().findViewById(R.id.textView);
setUiEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
getActivity().registerReceiver(broadcastReceiver, filter);
return rootView;
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
if (deviceVID ==1659)//Arduino Vendor ID
{
PendingIntent pi = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
break;
} else {
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView,"\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}
My MainActivity.java code
package com.example.rajat.blueusb;
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.app.Fragment;
import android.app.FragmentManager;
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.
Fragment fragment=null;
int id = item.getItemId();
if (id == R.id.nav_usb) {
fragment = new Usb();
} else if (id == R.id.nav_blue) {
fragment = new Bluetooth();
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_main, fragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
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>
LOGCAT:
android.view.InflateException: Binary XML file line #6: Error inflating class EditText
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at com.example.rajat.blueusb.Usb.onCreateView(Usb.java:109)
at android.app.Fragment.performCreateView(Fragment.java:2069)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:899)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1072)
You can't align your view to Left and Right at the same time.
If you wan't to align your EditText to left:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
change import android.app.Fragment; to
import android.support.v4.app.Fragment;
public class Usb extends Fragment

whenever i run the app on emulator it says unfortunately the app has stopped working and the log reads as below

MainActivity.java
package com.example.intel.dualboot;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements StatusAsyncTask.StatusAsyncTaskListener, SwipeRefreshLayout.OnRefreshListener, MainActivityListener {
private static final String TAG = "db::MainActivity";
/* public static final int ACT_INSTALL_ROM = 1;
public static final int ACT_CHANGE_PAGE = 2;
public static final int ACT_SELECT_ICON = 3;
public static final int ACT_UNINSTALL_ROM = 4;
public static final String INTENT_EXTRA_SHOW_ROM_LIST = "show_rom_list";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT == 20) {
showDeprecatedLAlert();
return;
}
setContentView(R.layout.activity_main);
// This activity is using different background color, which would cause overdraw
// of the whole area, so disable the default background
getWindow().setBackgroundDrawable(null);
Utils.installHttpCache(this);
PreferenceManager.setDefaultValues(this, R.xml.settings, false);
m_srLayout = (InSwipeRefreshLayout)findViewById(R.id.refresh_layout);
m_srLayout.setOnRefreshListener(this);
m_curFragment = -1;
m_fragmentTitles = getResources().getStringArray(R.array.main_fragment_titles);
m_drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
m_drawerList = (ListView) findViewById(R.id.left_drawer);
String[] fragmentClsNames = new String[MainFragment.MAIN_FRAG_CNT];
for(int i = 0; i < fragmentClsNames.length; ++i)
fragmentClsNames[i] = MainFragment.getFragmentClass(i).getName();
m_fragments = new MainFragment[MainFragment.MAIN_FRAG_CNT];
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
for(int i = 0; i < m_fragments.length; ++i) {
m_fragments[i] = (MainFragment)fragmentManager.findFragmentByTag(fragmentClsNames[i]);
if(m_fragments[i] == null) {
m_fragments[i] = MainFragment.newFragment(i);
t.add(R.id.content_frame, m_fragments[i], fragmentClsNames[i]);
}
t.hide(m_fragments[i]);
}
t.commit();
// Set the adapter for the list view
m_drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list, m_fragmentTitles));
// Set the list's click listener
m_drawerList.setOnItemClickListener(new DrawerItemClickListener());
m_drawerTitle = getText(R.string.app_name);
m_drawerToggle = new ActionBarDrawerToggle(
this, m_drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(m_title);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(m_drawerTitle);
}
};
m_drawerLayout.setDrawerListener(m_drawerToggle);
final ActionBar bar = getSupportActionBar();
if(bar != null) {
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
/* if (getIntent().hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
getIntent().getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
getIntent().removeExtra(INTENT_EXTRA_SHOW_ROM_LIST);
selectItem(1);
} else if(savedInstanceState != null) {
selectItem(savedInstanceState.getInt("curFragment", 0));
} else {
selectItem(0);
}*/
}
/*#Override
protected void onNewIntent(Intent i) {
super.onNewIntent(i);
if (i.hasExtra(INTENT_EXTRA_SHOW_ROM_LIST) &&
i.getBooleanExtra(INTENT_EXTRA_SHOW_ROM_LIST, false)) {
selectItem(1);
}
}*/
#Override
protected void onStop() {
super.onStop();
Utils.flushHttpCache();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curFragment", m_curFragment);
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
m_refreshItem = menu.findItem(R.id.action_refresh);
if(!StatusAsyncTask.instance().isComplete())
m_refreshItem.setEnabled(false);
return true;
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
/** Swaps fragments in the main content view */
private void selectItem(int position) {
if(position < 0 || position >= m_fragments.length) {
Log.e(TAG, "Invalid fragment index " + position);
return;
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction t = fragmentManager.beginTransaction();
if(m_curFragment != -1)
t.hide(m_fragments[m_curFragment]);
t.show(m_fragments[position]);
t.commit();
m_curFragment = position;
// Highlight the selected item, update the title, and close the drawer
m_drawerList.setItemChecked(position, true);
setTitle(m_fragmentTitles[position]);
m_drawerLayout.closeDrawer(m_drawerList);
}
#Override
public void setTitle(CharSequence title) {
m_title = title;
getSupportActionBar().setTitle(m_title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(m_drawerToggle != null)
m_drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(m_drawerToggle != null)
m_drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem it) {
if (m_drawerToggle.onOptionsItemSelected(it))
return true;
switch(it.getItemId()) {
case R.id.action_refresh:
refresh(false);
return true;
case R.id.action_reboot:
{
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Reboot")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setItems(R.array.reboot_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0: Utils.reboot(""); break;
case 1: Utils.reboot("recovery"); break;
case 2: Utils.reboot("bootloader"); break;
}
}
})
.create().show();
return true;
}
default:
return false;
}
}
public void startRefresh(boolean notifyRefreshLayout) {
if(notifyRefreshLayout)
m_srLayout.setRefreshing(true);
if(m_refreshItem != null)
m_refreshItem.setEnabled(false);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].startRefresh();
StatusAsyncTask.instance().setListener(this);
StatusAsyncTask.instance().execute();
}
#Override
public void refresh(boolean b) {
refresh(true);
}
#Override
public void setRefreshComplete() {
m_srLayout.setRefreshing(false);
if(m_refreshItem != null)
m_refreshItem.setEnabled(true);
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].setRefreshComplete();
}
#Override
public void onFragmentViewCreated() {
if(++m_fragmentViewsCreated == m_fragments.length) {
// postDelayed because SwipeRefresher view ignores
// setRefreshing call otherwise
m_srLayout.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = getIntent();
if(i == null || !i.getBooleanExtra("force_refresh", false)) {
startRefresh(true);
} else {
i.removeExtra("force_refresh");
refresh(false);
}
}
}, 1);
}
}
#Override
public void onFragmentViewDestroyed() {
--m_fragmentViewsCreated;
}
#Override
public void addScrollUpListener(InSwipeRefreshLayout.ScrollUpListener l) {
m_srLayout.addScrollUpListener(l);
}
#Override
public void onStatusTaskFinished(StatusAsyncTask.Result res) {
for(int i = 0; i < m_fragments.length; ++i)
m_fragments[i].onStatusTaskFinished(res);
}
#Override
public void onRefresh() {
refresh(false);
}
#TargetApi(20)
private void showDeprecatedLAlert() {
SpannableString msg = new SpannableString("Android Developer preview has bugs");
Linkify.addLinks(msg, Linkify.ALL);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle("Unsupported Android version")
.setCancelable(false)
.setMessage(msg)
.setNegativeButton("Exit Application", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog d = b.create();
d.show();
TextView msgView = (TextView)d.findViewById(android.R.id.message);
msgView.setMovementMethod(LinkMovementMethod.getInstance());
}
private DrawerLayout m_drawerLayout;
private ListView m_drawerList;
private String[] m_fragmentTitles;
private MainFragment[] m_fragments;
private int m_curFragment;
private CharSequence m_title;
private ActionBarDrawerToggle m_drawerToggle;
private CharSequence m_drawerTitle;
private MenuItem m_refreshItem;
private int m_fragmentViewsCreated;
private InSwipeRefreshLayout m_srLayout;
}
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:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.example.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
Stack Trace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.intel.dualboot, PID: 23319
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.intel.dualboot/com.example.intel.dualboot.MainActivity}:
java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2330)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5273)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.NullPointerException: Attempt to write to field
'android.app.FragmentManagerImpl
android.app.Fragment.mFragmentManager' on a null object reference
at android.app.BackStackRecord.doAddOp(BackStackRecord.java:469)
at android.app.BackStackRecord.add(BackStackRecord.java:464)
at com.example.intel.dualboot.MainActivity.onCreate(MainActivity.java:78)
at android.app.Activity.performCreate(Activity.java:6041)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1109)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2283)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392) 
at android.app.ActivityThread.access$800(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5273) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372)
replace
com.exmaple.intel.dualboot.InSwipeRefreshLayout
with
android.support.v4.widget.SwipeRefreshLayout
in your xml file,
as the com.exmaple.intel.dualboot.InSwipeRefreshLayout class is not defined
com.exmaple.intel.dualboot.InSwipeRefreshLayout
Check this path if it is correct in your xml.It seems the path of "InSwipeRefreshLayout" is not corect
in your xml
<?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<com.exmaple.intel.dualboot.InSwipeRefreshLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/refresh_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<FrameLayout android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.exmaple.intel.dualboot.InSwipeRefreshLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="#dimen/lviewdimen"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111" />
</android.support.v4.widget.DrawerLayout>
the com.exmaple.intel.dualboot.InSwipeRefreshLayout has that spelling of "exmaple", it should be example.
The posted layout working fine for me.Please check the package name properly com.example.intel.dualboot.InSwipeRefreshLayout whether exist or not and clean and build the project.

Android Studio - Writing text to a file using a Save button in the menu

I am a beginner to Android apps and I am sorry for wasting your time. But I have struggled for a while on this topic. I am building a text editor, and I have a Save button in a menu. I am trying to figure out how to make the Save button save the contents of a text area to a file. I have only one issue in my code, which is at "public void saveText(View v){": It says cannot resolve symbol V...
package natanrosenfeld.texteditor;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
import android.content.Intent;
import com.natanrosenfeld.texteditor.R;
import android.widget.Toast;
import android.view.Gravity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.Activity;
import java.io.OutputStreamWriter;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(getApplicationContext(),SettingsActivity.class);
startActivity(i);
Toast.makeText(this, "You opened Settings.", Toast.LENGTH_SHORT).show();
break;
case R.id.action_save: {
public void saveText(View v){
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("TextFile", MODE_APPEND));
EditText ET = (EditText)findViewById(R.id.editText);
String text = ET.getText().toString();
out.write(text);
out.write('\n');
out.close();
Toast.makeText(this, "The contents are saved in the file.", Toast.LENGTH_LONG).show();
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
//Toast.makeText(this, "Save not implemented yet.",Toast.LENGTH_SHORT).show();
break;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
}
}
}
Try this -MainActivity.class;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(getApplicationContext(),SettingsActivity.class);
startActivity(i);
Toast.makeText(this, "You opened Settings.",Toast.LENGTH_SHORT).show();
break;
case R.id.action_save:
savetext();
break;
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void savetext () {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("TextFile", MODE_APPEND));
EditText ET = (EditText)findViewById(R.id.editText);
String text = ET.getText().toString();
out.write(text);
out.write('\n');
out.close();
Toast.makeText(this, "The contents are saved in the file.", Toast.LENGTH_LONG).show();
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
//Toast.makeText(this, "Save not implemented yet.", Toast.LENGTH_SHORT).show();
}}
R.layout.activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" 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" tools:context=".MainActivity">
<EditText android:text="#string/hello_world" android:layout_width="wrap_content"
android:id="#+id/editText"
android:layout_height="wrap_content" /></RelativeLayout>
R.menu.menu_main
<menu 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" tools:context=".MainActivity">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
<item android:id="#+id/action_save" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" /></menu>

error: Binary XML file line#3: You must supply a layout width attribute

i'va already read all answers related with these questions and I'm sure none solves my problem, I'm getting crazy with this error, please any help would be appreciated
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dip"
android:orientation="vertical" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title_scaned_value"/>
<TextView
android:id="#+id/scanedFormat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/title_scaned_value_empty"/>
<TextView
android:id="#+id/scanedValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/title_scaned_value_empty"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/title_scan"
android:onClick="commandScan"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="productes"
android:onClick="productes"/>
My activity related with this layout works fine, but when i click a button to start another activity this error appears.
I'm workin with Zxing library and here's my CaptureActivity:
package org.example.sherlock_;
import org.example.sherlock_.helpers.ExceptionHelper;
import android.content.Intent;
import android.graphics.Bitmap;
import com.google.zxing.Result;
import com.google.zxing.client.android.result.ResultHandler;
public class CaptureActivity extends com.google.zxing.client.android.CaptureActivity {
#Override
public void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
//super.handleDecodeInternally(rawResult, resultHandler, barcode);
try {
Intent resultIntent = new Intent();
resultIntent.putExtra(com.google.zxing.client.android.Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
resultIntent.putExtra(com.google.zxing.client.android.Intents.Scan.RESULT, resultHandler.getDisplayContents());
setResult(RESULT_OK, resultIntent);
finish();
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
}
I post my MainActivity too because I'm going really mad :)
package org.example.sherlock_;
import org.example.sherlock_.helpers.ExceptionHelper;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainActivity extends SherlockActivity {
private TextView scanedValue;
private TextView scanedFormat;
private final static int SCAN_CODE_REQUEST_CODE = 123456;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanedValue = (TextView)findViewById(R.id.scanedValue);
scanedFormat = (TextView)findViewById(R.id.scanedFormat);
}
#Override
protected void onActivityResult(int pRequestCode, int pResultCode, Intent pData) {
try {
if (pRequestCode == SCAN_CODE_REQUEST_CODE) {
if (pResultCode == RESULT_OK) {
String result = pData.getStringExtra
(com.google.zxing.client.android.Intents.Scan.RESULT);
String format = pData.getStringExtra
(com.google.zxing.client.android.Intents.Scan.RESULT_FORMAT);
if (scanedValue != null) {
if (result != null &&
!result.trim().equals("")) {
scanedValue.setText(result);
//if(db != null){
//String valor= result ;
//}
} else {
scanedValue.setText(getString(R.string.title_scaned_value_empty));
}
}
if (scanedFormat != null) {
if (format != null &&
!format.trim().equals("")) {
scanedFormat.setText(format);
//if(db != null){
//String tipus = format;
//}
} else {
scanedFormat.setText(getString(R.string.title_scaned_value_empty));
}
}
} else {
if (scanedValue != null)
scanedValue.setText(getString(R.string.title_scaned_value_empty));
if (scanedFormat != null)
scanedFormat.setText(getString(R.string.title_scaned_value_empty));
}
}
//Insertamos los datos en la tabla Usuarios
// db.execSQL("INSERT INTO Productes (codi, tipus, valor) " +
// "VALUES (" + i + ", '" + tipus +"', '"+ valor +"')");
// db.close();
//i+=i;
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
public void commandScan(View pView) {
try {
Intent captureIntent = new Intent(this, CaptureActivity.class);
captureIntent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(captureIntent, SCAN_CODE_REQUEST_CODE);
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
Toast.makeText(this, "configuración pulsado"
, Toast.LENGTH_SHORT).show();
}
return true;
}
}

Categories

Resources