Getting NullPointerException with Checkbox - java

On one Android phone's I'm getting a NullPointerException and on the other one I'm not. I'm trying to save multiple Checkbox states for my privacy settings. As I said on one of the phones it works fine, saves it to sharedPreferences as it should, but on my main phone it crashes as soon as I open the Activity. Anyone see the issue?
public class PrivacySettings extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
CheckBox showAge,showLocation,showRelationship,showGender,showFacebookButton;
String TAG = getPackageName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_privacy_settings);
showAge=(CheckBox)findViewById(R.id.cbShowAge);
showAge.setChecked(getFromSP("cbShowAge"));
showAge.setOnCheckedChangeListener(this);
showLocation=(CheckBox)findViewById(R.id.cbShowLocation);
showLocation.setChecked(getFromSP("cbShowLocation"));
showLocation.setOnCheckedChangeListener(this);
showRelationship=(CheckBox)findViewById(R.id.cbShowRelationshipStatus);
showRelationship.setChecked(getFromSP("cbShowRelationship"));
showRelationship.setOnCheckedChangeListener(this);
showGender=(CheckBox)findViewById(R.id.cbShowGender);
showGender.setChecked(getFromSP("cbShowGender"));
showGender.setOnCheckedChangeListener(this);
showFacebookButton=(CheckBox)findViewById(R.id.cbShowFacebookLink);
showFacebookButton.setChecked(getFromSP("cbShowFacebookButton"));
showFacebookButton.setOnCheckedChangeListener(this);
setTitle("Privacy Settings");
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(TAG, android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences(TAG, android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.apply();
}
#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_privacy_settings, 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();
if (id == R.id.home) {
NavUtils.navigateUpFromSameTask(this);
}
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch(buttonView.getId()){
case R.id.cbShowAge:
saveInSp("cbShowAge",isChecked);
break;
case R.id.cbShowLocation:
saveInSp("cbShowLocation",isChecked);
break;
case R.id.cbShowRelationshipStatus:
saveInSp("cbShowRelationship",isChecked);
break;
case R.id.cbShowGender:
saveInSp("cbShowGender",isChecked);
break;
case R.id.cbShowFacebookLink:
saveInSp("cbShowFacebookButton",isChecked);
break;
}
}
Edit:
I changed the TAG name to "Different_name" just to test it and it worked. Can anyone explain as to why its working like this SharedPreferences preferences = getApplicationContext().getSharedPreferences("Different_name", android.content.Context.MODE_PRIVATE); ?

Not sure did I get it properly (since there is no log posted as of now) but from your comment
SharedPreferences preferences = getApplicationContext().getSharedPreferences("Different_name", android.content.Context.MODE_PRIVATE);
and your code
String TAG = getPackageName();
it seems your shared preference file name is returned as null on some devices, i.e. using getPackageName()
TAG == null
If you change your TAG to your activity name and it needs to be public and static:
public static final String TAG = PrivacySettings.class.getSimpleName();
you can use it from anywhere as:
SharedPreferences preferences = getContext().getSharedPreferences(PrivacySettings.TAG, Context.MODE_PRIVATE);
In short, it seems getPackageName() fails for some reason so just use a value which will never fail on any device, e.g. current class name

Related

Android: send data from adapter class to Activity

I want to add pictures to my favorite activity when a user tap on a picture. So far I'm able to get the data and display it but for some reason whenever I tap on an image it displays the favorited image, however, when I recheck the favorite activity by clicking on it, it shows empty.
Here's the little flow chart.
imageOnTap is implemented on RecyclerAdapter class. I have my Favorite activity and MainActivity.Any help would be appreciated. Thanks
Here's my MyRecyclerAdapter class
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.nameTxt.setText(albums.get(position).getName());
holder.img.setImageResource(albums.get(position).getImage());
//listener
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
Toast.makeText(c,albums.get(pos).getName() + " ,added to favorite ",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(c, favorite.class);
// intent.putExtra(Intent.EXTRA_TEXT, albums.get(pos).getImage());
c.startActivity(intent);
}
});
}
Here's my favorite activity
public class favorite extends AppCompatActivity {
int favImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
ImageView displayImage = (ImageView) findViewById(R.id.movieImage);
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));
// Intent intent = getIntent();
// if (intent.hasExtra(Intent.EXTRA_TEXT)) {
// favImage = intent.getIntExtra(Intent.EXTRA_TEXT,image);
// displayImage.setImageResource(favImage);
//
// }
}
}
Here's my MainActivity
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_favorite) {
Intent intent = new Intent(this,favorite.class);
startActivity(intent);
}
If you are checking favourite activity from nav menu then it will not display anything afterall you are not passing any intent extras in it. Is it being display when you click the image? Are you getting intent params null here?
Use those preferences:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
In your case it might be different activities observe different areas of settings.
THAT IS:
use:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
instead of:
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("favorite",albums.get(pos).getImage());
editor.commit();
AND
this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(ctx.getApplicationContext());
displayImage.setImageResource(settings.getInt("Favorite", 0));
instead of:
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
displayImage.setImageResource(settings.getInt("Favorite", 0));

Shared preferences? (Extremely simple issue!?)

I am just trying to store the users input from an editText in a Shared Preference, but it is not working:
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
}
return true;
});
When I first edit the text, I will first get a log of "mDefault" which is normal, since nothing is stored in the shared preference.
Then, I store something in the shared preference, and to make sure it stored, I log and I get a log of what I typed. Which means the shared preference data WAS stored.
Heres the problem: After I have stored something in the shared preference, I go to a different activity, and I come back, and all the data stored in the shared preference is GONE!
The very first log still says mDefault after navigating through activities.
What could the problem be?
EDIT:
Here is my instantiation:
onCreate:
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
Maybe you don't save on setOnEditorActionListener. Save when you go to a different activity. Because when it goes to different activity the setOnEditorActionListener editText.getText().toString() it returns null.
STORING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs",Context.MODE_PRIVATE);
// We need an editor object to make changes
SharedPreferences.Editor edit = pref.edit();
// Set/Store data
edit.putString("username", "Rishabh");
edit.putString("password", "rishabh123");
// Commit the changes
edit.commit();
RETRIEVING PREFERENCES:
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String username = pref.getString("username", "");
String password= pref.getString("password", "");
Log.d(TAG, username);
Log.d(TAG, password);
Adding this as an example in case you missed a key components. This is currently working for me:
public class Main2Activity extends ActionBarActivity {
private SharedPreferences keyword;
private SharedPreferences.Editor keywordEditor;
private String TAG = "TAG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
keyword = PreferenceManager.getDefaultSharedPreferences(this); //Making a shared preferences
keywordEditor = keyword.edit();
final EditText editText = (EditText) findViewById(R.id.et_text);
findViewById(R.id.btn_launch).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main2Activity.this, Main22Activity.class);
startActivity(intent);
}
});
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
Log.v(TAG, "Initial: " + keyword.getString("keyword", "mDefault")); //IT LOGS OUT THE DEFAULT STRING EVEN **AFTER** STORING THE PREFERENCES BEFORE
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
keywordEditor.putString("keyword", editText.getText().toString());
keywordEditor.commit();
Log.v(TAG, "Saving in prefs: " + keyword.getString("keyword", "default")); //CORRECT! THIS LINE WORKS
}
return true;
}
});
}
}
From a fresh install:
I typed in "test" and hit the send button on keyboard therefore invoked the onEditorAction
Then clicked on launch new activity -> hit back button and typed in "test2" and hit send button.
The following is the log out put:
02-29 23:26:42.068 18105-18105/com.example.naveed.myapplication V/TAG: Initial: mDefault
02-29 23:26:42.136 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test
02-29 23:26:53.281 18105-18105/com.example.naveed.myapplication V/TAG: Initial: test
02-29 23:26:53.338 18105-18105/com.example.naveed.myapplication V/TAG: Saving in prefs: test2
As you can see initially it was "mDefault" then "test" was saved. I launched a new activity and came back. Next time the initial was "test" since it was saved last time and "test2" was the new value saved.
Create SharedPreferences class
public class SharedPreferenceClass
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "INTELLIJ_AMIYO";
public static final String KEY_SET_VALUE= "KEY_SET_VALUE";
public SharedPreferenceClass(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, 0);
editor = pref.edit();
}
public void setUserDATA(String data)
{
editor.remove(KEY_SET_VALUE);
editor.putString(KEY_SET_VALUE, data);
editor.commit();
}
public String getUserDATA()
{
String getData= pref.getString(KEY_SET_VALUE, null);
return getData;
}
}
Now call this in your Activity section globally
SharedPreferenceClass sharedPrefClassObj;
& call onCreate(Bundle savedInstanceState) section
sharedPrefClassObj = new SharedPreferenceClass(getApplicationContext());
Now add this
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int keycode, KeyEvent event) {
if (keycode == EditorInfo.IME_ACTION_SEND) {
editText.setText(editText.getText().toString());
sharedPrefClassObj.setUserDATA(editText.getText().toString()); // Set data
// Get data sharedPrefClassObj.getUserDATA();
}
}
return true;
});
Very important: you need a Preference name (for example: "MY_PREFS_NAME") to set and retrieve the values:
SharedPreferences.Editor keywordEditor = context.getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
Use the same constant Preference name and it will give you the same preferences in any point of your app.

Android: SharedPreferences. How to implement them properly

I'm trying to store a user entry into an EditText field however when I exit the application it does not appear.
So for example a user types in his/her name and then exits the application. When the user returns and launches the Application the users name appears in the EditText field. However I can't get this to work. I believe its to do with sharedPreferences but I'm not sure where I'm going wrong.
I'm quite new to android and java so finding this quite difficult. Any help would be much appreciated.
public class MainActivity extends Activity {
public final static String EXTRA_FROM = "com.example.assignment1.FROM";
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = emailFrom.getText().toString();
outState.putString(EXTRA_FROM, from);
}
#Override
protected void onRestoreInstanceState(Bundle savedState)
{
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = savedState.getString(EXTRA_FROM);
emailFrom.setText(from);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void emailSend (View sendButton)
{
Intent intent = new Intent(this,DisplayEmailActivity.class);
EditText emailFrom =(EditText) findViewById(R.id.editEmailFrom);
String from = emailFrom.getText().toString();
intent.putExtra(EXTRA_FROM,from);
SharedPreferences saveFrom = getSharedPreferences(EXTRA_FROM, MODE_PRIVATE);
Editor editor = saveFrom.edit();
editor.putString(EXTRA_FROM, from);
editor.commit();
String storedfrom = saveFrom.getString(EXTRA_FROM, from);
emailFrom.setText(storedfrom);
startActivity(intent);
}
Second Activity
public class DisplayEmailActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_email);
Intent intent = getIntent();
String from = intent.getStringExtra(MainActivity.EXTRA_FROM);
TextView textFrom =(TextView)findViewById(R.id.displayEmailFrom);
textFrom.setText(from);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_display_email, menu);
return true;
}
Ok, so after you store value in your EditText emailFrom, you have to save it in SharedPreferences like this:
String from = emailFrom.getText().toString(); // Getting String value from EditText and storing it in "from" String
SharedPreferences settings = getSharedPreferences("MyPreferencesFile", 0); // Opening SharedPreferences
SharedPreferences.Editor editor = settings.edit(); // Opening editor for SharedPreferences
editor.putString("exampleName", from); // You are putting here a String "from" and give it a "exampleName" name. Later you will use this name to restore data.
And then when you launch your application, you need to load data from SharedPreferences:
SharedPreferences settings = getSharedPreferences("MyPreferencesFile", 0); // Again opening SharedPreferences
String from = settings.getString("exampleName", ""); // The second argument is the default value. The default value will be set if there wasn't saved any data with "exampleName" name
if(from != "") // If "from" is not empty, it means that the data was stored in SharedPreferences
emailFrom.setText(from); // Setting text in your EditText
You are using onSaveInstanceState() and onRestoreInstanceState() to save and restore the content of the EditText. However, this methods are called only when the application is being terminated by the OS to be immediatlly recreated (i.e. device rotation).
If you want to preserve values when the application is terminated by the user, you need to store it somewhere, a file, a database or in your case I would suggest SharedPreferences.
I've posted an answer to a similar question in: SharePreferences
Good luck.

SwitchPreference onChecked/onClick Listener

I've been racking my brains all night but can't seem to accomplish this one small thing. I would like to add a SwitchPreference into my PreferenceActivity of an app. Below is a picture.
Before I say too much, my problem is exactly this: I cannot seem to put a listener on just the Switch part of the preference. I am able to set an onPreferenceTreeClick and an onPreferenceClick on the preference, and that works fine if I press on the text portion. But When the Switch itself does nothing when I change it from OFF to ON.
I've read the documentation on SwitchPreference. I also looked at the android/packages/Settings and it looks like AOSP uses a Switch and not a SwitchPreference for Wi-Fi and Bluetooth.
Here is my attempt (working if you press on the entire preference item, but not if you just press the Switch):
Sample:
public class Preferences extends SherlockPreferenceActivity {
public static final String PREF_THEME = "pref_theme_interface";
public static final String PREF_ROOT = "pref_root";
public static final String PREF_APP = "pref_app";
public static SharedPreferences mTheme;
private static SharedPreferences mUpdate;
public static SharedPreferences.Editor mEditor;
public boolean SDK_COMPAT = true;
boolean pSwitch = false;
boolean update = true;
Preference autoUpdate;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(MainActivity.THEME);
super.onCreate(savedInstanceState);
final ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setIcon(R.drawable.ic_preferences);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
SDK_COMPAT = false;
}
mUpdate = PreferenceManager.getDefaultSharedPreferences(this);
update = mUpdate.getBoolean("update", false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
setPreferenceScreen(createPreferenceSDK());
}
private PreferenceScreen createPreferenceSDK() {
// Root
PreferenceScreen root = (PreferenceScreen)findPreference(PREF_ROOT);
PreferenceCategory prefApp = (PreferenceCategory)findPreference(PREF_APP);
//root.addPreference(prefApp);
if (SDK_COMPAT == true) {
pSwitch = true;
autoUpdate = new SwitchPreference(this);
autoUpdate.setKey("auto_update_pref");
autoUpdate.setTitle(R.string.auto_update);
//autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
prefApp.addPreference(autoUpdate);
} else {
pSwitch = false;
autoUpdate = new CheckBoxPreference(this);
autoUpdate.setKey("auto_update_pref");
autoUpdate.setTitle(R.string.auto_update);
autoUpdate.setSummary(R.string.auto_update_summary);
prefApp.addPreference(autoUpdate);
}
autoUpdate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
mEditor = mUpdate.edit();
boolean checked = ((SwitchPreference) preference)
.isChecked();
if (checked) {
update = true;
mEditor.putBoolean("update", true);
mEditor.commit();
autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
} else {
update = false;
mEditor.putBoolean("update", false);
mEditor.commit();
autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
}
return true;
}
});
return root;
}
So to reiterate my question in case I lost you. How does one set a listener on the Switch portion of the SwitchPreference? Please be kind if it is something so obvious. It was pretty late last night when I tried to add this.
Thank you so much in advance.
Notes:
1. I am not opposed to sticking with the CheckBoxPreference, but I prefer to use Switch because it looks nice.
Yes I know there is an easier/better? way of adding dynamic preference using res/xml and res/xml-v14 instead of doing the SDK check. I just did that for testing.
picture of preference screen
EDIT
Hopefully this helps someone else! Thanks Tushar for suggestion :-)
autoUpdate.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
boolean switched = ((SwitchPreference) preference)
.isChecked();
update = !switched;
mEditor = mUpdate.edit();
mEditor.putBoolean("update", update);
mEditor.commit();
autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
return true;
}
});
Use setOnPreferenceChangeListener() instead of setOnPreferenceClickListener().
Working code
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
SwitchPreference vibrateSwitch = (SwitchPreference) findPreference("notification_vibrate");
if (vibrateSwitch != null) {
vibrateSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference arg0, Object isVibrateOnObject) {
boolean isVibrateOn = (Boolean) isVibrateOnObject;
if (isVibrateOn) {
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(400);
}
return true;
}
});
}
}
}
If you still haven't figured out a good way for doing this I have figured something out that doesn't create multiple calls to onPreferenceChange which clicking the preference does. I wrote it in another question: dual functionality SwitchPreference.

Dynamic Tab Removal/Deletion in Tabhost

I've searched long and far and found a few different ways people are dealing with removing a single and often specific tab from a TabHost object. I would like to try, if I may, to gather all those methods to this single question so that people my "shop" for the right method they need and hopefully get the answer they need to write their code; I also feel that it will cut down on the number of these questions.
At the moment I'm having trouble finding a solution to my code as well. I'm attempting to get rid of a particular tab without touching the others; hopefully I too will find my answer.
I wont pick a particular answer for this question for a while, so please just list the method you used to deal with this problem here for others to see.
Thank you.
Update:
Okay, here is my current code:
TabHost mTabHost;
TabHost.TabSpec spec;
Intent mSettingsIntent;
Intent mSearchIntent;
int tabNum = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSearchIntent = new Intent().setClass(this, SearchTab.class);
mTabHost = getTabHost();
mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
makeTab("Tab");
final Button newSearchBtn = (Button) findViewById(R.id.new_search_btn);
newSearchBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
EditText searchBar = (EditText) findViewById(R.id.search_bar);
final String searchString = searchBar.getText().toString();
makeTab(searchString);
}
});
final EditText edittext = (EditText) findViewById(R.id.search_bar);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
EditText searchBar = (EditText) findViewById(R.id.search_bar);
final String searchString = searchBar.getText().toString();
makeTab(searchString);
return true;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.tab_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_close:
// TODO: Find/define method to close a single tab
closeTab();
return true;
case R.id.menu_settings:
// TODO: Create a basic Settings Activity and call constructor here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void makeTab(String tabText) {
String tabTag = "Tab" + tabNum++;
View tabview = createTabView(mTabHost.getContext(), tabText);
spec = mTabHost.newTabSpec(tabTag).setIndicator(tabview).setContent(new Intent().setClass(this, SearchTab.class));
mTabHost.addTab(spec);
mTabHost.setCurrentTabByTag(tabTag);
}
private void closeTab() {
// TODO: Define method for closing a single tab with tabTag
mTabHost.removeViewAt(mTabHost.getCurrentTab());
}
private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
}
My app locks up due to a NullPointer Exception I'm not sure why; I'm still trying to figure out how to read the debugger perspective in Eclispe for clues. I'll update when I have more.

Categories

Resources