Datatypes and application has stopped - java

I've this part of code:
public void onClickHandler(View a) {
String pressed = null;
String actual_text = null;
String new_text = null;
char last_char; //or char last_char = (Character) null; - the same problem
int bla;
pressed=((Button)a).getText().toString();
EditText lifeView = (EditText) findViewById(R.id.edittext);
actual_text = lifeView.getText().toString();
bla=actual_text.length()-1;
last_char = actual_text.charAt(bla);
}
And I'm solving the problem, that after pressed button I will get the error "The application has stopped unexpectedly. Please try it again."
The problem is on the line "char last_char" -- but I don't know why, Eclipse does not report a fault too...

You need to initialize the char last_char;
Ex:
char last_char=' ';
or similar but not null.

Try initilizing local variable char last_char;

Related

How to get StrikeThrough on a String ? Not a TextView, EditText or a View. But like String a = "my text" and then pass it to SQLite as a String

I have this method which works fine for an EditText or a view.
public SpannableString strikeThrough(String txt){
SpannableString spannableString = new SpannableString(txt);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
spannableString.setSpan(strikethroughSpan,0, txt.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
etChecklistItem.setText(strikeThrough(etChecklistItem.getText().toString()));
But my problem is after that, the text doesn't have StrikeThrough.
StringBuilder stringBuilderItem = new StringBuilder();
for( String list : itemslist) {
stringBuilderItem.append(list);
stringBuilderItem.append("\n");
}
String text = stringBuilderItem.toString();
strikeThrough(text);
dbHelper.insertChecklist(text);
When I get the data in RecyclerView, it would not be in Strikethrough.
Instead of storing a strike-through string inside the array, Create a class having two members a String and a boolean, and make the boolean true for the string you want to strike through.
class Message {
private String str;
private boolean strike;
public Message (String str, boolean strike) {
this.str = str;
this.strike = strike;
}
// getters and setters
}
and make string strike through when you're showing it on the screen
ArrayList<Message> arr = new ArrayList<>();
for (Message msg: arr) {
if (arr.getStrike()) {
// make string strikethrough
} else {
// keep as it is
}
}
To strike through a string in TextView
Method 1
textView.setText("I want like that")
textView.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Method 2: If you want to strike through only a part of the text then use
String str = "I want like that";
SpannableStringBuilder builder = new SpannableStringBuilder(str);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
builder.setSpan(
strikethroughSpan,
0, // Start
4, // End (exclusive)
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Text changes will not reflect in the strike changing
);
textView.setText(spanBuilder);
Method 3: If you want to strike through text in strings.xml
<string name="yourName"><strike>I want like that</strike></string>
references: [1]
Just Checkout this Code
First you need to initialise you edit text or text view
textView = findViewById(R.id.textView);
textView.setText("Hello World");
textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
I hope this will help you, if any problem just comment down

Why Im getting this error? java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to java.lang.String

When exporting my array list item, Im getting this error. In the first place it works but when updating my code adding data on my array it crashed my app and this error appear, do you have any idea why this happening?
java.lang.ClassCastException: android.text.SpannableStringBuilder
cannot be cast to java.lang.String
I'm getting error in this line 312 after if statement -
mEdit1.putString("Status_" + i,list_items.get(i));
I've already tried put empty string on my list like this
""+list_items.get(i));
but it's not working :(
ArrayList<String> list_items = new ArrayList<String>(); //declared global
ArrayAdapter arrayAdapter; //declared global
public boolean export_data()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putString("Status_","");
mEdit1.apply();
mEdit1.putInt("Status_size", list_items.size());
for(int i=0;i<list_items.size();i++)
{
mEdit1.remove("Status_" + i);
if (list_items.get(i) !=null){
mEdit1.putString("Status_" + i,list_items.get(i));
String[] separated = list_items.get(i).split(":");
mEdit1.putString("Status_" + i, separated[0]);
}
else{
Toast.makeText(getApplicationContext(), "List is Empty", Toast.LENGTH_SHORT).show();
}
}
return mEdit1.commit();
}
Adding item on ArrayAdapter
public void refreshInbox(){
arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
ContentResolver cResolver = getContentResolver();
Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,"date desc");
int indexBody = smsInboxCursor.getColumnIndex("body");
if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;
do{
String strbody = smsInboxCursor.getString( smsInboxCursor.getColumnIndex("body") );
if(strbody.contains("Notifier,") && strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
String[] sep = separate.split(" : ");
String sep1 = sep[1];
String finals = separate.replace(sep1, "<u>"+"<b>" + sep1 +"<b>"+ "</u>");
arrayAdapter.add(Html.fromHtml(finals));
}
else if(strbody.contains("Notifier,") && !strbody.contains(":")){
System.out.println ( strbody );
String str = strbody;
String[] separated = str.split(",");
String separate = separated[1];
arrayAdapter.add(separate);
}
}while (smsInboxCursor.moveToNext());
}
Assuming you want to keep displaying HTML in your list view, the problem is that the objects that ArrayAdapter is adding list_items are not Strings. That means, you have to change how you define the list_items variable from String to a more generic character sequence type:
ArrayList<CharSequence> list_items = new ArrayList<>();
The CharSequence interface does not have a "split" method though. To be able to use "split", you'll need to call toString to get a regular string:
String[] separated = list_items.get(i).toString().split(":");
It would also help if you used the type parameter with your ArrayAdapter. Using the type parameter would have made it harder (if not impossible) to make this mistake.
ArrayAdapter<CharSequence> arrayAdapter;
... inside the method ...
arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, list_items);
list_items.get(i));
Looks like you might be attempting to put an unusual type of string into the list...
see: java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String
I'm not an android dev but I suspect there are some "useful" shortcuts it provides in an attempt to make your life easier, that would probably trip you up.
Groovy's default string was a GString rather than a String. That tripped me up a number of times before I got used to it.
The error is with this line in refreshInbox()
arrayAdapter.add(Html.fromHtml(finals));
Html.fromHtml does't return String but instead it retuns Spanned
But you need to pass String to add() on adapter
To fix this convert it to String
adapter.add(Html.fromHtml(finals).toString()); // this will return plain text without html tags
or
adapter.add(finals); // this will be having HTML tags from this you can set text on views later

TextView Numbers shown in English in Persian font

I am loading a string which contains some number (all in Persian) into an android TextView. Everything was fine until I changed my custom font, numbers of text shown as English number.
Expected : ۱۲۳۴
Received : 1234
I know that my new font support Persian number. When I change the number locale using code below the number shown correctly.
NumberFormat numberFormat = NumberFormat.getInstance(new Locale("fa", "IR"));
String newNumber = numberFormat.format(number);
The problem is I have a string and it's hard to find the numeric part and change it. also my previous font works fine and I can't understand what's the problem with this font.
Any Idea how to globally solve this problem for all textview, or at least for a string?
Try to use this method:
private String setPersianNumbers(String str) {
return str
.replace("0", "۰")
.replace("1", "۱")
.replace("2", "۲")
.replace("3", "۳")
.replace("4", "۴")
.replace("5", "۵")
.replace("6", "۶")
.replace("7", "۷")
.replace("8", "۸")
.replace("9", "۹");
}
You can use this
String NumberString = String.format("%d", NumberInteger);
123 will become ١٢٣
Use this code for show Hegira date in Persian number:
String farsiDate = "1398/11/3";
farsiDate = farsiDate
.replace('0', '٠')
.replace('1', '١')
.replace('2', '٢')
.replace('3', '٣')
.replace('4', '٤')
.replace('5', '٥')
.replace('6', '٦')
.replace('7', '٧')
.replace('8', '٨')
.replace('9', '٩');
dateText.setText(farsiDate);
You'll have to translate it yourself. TextFormat does not automatically translate from arabic digits to any other language's, because that's actually not what people usually want. Each of those digits have their own character codes, a simple walk of the string and replacing them with the appropriate persian code would be sufficient.
private static String[] persianNumbers = new String[]{ "۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹" };
public static String PerisanNumber(String text) {
if (text.length() == 0) {
return "";
}
String out = "";
int length = text.length();
for (int i = 0; i < length; i++) {
char c = text.charAt(i);
if ('0' <= c && c <= '9') {
int number = Integer.parseInt(String.valueOf(c));
out += persianNumbers[number];
} else if (c == '٫') {
out += '،';
} else {
out += c;
}
}
return out;
}}
and after that u can use it like below vlock
TextView textView = findViewById(R.id.text_view);
textView.setText(PersianDigitConverter.PerisanNumber("این یک نمونه است ۱۲ "));
In JS, you can use the function below:
function toPersianDigits(inputValue: any) {
let value = `${inputValue}`;
const charCodeZero = '۰'.charCodeAt(0);
return String(value).replace(/[0-9]/g, w =>
String.fromCharCode(w.charCodeAt(0) + charCodeZero - 48),
);
}
export {toPersianDigits};

How to check if numeric textbox is empty?

I'm Starting to learn Android Studio java, i'm on basics yet.
Im doing an simple exercice i found on youtube "adding two numbers simple calculator".
I finished it and im trying to improve it by myself but im having trouble, if i let one of the EditTextBox empty the app crash, so i'm trying to check if the EdidTextbox is empty.
I Searched here and tried all thing and none works, or the code give error, or the one it works simple keep crashing. tried using some String to get de value and then check but wont work. (the one it's commented)
Just want a simple check in the editText if its empty just tell me error.
help please. thanks!
Code:
public void OnButtonClick(View ver) {
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float num1 = Float.parseFloat(et1.getText().toString());
float num2 = Float.parseFloat(et2.getText().toString());
//String input = et1.getText().toString();
//String input2 = et2.getText().toString();
if ( TextUtils.isEmpty(et1.getText().toString()) ) {
et1.setError("Error");
}
else {
et1.setError("Ok");
}
float sum = num1 + num2;
tv1.setText(String.valueOf(sum));
}
}
First implement TextWatcher in your class.
Then use this to check if your textfield is empty or not.
if(et1.getText().toString().lenghth()==0){
et1.setError("This Field cannot be empty");
}
Solution:The below statement will return true
if EditText remains empty
if(TextUtils.isEmpty(et1.getText()){
//enter code here
}
You can use a try catch clause instead of if like this
public void OnButtonClick(View ver) {
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float num1;
float num2;
try
{
num1 = Float.parseFloat(et1.getText().toString());
num2 = Float.parseFloat(et2.getText().toString());
float sum = num1 + num2;
tv1.setText(String.valueOf(sum));
et1.setError("Ok");
}catch(NullPointerException e){
et1.setError("Error");
}
}
But is just a approach you cant try another different. This catch clause it is only for null point exceptions, but imagine if its something different like division by 0, you can try another clause. Please read this article
So you want to check the editText field is empty or not,you have to check that when user press "add" button.
you do it this way:
if (!etEmail.getText().toString().equals("")) {
//the editbox is not empty
//do what ever you want
} else
etEmail.setError("the edit box is empty");
Update full code:
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!etText.getText().toString().equals("")) {
//do what ever you want
Integer sum = text1 + text2;
} else
etBox.setError(getText(R.string.noEmail));
}
});
}
Thank you for your help, like exe said i used a try catch and it worked, im gonna read the article for some try catch info since im more familiar with if's.
the if didnt work in any way, if there is a if way for this resolution please tell me, i want to try and learn all possible ways to do it.
Thank you.
Working code with try:
public void OnButtonClick(View ver) {
//Atribuir as caixas de texto a varariavel
EditText et1 = findViewById(R.id.et1);
EditText et2 = findViewById(R.id.et2);
TextView tv1 = findViewById(R.id.tv1);
float input1;
float input2;
//Atribui o conteudo das ET para as variaveis e faz/apresenta a soma
try {
input1 = Float.parseFloat(et1.getText().toString());
input2 = Float.parseFloat(et2.getText().toString());
float sum = input1 + input2;
tv1.setText(String.valueOf(sum));
}
catch(NumberFormatException ex) {
//Se estiver vazio msg de erro
Toast.makeText(getApplicationContext(), "Vazio", Toast.LENGTH_SHORT).show();
}
}
}

zerofill method using java

I want my textfield become like this “99999”
this is my code
while (rs.next()){
int s=rs.getInt("Number");
String num1 = String.valueOf(s);
String n = String.format("%05d",num1);
view.txtcustomernumber.setText(n);
}
why my txtcustomernumber(JTextField) always blank
Try this.
while (rs.next()){
int s=rs.getInt("Number");
String n = String.format("%05d",s);
view.txtcustomernumber.setText(n);
}
It might solve your problem.

Categories