How to add smileys to chat in android - java

I am developing a chat application in which I want to add smiley support to it. But I am not being able to use it.
I have gone through many codes but the symbols are not changing to smileys.
Here is my code...
private static final Factory spannableFactory = Spannable.Factory
.getInstance();
private static final Map<Pattern, Integer> emoticons = new HashMap<Pattern, Integer>();
static {
addPattern(emoticons, ":)", R.drawable.emo_im_happy);
addPattern(emoticons, ":-)", R.drawable.emo_im_happy);
// ...
}
private static void addPattern(Map<Pattern, Integer> map, String smile,
int resource) {
map.put(Pattern.compile(Pattern.quote(smile)), resource);
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.messaging_screen); // messaging_screen);
messageHistoryText = (EditText) findViewById(R.id.messageHistory);
messageText = (EditText) findViewById(R.id.message);
messageText.requestFocus();
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
}
public void appendToMessageHistory(String paramString1, String paramString2) {
if ((paramString1 != null) && (paramString2 != null)) {
if (paramString1.toString().equals(this.friend.userName.toString())) {
appendColoredText(this.messageHistoryText,paramString1 + ":\n", Layout.Alignment.ALIGN_NORMAL,-16711936);
appendColoredText(this.messageHistoryText, getSmiledText(this, paramString2) + "\n", Layout.Alignment.ALIGN_NORMAL, -16711936);
} else {
appendColoredText(this.messageHistoryText, "you:\n",Layout.Alignment.ALIGN_OPPOSITE, -65536);
appendColoredText(this.messageHistoryText, getSmiledText(this, paramString2) + "\n",Layout.Alignment.ALIGN_OPPOSITE, -65536);
}
}
}
public static boolean addSmiles(Context context, Spannable spannable) {
boolean hasChanges = false;
for (Entry<Pattern, Integer> entry : emoticons.entrySet()) {
Matcher matcher = entry.getKey().matcher(spannable);
while (matcher.find()) {
boolean set = true;
for (ImageSpan span : spannable.getSpans(matcher.start(),
matcher.end(), ImageSpan.class))
if (spannable.getSpanStart(span) >= matcher.start()
&& spannable.getSpanEnd(span) <= matcher.end())
spannable.removeSpan(span);
else {
set = false;
break;
}
if (set) {
hasChanges = true;
spannable.setSpan(new ImageSpan(context, entry.getValue()), matcher.start(), matcher.end(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
return hasChanges;
}
public static Spannable getSmiledText(Context context, CharSequence text) {
Spannable spannable = spannableFactory.newSpannable(text);
addSmiles(context, spannable);
return spannable;
}
public static void appendColoredText(EditText paramEditText,String paramString, Layout.Alignment paramAlignment, int paramInt) {
int i = paramEditText.getText().length();
paramEditText.append(paramString);
int j = paramEditText.getText().length();
Editable localEditable = paramEditText.getText();
localEditable.setSpan(new ForegroundColorSpan(paramInt), i, j, 0);
localEditable.setSpan(new AlignmentSpan.Standard(paramAlignment), i, j, 0);
//localEditable.setSpan(new BackgroundColorSpan(back), i, j, 0);
}
I am using this code with Static block so that the emoticons should be displayed but they are not being displayed. So what should I do to get it done?
Thank You

Related

How to if conditions between two intents in Android Studio?

Рow to use if statements between two intent activities? I have two different activities collecting data from external sensors. I would like to control some GPIO pins of Activity1 based on the sensor values of Activity2.
Activity 1
public class RealTimeData extends AppCompatActivity {
private static final String TAG = "sensor_data";
private static final String FRAGMENT_DIALOG = "dialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_data);
Resources res = getResources();
GetAllResources();
OpenSerialPort();
}
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private void GetAllResources() {
pressure1 = (TextView) findViewById(R.id.pressure);
temp1 = (TextView) findViewById(R.id.temperature);
co2ppm1 = (TextView) findViewById(R.id.co2);
humidity1 = (TextView) findViewById(R.id.humidity);
pressure1data = (TextView) findViewById(R.id.pressureData);
temp1data = (TextView) findViewById(R.id.temperatureData);
co2ppm1data = (TextView) findViewById(R.id.co2Data);
humidity1data = (TextView) findViewById(R.id.humidityData);
}
private sensorDataApplication sensordata = new sensorDataApplication();
private UartApplication[] mSerialport = {null, null};
private void SetValues()
{
TextView tv =(TextView) findViewById(R.id.pressureData);
tv.setText(String.valueOf(sensordata.get_pressure_value(0)));
tv =(TextView) findViewById(R.id.temperatureData);
tv.setText(String.valueOf(sensordata.get_temperature_value(0)));
tv =(TextView) findViewById(R.id.co2Data);
tv.setText(String.valueOf(sensordata.get_co2_value(0)));
tv =(TextView) findViewById(R.id.humidityData);
tv.setText(String.valueOf(sensordata.get_humidity_value(0)));
}
private void OpenSerialPort() {
new sensorDataApplication();
try {
int i =0;
for(String devicePath : Configs.uartdevicePath) {
mSerialport[i] = new UartApplication(new File(devicePath), mReaderCallback);
i++;
}
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_serial))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_uart_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private final UartApplication.ReaderCallback mReaderCallback=
new UartApplication.ReaderCallback() {
#Override
public void onDataReceived(final byte[] buffer, final int size) {
runOnUiThread(new Runnable() {
public void run() {
if (pressure1 != null) {
String received_str = new String(buffer, 0, size);
//uartRx.append(received_str);
sensordata.parse_and_update_sensordata(received_str);
SetValues();
Log.e(TAG,"received packet "+received_str);
}
}
});
}
};
TextWatcher mUartTxCallback = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(max(start,before) < s.length()) {
String changedStr = s.toString().substring(max(start, before), s.length());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable var1) {
}
};
private void CloseSerialPort(int idx)
{
mSerialport[idx].closeSerialPort();
}
private void WriteSerialPort(String writeString, int idx)
{
mSerialport[idx].writeData(writeString);
}
private static byte[] hexStringToByteArray(String s) {
int len = s.length();
s.toUpperCase();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
private static String toHexString(byte[] ba) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < ba.length; i++)
str.append(String.format("%02x", ba[i]));
return str.toString().toUpperCase();
}
private TextView pressure1;
private TextView temp1;
private TextView co2ppm1;
private TextView humidity1;
private TextView pressure1data;
private TextView temp1data;
private TextView co2ppm1data;
private TextView humidity1data;
}
Activity 2
public class ManualControl extends AppCompatActivity {
static {
System.loadLibrary("native-lib");
}
List<gpioApplication> mGPIO = new ArrayList<>();
private static final String FRAGMENT_DIALOG = "dialog";
private int[] mGPIOList = null;
private CheckBox[] cbGPIO;
private final gpioApplication.InterruptCallback mGPIOCallback =
new gpioApplication.InterruptCallback() {
#Override
public void onDataReceived(final int GPIOnum, final int value) {
runOnUiThread(new Runnable() {
public void run() {
//Do Nothing
CheckBox cbnGPIO = GetCheckBoxGpio(GPIOnum);
cbnGPIO.setOnCheckedChangeListener(null);
if (cbnGPIO != null)
cbnGPIO.setChecked(value > 0 ? true : false);
cbnGPIO.setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
});
}
};
private final CompoundButton.OnCheckedChangeListener mGPIOCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
int GPIOValue = buttonView.isChecked() == true ? 1 : 0;
if (gpioID < mGPIOList.length) {
gpioApplication gpio = mGPIO.get(gpioID);
gpio.GPIOWrite(GPIOValue);
}
}
};
private CheckBox GetCheckBoxGpio(int GPIOnum) {
if (GPIOnum < mGPIOList.length)
return cbGPIO[GPIOnum];
return null;
}
private void GetAllResources() {
cbGPIO = new CheckBox[20];
cbGPIO[9] = (CheckBox) findViewById(R.id.checkBox_GPIO92);
cbGPIO[0] = (CheckBox) findViewById(R.id.checkBox_GPIO16);
cbGPIO[1] = (CheckBox) findViewById(R.id.checkBox_GPIO17);
cbGPIO[6] = (CheckBox) findViewById(R.id.checkBox_GPIO69);
cbGPIO[2] = (CheckBox) findViewById(R.id.checkBox_GPIO23);
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
GetCheckBoxGpio(i).setText(Integer.toString(mGPIOList[i]));
GetCheckBoxGpio(i).setEnabled(true);
}
}
}
private final CompoundButton.OnCheckedChangeListener mIntCheckBoxCallback =
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//do stuff
int gpioID = Integer.parseInt(buttonView.getHint().toString());
boolean IntValue = buttonView.isChecked();
if (gpioID < mGPIOList.length) {
/*Use IntValue Re-configure GPIO Interrupt Here*/
mGPIO.get(gpioID).ConfigureInterrupt(IntValue);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_control);
try {
mGPIOList = gpio_list;
GetAllResources();
for (int i = 0; i < mGPIOList.length; i++) {
GPIOOpen(i);
}
ConfigureCallbacks();
GetAllResources();
} catch (Exception e) {
ErrorMessage.newInstance(e.getLocalizedMessage())
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
}
private void ConfigureCallbacks() {
ConfigureGPIOCheckboxCallback();
}
private void ConfigureGPIOCheckboxCallback() {
for (int i = 0; i < mGPIOList.length; i++) {
if (i == 9 || i == 0 || i == 1 || i == 6 || i == 2) {
cbGPIO[i].setOnCheckedChangeListener(mGPIOCheckBoxCallback);
}
}
}
private void GPIOOpen(int GPIOnum) {
if (GPIOnum == 9 || GPIOnum == 0 || GPIOnum == 1 || GPIOnum == 6 || GPIOnum == 2) {
mGPIO.add(new gpioApplication());
try {
mGPIO.get(GPIOnum).GPIOOpen(GPIOnum, mGPIOList[GPIOnum], mGPIOCallback);
} catch (SecurityException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (IOException e) {
ErrorMessage.newInstance(getString(R.string.error_unknown))
.show(getFragmentManager(), FRAGMENT_DIALOG);
} catch (InvalidParameterException e) {
ErrorMessage.newInstance(getString(R.string.error_gpio_config))
.show(getFragmentManager(), FRAGMENT_DIALOG);
}
} else {
mGPIO.add(null);
}
}
}
In the above codes the GPIO pins must be controlled by the co2ppm1 sensor values (If the co2ppm1 sensor value is above 2000, it must turn ON GPIO 9 pin).

onTextChangedListener goes into loop, but only on first ListView element, any following elements don't loop

I have a moneyConversion class which converts strings as I type them into an EditText which there are multiple of due to being contained in a listview. The conversion works fine for the EditText, but for some reason, the first list item always goes into a loop and hangs when typing something in, where as all other identical EditText boxes work absolutely fine and format without issue.
Here's my adapter.
public class DietyAmountAdapter extends ArrayAdapter {
Context context;
int layoutResourceId;
ArrayList<Dieties> data = null;
int counterTotal;
int currentlyActive;
public DietyAmountAdapter(Context context, int layoutResourceId, ArrayList<Dieties> data){
super(context, layoutResourceId, data);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.data = data;
}
public void addViews(){
SharedPreferences sharedPref = ((Activity) context).getPreferences(Context.MODE_PRIVATE);
currentlyActive = 0;
this.clear();
for(int i = 1; i <= counterTotal; i++) {
boolean a = sharedPref.getBoolean(Integer.toString(i), false);
if (a) {
currentlyActive = currentlyActive + 1;
}
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View ListItem = convertView;
Holder holder;
final Dieties Diety = data.get(position);
if (ListItem == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
ListItem = inflater.inflate(layoutResourceId, parent, false);
holder = new Holder();
holder.banner = (ImageView) ListItem.findViewById(R.id.DietyBanner);
holder.title = (TextView) ListItem.findViewById(R.id.titleText);
holder.text1 = (EditText) ListItem.findViewById(R.id.text1Amount);
holder.text2 = (EditText) ListItem.findViewById(R.id.text2Amount);
holder.text1Text = (TextView) ListItem.findViewById(R.id.text1Text);
holder.text2Text = (TextView) ListItem.findViewById(R.id.text2Text);
ListItem.setTag(holder);
} else {
holder = (Holder) ListItem.getTag();
}
MyTextWatcher text2Watcher = (new MyTextWatcher() {
public Holder holder;
public void setView(Holder newHolder){
holder = newHolder;
}
#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 (holder.text2.isFocused()) {
holder.text2.removeTextChangedListener(this);
String raw = moneyConversion.unformatToString(s.toString());
double text1Value = moneyConversion.gettext1Value(Double.parseDouble(raw));
holder.text2.setText(moneyConversion.formatLive(raw));
holder.text1.setText(moneyConversion.format(text1Value));
holder.text2.addTextChangedListener(this);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
MyTextWatcher text1Watcher = (new MyTextWatcher() {
public Holder holder;
public void setView(Holder newHolder){
holder = newHolder;
}
#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 (holder.text1.isFocused()) {
holder.text1.removeTextChangedListener(this);
String text1Value = moneyConversion.unformatToString(s.toString());
String formattedValue = moneyConversion.formatLive(text1Value);
double text2Value = moneyConversion.gettext2Value(Double.parseDouble(text1Value));
holder.text1.setText(formattedValue);
holder.text2.setText(moneyConversion.format(text2Value));
holder.text1.addTextChangedListener(this);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
HolderOnFocusChangeListener text1FocusListener = new HolderOnFocusChangeListener() {
public DietyAmountAdapter.Holder holder;
public void setHolder(Holder newHolder){
holder = newHolder;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Timer timer = new Timer();
// TimerTask t1 = new TimerTask() {
// #Override
// public void run() {
// holder.text1.clearFocus();
// }
// };
if (hasFocus){
holder.text1.setBackgroundColor(Color.parseColor("#5aa0ce"));
holder.text1Text.setBackgroundColor(Color.parseColor("#5aa0ce"));
holder.text1.setSelection(holder.text1.getText().length());
}
if (!hasFocus) {
if (!holder.text1.getText().toString().isEmpty()) {
holder.text1.setSelection(holder.text1.getText().length());
// holder.text2.setText(moneyConversion.format());
}
holder.text1.setBackgroundColor(Color.parseColor("#424242"));
holder.text1Text.setBackgroundColor(Color.parseColor("#424242"));
// timer.scheduleAtFixedRate(runOnUiThread(t1), 1, 500);
}
}
};
HolderOnFocusChangeListener text2FocusListener = new HolderOnFocusChangeListener() {
public DietyAmountAdapter.Holder holder;
public void setHolder(Holder newHolder){
holder = newHolder;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Timer timer = new Timer();
// TimerTask t2 = new TimerTask() {
// #Override
// public void run() {
// holder.text2.clearFocus();
// }
// };
if (hasFocus){
holder.text2.setBackgroundColor(Color.parseColor("#5aa0ce"));
holder.text2Text.setBackgroundColor(Color.parseColor("#5aa0ce"));
holder.text2.setSelection(holder.text2.getText().length());
}
if (!hasFocus) {
if (!holder.text2.getText().toString().isEmpty()) {
holder.text2.setSelection(holder.text2.getText().length());
}
holder.text2.setBackgroundColor(Color.parseColor("#424242"));
holder.text2Text.setBackgroundColor(Color.parseColor("#424242"));
}
}
};
text2FocusListener.setHolder(holder);
text1FocusListener.setHolder(holder);
text1Watcher.setView(holder);
text2Watcher.setView(holder);
holder.text2.addTextChangedListener(text2Watcher);
holder.text1.addTextChangedListener(text1Watcher);
holder.text2.setOnFocusChangeListener(text2FocusListener);
holder.text1.setOnFocusChangeListener(text1FocusListener);
holder.title.setText(Diety.title);
holder.banner.setImageResource(Diety.banner);
return ListItem;
}
static class Holder {
ImageView banner;
TextView title;
EditText text1;
EditText text2;
TextView text2Text;
TextView text1Text;
}
}
Here's my moneyConversion class:
public class moneyConversion {
public int currentlyActive;
public int counterTotal;
Context context;
public static double gettext1Value(double value){
double newValue = (value / 1.05);
return newValue;
}
public static double gettext2Value(double value){
double newValue = (value * 1.05);
return newValue;
}
public static String format(double value){
DecimalFormat df = new DecimalFormat();
df.applyPattern("###,###,###,###.##");
String formattedValue = df.format(value);
Log.d(TAG, formattedValue);
return formattedValue;
}
public static String formatLive(String s) {
if (s.endsWith(".")) {
return s;
}
DecimalFormat df = new DecimalFormat();
df.applyPattern("###,###,###,###.##");
Double value = Double.parseDouble(s);
String formattedValue = df.format(value);
// Log.d(TAG, formattedValue);
return formattedValue;
}
public static double unformat(String s){
if (s != null && s.isEmpty() ){
return 0;
}
String string = s.replace(",", "");
if (string.isEmpty()) {
return 0;
}
// if (string.equals(".")){
// return Double.parseDouble("0");
// }
return Double.parseDouble(string);
}
public static String unformatToString(String s){
if (s != null && s.isEmpty() ){
return "0";
}
String string = s.replace(",", "");
if (string.isEmpty()) {
return "0";
}
// if (string.equals(".")){
// return Double.parseDouble("0");
// }
return string;
}
}
Write your textchangeListener inside if (ListItem == null) { condition block, it will work.
What actually happening in your case is whenever you scroll your listview on change listener will call for each and every row that is visible.

Cannot set value to textview in runonuithread

public class PerformanceDashboard extends MotherActivity {
String dashboardData;
int SELECTED_PAGE, SEARCH_TYPE, TRAY_TYPE;
List<String[]> cachedCounterUpdates = new ArrayList<String[]>();
List<DasDetails> docList = new ArrayList<DasDetails>();
ListView listViewDashboard;
DataAdapter dataAdap = new DataAdapter();
TextView noOfItems, userCount, totalLoginTime;
int itemsTotal = 0, userTotal = 0, totalTime = 0;
String KEYWORD = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (App.isTestVersion) {
Log.e("actName", "StoreOut");
}
if (bgVariableIsNull()) {
this.finish();
return;
}
setContentView(R.layout.dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setProgressBarIndeterminateVisibility(false);
lytBlocker = (LinearLayout) findViewById(R.id.lyt_blocker);
listViewDashboard = (ListView) findViewById(R.id.dashboard_listview);
noOfItems = ((TextView) findViewById(R.id.noOfItems));
userCount = ((TextView) findViewById(R.id.userCount));
totalLoginTime = ((TextView) findViewById(R.id.totalLoginTime));
new DataLoader().start();
listViewDashboard.setAdapter(dataAdap);
System.out.println("PerformanceDashboard. onCreate processOutData() -- item total " + itemsTotal); //0 i am not getting that adapter value i.e. 6
System.out.println("PerformanceDashboard. onCreate processOutData() -- user total " + userTotal); //0 i am not getting that adapter value i.e. 4
System.out.println("PerformanceDashboard. onCreate processOutData() -- total total " + totalTime); //0 i am not getting that adapter value i.e. 310
}
private class DataAdapter extends BaseAdapter {
#Override
public int getCount() {
return docList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.dashboard_item, null);
final DasDetails item = docList.get(position);
((TextView) convertView.findViewById(R.id.cMode))
.setText(item.cMode);
((TextView) convertView.findViewById(R.id.noOfItems))
.setText(item.totPickItemCount);
((TextView) convertView.findViewById(R.id.userCount))
.setText(item.userCount);
((TextView) convertView.findViewById(R.id.totalLoginTime))
.setText(item.totLoginTime);
TextView textView = ((TextView) convertView
.findViewById(R.id.avgSpeed));
Double s = Double.parseDouble(item.avgPickingSpeed);
textView.setText(String.format("%.2f", s));
if (position == 0 || position == 2 || position == 4) {
convertView.setBackgroundColor(getResources().getColor(
R.color.hot_pink));
} else if (position == 1 || position == 3 || position == 5) {
convertView.setBackgroundColor(getResources().getColor(
R.color.lightblue));
}
return convertView;
}
}
class ErrorItem {
String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public ErrorItem(HashMap<String, String> row) {
cMode = row.get(XT.MODE);
dDate = row.get(XT.DATE);
userCount = row.get(XT.USER_COUNT);
totLoginTime = row.get(XT.TOT_LOGIN_TIME);
totPickItemCount = row.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = row.get(XT.AVG_PICKING_SPEED);
}
}
private class DataLoader extends Thread {
#Override
public void run() {
super.run();
System.out.println("DataLoader dashboard");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair(C.PRM_IDX, C.GET_SUMMARY));
param.add(new BasicNameValuePair(C.PRM_HDR_DATA, "2016-07-04")); // yyyy-mm-dd
toggleProgressNoUINoBlock(true);
final String result = callService(C.WS_ST_PERFORMANCE_DASHBOARD,
param);
if (!App.validateXmlResult(actContext, null, result, true))
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Runnable r = new Runnable() {
#Override
public void run() {
dataAdap.notifyDataSetChanged();
toggleProgressNoUINoBlock(false);
}
};
dashboardData = result;
processOutData(r);
}
});
}
}
private String callService(String serviceName, List<NameValuePair> params) {
String result = ws.callService(serviceName, params);
return result;
}
private void processOutData(final Runnable rAfterProcessing) {
if (dashboardData == null || dashboardData.length() == 0)
return;
new Thread() {
#Override
public void run() {
super.run();
final List<HashMap<String, String>> dataList = XMLfunctions
.getDataList(dashboardData, new String[] { XT.MODE,
XT.DATE, XT.USER_COUNT, XT.TOT_LOGIN_TIME,
XT.TOT_PICK_ITEM_COUNT, XT.AVG_PICKING_SPEED });
final List<DasDetails> tempList = new ArrayList<DasDetails>();
for (int i = 0; i < dataList.size(); i++) {
int pos = docExists(tempList, dataList.get(i).get(XT.MODE));
if (pos == -1) {
if (SEARCH_TYPE == 0
|| KEYWORD.equals("")
|| (SEARCH_TYPE == 1 && dataList.get(i)
.get(XT.CUST_NAME).contains(KEYWORD))
|| (SEARCH_TYPE == 2 && dataList.get(i)
.get(XT.DOC_NO).contains(KEYWORD))) {
DasDetails doc = new DasDetails(dataList.get(i));
int cachePos = getPosInCachedCounterUpdates(doc.cMode);
if (cachePos != -1) {
if (cachedCounterUpdates.get(cachePos)[1]
.equals(doc.dDate))
cachedCounterUpdates.remove(cachePos);
else
doc.dDate = cachedCounterUpdates
.get(cachePos)[1];
}
tempList.add(doc);
pos = tempList.size() - 1;
}
}
if (pos == -1)
continue;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
docList = tempList;
rAfterProcessing.run();
logit("processOutData", "Processing OVER");
}
});
for (int i = 0; i < docList.size(); i++) {
itemsTotal = itemsTotal+ Integer.parseInt(docList.get(i).totPickItemCount);
userTotal = userTotal + Integer.parseInt(docList.get(i).userCount);
totalTime = totalTime + Integer.parseInt(docList.get(i).totLoginTime);
}
System.out.println("PerformanceDashboard.processOutData() -- fINAL item TOTAL " + itemsTotal); // 6 i have data here but i need this data in my oncreate but not getting why?????
System.out.println("PerformanceDashboard.processOutData() -- userTotal TOTAL " + userTotal); //4
System.out.println("PerformanceDashboard.processOutData() -- totalTime TOTAL " + totalTime); //310
noOfItems.setText(itemsTotal); // crashing with null pointer exception
// userCount.setText(userTotal);
// totalLoginTime.setText(totalTime);
};
}.start();
}
private class DasDetails {
public String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public DasDetails(HashMap<String, String> data) {
cMode = data.get(XT.MODE);
dDate = data.get(XT.DATE);
userCount = data.get(XT.USER_COUNT);
totLoginTime = data.get(XT.TOT_LOGIN_TIME);
totPickItemCount = data.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = data.get(XT.AVG_PICKING_SPEED);
}
}
public Integer docExists(List<DasDetails> list, String docNo) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).cMode.equals(docNo))
return i;
}
return -1;
}
private int getPosInCachedCounterUpdates(String docNo) {
for (int i = 0; i < cachedCounterUpdates.size(); i++) {
if (cachedCounterUpdates.get(i)[0].equals(docNo))
return i;
}
return -1;
}
}
This is the above code please go through it and let me know if any clarifications are required. I cannot able to set "itemsTotal" value to "noOfIttems" textview. I have added the comments. Please help me in solving this issue.
Thanks in advance.
Please check your noOfItems textView's id. TextView is null.

Sharing Intent Not working Properly

I have one quote application. I have implemented share and copy function in it. I am facing issue is that I am not getting shared first time sharing quote. Means if there 50 quote in list and if I try to share any quote from list than it is not sharing anything. after that if I move on another quote and try to sharing than its working fine. I have same issue in copy function also. I also face some time issue like if I share quote number 50 than its sharing another number quote. Please help me for solve the bug. Thanks
My Activity for it is like below.
public class QuoteDialogActivity extends Activity {
DAO db;
static final String KEY_ID = "_quid";
static final String KEY_TEXT = "qu_text";
static final String KEY_AUTHOR = "au_name";
static final String KEY_PICTURE = "au_picture";
static final String KEY_PICTURE_SDCARD = "au_picture_sdcard";
static final String KEY_FAVORITE = "qu_favorite";
static final String KEY_WEB_ID = "au_web_id";
ArrayList<HashMap<String, String>> quotesList;
HashMap<String, String> map;
ImageButton btnnext,btnprev,star,copy;
int pos,lstcount = 0;
ScrollView ll_quote;
String quote_id;
TextView text;
String quText, quAuthor, quPicture, quFavorite,quoteShare;
int auPictureSDCard;
String isFavorite;
String auPictureDir;
String siteUrl;
private ImageLoader imgLoader;
/**
* Register your here app https://dev.twitter.com/apps/new and get your
* consumer key and secret
* */
String TWITTER_CONSUMER_KEY;
String TWITTER_CONSUMER_SECRET;
// Preference Constants
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_FACEBOOK_LOGIN = "isFacebookLogedIn";
Typeface tf;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
String quote;
ProgressDialog pDialog;
private SharedPreferences mSharedPreferences;
private static SharedPreferences facebookPreferences, twitterPreferences;
Cursor c, c2;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
//private UiLifecycleHelper uiHelper;
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imgLoader = new ImageLoader(this);
//TWITTER_CONSUMER_KEY = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
// uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
//facebookPreferences = getApplicationContext().getSharedPreferences("facebookPref", 0);
//twitterPreferences = getApplicationContext().getSharedPreferences("twitterPref", 0);
db = new DAO(this);
db.open();
c2 = db.getSettings();
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
c = db.getOneQuote(mSharedPreferences.getString("QOTD", ""));
} else {
c = db.getOneQuote(getIntent().getStringExtra("QuoteId"));
}
// if (c.getCount() != 0) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quote_dialog);
// ============================ check if user want to display
// ============================ background image for quote
if (c2.getString(c2.getColumnIndex("background")).equals("1")) {
Random random = new Random();
int idNumber = random.nextInt(20 - 1 + 1) + 1;
RelativeLayout layout = (RelativeLayout) findViewById(R.id.RelativeLayout1);
Drawable d = null;
try {
View topShadow = (View) findViewById(R.id.topShadow);
View bottomShadow = (View) findViewById(R.id.bottomShadow);
topShadow.setVisibility(View.INVISIBLE);
bottomShadow.setVisibility(View.INVISIBLE);
d = Drawable.createFromStream(getAssets().open("backgrounds/" + String.valueOf(idNumber) + ".jpg"),
null);
layout.setBackgroundDrawable(d);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
// ===========================================================================================
quText = c.getString(c.getColumnIndex(KEY_TEXT));
quAuthor = c.getString(c.getColumnIndex(KEY_AUTHOR));
quPicture = c.getString(c.getColumnIndex(KEY_PICTURE));
auPictureSDCard = c.getInt(c.getColumnIndex(KEY_PICTURE_SDCARD));
quFavorite = c.getString(c.getColumnIndex(KEY_FAVORITE));
text = (TextView) findViewById(R.id.text); // title
// tf = Typeface.createFromAsset(getAssets(), "fonts/devnew.ttf");
//text.setTypeface(tf);
// author = (TextView) findViewById(R.id.author); // author
// picture = (ImageView) findViewById(R.id.picture); // thumb
text.setText(quText);
// author.setText("- " + quAuthor.trim());
// if (auPictureSDCard == 0) {
// AssetManager assetManager = getAssets();
// InputStream istr = null;
// try {
// istr = assetManager.open("authors_pics/" + quPicture);
// } catch (IOException e) {
// Log.e("assets", assetManager.toString());
// e.printStackTrace();
// }
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
// } else {
// siteUrl = getResources().getString(R.string.siteUrl);
//
// auPictureDir = siteUrl + "global/uploads/authors/";
// imgLoader.DisplayImage(
// auPictureDir + quPicture, picture);
// }
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open("authors_pics/" + quPicture);
} catch (IOException e) {
Log.e("assets", assetManager.toString());
e.printStackTrace();
}
// Bitmap bmp = BitmapFactory.decodeStream(istr);
// picture.setImageBitmap(bmp);
final ImageButton dismiss = (ImageButton) findViewById(R.id.close);
dismiss.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
//=============================Next Button and Prev Button
star = (ImageButton) findViewById(R.id.star);
btnnext = (ImageButton)findViewById(R.id.nextButton);
btnprev = (ImageButton)findViewById(R.id.PrevioustButton);
pos= getIntent().getIntExtra("Pos",0);
quote_id = getIntent().getStringExtra("QuoteId");
lstcount = getIntent().getIntExtra("LstCount",0);
#SuppressWarnings("unchecked")
final ArrayList<HashMap<String, String>> quotesList =(ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("Quotes");
btnnext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
text.setText(quotesList.get(pos).get(KEY_TEXT));
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quoteShare = quotesList.get(pos).get(KEY_TEXT);
Log.e("ErrorMsg", "quoteShare is: " + quoteShare);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();//new
Log.i("quote is",quote_id);
}
}
});
btnprev.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(pos == 1 ||pos == 0)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
text.setText(quotesList.get(p-1).get(KEY_TEXT));
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
pos = p;
FirstFav();
}
}
});
//======================================================= Swipe
ll_quote = (ScrollView)findViewById(R.id.scrollView1);
ll_quote.setOnTouchListener(new OnTouchListener() {
int downX, upX;
#Override
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
if(pos == 0 || pos == 1)
{
Toast.makeText(getApplicationContext(), "Start of List",Toast.LENGTH_SHORT).show();
}
else
{
int p = pos-1;
quFavorite = quotesList.get(p-1).get(KEY_FAVORITE);
quote_id = quotesList.get(p-1).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(p-1).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
else if (downX - upX > -100) {
if(pos == lstcount)
{
Toast.makeText(getApplicationContext(), "End of List", Toast.LENGTH_SHORT).show();
}
else
{
int p = pos+1;
quFavorite = quotesList.get(pos).get(KEY_FAVORITE);
quote_id = quotesList.get(pos).get(QuoteDialogActivity.KEY_ID);
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
text.setText(quotesList.get(pos).get(KEY_TEXT));
pos = p;
FirstFav();
}
}
return true;
}
return false;
}
});
// ========================== share button
final ImageButton share = (ImageButton) findViewById(R.id.share);
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,pos);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
});
//copy button
final ImageButton copyy = (ImageButton) findViewById(R.id.copy);
copyy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",quoteShare);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Status Copied",
Toast.LENGTH_LONG).show();
}
});
// ========================== set as favorite and unfavorite
isFavorite = quFavorite;
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
star.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isFavorite.equals("0")) {
isFavorite = "1";
star.setImageResource(R.drawable.star_on);
} else {
isFavorite = "0";
star.setImageResource(R.drawable.star_off);
}
if (getIntent().getIntExtra("isQOTD", 0) == 1) {
db.addOrRemoveFavorites(mSharedPreferences.getString("QOTD", ""), isFavorite);
} else {
// Log.i("quotes",quotesList.get(pos).get(String.valueOf(KEY_WEB_ID))+"POS"+pos+"quid"+quotesList.get(pos).get(KEY_ID));
db.addOrRemoveFavorites(quote_id, isFavorite);
// db.addOrRemoveFavorites(getIntent().getStringExtra("QuoteId"), isFavorite);
if (getIntent().getIntExtra("quotesType", 0) == 2 && isFavorite.equals("0")) {
Intent i = new Intent(QuoteDialogActivity.this, QuotesActivity.class);
i.putExtra("quotesType", 2);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(i);
}
}
}
});
// }
}
// ==============================================================================
public void FirstFav()
{
String Image_id=quote_id;
quFavorite = db.getFavQuotes(quote_id);
if(quFavorite.length()>0)
isFavorite = quFavorite;
else
isFavorite = "0";
if (isFavorite.equals("0")) {
star.setImageResource(R.drawable.star_off);
} else {
star.setImageResource(R.drawable.star_on);
}
}
//===================================================================================
}
Thanks

Multiselect Spinner with hints

hey i want add hint to MultiSelector from https://github.com/wongk/MultiSelectSpinner
i mixed it with https://github.com/ravivyas84/AndroidSpinnerHint
its look like this i add own SpinnerAdapterProxy that extends ArrayAdapter<String>
public MultiSelectSpinner(Context context) {
super(context);
_proxyAdapter = new SpinnerAdapterProxy(context, android.R.layout.simple_spinner_item);
super.setAdapter(_proxyAdapter);
_context = context;
}
(...)
public void setHint(String hint) {
_proxyAdapter.setHint(hint);
}
adapter
public class SpinnerAdapterProxy extends ArrayAdapter<String> {
private LayoutInflater mInflator;
private TextView text;
private boolean selected = false;
private String hint;
public SpinnerAdapterProxy(Context context, int resource) {
super(context, resource);
// TODO Auto-generated constructor stub
mInflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflator.inflate(android.R.layout.simple_spinner_item, null);
}
text = (TextView) convertView.findViewById(android.R.id.text1);
if (!selected) {
text.setHint(hint);
} else {
text.setHint(this.getItem(position));
}
return convertView;
}
public void setHint(String hint) {
this.hint = hint;
this.notifyDataSetChanged();
this.notifyDataSetInvalidated();
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
and place where i create MultiSelectSpinner and setTitle
province = (MultiSelectSpinner) findViewById(R.id.subregion);
province.setHint(getResources().getString(R.string.choose_province));
province.setItems(getResources().getStringArray(R.array.provinces));
the problem is that after setHint adapter did not refresh and did not show hint
i just fixed by myself
i throw out SpinnerAdapterProxy and just modify MultiSelectSpinner
by change
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (_selection != null) {
String select = null;
if (which < _selection.length) _selection[which] = isChecked;
if (!isAnySelect())
select = _title;
else
select = buildSelectedItemString();
_proxyAdapter.clear();
_proxyAdapter.add(select);
setSelection(0);
}
else {
throw new IllegalArgumentException("Argument 'which' is out of bounds.");
}
}
and
public void setTitle(String title) {
_title = title;
_proxyAdapter.clear();
_proxyAdapter.add(title);
setSelection(0);
}
and added testing finction that test if any item is selected
private boolean isAnySelect() {
for (boolean b : _selection) {
if (b == true) return true;
}
return false;
}
If you use following class you can add hint as following methord
public class MultiSelectionSpinner extends android.support.v7.widget.AppCompatSpinner implements
DialogInterface.OnMultiChoiceClickListener {
String _title;
String[] _items = null;
boolean[] mSelection = null;
ArrayAdapter<String> simple_adapter;
List<KotItems> mKotdata;
int pos;
public MultiSelectionSpinner(Context context)
{
super(context);
simple_adapter = new ArrayAdapter<String>(context,
R.layout.spinneritemstyle);
super.setAdapter(simple_adapter);
}
public MultiSelectionSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
simple_adapter = new ArrayAdapter<String>(context,
R.layout.spinneritemstyle);
super.setAdapter(simple_adapter);
}
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (mSelection != null && which < mSelection.length) {
mSelection[which] = isChecked;
simple_adapter.clear();
simple_adapter.add(buildSelectedItemString());
} else {
simple_adapter.add("N/A");
throw new IllegalArgumentException(
"Argument 'which' is out of bounds.");
}
}
#Override
public boolean performClick() {
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMultiChoiceItems(_items, mSelection, this);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1)
{
mKotdata.get(pos).setKotnote(buildSelectedItemString());
}
});
builder.show();
return true;
}
#Override
public void setAdapter(SpinnerAdapter adapter) {
throw new RuntimeException(
"setAdapter is not supported by MultiSelectSpinner.");
}
//Add Your Hint in this methord
public void setItems(List<String> items) {
if(items.size()>0){
_items = items.toArray(new String[items.size()]);
mSelection = new boolean[_items.length];
simple_adapter.clear();
simple_adapter.add("Add Your Hint Here");
Arrays.fill(mSelection, false);
}
}
public void setArrayList(List<KotItems> mKotdata,int pos){
this.mKotdata = mKotdata;
this.pos = pos;
}
public void setSelection(int index) {
for (int i = 0; i < mSelection.length; i++) {
mSelection[i] = false;
}
if (index >= 0 && index < mSelection.length) {
mSelection[index] = true;
} else {
throw new IllegalArgumentException("Index " + index
+ " is out of bounds.");
}
simple_adapter.clear();
simple_adapter.add(buildSelectedItemString());
}
private String buildSelectedItemString() {
StringBuilder sb = new StringBuilder();
boolean foundOne = false;
for (int i = 0; i < _items.length; ++i) {
if (mSelection[i]) {
if (foundOne) {
sb.append(", ");
}
foundOne = true;
sb.append(_items[i]);
}
}
System.out.println("u8u8 "+sb.toString());
return sb.toString();
}
}

Categories

Resources