I'm first using Android Preferences and encountered unexpected problem.
I'm extend DialogPreference class and all works fine except one thing: in method onDialogClosing(boolean positiveResult) I'm receiving false no matter what button I'v pressed.
What I'm doing wrong?
Whole code of the class is listed below.
package edu.kpi.ept.labwork1;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
public class PositivePickerPreference extends DialogPreference {
private static int DEFAULT_VALUE = 0;
private int selectedValue;
private EditText intEdit;
public PositivePickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.setDialogLayoutResource(R.layout.int_pick_pref_dialog);
this.setPositiveButtonText(R.string.preference_ok);
this.setNegativeButtonText(R.string.preference_cancel);
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
intEdit = (EditText) view.findViewById(R.id.intEdit);
selectedValue = getPersistedInt(DEFAULT_VALUE);
intEdit.setText(Integer.toString(selectedValue));
}
public void onClick (DialogInterface dialog, int which) {
super.onClick();
selectedValue = Integer.parseInt(intEdit.getText().toString());
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
persistInt(selectedValue);
}
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
super.onSetInitialValue(restorePersistedValue, defaultValue);
if (restorePersistedValue) {
selectedValue = getPersistedInt(DEFAULT_VALUE);
} else {
selectedValue = (Integer) defaultValue;
persistInt(selectedValue);
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInteger(index, DEFAULT_VALUE);
}
}
Just had this same issue. Its because of the onClick handler:
public void onClick (DialogInterface dialog, int which) {
super.onClick();
selectedValue = Integer.parseInt(intEdit.getText().toString());
}
Remove it, and you won't have the issue. If you need to know the button pressed, then just check the button type in that event handler block. For example
#Override
public void onClick(DialogInterface dialog, int which) {
buttonPress = which;
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (buttonPress == DialogInterface.BUTTON_NEGATIVE) {
String computerName = _etComputerName.getText().toString();
SharedPreferences computers = _context.getSharedPreferences(
"COMPUTERS", 0);
SharedPreferences.Editor editor = computers.edit();
editor.remove(computerName);
editor.commit();
this.callChangeListener(-1);
}
}
Related
This is the TimePreference class which extends DialogPreference
import android.content.Context;
import android.content.res.TypedArray;
import androidx.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
public class TimePreference extends DialogPreference {
private int lastHour=0;
private int lastMinute=0;
private TimePicker picker=null;
public static int getHour(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[0]));
}
public static int getMinute(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[1]));
}
public TimePreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
#Override
protected View onCreateDialogView() {
picker=new TimePicker(getContext());
return(picker);
}
#Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time;
if (restoreValue) {
if (defaultValue==null) {
time=getPersistedString("00:00");
}
else {
time=getPersistedString(defaultValue.toString());
}
}
else {
time=defaultValue.toString();
}
lastHour=getHour(time);
lastMinute=getMinute(time);
}
}
When I use androidx.preference.DialogPreference, it is showing Cannot resolve methods 'onDialogClosed', 'onBindDialogView' in 'DialogPreference' Also, onSetInitialValue method is showing deprecated. I have used PreferenceFragmentCompat instead of PreferenceFragment
I have seen few solutions where it is told to split the TimePreference class into two classes, but I am not getting how exactly that is to be done and what extra settings are to be done in PreferenceFragmentCompat
Can I get a solution to this with a working example.
I am a newbie at android studio and am trying to make a simple todolist app. I have a daily alarm set up using Alarm Manager but I would like the user to be able to change the timing that this daily alarm goes off in the settings page. Therefore, I need a timepicker in preferencescreen and I have learnt that you can do this using custom DialogPreferences.
I have tried to follow this tutorial http://www.infiniteimprob.com/blog/custom-preferences/ but it shows this exceptioncom.example.todolist.TimePickerPreference cannot be cast to androidx.preference.Preference I have a feeling that this is due to compatibility issues because I used the androidx library for my other imports. I think that this will be solved if I were to import the androidx.preference.DialogPreference instead of android.preference.DialogPreference; Can someone tell me how I can go about this change? I have read this answer Difference between DialogPreference before and after AndroidX but I still do not really know how to execute it.
This is my timepickerpreference class as followed on the website:
import android.content.res.TypedArray;
import android.os.Build;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerPreference extends DialogPreference {
private static final int DEFAULT_TIME = 0;
private TimePicker mTimePicker;
private int currentTime;
public TimePickerPreference(Context context, AttributeSet attrs){
super(context, attrs);
setDialogLayoutResource(R.layout.timepickerpreferencelayout);
setPositiveButtonText("ok");
setNegativeButtonText("cancel");
}
private static int getTime(int hour, int minute){
return hour*60*60*1000 + minute*60*1000;
}
private static int getHour(int value){
return (int)(value / (60*60*1000));
}
private static int getMinute(int value){
return (int)(value % (60*60*1000));
}
#Override
protected View onCreateDialogView() {
View view = super.onCreateDialogView();
mTimePicker = (TimePicker) view.findViewById(R.id.timePicker);
mTimePicker.setIs24HourView(true);
if (Build.VERSION.SDK_INT >= 23)
{
mTimePicker.setHour(getHour(currentTime));
mTimePicker.setMinute(getMinute(currentTime));
}
else
{
mTimePicker.setCurrentHour(getHour(currentTime));
mTimePicker.setCurrentMinute(getMinute(currentTime));
}
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener()
{
#Override
public void onTimeChanged(TimePicker timePicker, int hour, int minute)
{
TimePickerPreference.this.currentTime = getTime(hour, minute);
}
});
TextView messageTextView = (TextView) view.findViewById(R.id.messageTextView);
if (getDialogMessage() == null || getDialogMessage().toString().trim().length() == 0)
messageTextView.setVisibility(View.GONE);
messageTextView.setText(getDialogMessage());
return view;
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index)
{
return a.getInt(index, DEFAULT_TIME);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue)
{
if(restorePersistedValue)
{
currentTime = this.getPersistedInt((int) (defaultValue == null ? DEFAULT_TIME : defaultValue));
}
else
{
currentTime = (int) defaultValue;
if (shouldPersist())
persistInt(currentTime);
}
}
#Override
protected void onDialogClosed(boolean positiveResult)
{
if (positiveResult)
persistInt(currentTime);
}
}
I've been working on a messaging app and within the group and private chat, the first message duplicates and then when another message is sent, it's hidden behind the duplicated text until another one is sent and then so on. Can anybody help me with this problem? I'm using Quickblox as a database
ChatMessage Class
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.liftersheaven.messaging.Adapter.ChatMessageAdapter;
import com.liftersheaven.messaging.Common.Common;
import com.liftersheaven.messaging.Holder.QBChatMessagesHolder;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBIncomingMessagesManager;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.exception.QBChatException;
import com.quickblox.chat.listeners.QBChatDialogMessageListener;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.chat.model.QBChatMessage;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.chat.request.QBDialogRequestBuilder;
import com.quickblox.chat.request.QBMessageGetBuilder;
import com.quickblox.chat.request.QBMessageUpdateBuilder;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smackx.muc.DiscussionHistory;
import java.util.ArrayList;
public class ChatMessage extends AppCompatActivity implements
QBChatDialogMessageListener{
QBChatDialog qbChatDialog;
ListView lstChatMessages;
ImageButton submitButton;
EditText edtContent;
ChatMessageAdapter adapter;
int contextMenuIndexClicked = -1;
boolean isEditMode = false;
QBChatMessage editMessage;
Toolbar toolbar;
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId()){
case R.id.chat_group_edit_name:
editNameGroup();
break;
case R.id.chat_group_add_user:
addUser();
break;
case R.id.chat_group_remove_user:
removeUser();
break;
}
return true;
}
private void removeUser() {
Intent intent = new Intent(this,ListUsers.class);
intent.putExtra(Common.UPDATE_DIALOG_EXTRA, qbChatDialog);
intent.putExtra(Common.UPDATE_MODE, Common.UPDATE_REMOVE_MODE);
startActivity(intent);
}
private void addUser() {
Intent intent = new Intent(this,ListUsers.class);
intent.putExtra(Common.UPDATE_DIALOG_EXTRA, qbChatDialog);
intent.putExtra(Common.UPDATE_MODE,Common.UPDATE_ADD_MODE);
startActivity(intent);
}
private void editNameGroup() {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.dialog_edit_group_layout, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(view);
final EditText newName = (EditText) view.findViewById(R.id.edt_group_name);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
qbChatDialog.setName(newName.getText().toString());
QBDialogRequestBuilder requestBuilder = new QBDialogRequestBuilder();
QBRestChatService.updateGroupChatDialog(qbChatDialog, requestBuilder)
.performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog qbChatDialog, Bundle bundle) {
Toast.makeText(ChatMessage.this, "Group name edited", Toast.LENGTH_SHORT);
toolbar.setTitle(qbChatDialog.getName());
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getBaseContext(), ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (qbChatDialog.getType() == QBDialogType.GROUP || qbChatDialog.getType() == QBDialogType.PUBLIC_GROUP)
getMenuInflater().inflate(R.menu.chat_message_group_menu, menu);
return true;
}
#Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
contextMenuIndexClicked = info.position;
switch (item.getItemId()){
case R.id.chat_message_update:
updateMessage();
break;
case R.id.chat_message_delete:
deleteMessage();
break;
}
return true;
}
private void deleteMessage() {
final ProgressDialog deleteDialog = new ProgressDialog(ChatMessage.this);
deleteDialog.setMessage("Please wait...");
deleteDialog.show();
editMessage = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatDialog.getDialogId())
.get(contextMenuIndexClicked);
QBRestChatService.deleteMessage(editMessage.getId(),false).performAsync(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
retrieveAllMessage();
deleteDialog.dismiss();
}
#Override
public void onError(QBResponseException e) {
}
});
}
private void updateMessage() {
editMessage = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatDialog.getDialogId())
.get(contextMenuIndexClicked);
edtContent.setText(editMessage.getBody());
isEditMode = true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
getMenuInflater().inflate(R.menu.chat_message_content_menu, menu);
}
#Override
protected void onDestroy(){
super.onDestroy();
qbChatDialog.removeMessageListrener(this);
}
#Override
protected void onStop(){
super.onStop();
qbChatDialog.removeMessageListrener(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_message);
initViews();
initChatDialogs();
retrieveAllMessage();
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!edtContent.getText().toString().isEmpty()){
if (!isEditMode) {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody(edtContent.getText().toString());
chatMessage.setSenderId(QBChatService.getInstance().getUser().getId());
chatMessage.setSaveToHistory(true);
try {
qbChatDialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
if (qbChatDialog.getType() == QBDialogType.PRIVATE){
QBChatMessagesHolder.getInstance().putMessage(qbChatDialog.getDialogId(),chatMessage);
ArrayList<QBChatMessage> messages = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(chatMessage.getDialogId());
adapter = new ChatMessageAdapter(getBaseContext(),messages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
edtContent.setText("");
edtContent.setFocusable(true);
}else
{
final ProgressDialog updateDialog = new ProgressDialog(ChatMessage.this);
updateDialog.setMessage("Please wait...");
updateDialog.show();
QBMessageUpdateBuilder messageUpdateBuilder = new QBMessageUpdateBuilder();
messageUpdateBuilder.updateText(edtContent.getText().toString()).markDelivered().markRead();
QBRestChatService.updateMessage(editMessage.getId(),qbChatDialog.getDialogId(),messageUpdateBuilder)
.performAsync(new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
retrieveAllMessage();
isEditMode = false;
updateDialog.dismiss();
edtContent.setText("");
edtContent.setFocusable(true);
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(getBaseContext(),""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
}
});
}
private void retrieveAllMessage() {
QBMessageGetBuilder messageGetBuilder = new QBMessageGetBuilder();
messageGetBuilder.setLimit(500);
if(qbChatDialog != null){
QBRestChatService.getDialogMessages(qbChatDialog,messageGetBuilder).performAsync(new QBEntityCallback<ArrayList<QBChatMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatMessage> qbChatMessages, Bundle bundle) {
QBChatMessagesHolder.getInstance().putMessages(qbChatDialog.getDialogId(),qbChatMessages);
adapter = new ChatMessageAdapter(getBaseContext(),qbChatMessages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
private void initChatDialogs() {
qbChatDialog = (QBChatDialog)getIntent().getSerializableExtra(Common.DIALOG_EXTRA);
qbChatDialog.initForChat(QBChatService.getInstance());
QBIncomingMessagesManager incomingMessage = QBChatService.getInstance().getIncomingMessagesManager();
incomingMessage.addDialogMessageListener(new QBChatDialogMessageListener() {
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
}
#Override
public void processError(String s, QBChatException e, QBChatMessage qbChatMessage, Integer integer) {
}
});
if (qbChatDialog.getType() == QBDialogType.PUBLIC_GROUP || qbChatDialog.getType() == QBDialogType.GROUP){
DiscussionHistory discussionHistory = new DiscussionHistory();
discussionHistory.setMaxStanzas(0);
qbChatDialog.join(discussionHistory, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
}
#Override
public void onError(QBResponseException e) {
Log.d("ERROR", ""+e.getMessage());
}
});
}
qbChatDialog.addMessageListener(this);
toolbar.setTitle(qbChatDialog.getName());
setSupportActionBar(toolbar);
}
private void initViews() {
lstChatMessages = (ListView)findViewById(R.id.messages_list);
submitButton = (ImageButton)findViewById(R.id.send);
edtContent = (EditText)findViewById(R.id.edt_content);
registerForContextMenu(lstChatMessages);
toolbar = (Toolbar)findViewById(R.id.chatmessage_toolbar);
}
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
QBChatMessagesHolder.getInstance().putMessage(qbChatMessage.getDialogId(),qbChatMessage);
ArrayList<QBChatMessage> messages = QBChatMessagesHolder.getInstance().getChatMessagesByDialogId(qbChatMessage.getDialogId());
adapter = new ChatMessageAdapter(getBaseContext(),messages);
lstChatMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void processError(String s, QBChatException e, QBChatMessage qbChatMessage, Integer integer) {
Log.e("ERROR",""+e.getMessage());
}
}
ChatMessageAdapter Class
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.github.library.bubbleview.BubbleTextView;
import com.liftersheaven.messaging.Holder.QBUsersHolder;
import com.liftersheaven.messaging.R;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.model.QBChatMessage;
import java.util.ArrayList;
public class ChatMessageAdapter extends BaseAdapter {
private Context context;
private ArrayList<QBChatMessage> qbChatMessages;
public ChatMessageAdapter(Context context, ArrayList<QBChatMessage> qbChatMessages){
this.context = context;
this.qbChatMessages = qbChatMessages;
}
#Override
public int getCount() {
return qbChatMessages.size();
}
#Override
public Object getItem(int position) {
return qbChatMessages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (qbChatMessages.get(position).getSenderId().equals(QBChatService.getInstance().getUser().getId())){
view = inflater.inflate(R.layout.list_message_send, null);
BubbleTextView bubbleTextView = (BubbleTextView)view.findViewById(R.id.message_content);
bubbleTextView.setText(qbChatMessages.get(position).getBody());
}
else{
view = inflater.inflate(R.layout.list_recieve_message, null);
BubbleTextView bubbleTextView = (BubbleTextView)view.findViewById(R.id.message_recieve);
bubbleTextView.setText(qbChatMessages.get(position).getBody());
TextView txtName = (TextView)view.findViewById(R.id.message_user);
txtName.setText(QBUsersHolder.getInstance().getUserById(qbChatMessages.get(position).getSenderId()).getFullName());
}
}
return view;
}
}
QBChatMessagesHolder Class
import com.quickblox.chat.model.QBChatMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class QBChatMessagesHolder {
private static QBChatMessagesHolder instance;
private HashMap<String,ArrayList<QBChatMessage>> qbChatMessageArray;
public static synchronized QBChatMessagesHolder getInstance(){
QBChatMessagesHolder qbChatMessagesHolder;
synchronized (QBChatMessagesHolder.class){
if (instance == null)
instance = new QBChatMessagesHolder();
qbChatMessagesHolder = instance;
}
return qbChatMessagesHolder;
}
private QBChatMessagesHolder(){
this.qbChatMessageArray = new HashMap<>();
}
public void putMessages(String dialogId,ArrayList<QBChatMessage> qbChatMessages){
this.qbChatMessageArray.put(dialogId,qbChatMessages);
}
public void putMessage(String dialogId,QBChatMessage qbChatMessage){
List<QBChatMessage> lstResult = (List)this.qbChatMessageArray.get(dialogId);
lstResult.add(qbChatMessage);
ArrayList<QBChatMessage> lstAdded = new ArrayList(lstResult.size());
lstAdded.addAll(lstResult);
putMessages(dialogId, lstAdded);
}
public ArrayList<QBChatMessage> getChatMessagesByDialogId(String dialogId){
return (ArrayList<QBChatMessage>)this.qbChatMessageArray.get(dialogId);
}
}
I want to evaluate a Dialog under Android.
My problem is that the Dialog does not wait
with returning a value until I pressed a
button. And when I use a Semaphore the
program hangs at Semaphore.acquire().
Why does it hang at Semaphore.acquire()?
Can you see where I go wrong?
Here is the main activity
package com.example.modaldialog;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDialog meinDialog = new mDialog(this);
if (meinDialog.ShowMyModalDialog() == 1)
Toast.makeText(this, "Pressed Button 1",
Toast.LENGTH_LONG).show();
}
}
and here the dialog class
package com.example.modaldialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
import java.util.concurrent.Semaphore;
import android.app.Activity;
import java.lang.Runnable;
public class mDialog
{
int pressedButtonID;
Activity act;
private final Semaphore dialogSemaphore;
mDialog(Activity act_in)
{
act = act_in;
dialogSemaphore = new Semaphore(0, true);
};
final Runnable mMyDialog = new Runnable()
{
public void run()
{
AlertDialog errorDialog = new
AlertDialog.Builder(act).create();
errorDialog.setMessage("Press a Button!");
errorDialog.setButton("Button2", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 2;
dialogSemaphore.release();
}
});
errorDialog.setButton2("Button1", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 1;
dialogSemaphore.release();
}
});
errorDialog.setCancelable(false);
errorDialog.show();
}
};
public int ShowMyModalDialog() //should be called from non-UI thread
{
pressedButtonID = 0;
act.runOnUiThread(mMyDialog);
try
{
dialogSemaphore.acquire();
}
catch (InterruptedException e)
{
}
return(pressedButtonID);
}
}
I am not much aware about the Semaphore but you can achieve the same with Interface. I have updated your code please find it below,
package com.example.modaldialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class mDialog
{
int pressedButtonID=0;
private HandleDialogEvent dialogEvent;
mDialog(HandleDialogEvent dialogEvent)
{
this.dialogEvent = dialogEvent;
}
public void ShowMyModalDialog() //should be called from non-UI thread
{
pressedButtonID = 0;
AlertDialog errorDialog = new
AlertDialog.Builder(act).create();
errorDialog.setMessage("Press a Button!");
errorDialog.setButton("Button2", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 2;
dialogEvent.getDialogId(pressedButtonID);
}
});
errorDialog.setButton2("Button1", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
pressedButtonID = 1;
dialogEvent.getDialogId(pressedButtonID);
}
});
errorDialog.setCancelable(false);
errorDialog.show();
}
public interface HandleDialogEvent{
public void getDialogId(int Id);
}
}
I have 3 editText fields of the type Number(Decimal). Two of which have onTextChanged listeners supposed to carry out mathematical functions when any integer is entered. My problem is the edittext fields with the listeners have the cursors stuck on the starting position i.e if i try to type 25, it ends up being 52.
CODE:
package com.example.Prototype;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class productsFragmentTab extends Fragment {
Button newProduct, clear;
Spinner productList;
EditText quantity, unit, total;
String invoice_id;
ShowAlert alert = new ShowAlert();
int unitcost, totalcost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.product_layout, container, false);
newProduct = (Button)rootView.findViewById(R.id.button4);
clear = (Button)rootView.findViewById(R.id.button5);
productList = (Spinner)rootView.findViewById(R.id.spinner2);
quantity = (EditText)rootView.findViewById(R.id.editText5);
unit = (EditText)rootView.findViewById(R.id.editText7);
total = (EditText)rootView.findViewById(R.id.editText8);
invoice_id = GlobalApp.data().id;
newProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Save current records in array
//Clear all textboxes
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//clear all textboxes
}
});
unit.addTextChangedListener(new TextWatcher() {
boolean isChangingByCode = false;
#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 (isChangingByCode) {
return;
}
String qty = quantity.getText().toString();
if (qty.matches("")) {
} else {
totalcost = Integer.parseInt(qty) * Integer.parseInt(unit.getText().toString());
isChangingByCode = true;
total.setText(Integer.toString(totalcost));
isChangingByCode = false;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
total.addTextChangedListener(new TextWatcher() {
boolean isChangingByCode = false;
#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 (isChangingByCode) {
return;
}
String qty = quantity.getText().toString();
if (qty.matches("")) {
} else {
unitcost = Integer.parseInt(total.getText().toString()) / Integer.parseInt(qty);
isChangingByCode = true;
unit.setText(Integer.toString(unitcost));
isChangingByCode = false;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
return rootView;
}
}
Use setSelection() method to set cursor position at last.
Add following code:
total.setText(Integer.toString(totalcost));
total.setSelection(total.getText().length());
in place of total.setText(Integer.toString(totalcost)); in onTextChanged() callback.
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (isChangingByCode) {
return;
}
String qty = quantity.getText().toString();
if (qty.matches("")) {
} else {
totalcost = Integer.parseInt(qty) * Integer.parseInt(unit.getText().toString());
isChangingByCode = true;
total.setText(Integer.toString(totalcost));
total.setSelection(total.getText().length());
isChangingByCode = false;
}
}