Android - Store Spans in SQLiteDatabase - android

I'm making an app in which I'm using Spannble class to create a highlighter mechanism in an EditText, which works fine. Now, I want to store the span position(s) in a SQLiteDatabase, so that I can reload them and have the Spanned Text to show it in a TextView.
Here's my TextView alongwith the highlighter mechanism -
package com.Swap.RR;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.view.Menu;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ToggleButton;
public class Add_New_Note extends Activity {
private EditText note;
private int mStart;
private Typeface Roboto_lt;
private int end;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add__new__note);
note = (EditText) findViewById(R.id.notecontent);
ToggleButton highlighter = (ToggleButton) findViewById(R.id.highlightToggle);
Roboto_lt = Typeface.createFromAsset(getAssets(), "Roboto-Light.ttf");
note.setTypeface(Roboto_lt);
mStart = -1;
final TextWatcher highlightWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if(mStart > 0)
{
end = note.getText().length();
note.getText().setSpan(new BackgroundColorSpan(getResources().getColor(R.color.highlighter_green)), mStart, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
public void afterTextChanged(Editable s) {
}
};
highlighter.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (isChecked == true) {
//start highlighting when the ToggleButton is ON
if(mStart == -1) mStart = note.getText().length();
else mStart = -1;
mStart = note.getText().length();
note.addTextChangedListener(highlightWatcher);
} else {
//stop highlighting when the ToggleButton is OFF
note.removeTextChangedListener(highlightWatcher);
}
}
});
}
public void noteDone(View v) {
String noteContent = note.getText().toString();
Intent i = new Intent("com.Swap.Notes_page");
i.putExtra("NOTE", noteContent);
setResult(RESULT_OK, i);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_add__new__note, menu);
return true;
}
}
Please help me with some suggestions on how to do it. Thanks!

Your best bet is to use Html.toHtml() to convert the Spannable into HTML. You can then use Html.fromHtml() to convert the HTML back into a Spannable when you query the database later on. You will want to do adequate testing, though, as toHtml() and fromHtml() are not guaranteed to support the same HTML tags.

Related

How can I pass an integer variable from an activity to a fragment?

I have an activity with two variables
int cifracero
and
int cifrauno
I want to pass those variables to a fragment to be shown in some TextViews as the result of the multiplication made in the previous screen...like a "Congratulations, the multiplication was..."
I need to do something like a bundle to pass the variables as arguments of the second screen, in this case a fragment.
And then I have a third variable resultado which is the result of the multiplication of cifracero and cifrauno
This is the activity code
package com.example.aprendelastablasdemultiplicar;
import androidx.activity.ComponentActivity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.ListFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class quizingresar extends ComponentActivity {
private EditText cifracero;
private EditText cifrauno;
private TextView resultado;
private Button calcular;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizingresar);
cifracero = (EditText) findViewById(R.id.cifracero);
cifrauno = (EditText) findViewById(R.id.cifrauno);
resultado = (TextView) findViewById(R.id.resultado);
calcular = (Button)findViewById(R.id.calcular);
TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int multiplicationResult = multiplicarValores();
resultado.setText(Integer.toString(multiplicationResult));
}
#Override
public void afterTextChanged(Editable s) {
}
};
cifracero.addTextChangedListener(textWatcher);
cifrauno.addTextChangedListener(textWatcher);
calcular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCongratulationsCalcular();
}
});
}
private int multiplicarValores() {
final String strnumber0 = cifracero.getText().toString();
final String strnumber1 = cifrauno.getText().toString();
int number0 = 0;
int number1 = 0;
try {
number0 = Integer.parseInt(strnumber0);
} catch (NumberFormatException e) {
}
try {
number1 = Integer.parseInt(strnumber1);
} catch (NumberFormatException e) {
}
return number0 * number1;
}
public void openCongratulationsCalcular(){
Intent intent = new Intent(this, congratulationscalcular.class);
startActivity(intent);
}
}
I need to recover the variables from the previous screen to be shown in the new fragment screen
You can have both of your fragments share the data between them by having them both under the same viewmodel, as shown here.
If you are going to be swapping screens, I think a very efficient solution would be to pass the desired data from one (screen) fragment to another using attributes in your Navigation Graph. Shown here.
Take a look at Data-Binding as well if you'd like, might be useful.
Intent intent = new Intent(this, DisplayMessageActivity.class);
String result = resultado.getText().toString();
intent.putExtra("EXTRA_MESSAGE", result);
startActivity(intent);
to get the message that was passed by the first activity
Intent intent = getIntent();
String message = intent.getStringExtra("EXTRA_MESSAGE");

How to take bold characters as input in EditText in Android? [duplicate]

This question already has answers here:
Implementing a rich text editor in Android?
(7 answers)
Closed 5 years ago.
I am making a Note Making App which has a feature of adding Bold text via a button. When the bold button is clicked the bold mode should be turned on i.e the text taken from user in EditText should now be Bold. On the next Click on the bold button the bold mode should be turned off i.e text taken from the user should now be of Normal type.
I saw this post. Change future text to bold in EditText in Android
But the answer in that post did not work out.
When I first click the button it takes bold input but when I clicked the button again to take Normal text as input it was still taking bold text as input.
Here is the code:
TextArea.java
package com.example.syed.andtexteditor;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatEditText;
import android.text.Spannable;
import android.text.style.StyleSpan;
import android.util.AttributeSet;
import android.widget.EditText;
public class TextArea extends AppCompatEditText {
public static final int TYPEFACE_NORMAL = 0;
public static final int TYPEFACE_BOLD = 1;
public static final int TYPEFACE_ITALICS = 2;
public static final int TYPEFACE_BOLD_ITALICS = 3;
private int currentTypeface;
private int lastCursorPosition;
private int tId;
public TextArea(Context context) {
super(context);
lastCursorPosition = this.getSelectionStart();
}
public TextArea(Context context, AttributeSet attrs) {
super(context, attrs);
}
public int gettId() {
return tId;
}
public void settId(int tId) {
this.tId = tId;
}
public void changeTypeface(int tfId) {
currentTypeface = tfId;
lastCursorPosition = this.getSelectionStart();
}
#Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
Spannable str = this.getText();
StyleSpan ss;
int endLength = text.toString().length();
switch(currentTypeface) {
case TYPEFACE_NORMAL:
ss = new StyleSpan(Typeface.NORMAL);
break;
case TYPEFACE_BOLD:
ss = new StyleSpan(Typeface.BOLD);
break;
case TYPEFACE_ITALICS:
ss = new StyleSpan(Typeface.ITALIC);
break;
case TYPEFACE_BOLD_ITALICS:
ss = new StyleSpan(Typeface.BOLD_ITALIC);
break;
default:
ss = new StyleSpan(Typeface.NORMAL);
}
str.setSpan(ss, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
MainActivity.java:
package com.example.syed.andtexteditor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class MainActivity extends AppCompatActivity {
boolean boldClicked=false;
int typefaceStyle = TextArea.TYPEFACE_NORMAL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button boldButton = (Button)findViewById(R.id.bold_button);
boldButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextArea t = (TextArea) findViewById(R.id.textInput);
if (!boldClicked)
boldClicked = true;
else if (boldClicked)
boldClicked = false;
if (boldClicked) {
typefaceStyle = TextArea.TYPEFACE_BOLD;
t.changeTypeface(typefaceStyle);
}
}
});
}
}
add this line to your layout's Editext
android:textStyle="bold"

Can't find the symbol addTextChangedListener

I am having issues with addTextChangedListener. I have 2 edittext (edittext1 and edittext2) that when the text (in this case numbers) are added or changed I need it to run a calculation and output it to a textview called resultstext.
I have found many examples and have modified them to do what I need them to do, but when I call the editText1.addTextChangedListener.inputTextwatcher; it tells me it cant find the symbol addTextChangedListener. Below is the code, how to straighten this out?
package com.example.MyProject;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.view.FocusFinder;
import android.view.Menu;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private android.widget.EditText editText1;
private android.widget.EditText editText2;
private android.widget.TextView resultsText;
private void onItemSelected() {
editText1 = (EditText)findViewById(R.id.textView13);
editText2 = (EditText)findViewById(R.id.textView15);
resultsText = (android.widget.TextView)findViewById(R.id.textView16);
}
android.text.TextWatcher inputTextWatcher = new android.text.TextWatcher()
{
public void afterTextChanged(android.text.Editable s) {
calculateResult();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
};
editText1.addTextChangedListener.inputTextWatcher;
editText2.addTextChangedListener.inputTextWatcher;
private void calculateResult() throws NumberFormatException {
Editable editableValue1 = editText1.getText(),
editableValue2 = editText2.getText();
double value1 = 0.0,
value2 = 0.0,
result;
if (editableValue1 != null)
value1 = Double.parseDouble(editableValue1.toString());
if (editableValue2 != null)
value2 = Double.parseDouble(editableValue2.toString());
result = ((0.5 * value1) / 6.1) * value2;
resultsText.setText(String.valueOf(result));
}
}
Placement of some of your code was wrong. I have attempted to fix it. See if the following works for you:
package com.example.MyProject;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.view.FocusFinder;
import android.view.Menu;
import android.widget.EditText;
public class MainActivity extends Activity {
private android.widget.EditText editText1;
private android.widget.EditText editText2;
private android.widget.TextView resultsText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.textView13);
editText2 = (EditText)findViewById(R.id.textView15);
resultsText = (android.widget.TextView)findViewById(R.id.textView16);
android.text.TextWatcher inputTextWatcher = new android.text.TextWatcher() {
public void afterTextChanged(android.text.Editable s) {
calculateResult();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
};
editText1.addTextChangedListener(inputTextWatcher);
editText2.addTextChangedListener(inputTextWatcher);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void calculateResult() throws NumberFormatException {
Editable editableValue1 = editText1.getText();
Editable editableValue2 = editText2.getText();
double value1 = 0.0,
value2 = 0.0,
result;
if (editableValue1 != null)
value1 = Double.parseDouble(editableValue1.toString());
if (editableValue2 != null)
value2 = Double.parseDouble(editableValue2.toString());
result = ((0.5 * value1) / 6.1) * value2;
resultsText.setText(String.valueOf(result));
}
}
try to use
private TextWatcher watcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//your code here
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
};
Then add watcher to your edittext
youredittext.addTextChangedListener(watcher);

Hide an android ListView until search string is entered

I've followed this tutorial http://www.androidpeople.com/android-listview-searchbox-sort-items and I have the search working on the list. The only change I'd like to make is to have the list view hidden initially and the results only appearing when the user starts typing. Is there a way to do this?
EDIT: Added code.
package com.example.testapp;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private EditText ed;
private String lv_arr[]= {"Android","Cupcake","Donut","Eclairs","AndroidPeople","Froyo",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.activity_main);
lv1=(ListView)findViewById(R.id.ListView);
ed=(EditText)findViewById(R.id.EditText01);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if(lv1.getVisibility() != View.VISIBLE)
lv1.setVisibility(View.VISIBLE);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<lv_arr.length;i++)
{
if(textlength<=lv_arr[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength)))
{
arr_sort.add(lv_arr[i]);
}
}
}
lv1.setAdapter(new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_list_item_1 , arr_sort));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I would do it like this:
EditText etSearch = (EditText) getView().findViewById(R.id.etSearch);
etSearch.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
if(view.getVisibility() != View.Visible)
view.setVisiblity(View.Visible);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});

Change text color as the user is typing?

While the user is typing in an EditText I would like certain keywords to change colors.
I could place HTML tags around the keywords when the app discovers the user typed it and use Html.fromHtml but the user will be entering real HTML tags themselves and that would mess it up. So I guess I should use Spannable?
And how exactly should I scan the EditText for these keywords? Meaning - what is the most efficient way? I was thinking maybe an array of all the keywords - and then loop through and see if any matches are found . Any ideas on how to approach this?
Hi Use TextWatcher on EditText to see what user is typing and use Linkify to check pattern.
https://developer.android.com/reference/android/text/util/Linkify.html
EditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
}
Use onTextChanged Listener to check what user is typing.
Sample for Pattern matching..
int flags = Pattern.CASE_INSENSITIVE;
Pattern p = Pattern.compile("\[0-9]*\", flags);
Linkify.addLinks(myTextView, p,
"content://com.foo");
Create a Pattern Matcher and match pattern with Text in onTextChanged Listener
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.widget.EditText;
public class ColorEditText extends Activity {
private Pattern helloPattern = Pattern.compile("Hello");
private Pattern simplePattern = Pattern.compile("Simple");
private SpannableStringBuilder spannable;
private EditText edit;
private TextWatcher colorChangeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_edit_text);
edit =(EditText) findViewById(R.id.edit);
colorChangeText = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
edit.removeTextChangedListener(colorChangeText);
Log.d("Changes",edit.getText().toString());
spannable = new SpannableStringBuilder( edit.getText().toString() );
Matcher o = helloPattern.matcher(spannable);
while (o.find()) {
spannable.setSpan(new StyleSpan(Typeface.BOLD), o.start(), o.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(Color.rgb(103, 58, 183)), o.start(), o.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
Matcher n = simplePattern.matcher(spannable);
while (n.find()) {
spannable.setSpan(new StyleSpan(Typeface.BOLD), n.start(), n.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(Color.rgb(0, 105, 92)), n.start(), n.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
edit.setText(spannable);
edit.setSelection(spannable.length());
edit.addTextChangedListener(colorChangeText);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
};
edit.addTextChangedListener(colorChangeText);
}
}

Categories

Resources