In my application I extend the Dialog class to get user input for each field and now I want to validate them.
public abstract class EditDialogHelper extends Dialog implements android.view.View.OnClickListener {
private Context context;
private String title;
private String field;
private String positive;
private String negative;
private EditText etField;
private TextView tvCount;
private int characterCount;
public EditDialogHelper(Context context, String title, String field, String positive, String negative, int characterCount) {
super(context);
this.context = context;
this.title = title;
this.field = field;
this.positive = positive;
this.negative = negative;
this.characterCount = characterCount;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_edit_view);
TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
etField = (EditText) findViewById(R.id.etField);
tvCount = (TextView) findViewById(R.id.tvInputCount);
Button btnConfirmationOk = (Button) findViewById(R.id.btnPositive);
Button btnConfirmationCancel = (Button) findViewById(R.id.btnNegative);
final 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) {
tvCount.setText(String.valueOf(characterCount - s.length()));
}
#Override
public void afterTextChanged(Editable s) {
}
};
etField.addTextChangedListener(textWatcher);
tvTitle.setText(title);
etField.setText(field);
etField.setFilters(new InputFilter[]{new InputFilter.LengthFilter(characterCount)});
btnConfirmationOk.setOnClickListener(this);
btnConfirmationCancel.setOnClickListener(this);
}
public String getValue() {
return etField.getText().toString().trim();
}
private boolean validateInputs(String value) {
boolean valid = false;
if (value != null && !(value.equals(""))) {
valid = true;
} else {
etField.setError("This can't be left empty");
}
return valid;
}
}
Once the dialog opens up I want it to be validated once the btnConfirmationOk is clicked and if the field is empty, it should be prevented from dismissing the dialog while showing the error.
Where should I use this validateInputs method and in which way it should be modified.
Answer is quite simple i guess
#Override
void onClick(View view) {
if (view.getId == R.id.btnPositive) {
boolean valid = validate("my string");
if(valid) {
// do stuff
dissmis();
}
} else {
dissmis();
}
}
But in my oppinion you should set different listeners to your possitive and negative buttons, instead of tracking everything with EditDialogHelper class.
this could be done like this.
button.setOnClickListener(new OnClickListener {
#Override
void onClick(View v) {
}
});
p.s. I wrote everything from my head so this could contain compilation errors.
Related
So I want to pass the data between the activities,so I've make that there's 3 separate integers should be send to the second activity,but i don't know why,the emulator keeps adding all of them. Basically,I making an app, at case of my course - i need to create an app that keeping score,in my case,app would keep the score,number of fouls,and number of corners during the football match. To set the data,we are clicking in special button (press score to increment score etc.) when we want to go to the second activity and see the detailed statistics we should see like 3 goals,6 fouls,and like 2 corners for team "A" during the match,but when i clicking in buttons (suppose that is 1 time for goal,2 times for fouls,and 3 times for corner the app should be like 1 goal,2 fouls,3 corner's but it keep adding all of integers,and it's like 6 goals,6 fouls,6 corners. What can be wrong?
Count activity (here program storage the value of integers)
public class CountActivity extends AppCompatActivity {
public int team_a_score;
public int team_a_foul;
public int team_a_corner;
public int team_b_score;
public int team_b_foul;
public int team_b_corner;
private Button goToDetailedStats;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count);
goToDetailedStats = (Button) findViewById(R.id.go_to_stats);
goToDetailedStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDetailedScore();
}
});
}
private void openDetailedScore() {
Intent intent = new Intent(this,DeatiledScoreActivity.class);
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
startActivity(intent);
}
public void resetScore(View view) {
team_a_score = 0;
display_a_score(team_a_score);
team_b_score = 0;
display_b_score(team_b_score);
}
private void display_a_score (int a_score){
TextView team_a_score_tv = (TextView) findViewById(R.id.team_a_score_tv);
team_a_score_tv.setText(String.valueOf(a_score));
}
private void display_b_score (int b_score){
TextView team_b_score_tv = (TextView) findViewById(R.id.team_b_score_tv);
team_b_score_tv.setText(String.valueOf(b_score));
}
public void increment_a_score(View view) {
team_a_score = team_a_score+1;
display_a_score(team_a_score);
}
public void increment_a_foul(View view) {
team_a_foul = team_a_foul+1;
}
public void increment_a_corner(View view) {
team_a_corner = team_a_corner+1;
}
public void increment_b_score(View view) {
team_b_score = team_b_score+1;
display_b_score(team_b_score);
}
public void increment_b_foul(View view) {
team_b_foul = team_b_foul+1;
}
public void increment_b_corner(View view) {
team_b_corner = team_b_corner+1;
}
}
Detailed activity have to receive data that we send as intent from Counting activity.
public class DeatiledScoreActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deatiled_score);
int team_a_score_detail_int = 0;
int team_a_foul_detail_int = 0;
int team_a_corner_detail_int = 0;
int team_b_score_detail_int = 0;
int team_b_foul_detail_int = 0;
int team_b_corner_detail_int = 0;
Intent goal_intent = getIntent();
int goal = goal_intent.getIntExtra("", team_a_score_detail_int);
display_a_goal(goal);
Intent foul_intent = getIntent();
int foul = foul_intent.getIntExtra("", team_a_foul_detail_int);
display_a_foul(foul);
Intent corner_intent = getIntent();
int corner = corner_intent.getIntExtra("", team_a_corner_detail_int);
display_a_corner(corner);
}
public void display_a_goal(int score) {
TextView a_score = (TextView) findViewById(R.id.team_a_goal_detail);
a_score.setText(String.valueOf(score));
}
public void display_a_foul(int foul){
TextView a_foul = (TextView) findViewById(R.id.team_a_foul_detail);
a_foul.setText(String.valueOf(foul));
They cannot have the same key:
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
So in order to make it work set:
intent.putExtra("some",team_a_score);
intent.putExtra("some2",team_a_foul);
intent.putExtra("some4",team_a_corner);
Intent putExtra method accepts two arguments key - value.
I have one edittext: edittextmysite.
Now I want to provide default text, for example: "https://wwww.mysite.com/"
I have achieved it this as follows:
edittextmysite.setText("https://wwww.mysite.com/");
Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());
edittextmysite.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().contains("https://wwww.mysite.com/")) {
edittextmysite.setText("https://wwww.mysite.com/");
Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());
}
}
});
So if anyone enters text it will automatically be appended to the default, like this: https://wwww.mysite.com/<Mytext>
Now what I want is if anyone writes something like this in edittext:
https://wwww.mysite.com/https://wwww.mysite.com/helloworld
or
https://wwww.mysite.com/wwww.mysite.com/helloworld
or
https://wwww.mysite.com/wwww.anyothersite.com/helloworld
that it will automatically convert it to the correct format, like this:
https://wwww.mysite.com/helloworld
How can I achieve this?
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().contains("https://wwww.mysite.com/")) {
String text = s.toString.subString(0, s.lastIndexOf("/"));
edittextmysite.setText(s.toString().replace(text, "https://wwww.mysite.com/");
Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());
}
}
edittextmysite.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
if(edittextmysite.getText().toString().length() == 0)
edittextmysite.setText("https://wwww.mysite.com/" + s.toString());
else
edittextmysite.append(s.toString());
}
});
Here is what i have tried.
private String str = "https://wwww.mysite.com/";
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().contains("https://wwww.mysite.com/")) {
edittextmysite.setText("https://wwww.mysite.com/");
Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());
}
String s1 = s.toString();
String s2 = s1.substring(str.length());
if(s2.contains("/")) {
String s3 = s1.substring(str.length());
if (Patterns.WEB_URL.matcher(s3).matches()) {
// Valid url
edittextmysite.setText(s.toString().replace(s3, ""));
Selection.setSelection(edittextmysite.getText(), edittextmysite.getText().length());
}
}
}
This piece of code won't allow you to enter another URL and user can only enter string after URL as you explained above.
Thanks
Rather that editing the text afterwards, there are many nicer ways to accomplish this:
Place "https://example.com/" on the left of the edittext, then if you really have to, you can search the string for .com, www., etc. and remove it and the name they encapsulate using any algorithm found easily on the web. Then concatenate the strings.
Use a hint in the edittext.
here I have sharing complete working example. There is explanation along with it.
public class MainActivity extends AppCompatActivity implements TextWatcher {
String BASE_URL = "https://wwww.mysite.com";
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*paste this editText --> https://wwww.mysite.com/https://wwww.mysite.com/helloworld <--*/
editText = findViewById(R.id.et);
editText.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = s.toString().trim();
editText.removeTextChangedListener(this);
if (text.length() > 0) {
if (!text.contains(BASE_URL)) {
String tempText = BASE_URL +"/"+ text;
editText.setText(tempText); //setting text here
proceed(tempText); //sending here for further test, if pasted the link
} else {
proceed(text);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
private void proceed(String text) {
String newText="";
String firstHalf = text.substring(0,text.lastIndexOf('/'));
String secondHalf = text.substring(text.lastIndexOf('/',(text.length()-1)));
String[] words = firstHalf.split("/"); //Split the word from String
for (int i = 0; i < words.length; i++){ //Outer loop for Comparison
if (words[i] != null) {
for (int j = i + 1; j < words.length; j++){ //Inner loop for Comparison
if (words[i].equals(words[j])) //Checking for both strings are equal
words[j] = null; //Delete the duplicate words
}
}
}
//Displaying the String without duplicate words{
for (int k = 0; k < words.length; k++){
if (words[k] != null)
newText=newText+words[k];
}
StringBuffer formattedText = new StringBuffer((newText+secondHalf));
formattedText.insert(6,"//"); //length of https;//
editText.setText(formattedText);
//attaching textwatcher again
editText.addTextChangedListener(this);
//moving cusor pointer to the end point
editText.setSelection(editText.getText().toString().length());
}
}
You should fix the prefix text into EditText which can not be editable and user only can edit the text after base-url (like after https://wwww.mysite.com/ ).
So you should follow these steps
Prefix the base url to EditText and make it un-editable
Let user enter sub part of the url
Validate input with Patterns.WEB_URL.matcher(inputUrl).matches() for valid url. You can add this validation on TextChange of EditText or on click of a button.
Below is a custom EditText code which you can use directly
public class UrlEditText extends AppCompatEditText {
float mLeftPadding = -1;
public UrlEditText(Context context) {
super(context);
}
public UrlEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public UrlEditText(Context context, AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
initPrefix();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
String prefix = (String) getTag();
canvas.drawText(prefix, mLeftPadding,
getLineBounds(0, null), getPaint());
}
private void initPrefix() {
if (mLeftPadding == -1) {
String prefix = (String) getTag();
float[] widths = new float[prefix.length()];
getPaint().getTextWidths(prefix, widths);
float textWidth = 0;
for (float w : widths) {
textWidth += w;
}
mLeftPadding = getCompoundPaddingLeft();
setPadding((int) (textWidth + mLeftPadding),
getPaddingRight(), getPaddingTop(),
getPaddingBottom());
}
}
}
and in layout xml file, it would be like
<com.path_of_custom_view.UrlEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="https://wwww.mysite.com/"
android:text="helloworld" />
Instead of using android:tag you can define custom attribute for this edittext.
And for input validation you can validate it like
String enteredUrl = textField.getText().toString();
if (Patterns.WEB_URL.matcher(enteredUrl).matches()) {
// Valid url
} else {
// Invalid url
}
You can Just store it as String and than simply String newReplacedString = stringtoReplace.replace("Phrase To Replace", "WHAT TO REPLACE WITH");
This one works for me, I hope this will work for you too.
#Override
public void afterTextChanged(Editable s) {
String text = edittextmysite.getText().toString();
String URL = "https://www.example.com/";
if (text.contains(URL)) {
String url = getUrl(URL, text);
if (!text.equals(url)) {
edittextmysite.setText(url);
edittextmysite.setSelection(url.length());
}
} else {
String tempUrl = URL + text;
String url = getUrl(URL, tempUrl);
if (!tempUrl.equals(url)) {
edittextmysite.setText(url);
edittextmysite.setSelection(url.length());
} else if (!text.contains(URL)) {
edittextmysite.setText(URL);
edittextmysite.setSelection(URL.length());
}
}
}
private String getUrl(String URL, String text) {
String urls[] = text.split("(?<!/)/(?!/)");
Log.v(TAG, Arrays.toString(urls));
String lastWord = urls[urls.length - 1];
String lastChar = text.substring(text.length() - 1);
if (lastChar.equals("/"))
lastWord = lastWord.concat(lastChar);
for (String url : urls) {
url = url.concat("/");
if (Patterns.WEB_URL.matcher(url).matches()) {
if (url.equals(URL)) {
if (!lastWord.contains("/"))
return url + lastWord;
else return text;
}
}
}
return URL;
}
In this code I tried your inputs, and its working.
It's not an elegant solution and I suggest you to use alternative UX for what you are trying to do entirely but if you really want to pursue this way then try the following code in your TextWatcher,
final String baseString="https://wwww.mysite.com/";
#Override
public void afterTextChanged(Editable s) {
if(!s.toString().contains(baseString)){
editText.setText(baseString+s.toString());
editText.setSelection(editText.length());
}else {
String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Pattern pattern=Pattern.compile(regex);
String subStr=s.toString().substring(baseString.length());
Matcher matcher= pattern.matcher(subStr);
if(matcher.matches()){
editText.setText(baseString+subStr.replaceAll(regex,""));
editText.setSelection(editText.length());
}else if(subStr.contains("https:")){
editText.setText(baseString+subStr.replace("https:",""));
editText.setSelection(editText.length());
}else if(subStr.contains("www.")){
editText.setText(baseString+subStr.replace("www.",""));
editText.setSelection(editText.length());
}else if(subStr.contains(".")){
editText.setText(baseString+subStr.replaceAll("\\.",""));
editText.setSelection(editText.length());
}else if(subStr.contains("//")){
editText.setText(baseString+subStr.replaceAll("//",""));
editText.setSelection(editText.length());
}else if(subStr.contains(":")){
editText.setText(baseString+subStr.replaceAll(":",""));
editText.setSelection(editText.length());
}
}
}
Once user starts typing, it sets our base string in the edittext and forces
user not to write anything that can be a part of uri. One important thing to consider when user is trying to hit backspace, this is taken care of using the special condition and user won't be able to remove base string once he/she starts typing.
Note: This solution can be optimized as well
Answer
You can set edittext text to not remove by user. So the predefined text will stay with ediitext and automatically append the new text.
Try this:
private EditText et;
private String str_value = "http://example.com/";
private String added_str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = findViewById(R.id.edittext);
et.setText(str_value);
et.setSelection(str_value.length());
et.addTextChangedListener(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) {
if(start == str_value.length() - 1)
{
et.setText(str_value);
et.setSelection(str_value.length());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
Edited
If you want elimnate the domain name after user entered in the edittext. You can try below code
#Override
public void afterTextChanged(Editable s) {
if(s.length() > str_value.length()) {
added_str = s.toString().substring(str_value.length(), s.length()); //this will get text after predefined text.
if(Patterns.DOMAIN_NAME.matcher(added_str).matches() || added_str.contains("http:"))
{
et.setText(str_value);
et.setSelection(str_value.length());
}
}
}
Below are the 3 java classes that I am using for my android application development. I would like to add the student data (name and phone number) from the AddActivity to be stored in MainActivity page after clicking "Add". I have researched on this and tried using an array but I am quite confused on how the logic must be for the code to send the datas keyed in AddActivity into the MainActivity page. Can anyone give me a guidance on how to work this out and would really be grateful if you could show me another way rather the way I am trying. I want the data to be stored in a ListView format in the MainActivity after each "Add" I have clicked in the AddActivity page. Do hope that someone will be able to guide me in doing this. Thank you.
MainActivity.java - https://jsfiddle.net/eb1fprnn/
public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList<Student> students = new ArrayList<Student>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add();
}
public void add() {
Student student;
addStudent = (Button) findViewById(R.id.add);
addStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
AddActivity.java - https://jsfiddle.net/40k5mas2/
public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList<Student> students;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
students = (ArrayList<Student>) getIntent().getSerializableExtra("AddNewStudent");
setContentView(R.layout.activity_add);
edit();
addStudent();
}
public void edit() {
name = (EditText) findViewById(R.id.StudentName);
phone = (EditText) findViewById(R.id.phone);
final Button addStudent = (Button) findViewById(R.id.AddStudent);
name.addTextChangedListener(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) {
addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
Fname = name.getText().toString();
String phoneNumber = phone.getText().toString();
FphoneNumber = Integer.parseInt(phoneNumber);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void addStudent() {
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this, MainActivity.class);
intent.putExtra("studentName",name.getText().toString() );
intent.putExtra("phoneNumber",phone.getText().toString());
startActivity(intent);
Student student = new Student(Fname, FphoneNumber);
students.add(student);
}
});
}
public void addStudent(){
add = (Button) findViewById(R.id.AddStudent);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddActivity.this,Record.class);
startActivity(intent);
}
});
}
Student.java - https://jsfiddle.net/gy0g7b0s/
public class Student {
String mName;
int mPhoneNumber;
public Student (String name, int number){
mName = name;
mPhoneNumber = number;
};
public String getmName() {
return mName;
}
public String getmName(String newName) {
return (this.mName = newName);
}
public int getmPhoneNumber() {
return this.mPhoneNumber;
}
public int getmPhoneNumber(int newPhoneNumber) {
return (this.mPhoneNumber = newPhoneNumber);
}
#Override
public String toString() {
return String.format("%s\t%f",this.mName, this.mPhoneNumber);
[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4
[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc
you can store them as public static variable or create AddActivity constructor and get functions.
String student name; /*add value to this variable #onCreate or wherever in your AddActivity*/
public class AddActivity(/*here to pass data to addactivity*/){
//
}
public String getName(){
return this.name;
}
in another activity
AddActivity ac = new AddActivity();
String someName = ac.getName();
you can use this logic to pass data.
Edit
but if you want to pass data with Intent then just check intenr content onCreate()
Intent i = getIntent();
if(i.hasExtra("intentKey")){//check if it s not null
String name = i.getExtraString("intentKay");
}
The best solution I could find is, declare that array list as static and you could access those wherever you want provided if the classes are in the same package. But if you want to store those values, used shared preferences. Hope this may helps out.
I am trying to develop an UI actionsheet in android. Using dependency:
compile 'com.baoyz.actionsheet:library:1.1.6'
I have developed an actionsheet in android which look like this:
ActionSheet in Android
I am trying to change the button text whenever any option is selected from the actionSheet. The index in the javafile below contains the string position just like array but i am unable to get the string value from that index.
Here is my javafile:
public class billBookInfo extends AppCompatActivity implements ActionSheet.ActionSheetListener{
private Button change;
private String setValue;
private Button vtype;
private Button zone;
Button next;
Button previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bill_book_info);
getSupportActionBar().hide();
vtype = (Button) findViewById(R.id.info_billbook_bt_vtype);
zone = (Button)findViewById(R.id.info_billbook_bt_zone);
}
}
public void onClick(View v){
switch (v.getId()) {
case R.id.info_billbook_bt_vtype:
setTheme(R.style.ActionSheetStyleiOS7);
change = vtype;
showActionSheet1();
break;
case R.id.info_billbook_bt_zone:
setTheme(R.style.ActionSheetStyleiOS7);
showActionSheet2();
change = zone;
break;
}
}
private void showActionSheet1() {
ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles("Motorcycle","Scooter","Car","Van")
.setCancelableOnTouchOutside(true).setListener(this).show();
}
private void showActionSheet2() {
ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles("Me", "Ko", "Sa", "Ja")
.setCancelableOnTouchOutside(true).setListener(this).show();
}
#Override
public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
}
#Override
public void onOtherButtonClick(ActionSheet actionSheet, int index) {
int i = 0;
if ( i == index){
setValue = "".concat(getString(index));
change.setText(setValue);
}
}
}
Why don't you use a variable to store those values.
String vArr[] = new String[]{"Motorcycle","Scooter","Car","Van"};
String dArr[] = new String[]{"Me", "Ko", "Sa", "Ja"};
ActionSheet vSheet, dSheet;
private void showActionSheet1() {
vSheet = ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles(vArr[0],vArr[1],vArr[2],vArr[3])
.setCancelableOnTouchOutside(true).setListener(this).show();
}
private void showActionSheet2() {
dSheet = ActionSheet.createBuilder(this,getSupportFragmentManager())
.setCancelButtonTitle("Cancel")
.setOtherButtonTitles(dArr[0],dArr[1],dArr[2],dArr[3])
.setCancelableOnTouchOutside(true).setListener(this).show();
}
#Override
public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
}
#Override
public void onOtherButtonClick(ActionSheet actionSheet, int index) {
if ( actionSheet == vSheet){
change.setText(vArr[index]);
}
else{
change.setText(dArr[index]);
}
}
Hey I've just upgraded my app to AppCompat v22.1.0 and got this exception
Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features
at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:360)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106)
I found soln. here https://stackoverflow.com/a/29790071/2781359
Still the problem wasn't solved because I was calling the setContentView after super.onCreate, in the ConnectionWifiEditActivity Class.
When I changed this it throws NullPointerException
How Can I Solve this?
Caused by: java.lang.NullPointerException
at Client.Activity.connection.ConnectionEditActivity.onResume(ConnectionEditActivity.java:46)
at Client.Activity.connection.ConnectionWifiEditActivity.onResume(ConnectionWifiEditActivity.java:81)
ConnectionWifiEditActivity
public class ConnectionWifiEditActivity extends ConnectionEditActivity implements OnClickListener
{
private ConnectionWifi connection;
private EditText host;
private EditText port;
Button scan;
ListView lv;
private Toolbar mToolbar;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.connectionwifiedit);
lv = (ListView) findViewById(android.R.id.list);
this.connection = (ConnectionWifi) connectionParam;
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.host = (EditText) this.findViewById(R.id.host);
this.port = (EditText) this.findViewById(R.id.port);
SnackbarManager.show(
Snackbar.with(getApplicationContext()) // context
.type(SnackbarType.MULTI_LINE) // Set is as a multi-line snackbar
.text(R.string.tip) // text to be displayed
.duration(Snackbar.SnackbarDuration.LENGTH_INDEFINITE)
, this);
}
public void Save(View v){
this.finish();
}
#Override
public void onClick(View v)
{
}
protected void onResume()
{
super.onResume();
this.host.setText(this.connection.getHost());
this.port.setText(Integer.toString(this.connection.getPort()));
}
protected void onPause()
{
super.onPause();
this.connection.setHost(this.host.getText().toString());
this.connection.setPort(Integer.parseInt(this.port.getText().toString()));
}}
ConnectionEditActivity
public static Connection connectionParam;
private Connection connection;
private EditText name;
private EditText password;
public class ConnectionEditActivity extends AppCompatActivity implements OnClickListener
{
public static Connection connectionParam;
private Connection connection;
private Button save;
private EditText name;
private EditText password;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.connection = connectionParam;
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
}
protected void onResume()
{
super.onResume();
this.name.setText(this.connection.getName());
this.password.setText(this.connection.getPassword());
}
protected void onPause()
{
super.onPause();
this.connection.setName(this.name.getText().toString());
this.connection.setPassword(this.password.getText().toString());
}
public void onClick(View v)
{
if (v == this.save)
{
this.finish();
}
}
}
Connection
public abstract class Connection implements Comparable<Connection>, Serializable
{
private static final long serialVersionUID = 1L;
public static final int TYPE_COUNT = 2;
public static final int WIFI = 0;
public static final int BLUETOOTH = 1;
private String name;
private String password;
public Connection()
{
this.name = "";
this.password = RemoteItConnection.DEFAULT_PASSWORD;
}
public static Connection load(SharedPreferences preferences, ConnectionList list, int position)
{
Connection connection = null;
int type = preferences.getInt("connection_" + position + "_type", -1);
switch (type)
{
case WIFI:
connection = ConnectionWifi.load(preferences, position);
break;
case BLUETOOTH:
connection = ConnectionBluetooth.load(preferences, position);
break;
}
connection.name = preferences.getString("connection_" + position + "_name", null);
connection.password = preferences.getString("connection_" + position + "_password", null);
return connection;
}
public void save(Editor editor, int position)
{
editor.putString("connection_" + position + "_name", this.name);
editor.putString("connection_" + position + "_password", this.password);
}
public abstract RemoteItConnection connect(RemoteIt application) throws IOException;
public abstract void edit(Context context);
protected void edit(Context context, Intent intent)
{
ConnectionEditActivity.connectionParam = this;
context.startActivity(intent);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public int compareTo(Connection c)
{
return this.name.compareTo(c.name);
}
}
Since you want to get some ui elements in the super method, you have to find a way to define the layout in the superclass. It is the reason because you are getting an NPE as described in the other answers.
You can use the setContentView() in the superclass, using a method to return the layout to use.
In this way you can override the layout in the sub class, overriding the method.
For example you can use something like setContentView(getLayoutId()):
public class ConnectionEditActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(getLayoutId()); //pay attention here...
this.connection = connectionParam;
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
}
protected int getLayoutId(){
//....
}
}
And you can override it in other activity, where you can avoid the setContentView method.
public class ConnectionWifiEditActivity extends ConnectionEditActivity{
#Override
protected int getLayoutId(){
return R.layout.connectionwifiedit;
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(); //comment this line
//..
}
}
Just add this to your style (both are needed)
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
and in ConnectionEditActivity you call findViewById BEFORE calling setContentView it will always return null. So your view will be always null.
this.connection = connectionParam;
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
Little trick is to use override fun onPostCreate(savedInstanceState: Bundle?) method in you parent to find views