pressing equal button says app stop working - android

My button goes to InfixtoPostfix class and by then it should display result. However, it is showing that the app has stopped.
public class InfixtoPostfix extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
TextView tv=(TextView) findViewById(R.id.textview_display);
String s = null;
String p;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//BufferedReader br=new BufferedReader(new OutputStreamReader(System.out));
Stack b=new Stack();
try {
s=br.readLine();
// s=tv.getText().toString();
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("inn");
p=b.postfix(s);
Evaluation e=new Evaluation();
tv.setText("Result:- "+e.calculate(p));
}
class Stack1
{
private int[] a;
private int top,m;
public Stack1(int max)
{
m=max;
a=new int[m];
top=-1;
}
public void push(int key)
{
a[++top]=key;
}
public int pop()
{
return(a[top--]);
}
}
class Evaluation{
public int calculate(String s)
{
int n,r=0;
n=s.length();
Stack1 a=new Stack1(n);
for(int i=0;i<n;i++)
{
char ch=s.charAt(i);
if(ch>='0'&&ch<='9')
a.push((int)(ch-'0'));
else
{
int x=a.pop();
int y=a.pop();
switch(ch)
{
case '+':r=x+y;
break;
case '-':r=y-x;
break;
case '*':r=x*y;
break;
case '/':r=y/x;
break;
default:r=0;
}
a.push(r);
}
}
r=a.pop();
return(r);
}
}
}
package com.example.calculator;
public class Stack {
char stack1[]=new char[20];
int top;
void push(char ch)
{
top++;
stack1[top]=ch;
}
char pop()
{
char ch;
ch=stack1[top];
top--;
return ch;
}
int pre(char ch)
{
switch(ch)
{
case '-':return 1;
case '+':return 1;
case '*':return 2;
case '/':return 2;
}
return 0;
}
boolean operator(char ch)
{
if(ch=='/'||ch=='*'||ch=='+'||ch=='-')
return true;
else
return false;
}
boolean isAlpha(char ch)
{
if(ch>='a'&&ch<='z'||ch>='0'&&ch=='9')
return true;
else
return false;
}
String postfix(String str)
{
char output[]=new char[str.length()];
char ch;
int p=0,i;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch=='(')
{
push(ch);
}
else if(isAlpha(ch))
{
output[p++]=ch;
}
else if(operator(ch))
{
if(stack1[top]==0||(pre(ch)>pre(stack1[top]))||stack1[top]=='(')
{
push(ch);
}
}
else if(pre(ch)<=pre(stack1[top]))
{
output[p++]=pop();
push(ch);
}
else if(ch=='(')
{
while((ch=pop())!='(')
{
output[p++]=ch;
}
}
}
while(top!=0)
{
output[p++]=pop();
}
return output.toString();
}
}

Related

Why NullPointerException occurs when calling getColor from single instance?

google play crash log:
Caused by: java.lang.NullPointerException:
at com.manager.loader.SkinManager.getColor (SkinManager.java:28)
at base.util.ui.titlebar.BaseTitlebarFragmentActivity.getImmersiveColor (BaseTitlebarFragmentActivity.java:6)
at base.util.ui.titlebar.BaseTitlebarFragmentActivity.onCreate (BaseTitlebarFragmentActivity.java)
activity:
public abstract class BaseTitlebarFragmentActivity extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
setImmersive(getImmersiveColor());
super.onCreate(savedInstanceState);
}
protected int getImmersiveColor(){
return SkinManager.getInstance().getColor(R.color.v8_common_title_bg);
}
SkinManager:
public class SkinManager implements ISkinLoader {
private static final Object synchronizedLock = new Object();
private static SkinManager instance;
private SkinManager() { }
public static SkinManager getInstance() {
if (instance == null) {
synchronized (synchronizedLock) {
if (instance == null){
instance = new SkinManager();
}
}
}
return instance;
}
public int getColor(int resId){
int originColor;
if(mResources == null || isDefaultSkin){
try {
originColor = context.getResources().getColor(resId);
return originColor;
} catch (Exception e) {
}
}
int trueColor = 0;
try{
trueColor = mResources.getColor(resId);
}catch(Exception e){
originColor = context.getResources().getColor(resId);
trueColor = originColor;
}
return trueColor;
}
App:
public class App extends BaseApplication {
public void onCreate() {
super.onCreate();
initSkins();
}
private void initSkins() {
AttrFactory.addSupportAttr("iiv_background_color", new IconicsImageViewBgColorAttr());
AttrFactory.addSupportAttr("iiv_color", new IconicsImageViewColorAttr());
AttrFactory.addSupportAttr("matProg_barColor", new ProgressWheelBarColorAttr());
AttrFactory.addSupportAttr("progressDrawable", new ProgressBarDrawableAttr());
AttrFactory.addSupportAttr("indeterminateDrawable", new ProgressBar2DrawableAttr());
AttrFactory.addSupportAttr("button", new CheckBoxButtonDrawableAttr());
SkinManager.getInstance().init(this);
SkinManager.getInstance().setUpSkinFile();
if (!ProcessManager.isMainProcess(getContext())) {
SkinManager.getInstance().registerProcessSkinLoadReceiver();
}
}
Although it's impossible as crash log shows, I will refactoring getColor to this and have a look:
public int getColor(int resId){
if(mResources == null || isDefaultSkin){
try {
int originColor = context.getResources().getColor(resId);
return originColor;
} catch (Exception ignored) {
}
}
try{
int trueColor = mResources.getColor(resId);
return trueColor;
} catch(Exception ignored) {
}
try {
int originColor = context.getResources().getColor(resId);
return originColor;
} catch (Exception ignored) {
}
return 0;
}

Android Design: Intentservice causing application not responding

I have designed a code which leads to application not responding.
I have used okhttp3.WebSocket for continuous input stream of data on which i am deciding to start an IntentService which will be fetching data from server.
I have an IntentService; in onHandleIntent i am giving an service call for fetching data from the server(roughly 3 calls).
For Service call i am using AsyncTask of android inside which my WebConnectionManger class runs on different thread.
Inside websocket i am getting details of a particular record for which i am going to fetch the details from the service call.
For 5-6 such records my application runs fine, but if records get 80-100 my application do not respond at all and i get ANR.
I am using simple plain TCP request for this.
can any on tells me what is the actual issue and how i can get rid of it?
any help is appreciated.
i am pasting the code of WebSocket, AsyncTask(rest two have same implementation), WebConnectionManger class and IntentService class.
WebSocket.class
public class WebSocket {
public static boolean isConnected;
public static String TO_UPDATE = "toOrderUpdate";
#SuppressLint("StaticFieldLeak")
private static WebSocket _instance;
private static OkHttpClient client;
private static WebSocket webSocket = null;
private Context mContext;
private AppPreferences preferences;
private WebSocket() {
client = new OkHttpClient();
}
public WebSocket(Context context) {
client = new OkHttpClient();
mContext = context;
preferences = new AppPreferences(mContext);
init(mContext);
}
public static WebSocket getInstance(Context mContext) {
if (_instance == null) {
_instance = new WebSocket(mContext);
}
return _instance;
}
public static void closeWebSocket() {
if (isConnected) {
webSocket.close(1001, LOGOUT);
_instance = null;
webSocket = null;
isConnected = false;
}
}
public void init(Context context) {
if (webSocket == null) {
preferences = new AppPreferences(context);
Request request = new Request.Builder()
.url(preferences.getWSUrl() + ":" + preferences.getWSPort() + "/" + preferences.getUserID())
.build();
WebSocketMessageListener messageListener = new WebSocketMessageListener();
webSocket = client.newWebSocket(request, messageListener);
isConnected = true;
}
}
private class WebSocketMessageListener extends WebSocketListener {
// private static final int NORMAL_CLOSURE_STATUS = 1000;
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
Log.i("******", "Socket Open");
}
#Override
public void onMessage(WebSocket webSocket, String response) {
try {
super.onMessage(webSocket, response);
Log.i("******", "Message Received " + response);
// Logger.log("OnMessage : " + response);
ModelAdvertisements modelAdvertisements = DecoderJSONWebSocket.decode(response);
Intent intentForService = new Intent(mContext, WebSocketService.class);
int transCode = Integer.parseInt(modelAdvertisements.getTC());
Intent mwBroadcastIntent = new Intent();
switch (transCode) {
case 1005:
mwBroadcastIntent.setAction(Constants.IntentKeys.KEY_LOGICAL_SESSION_START_END);
mContext.sendBroadcast(mwBroadcastIntent);
break;
case 1004:
case 1006:
case 1007:
intentForService.putExtra(TO_UPDATE, true);
mContext.startService(intentForService);
break;
case 1008:
try {
mwBroadcastIntent.putExtra(KEY_AUCTION_FLOOR_SNAPSHOT, modelAdvertisements);
mwBroadcastIntent.setAction(Constants.IntentKeys.KEY_MARKET_DATASNAPSHOT);
mContext.sendBroadcast(mwBroadcastIntent);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
} catch (Exception e) {
// e.printStackTrace();
}
}
#Override
public void onClosing(WebSocket webSockett, int code, String reason) {
super.onClosing(webSockett, code, reason);
Log.i("******", "Socket Closing Reason: " + reason);
}
#Override
public void onClosed(WebSocket webSockett, int code, String reason) {
super.onClosed(webSockett, code, reason);
Log.i("******", "Socket closed reason: " + reason);
webSocket = null;
isConnected = false;
}
#Override
public void onFailure(WebSocket webSockett, Throwable t, Response response) {
super.onFailure(webSockett, t, response);
isConnected = false;
webSocket = null;
Logger.log(e);
}
}
}
WebSocketService.class
public class WebSocketService extends IntentService {
String securityId;
private Context mContext;
private String tokenId;
private String contractCode;
private int transCode;
private boolean toUpdate;
private String mktCode;
public WebSocketService() {
super("WebSocketService");
}
public WebSocketService(String name) {
super(name);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if (intent != null) {
tokenId = intent.getStringExtra(KEY_TOKEN_ID);
transCode = intent.getIntExtra(KEY_TRANSCODE, 0);
toUpdate = intent.getBooleanExtra(NeMLWebSocket.TO_UPDATE, false);
contractCode = intent.getStringExtra(KEY_SYMBOL);
mktCode = intent.getStringExtra(KEY_ADV_REF_ID);
}
securityId = DatabaseUtils.getSecurityIdFromFOOrders(mContext, tokenId);
performTokenMasterTask();
}
#Override
public void onCreate() {
super.onCreate();
mContext = this;
}
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
protected void performTokenMasterTask() {
synchronized (this) {
TokenMasterTask tokenMasterTask = new TokenMasterTask(mContext, new RequestCallback() {
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
if (transCode == TC_1004_WEB_SOCKET) {
Intent mwBroadcastIntent = new Intent();
mwBroadcastIntent.setAction(Constants.IntentKeys.KEY_TOKEN_SESSION_START_END);
mContext.sendBroadcast(mwBroadcastIntent);
// stopSelf();
} else if (transCode == TC_TIME_WEB_SOCKET || transCode == TC_AUCTION_WEB_SOCKET) {
performTimeSessionTask();
}
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
try {
Logger.log(transCode + "--->" + msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}, mktCode);
tokenMasterTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tokenId);
if (transCode == TC_TIME_WEB_SOCKET || transCode == TC_AUCTION_WEB_SOCKET) {
performTimeSessionTask();
}
}
}
public void performTimeSessionTask() {
synchronized (this) {
TimeSessionMapTask timeSessionMapTask = new TimeSessionMapTask(mContext, new RequestCallback() {
ProgressDialog progressDialog;
private boolean m_ConnectionErr = false;
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
if (!m_ConnectionErr) {
if (transCode == TC_AUCTION_WEB_SOCKET) {
performFoOrderTask();
}
}
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
try {
Logger.log("Received ErrorMessage :" + msg + " \n ErrorCode :" + transCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}, modelMarket);
timeSessionMapTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, TIME_SESSION);
if (transCode == TC_AUCTION_WEB_SOCKET) {
performFoOrderTask();
}
}
}
private synchronized void performFoOrderTask() {
synchronized (mContext) {
FOOrdersTask foOrdersTask = new FOOrdersTask(mContext, new RequestCallback() {
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
}
});
foOrdersTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, tokenId);
}
}
}
TokenMasterTask.class
public class TokenMasterTask extends AsyncTask<Object, Void, ModelToken> {
private final String mktCode;
private RequestCallback _callback;
#SuppressLint("StaticFieldLeak")
private Context context;
private boolean isConnectionError;
private ModelToken modelToken;
private boolean isServerDown;
public TokenMasterTask(Context context, RequestCallback requestCallback, String mktCode) {
this.context = context;
this.mktCode = mktCode;
if (requestCallback == null) {
requestCallback = new RequestCallback() {
#Override
public void onStart() {
}
#Override
public void onComplete(Object object) {
}
#Override
public void onProgress(int current, int total) {
}
#Override
public void onError(int transCode, String msg) {
}
};
}
this._callback = requestCallback;
}
#Override
protected ModelToken doInBackground(Object... voids) {
if (voids != null && voids.length > 0) {
String tokenId = String.valueOf(voids[0]);
isConnectionError = false;
transactionCall(tokenId);
}
return modelToken;
}
private void transactionCall(String tokenId) {
try {
WebConnectionManager connectionManager = new WebConnectionManager(context, new ConnectionListener() {
#Override
public void notifyReadCompleted(String f_Response) {
modelToken = DecoderTokenRequest.decode(f_Response);
synchronized (TokenMasterTask.this) {
TokenMasterTask.this.notify();
}
}
#Override
public void notifySocketError(boolean isServerDown) {
if (!isServerDown) {
isConnectionError = true;
}
TokenMasterTask.this.isServerDown = isServerDown;
synchronized (TokenMasterTask.this) {
TokenMasterTask.this.notify();
}
}
#Override
public void onReceivePacket(int total, int current) {
_callback.onProgress(current, total);
}
});
connectionManager.modifiedHandleRequest(EncoderTokenRequest.encode(context, tokenId,mktCode).getBytes());
} catch (Exception e) {
e.printStackTrace();
Logger.log(e);
}
synchronized( TokenMasterTask.this) {
try {
TokenMasterTask.this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(ModelToken modelToken) {
if (isServerDown) {
_callback.onError(Constants.ErrorCode.TC_ERROR_SERVER_DOWN, "");
} else if (isConnectionError) {
_callback.onError(0, "Connection Error.");
} else if (modelToken!=null && modelToken.getErrorCode() != null && !TextUtils.isEmpty(modelToken.getErrorCode()) && !modelToken.getErrorCode().equalsIgnoreCase("200")) {
_callback.onError(Integer.parseInt(modelToken.getErrorCode()), modelToken.getError());
} else {
_callback.onComplete(modelToken);
}
super.onPostExecute(modelToken);
}
}
WebConnectionManager.class
public class WebConnectionManager {
private String m_Response = "";
byte[] m_RequestData;
boolean m_Read_Response_Completed = false;
Thread l_WorkerThread;
ConnectionListener m_ConnectionListener;
boolean m_IsFetchCompleted;
Context context;
AppPreferences preferences;
Socket mWebSocket;
public WebConnectionManager(Context mcontext, ConnectionListener f_LoginListener) {
m_ConnectionListener = f_LoginListener;
m_IsFetchCompleted = false;
context = mcontext;
preferences = new AppPreferences(context);
}
public String modifiedHandleRequest(byte[] f_RequestData) {
m_RequestData = f_RequestData;
Logger.log("" + Constants.TIME_OUT);
l_WorkerThread = new Thread(new Runnable() {
#Override
public void run() {
String encodedIP = null;
try {
if (mWebSocket == null || !mWebSocket.isBound()
|| mWebSocket.isClosed() ) {
mWebSocket = new Socket(ip, port);
mWebSocket.setKeepAlive(true);
mWebSocket.setSoTimeout(Constants.TIME_OUT);
}
if (m_RequestData == null) {
m_Read_Response_Completed = true;
if (!mWebSocket.isClosed()) {
m_ConnectionListener.notifyReadCompleted("Connected");
return;
} else {
m_ConnectionListener.notifyReadCompleted("Disconnected");
return;
}
} else {
String request = new String(m_RequestData);
Logger.log(Utils.encodePackets(request));
}
InputStream inputStream = mWebSocket.getInputStream();
try {
mWebSocket.getOutputStream().write(m_RequestData);
} catch (Exception e) {
Logger.log(e);
}
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1048576);
byte[] buffer = new byte[1048576];
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
m_Response = byteArrayOutputStream.toString();
}
inputStream.close();
byteArrayOutputStream.close();
mWebSocket.close();
if (TextUtils.isEmpty(m_Response.toString().trim())) {
throw new IOException("Empty Response");
} else {
m_ConnectionListener.notifyReadCompleted(m_Response.toString());
}
} catch (UnknownHostException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
} catch (SocketTimeoutException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(false);
mWebSocket = null;
e.printStackTrace();
} catch (SocketException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
e.printStackTrace();
} catch (IOException e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
e.printStackTrace();
} catch (Exception e) {
Logger.log(e);
m_ConnectionListener.notifySocketError(true);
mWebSocket = null;
e.printStackTrace();
}
}
});
l_WorkerThread.start();
return m_Response;
}
}
And the interfaces.
public interface ConnectionListener {
void notifyReadCompleted(String f_Response);
void notifySocketError(boolean isServerDown);
void onReceivePacket(int total, int current);
}
public interface RequestCallback {
void onStart();
void onComplete(Object object);
void onProgress(int current, int total);
void onError(int transCode, String msg);
}
You may want to check what is blocking the main thread for more than 6 seconds.
Usually ANR happens when main thread is blocked for some time. 6-10 seconds.

File.exists returning false

I am trying to access a file twice in my program.
First I am reading from the file, which runs fine.
The second time, I am trying to delete the same file from which I read.
Strangely the second time no records are present in the file. In fact when I try to run the command file.exists it returns false. Why is this happening?
Following is my code:
public class ControlLights extends AppCompatActivity {
private RoomListAdapter adapter;
private List<ROOM> mRoomList;
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.popup,menu);
}
public void filedel(int pos) {
Toast.makeText(getApplicationContext(), String.valueOf(pos), Toast.LENGTH_LONG).show();
File filemain = new File("roomdata.txt");
try {
File temp = File.createTempFile("file",".txt",filemain.getParentFile());
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(temp), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
int p=0;
for(String line; (line=reader.readLine())!=null;) {
if(p == pos) {
line = line.replace(line,"");
writer.println(line);
}
writer.println(line);
}
reader.close();
writer.close();
filemain.delete();
temp.renameTo(filemain);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.Edit:
return true;
case R.id.Delete:
filedel(info.position);
mRoomList.remove(info.position);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
public void loadrooms() {
int block = 1024;
try {
boolean exists = (new File("roomdata.txt").exists());
Toast.makeText(getApplicationContext(), String.valueOf(exists), Toast.LENGTH_LONG).show();
FileInputStream fis = openFileInput("roomdata.txt");
InputStreamReader isr = new InputStreamReader(fis);
char[] data = new char[block];
String roomdata = "";
int size;
try {
while ((size = isr.read(data)) > 0) {
String read_data = String.copyValueOf(data, 0, size);
roomdata += read_data;
data = new char[block];
}
} catch (IOException e) {
e.printStackTrace();
}
String[] room_display = roomdata.split("\n");
String[] tempstring;
ListView lsv = (ListView) findViewById(R.id.Room_list);
mRoomList = new ArrayList<>();
for (int b = 0; b < room_display.length; b++) {
tempstring = room_display[b].split(":");
mRoomList.add(new ROOM(tempstring[0], tempstring[1], tempstring[2], tempstring[3], tempstring[4], tempstring[5], tempstring[6], tempstring[7], tempstring[8], tempstring[9]));
}
adapter = new RoomListAdapter(getApplicationContext(), mRoomList);
lsv.setAdapter(adapter);
registerForContextMenu(lsv);
int count = mRoomList.size();
final ArrayList<Integer> disabledpos = new ArrayList<Integer>();
for (int q = 0; q < count; q++) {
ROOM temp_room1 = mRoomList.get(q);
String IP = temp_room1.getRoom_IP_Address();
String online = null;
ConnectionTest CT = new ConnectionTest();
try {
online = CT.execute(IP, "a", "b").get();
Boolean b1 = Boolean.valueOf(online);
if (!b1) {
disabledpos.add(q);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
try {
isr.reset();
isr.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (new File("roomdata.txt").delete()) {
Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "not deleted", Toast.LENGTH_LONG).show();
// Not deleted
}
lsv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int temp_position = position;
Intent p = new Intent(ControlLights.this, Electrical_equipment_list.class);
if (!(disabledpos.contains(position))) {
ROOM temp_room = mRoomList.get(temp_position);
p.putExtra("EE1", temp_room.getEE1());
p.putExtra("EE2", temp_room.getEE2());
p.putExtra("EE3", temp_room.getEE3());
p.putExtra("EE4", temp_room.getEE4());
p.putExtra("EE5", temp_room.getEE5());
p.putExtra("EE6", temp_room.getEE6());
p.putExtra("EE7", temp_room.getEE7());
p.putExtra("EE8", temp_room.getEE8());
p.putExtra("IPaddress", temp_room.getRoom_IP_Address());
startActivity(p);
}
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_lights);
loadrooms();
}
public class ConnectionTest extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
Boolean online;
String tempstring = null;
try {
InetAddress roomaddress = InetAddress.getByName(params[0]);
online = roomaddress.isReachable(100);
tempstring = String.valueOf(online);
} catch (IOException e) {
e.printStackTrace();
}
return tempstring;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
Keep your File as a class' member, since it is an essential component of what the class does
Move your inner logic and file reference initialization to onStart()
public class ControlLights extends AppCompatActivity {
private RoomListAdapter adapter;
private List mRoomList;
private File filemain;
...
public void filedel(int pos) {
Toast.makeText(getApplicationContext(), String.valueOf(pos), Toast.LENGTH_LONG).show();
try {
File temp = File.createTempFile("file",".txt", filemain.getParentFile());
...
}
}
public void loadrooms() {
int block = 1024;
try {
boolean exists = filemain.exists();
...
if (filemain.delete()) {
Toast.makeText(getApplicationContext(), "deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "not deleted", Toast.LENGTH_LONG).show();
// Not deleted
}
} ...
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control_lights);
}
#Override
protected void onStart() {
super.onStart();
filemain = new File("roomdata.txt");
loadrooms();
}
}
Foot note
I apologize for the horrible code format, but apparently they changed the parsing algorithm to a point where you have to manually type all the code again here instead of just being able to copy-paste it. Anyone being to edit it accordingly is welcome.

Android XMLRPC Exception handling

I wanted to ask what is the best way to handle an exception when you are calling a XMLRPC function and the server is down or not responding. I have the following code:
try
{
mXmlRpcClient.call(mRequestVariantsFunc, SessionID, newID, "1970-01-01T00:00:00+00" ,"1970-01-01T00:00:00+00");
}
catch (Exception e)
{
e.printStackTrace();
}
The code above works alright when the server is running but when its down I get a black screen and the phone freezes. The rest of the code is running while in black screen but no exception is thrown. Is there a way to handle this problem in case the server is down not to go into a black screen?
For me, in another tool there is a message going via a handler to indicate progress. Also, a seperate class to handle exceptions is nice to have.
If you have the same library as me, here my example for what it's worth:
package hha.zhongcan.communication;
import java.net.URI;
import android.os.Handler;
import android.util.Log;
import hha.zhongcan.framework.Citem;
import hha.zhongcan.framework.Configuration;
import hha.zhongcan.framework.CtimeFrame;
import hha.zhongcan.framework.Ctransaction;
import hha.zhongcan.microfood.AskTableDialog;
import hha.zhongcan.resources.Global;
import org.apache.http.conn.HttpHostConnectException;
interface XMLRPCMethodCallback
{
void callFinished(Object result);
}
/** Messages to send to the PC at high level. Receive the menu items, pages, transactions.
* Create fake data for the demo.
*
* #author mensfort
*
*/
public class Cmessage
{
static private Cmessage m_message =null;
private static URI m_uri;
public static XMLRPCClient m_client;
private final static String TAG="message";
private boolean m_connected =false;
private int m_pingId =0;
private int m_lost =0;
private int m_wait =0;
private boolean m_sendTransactions =true;
private Handler m_updateHandler = new Handler();
boolean m_getItems = false;
boolean m_getPages = false;
private static Global m_global =null;
private int m_countTransactions =10;
private int transactionMessageCount =0;
private long getValue( String s)
{
try
{
if ( s.startsWith("0x") || s.startsWith("0X"))
{
s =s.substring(2);
while (s.startsWith("0"))
{
s=s.substring(1);
}
if ( s.length() ==0)
{
return 0;
}
return Long.parseLong(s, 16);
}
if ( s=="")
{
return 0;
}
return Long.parseLong(s);
}
catch(Exception e)
{
e.printStackTrace();
return 0;
}
}
/// #brief New thread for running ask-table.
private Runnable messageTask = new Runnable()
{
//#override
public void run()
{
if ( m_getItems)
{
m_getItems =false;
getMenuItems();
}
else if ( m_getPages)
{
m_getPages =false;
getMenuPages();
}
else if ( m_sendTransactions)
{
// If I have sth to send and I'm not in page mode, then start sending items.
sendTransactions();
m_wait =2;
}
else if ( Configuration.getInstance().isDemo())
{
m_connected =true;
next();
}
else if ( m_wait>0)
{
m_wait--;
next();
}
else if ( --m_countTransactions<=0)
{
sendMessage_getTransactions();
m_countTransactions =5;
}
else
{
// Update this screen every 10 seconds.
sendConnected();
}
}
};
/** #brief At startup start the first message after a second.
*/
private Cmessage()
{
m_updateHandler.postDelayed( messageTask, 1000);
}
/** #brief Set the address and port.
*
* #param address [in] Address to use.
* #param port [in] Port to use.
*/
public void setPath( String address, Integer port)
{
m_uri = URI.create("http://192.168.0.105:9876");
m_client =new XMLRPCClient( m_uri);
}
/** #brief Singleton implementation, only this instance can send messages.
*
* #return Pointer to the singleton.
*/
public static Cmessage getInstance()
{
if ( m_message ==null)
{
m_message =new Cmessage();
m_global =Global.getInstance();
}
return m_message;
}
/** #brief In a second, the next command can be send to the PC.
*/
public void next()
{
m_updateHandler.postDelayed( messageTask, 1000);
}
/** #brief Check if we are connected to the PC.
*
* #return true when connected.
*/
public boolean isConnected()
{
return m_connected;
}
/** #brief Send Ping message, just to check the connection status.
*/
public void sendConnected()
{
{
XMLRPCMethod method =new XMLRPCMethod( "ping", new XMLRPCMethodCallback() {
public void callFinished(Object result)
{
try
{
String s = (String) (result);
if ( s.equals("bart"))
{
m_lost =0;
m_connected =true;
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
m_lost++;
}
}
});
Object[] params ={ m_pingId++ }; // {};
method.call(params);
}
if ( ++m_lost>2)
{
m_connected =false;
}
}
public void sendMessage_getConfiguration()
{
// TODO Auto-generated method stub
}
private void createMenuFrom( Object [] arrY)
{
if ( arrY.length >0)
{
m_global.itemDB.clean();
}
int v=(int)(arrY.length/9);
int lvl=1;
for (int y=0; y<arrY.length; y++)
{
if ( y==lvl*v)
{
setSlider(lvl++);
}
Log.i(TAG, "item " + y);
Object[] arrX = (Object[]) arrY[y];
int id =(Integer) arrX[0];
String alias =(String) arrX[1];
String local =(String) arrX[2];
String chinese =(String) arrX[3];
int restaurant_price =(Integer) arrX[4];
int takeaway_price =(Integer) arrX[5];
int level =(Integer) arrX[6];
int page =(Integer) arrX[7];
int sequence =(Integer) arrX[8];
int colour_text = (int)(getValue( (String) arrX[9])&0xffffffff);
int colour_background = (int)(getValue( (String) arrX[10])&0xffffffff);
int colour_selected_text = (int)(getValue( (String) arrX[11])&0xffffffff);
int colour_selected_background = (int)(getValue( (String) arrX[12])&0xffffffff);
int colour_background2 = (int)(getValue( (String) arrX[13])&0xffffffff);
int colour_selected_background2 = (int)(getValue( (String) arrX[14])&0xffffffff);
if ( m_global.mainMenuHandler !=null)
{
// m_global.mainMenuHandler.obtainMessage( y, "UPDATE_MENU_SLIDEBAR "+y).sendToTarget();
}
m_global.itemDB.insert( id, alias, local, chinese, restaurant_price,
takeaway_price, (byte)level, (byte)page, (short)sequence,
colour_text, colour_background, colour_selected_text,
colour_selected_background, colour_background2,
colour_selected_background2);
}
m_global.itemDB.complete();
Log.i(TAG, "Items received correct.");
}
/** Indicate that we want to get the menu card.
*/
public void sendMessage_getMenuItems()
{
m_getItems = true;
m_getPages = true;
}
/** #brief Get the menu items. */
public void getMenuItems()
{
boolean demo =Configuration.getInstance().isDemo();
if (demo ==true)
{
createMenuFrom( demoMenu.items);
next();
}
else
{
XMLRPCMethod method =new XMLRPCMethod( "items", new XMLRPCMethodCallback() {
public void callFinished(Object result)
{
try
{
m_global.itemDB.deleteAll();
m_global.itemDB.clean();
Object[] arrY = (Object[]) result;
createMenuFrom( arrY);
m_connected =true;
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
});
Object[] params = {};
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 1, "UPDATE_MENU_SLIDEBAR 1").sendToTarget();
}
method.call(params);
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 1, "UPDATE_MENU_SLIDEBAR 5").sendToTarget();
}
}
}
/** Call to get all transactions from the server, including payments, items and time-frames. */
public void sendMessage_sendTransactions()
{
m_sendTransactions =true;
}
/** Set slider to a value 1..10
*
* #param n [in] 0..10
*/
private void setSlider( int n)
{
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 0, "UPDATE_MENU_SLIDEBAR "+n).sendToTarget();
}
}
/** After sending the orders, the database can be cleaned...
*/
private void cleanDatabase()
{
try
{
m_global.transactionDB.clean();
m_global.timeFrameDB.clean();
m_global.transactionItemDB.clean();
m_connected =true;
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
/** Send all transaction */
private void sendTransactions()
{
if ( m_global.transactionDB.size() ==0)
{
m_sendTransactions =false;
cleanDatabase();
next();
return;
}
if ( Configuration.getInstance().isDemo())
{
cleanDatabase();
try
{
m_global.askTableHandler.obtainMessage( AskTableDialog.MESSAGE_DATA_SENT,-1,-1, -1).sendToTarget();
}
catch (Exception e)
{
e.printStackTrace();
}
m_sendTransactions =false;
}
XMLRPCMethod method =new XMLRPCMethod( "orders", new XMLRPCMethodCallback()
{
public void callFinished(Object result)
{
cleanDatabase();
m_global.askTableHandler.obtainMessage( AskTableDialog.MESSAGE_DATA_SENT,-1,-1, -1).sendToTarget();
m_sendTransactions =false;
}
});
Object[][] transaction =m_global.transactionDB.get();
Object[][] timeFrame =m_global.timeFrameDB.get();
Object[][] item =m_global.transactionItemDB.get();
Object[] params ={ transaction,timeFrame,item };
//{
// transaction, timeFrame, item
//}/;
if ( transaction ==null || timeFrame ==null || item ==null)
{
cleanDatabase();
Log.e( TAG,"Database problem!!");
}
method.call( params);
}
/// Call to get all transactions from the server, including payments, items and time-frames.
public void sendMessage_getTransactions()
{
if ( m_global.transactionDB.size() >0)
{
return;
}
if ( m_global.timeFrameDB.size() >0)
{
return;
}
if ( m_global.transactionItemDB.size() >0)
{
return;
}
XMLRPCMethod method =new XMLRPCMethod( "get_transactions", new XMLRPCMethodCallback()
{
public void callFinished(Object result)
{
m_countTransactions =10;
m_connected =true;
if ( m_global.transactionDB.size() >0)
{
Log.i(TAG, "Transaction DB not empty.");
return;
}
if ( m_global.timeFrameDB.size() >0)
{
Log.i(TAG, "Time Frame DB not empty.");
return;
}
if ( m_global.transactionItemDB.size() >0)
{
Log.i(TAG, "Transaction Item DB not empty.");
return;
}
try
{
m_global.transactionList.clean();
Object[] arrY = (Object[]) result;
Object[] transactions =(Object[]) arrY[0];
Object[] timeFrames =(Object[]) arrY[1];
Object[] items =(Object[]) arrY[2];
//Object[] payments =(Object[]) arrY[3];
for (int y=0; y<transactions.length; y++)
{
Object[] trx = (Object[]) transactions[y];
int id = Integer.valueOf(trx[0].toString());
String tme =trx[1].toString();
String name =trx[2].toString();
int customer_id =Integer.valueOf( trx[3].toString());
int status =Integer.valueOf( trx[4].toString());
int total =Integer.valueOf( trx[5].toString());
Ctransaction t=new Ctransaction( id, name, tme, status, customer_id, total);
m_global.transactionList.insert( t);
}
for (int y=0; y<timeFrames.length; y++)
{
Object[] trx = (Object[]) timeFrames[y];
int id = Integer.valueOf( trx[0].toString());
int tfi =Integer.valueOf( trx[1].toString());
int waiter =Integer.valueOf( trx[2].toString());
String start_time =trx[3].toString();
String end_time =trx[4].toString();
int transaction_id =Integer.valueOf( trx[5].toString());
int device_id =Integer.valueOf( trx[6].toString());
CtimeFrame c =new CtimeFrame( id, (short)tfi, waiter,
start_time, end_time,
transaction_id, device_id);
m_global.transactionList.insert( c);
}
for (int y=0; y<items.length; y++)
{
Object[] trx = (Object[]) items[y];
//int id = (Integer) trx[0];
long menu_item_id =Long.valueOf( trx[1].toString());
int sequence =Integer.valueOf( trx[2].toString());
int time_frame_index =Integer.valueOf( trx[3].toString());
int deleted_time_frame_index =Integer.valueOf( trx[4].toString());
long transaction_id =Long.valueOf( trx[5].toString());
int quantity =Integer.valueOf( trx[6].toString());
int level =Integer.valueOf( trx[7].toString());
int deleted =Integer.valueOf( trx[8].toString());
int portion =Integer.valueOf( trx[9].toString());
int orig_price =Integer.valueOf( trx[10].toString());
int unit_price =Integer.valueOf( trx[11].toString());
String time =trx[12].toString();
Citem i=new Citem( menu_item_id, y, (short)sequence,
(short)time_frame_index,
(short)deleted_time_frame_index,
transaction_id, quantity,
(byte)level, deleted, (byte)portion, unit_price, orig_price, time);
m_global.transactionList.insert( i);
}
//for (int y=0; y<payments.length; y++)
//{
//Object[] pay = (Object[]) payments[y];
//int id = (Integer) pay[0];
//String time =(String) pay[1];
//int money_received =(Integer) pay[2];
//int customer_id =(Integer) pay[3];
//int pay_method =(Integer) pay[4];
//int partial_index =(Integer) pay[5];
//global.paymentsDB.insert( id, time, money_received, customer_id, pay_method, partial_index);
//}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
});
Object[] params = { transactionMessageCount++ };
method.call(params);
}
/// Call, but not in main thread, answer comes in a thread.
private void getMenuPages()
{
if ( Configuration.getInstance().isDemo())
{
decodePages( demoMenu.pages);
next();
return;
}
XMLRPCMethod method =new XMLRPCMethod( "pages", new XMLRPCMethodCallback()
{
public void callFinished(Object result)
{
decodePages( result);
}
});
setSlider(7);
Object[] params = {};
method.call(params);
setSlider(8);
}
/**
* #brief Convert an array to page data.
* #param result [in] array with local, chinese names.
*/
private void decodePages( Object result)
{
try
{
m_global.pageDB.clean();
Object[] arrY = (Object[]) result;
setSlider(9);
for (int y=0; y<arrY.length; y++)
{
Object[] arrX = (Object[]) arrY[y];
int id = (Integer) arrX[0];
String local =(String) arrX[1];
String chinese =(String) arrX[2];
String lc =local.replace( "'", "''");
String ch =chinese.replace( "'", "''");
m_global.pageDB.insert( id, lc, ch);
}
m_connected =true;
if ( m_global.mainMenuHandler !=null)
{
m_global.mainMenuHandler.obtainMessage( 0, "UPDATE_MENU_READY").sendToTarget();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
m_connected =false;
}
}
class XMLRPCMethod extends Thread
{
private String method;
private Object[] params;
private Handler handler;
private XMLRPCMethodCallback callBack;
public XMLRPCMethod(String method, XMLRPCMethodCallback callBack)
{
this.method = method;
this.callBack = callBack;
handler = new Handler();
}
public void call()
{
call(null);
}
public void call(Object[] params)
{
this.params = params;
start();
}
//#Override
public void run()
{
synchronized(this)
{
try
{
final long t0 = System.currentTimeMillis();
final Object result = m_client.callEx(method, params);
final long t1 = System.currentTimeMillis();
handler.post(new Runnable()
{
public void run()
{
Log.i(TAG, "XML-RPC call took " + (t1-t0) + "ms");
callBack.callFinished(result);
next();
}
});
}
catch (final XMLRPCFault e)
{
handler.post(new Runnable()
{
public void run()
{
Log.e(TAG, "Fault message: " + e.getFaultString() + "\nFault code: " + e.getFaultCode());
Log.d("Test", "error", e);
next();
}
});
}
catch (final XMLRPCException e)
{
next();
handler.post(new Runnable()
{
public void run()
{
Throwable couse = e.getCause();
if (couse instanceof HttpHostConnectException)
{
Log.e(TAG, "Cannot connect to " + m_uri.getHost() + "\nMake sure server.py on your development host is running !!!");
}
else
{
Log.e(TAG, "Error " + e.getMessage());
}
Log.d(TAG, "error", e);
}
});
}
catch (Exception e)
{
next();
e.printStackTrace();
}
}
}
}
}

Calculator leading 0 and its value

I am new to android so i was trying to make calculator as my first app. I have done everything but i only have one problem
I have a leading 0 when the value is 0. Then it shows 0.0 after i click Clear i want to change it to 0 I don’t know how to change it.
MainActivity
public class MainActivity extends Activity implements OnClickListener {
private TextView calculatorDisplay;
private static final String DIGITS = "0123456789.";
private Boolean userIsInTheMiddleOfTypingANumber = false;
DecimalFormat df = new DecimalFormat("############");
CalculatorBrain brain;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
brain = new CalculatorBrain();
calculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
findViewById(R.id.buttonInvert).setOnClickListener(this);
findViewById(R.id.buttonCos).setOnClickListener(this);
findViewById(R.id.buttonSin).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
findViewById(R.id.buttonClearMemory).setOnClickListener(this);
findViewById(R.id.buttonAddToMemory).setOnClickListener(this);
findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(this);
findViewById(R.id.buttonRecallMemory).setOnClickListener(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.hide();
}
}
// #Override
public void onClick(View view) {
String buttonPressed = ((Button) view).getText().toString();
// String digits = "0123456789.";
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
calculatorDisplay.append(buttonPressed);
} else {
calculatorDisplay.setText(buttonPressed);
userIsInTheMiddleOfTypingANumber = true;
}
} else {
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
brain.setOperand(Double.parseDouble(calculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
brain.performOperation(buttonPressed);
calculatorDisplay.setText(df.format(brain.getResult()));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", brain.getResult());
outState.putDouble("MEMORY", brain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
brain.setOperand(savedInstanceState.getDouble("OPERAND"));
brain.setMemory(savedInstanceState.getDouble("MEMORY"));
calculatorDisplay.setText(df.format(brain.getResult()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
CalculatorBrain
public class CalculatorBrain {
// 3 + 6 = 9
// 3 & 6 are called the operand.
// The + is called the operator.
// 9 is the result of the operation.
private double operand = 0;
private double waitingOperand = 0;
private String waitingOperator = "";
private double calculatorMemory = 0;
public void setOperand(double operand) {
this.operand = operand;
}
public double getResult() {
return operand;
}
// used on screen orientation change
public void setMemory(double calculatorMemory) {
this.calculatorMemory = calculatorMemory;
}
// used on screen orientation change
public double getMemory() {
return calculatorMemory;
}
public String toString() {
return Double.toString(operand);
}
protected double performOperation(String operator) {
/*
* If you are using Java 7, then you can use switch in place of if statements
*
* switch (operator) {
* case "MC":
* calculatorMemory = 0;
* break;
* case "M+":
* calculatorMemory = calculatorMemory + operand;
* break;
* }
*/
if (operator.equals("MC")) {
calculatorMemory = 0;
} else if (operator.equals("M+")) {
calculatorMemory = calculatorMemory + operand;
} else if (operator.equals("M-")) {
calculatorMemory = calculatorMemory - operand;
} else if (operator.equals("MR")) {
operand = calculatorMemory;
} else if (operator.equals("C")) {
operand = 0;
waitingOperator = "";
waitingOperand = 0;
calculatorMemory = 0;
} else if (operator.equals("Sqrt")) {
operand = Math.sqrt(operand);
} else if (operator.equals("1/x")) {
if (operand != 0) {
operand = 1 / operand;
}
} else if (operator.equals("+/-")) {
operand = -operand;
} else if (operator.equals("sin")) {
operand = Math.sin(operand);
} else if (operator.equals("cos")) {
operand = Math.cos(operand);
} else {
performWaitingOperation();
waitingOperator = operator;
waitingOperand = operand;
}
return operand;
}
protected void performWaitingOperation() {
if (waitingOperator.equals("+")) {
operand = waitingOperand + operand;
} else if (waitingOperator.equals("*")) {
operand = waitingOperand * operand;
} else if (waitingOperator.equals("-")) {
operand = waitingOperand - operand;
} else if (waitingOperator.equals("/")) {
if (operand != 0) {
operand = waitingOperand / operand;
}
}
}
This is happening because getResult() retuns a double.
If you want a 0 to be displayed in place of 0.0, perform a check like this:
Replace:
calculatorDisplay.setText(df.format(brain.getResult()));
with:
if (new Double(brain.getResult()).equals(0.0)){
calculatorDisplay.setText("" + 0);
} else {
calculatorDisplay.setText(df.format(brain.getResult()));
}
This should solve your problem.
Edit 1:
Try the following changes:
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
calculatorDisplay.append(buttonPressed);
} else {
if (buttonPressed.equals("0") && !calculatorDisplay.getText().toString().equals("0")) {
calculatorDisplay.setText("0");
} else if (!buttonPressed.equals("0")) {
if (buttonPressed.equals(".")) {
calculatorDisplay.setText("0.");
} else {
calculatorDisplay.setText(buttonPressed);
}
userIsInTheMiddleOfTypingANumber = true;
}
}
}
You have to use text watcher listener on your text view:
textview.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(textview.gettText().toString().equals("0"))
{
textview.settText("0.0");
}
}
});

Categories

Resources