How to Reference Buttons in the same Activity from a Custom View - java

I am trying to make a simple drawing application, but am running into problems switching the paint color.Here is the tutorial I used to get to the point I am at. Here is my code:
Drawing_View.java
public class Drawing_View extends View {
private Path path = new Path();
private Paint paint = new Paint();
public String paint_color = "#FFBB00";
public Drawing_View(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(5f);
paint.setColor(Color.parseColor(paint_color));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventY = event.getY();
float eventX = event.getX();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Set a new starting point
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
// Connect the points
path.lineTo(eventX, eventY);
break;
default:
return false;
}
invalidate();
return true;
}
}
Here is the code for the activity the custom view sits inside.
Drawing_Main.java
public class Drawing_Main extends ActionBarActivity {
Button green_light,green_dark,blue_light,blue_dark,blue_verydark,purple,magenta,red,orange_dark,orange_light,orange_lightest,yellow,black;
String btn_color_hex;
SharedPreferences.Editor editor = getSharedPreferences("paint_color", MODE_PRIVATE).edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
green_light = (Button)findViewById(R.id.button1);
green_dark = (Button)findViewById(R.id.button2);
blue_light = (Button)findViewById(R.id.button3);
blue_dark = (Button)findViewById(R.id.button4);
blue_verydark = (Button)findViewById(R.id.button5);
purple = (Button)findViewById(R.id.button6);
magenta = (Button)findViewById(R.id.button7);
red = (Button)findViewById(R.id.button8);
orange_dark = (Button)findViewById(R.id.button9);
orange_light = (Button)findViewById(R.id.button10);
orange_lightest = (Button)findViewById(R.id.button11);
yellow = (Button)findViewById(R.id.button12);
black = (Button)findViewById(R.id.button13);
green_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn_color_hex="#0fad00";
editor.putString("paint_color_hex", btn_color_hex);
editor.commit();
}
});
green_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
blue_verydark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
purple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
magenta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_light.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_lightest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
orange_dark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
yellow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
black.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#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_emojicreation, 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);
}
}
As you can see I started exploring the sharedPreferences option, after my attempt to create a service failed. If a Service is the best option, how can I make Drawing_View.java constantly listen for color changes? Thanks everyone!

You could add a setPaintColor method to your Drawing_View class. That way, you would not need to use SharedPreferences
and you could just change the paint color in your onClickListeners.
Something like this should work:
In your Drawing_View class, add:
public void setPaintColor (String color) {
paint.setColor(Color.parseColor(color));
}
In your onClickListener, call the setPaintColor method:
drawingView.setPaintColor(color);
I assume that your Drawing_View is already instantiated.
Update
You need to instantiate your Drawing_View the same way you instantiated the Buttons in your activity's onCreate method.
public class Drawing_Main extends ActionBarActivity {
...
Drawing_View drawingView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emoji_creation);
drawingView = (Drawing_View)findViewById(R.id.drawing_view);
green_light = (Button)findViewById(R.id.button1);
...
I hope this helps.

Related

Toolbar Icon unable to click and execute to next page Android Studio Java

I want my Home Icon in my Toolbar in my MainActivity to execute to go next page, but apparently, it is not working. Despite clicking the Home Icon in the Toolbar, it did not execute.
What is the correct way to correct the codes below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setSupportActionBar(toolbar);
buttonTiaoLiWan = (ImageButton) findViewById(R.id.BtnTLW);
buttonTiaoLiWan.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
openTLWpage();
}
});
buttonZhenZhuWan = (ImageButton) findViewById(R.id.BtnZZW);
buttonZhenZhuWan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openZZWpage();
}
});
buttonBuYaoJing = (ImageButton) findViewById(R.id.BtnBYJ);
buttonBuYaoJing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { openBYJpage();}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case R.id.action_home:
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Pass a XML resource from one activity to another activity using java code in Android Studio?

I want to pass an XML resource from one activity to another activity using Java Code? I don't want to create separate different activities for different buttons.
ImageButton imageBttn = (ImageButton)findViewById(R.id.imageButton1);
imageBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, info.class));
}
});
Pseudocode to explain what I'm trying to do:
If BUTTON_1 is clicked
-Pass swirl.png to info.class
If BUTTON_2 is clicked
-Pass golden.png to info.class
If BUTTON_3 is clicked
-Pass arcade.png
imageBttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, info.class)
intent.putExtra("image",R.drawable.ic_search_grey);
startActivity(intent);
}
});
On Mainactvitiy get the int drawable
int res = getIntent().getIntExtra("image", -1);
if(res > -1) {
Drawable drawable = getResources().getDrawable(res, null);
imgBtn.setImageDrawable(drawable);
}
InfoActivity.java
public class InfoActivity extends Activity {
private static final String EXTRA_IMAGE = "image";
public static void launch(Activity activity, #DrawableRes int imageResId) {
Intent intent = new Intent(activity, InfoActivity.class);
intent.putExtra(EXTRA_IMAGE, imageResId);
activity.startActivity(intent);
}
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
int imageResId = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (imageResId == -1) {
throw new IllegalArgumentException(EXTRA_IMAGE);
// or set error/default image resource id
}
// ... something to do with imageResId
}
}
MainActivity.java
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.swirl);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.golden);
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InfoActivity.launch(MainActivity.this, R.drawable.arcade);
}
});
}

android app crash after adding actionbar.setsubtitle

I tried to run my app (from bignerdranch) and could not run it after adding the following code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
I get a runtime exception . If i remove these lines the app runs ok .
ofcourse i added the line #TargetApi(11)
i tried changing my target sdk, i tried copying other people's code. nothing works!!
this is my code :
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater[mCurrentIndex]) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
}
mIsCheater[mCurrentIndex] = data.getBooleanExtra(
CheatActivity.EXTRA_ANSWER_SHOWN, false);
}
#TargetApi(11)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("Bodies of Water");
}
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
}
);
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
// mIsCheater=false;
updateQuestion();
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater[mCurrentIndex] = savedInstanceState.getBoolean(CHEATED);
}
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex]
.isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i, 0);
}
});
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBoolean(CHEATED, mIsCheater[mCurrentIndex]);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, 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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
`
what could be the problem?
please help me..
I had the same problem with bignerdranch.
It seems that because QuizActivity is a subclass of ActionBarActivity
instead of Activity I have to use getSupportActionBar() instead of
getActionBar()

How do I disable my Seekbar in Android with a Switch?

I want to disable my Seekbar and buttons with a switch which is Powerswitch
Here is a code snippet:
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
String sval = String.valueOf(i);
speakerVal.setText(sval);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// button - Favorite Channel ABC
cabc = (Button) findViewById(R.id.buttonABC);
cabc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Set Favorite
curChannel.setText("007");
}
});
and here is my switch code:
final Switch switch1 = (Switch) findViewById(R.id.switch1);
switch1.setOnCheckedChangeListener(this);
more switch code:
public void onSwitchClicked(View view) {
final TextView PowerSwitch = (TextView) findViewById(R.id.PwrSwitchVal);
Switch sw = (Switch) view;
if (sw.isChecked()) {
PowerSwitch.setText("ON");
pwr = true;
} else {
PowerSwitch.setText("OFF");
pwr = false;
}
}
I know I can use the switch.isChecked(), but when I change the seekba1.setEnabled(false), I can't seem to get it to turn back on.
I haven't even tried to disable the buttons yet.
any help would be appreciated.
In your onSwitchClicked method, you should be calling seekbar.setEnabled in the if checked if-else statement. If checked seekbar.setEnabled(true) else seekbar.setEnabled(false)
try this.
switch1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
if (arg1) {
seekbar1.setEnabled(true);
}
else{
seekbar1.setEnabled(false);
}
}
});

save .class name in a listview through sharedpreferences [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hi i am making a dictionary app and i want that when i open a word from a listview , then in the word page (word.class) (where the word meaning is explained), i want to add that word into a favorite.class activity in a listview shape and later on i can retrive that word from the listview.
i want to hit the favorite button in one java class and to save that word(string which is class name for that word) in anathor activity of favorite.class. the favorite button is actually is the menu item visible on the action bar. please explain me all the code and the way how can i do this..please give some code so to acomplish it.
public class Atherosclerosis extends Activity {
// declare variables for the table of content and paragraph heading here//
ScrollView scrollView;
TextView sign_atherosclerosis;
TextView sign_id;
TextView def_id;
TextView def_atherosclerosis;
TextView riskfac_id;
TextView riskfac_atherosclerosis;
TextView pathophy_id;
TextView pathophy_atherosclerosis;
TextView Dx_id;
TextView Dx_atherosclerosis;
TextView Rx_id;
TextView Rx_atherosclerosis;
TextView prevent_id;
TextView prevent_atherosclerosis;
TextView compl_id;
TextView compl_atherosclerosis;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atherosclerosis);
//here relate the variable for clickonlistener activity and direct scrolldown activity //
final ScrollView scrollView=(ScrollView)findViewById(R.id.scrollatherosclerosis);
TextView sign_id=(TextView)findViewById(R.id.Signandsymptomps_id);
final TextView sign_atherosclerosis=(TextView)findViewById(R.id.Signandsymptoms_atherosclerosis);
TextView def_id=(TextView)findViewById(R.id.definition_id);
final TextView def_atherosclerosis=(TextView)findViewById(R.id.definition_atherosclerosis);
TextView riskfac_id=(TextView)findViewById(R.id.riskfactor_id);
final TextView riskfac_atherosclerosis=(TextView)findViewById(R.id.riskfactor_atherosclerosis);
TextView pathophy_id=(TextView)findViewById(R.id.pathophysiology_id);
final TextView pathophy_atherosclerosis=(TextView)findViewById(R.id.pathophysiology_atherosclerosis);
TextView Dx_id=(TextView)findViewById(R.id.Diagnosis_id);
final TextView Dx_atherosclerosis=(TextView)findViewById(R.id.diagnosis_atherosclerosis);
TextView Rx_id=(TextView)findViewById(R.id.treatment_id);
final TextView Rx_atherosclerosis=(TextView)findViewById(R.id.treatment_atherosclerosis);
TextView prevent_id=(TextView)findViewById(R.id.prevention_id);
final TextView prevent_atherosclerosis=(TextView)findViewById(R.id.prevention_atherosclerosis);
TextView compl_id=(TextView)findViewById(R.id.complication_id);
final TextView compl_atherosclerosis=(TextView)findViewById(R.id.complication_atherosclerosis);
// this code is used for the action bar color change//
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#6B8E23")));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// this is the code for jumping from the table of content to the paragraph//
sign_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (sign_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
def_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (def_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
riskfac_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (riskfac_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
pathophy_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (pathophy_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
Dx_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (Dx_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
Rx_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (Rx_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
prevent_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (prevent_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
compl_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
scrollView.post(
new Runnable() {
#Override
public void run() {
new CountDownTimer(300, 20) {
#Override
public void onTick(long millisUntilFinished) {
scrollView.scrollTo(0, (int) (compl_atherosclerosis.getBottom()-millisUntilFinished));
}
#Override
public void onFinish() {
}
}.start();
}
}
);
}
});
}
// this is for the options selected from the menu button of mobile//
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.atherosclerosis, menu);
return true;
}
// for starting activity from the option or menu//
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.id_search:
Intent newActivity0 = new Intent(this,Search.class);
startActivity(newActivity0);
return true;
case R.id.id_favorit:
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("favorite", "com.kmcpesh.shortreviewofcardiology.Favorite");
editor.commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is my favorite.class activity
public class Favorite extends Activity {
private TextView mEmptyText;
private LinearLayout mBookmarkLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
mEmptyText = (TextView) findViewById(R.id.empty_textview);
mBookmarkLayout = (LinearLayout) findViewById(R.id.bookmark_insert_point);
getAllKeys();
}
private void getAllKeys()
{
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Map<String,?> keys = sp.getAll();
int count = 0;
for(Map.Entry<String,?> entry : keys.entrySet())
{
String value = entry.getValue().toString();
System.out.println("!!!!!!!!!!!!!!!!!value = "+value);
String delimiter = ",";
String[] values_array = value.split(delimiter);
addBookmark(values_array);
count++; //keep track of the number of bookmarks
}
//if there are no bookmarks, display a text view saying so. Otherwise, make the text view go away
if (count == 0)
{
mEmptyText.setVisibility(View.VISIBLE);
mEmptyText.setText(getString(R.string.no_bookmark));
}
else
mEmptyText.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
private void addBookmark(String[] values_array)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.favorite, null);
TextView text = (TextView) v.findViewById(R.id.bookmark_text);
text.setText(values_array[1]);
// insert into main view
mBookmarkLayout.addView(v, 0, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
System.out.println("!!!!!!!!!!!!!!!!!!!!Just added a view");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favorite, menu);
return true;
}
}
SharedPreferences in Android is generally used to store key=value pairs, not lists such as the one you describe. To store a value into SharedPreferences, you can do this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = sp.edit();
ed.putString("myKey", "myValue");
And then to retrieve a string key from SharedPreferences, you would do this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String value = sp.getString("myKey", "");
You could have a comma-delimited list of favorite words stored in here, and just parse the list:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = sp.edit();
ed.putString("favorites", "dog,cat,bird,fish");
And then to retrieve them:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String favorites = sp.getString("myKey", "");
String[] words = values.split(",");
System.out.println(Arrays.toString(words));
Then you have an array containing all of your favorite words.
[dog, cat, bird, fish]

Categories

Resources