Main Class:
public class ProgressIndicator {
static ProgressIndicator instance;
Context context;
public static ProgressIndicator getInstance() {
if (instance == null) {
instance = new ProgressIndicator();
}
return instance;
}
private ProgressIndicator() {
}
IndicatorThread sd;
public void showIndicator(Activity activity, String title, String message, boolean flag) {
sd = new IndicatorThread(activity, title, message, flag);
sd.start();
}
public void dismissIndicator(Activity activity) throws InterruptedException{
sd.dismiss();
// sd.join();
}
private static class IndicatorThread extends Thread {
private static final Message listener = null;
private static String mTitle;
private static String mText;
private Activity mActivity;
private boolean mflag;
private ProgressDialog mDialog;
protected boolean dismiss;
IndicatorThread(Activity activity, String title, String text, boolean flag) {
super();
IndicatorThread.mText = text;
IndicatorThread.mTitle = title;
this.mActivity = activity;
this.mflag = flag;
if (mDialog == null) {
mDialog = new ProgressDialog(mActivity);
mDialog.setTitle(mTitle);
mDialog.setMessage(mText);
mDialog.setIndeterminate(true);
mDialog.setCancelable(true);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
if(mflag == true){
mDialog.setButton("Cancel", listener);
mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
mDialog.dismiss();
interrupt();
}
});
}
}
mDialog.show();
mDialog.getWindow().setLayout(160, 350);
mDialog.getWindow().setGravity(0);
}
public void dismiss() {
dismiss = true;
mDialog.dismiss();
System.out.println("notifying..."+dismiss);
synchronized (this) {
notifyAll();
}
}
#Override
public void run() {
System.out.println("Running..."+dismiss);
while (!dismiss) {
System.out.println("waiting..."+!dismiss);
synchronized (this) {
try {
wait();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
System.out.println("Quitting...");
}
}
}
Call from AppController class:
private ProgressIndicator progressInstance = null;
public void showWaitingAnimation(Activity parent) {
progressInstance.showIndicator(AppController.getInstance().currentActivity, "" , "", false);
}
Test Class:
public class ProgressIndicatorTest extends
ActivityInstrumentationTestCase2<MyTestActivity> {
private Solo solo;
private ProgressIndicator progressIndicatorInstance;
public ProgressIndicatorTest() {
super("com.test.activity",
MyTestActivity.class);
}
protected void setUp() throws Exception {
AppController.getInstance().startApp(getActivity());
solo = new Solo(getInstrumentation(), getActivity());
progressIndicatorInstance = ProgressIndicator.getInstance();
}
protected void tearDown() throws Exception {
try {
solo.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
public void testGetInstance() {
try {
ProgressIndicator instance = ProgressIndicator.getInstance();
assertNotNull(instance);
} catch (Exception e) {
fail("Creation of ExceptionDetails get instance failed!");
}
}
public void testShowIndicator() {
Log.d("testCase Name:-", "testShowIndicator");
ProgressIndicator progressInstance = ProgressIndicator.getInstance() ;
progressInstance.showIndicator(AppController.getInstance().getCurrentActivity(), "" , "", false);
//AppController.getInstance().showWaitingAnimation(AppController.getInstance().getCurrentActivity());
solo.waitForDialogToClose(8000);
try {
progressInstance.dismissIndicator(AppController.getInstance().getCurrentActivity());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void testDismissIndicator() {
Log.d("testCase Name:-", "testDismissIndicator");
ProgressIndicator progressInstance = ProgressIndicator.getInstance() ;
progressInstance.showIndicator(AppController.getInstance().getCurrentActivity(), "" , "", false);
solo.waitForDialogToClose(2000);
try {
progressInstance.dismissIndicator(AppController.getInstance().getCurrentActivity());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//AppController.getInstance().showAppTerminationDialog("", AppController.getInstance().getCurrentActivity());
}
}
While running the project the dialog is visible & working properly. But while running the test case only a black screen is visible, no dialog is getting displayed (after using solo.waitForDialogToClose(8000); problem is there). No error or exception is getting thrown and the test cases are getting passed in Android Junit test. If anyone has any idea how to display this progress dialog in case of robotium test, Please share.
In my case I can successfully display progress dialogs.
I simply used
boolean showProgressBar = false;
showProgressBar = solo.waitForText("Verifying and Saving Credentials...", 1, 3000);
I hope it should also work for you.. :)
Related
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.
I'm trying Smack 4.2 on Android and I have a problem with the IncomingListener.
I created a class MyXMPP totaly dedicated to XMPP work.
( I just have one android activity. )
In this activity, in OnCreate(), I connected to XMPP server using my class MyXMPP and I retrieved my ChatManager in my a final value to place on an IncomingChatMessageListener().
Everything works well in the first try. But when I pause my activity and relaunch it, it's like the older listener remains. So at this moment, I receive messages in double.
If I pause again my application, it's like I have 3 listeners and so on.
I precise I have no problem whith connection to my server.
Here my code :
Android activity :
public class TestMessagingActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_messaging);
MyXMPPP.getInstance().init("test", "test");
MyXMPPP.getInstance().connect();
final ChatManager chatManager = MyXMPPP.getInstance().getChatManager();
chatManager.addIncomingListener(new IncomingChatMessageListener() {
#Override
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
final AsyncTask<Message, Void, Void> mReceiveMessage = new AsyncTask<Message, Void, Void>() {
#Override
protected Void doInBackground(Message... params) {
ChatMessage chatMessage = new ChatMessage(params[0].getBody(), false);
Log.v("TAG", "index=message arrived");
Log.v("TAG", params[0].getBody());
return null;
}
#Override
protected void onPostExecute(Void res) {
}
};
mReceiveMessage.execute(message);
}
});
}
}
MyXMPP class :
public class MyXMPPP {
private static final String DOMAIN = "test.com";
private AbstractXMPPConnection connection;
private XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private ChatManager chatManager;
private Presence presence;
boolean isConnected=false;
boolean chatManagerCreated=false;
private static MyXMPPP instance =null;
public synchronized static MyXMPPP getInstance() {
if(instance==null){
instance = new MyXMPPP();
}
return instance;
}
public void init(String user, String password) {
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(user, password);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
configBuilder.setKeystoreType(null);
try {
configBuilder.setXmppDomain(DOMAIN);
} catch (XmppStringprepException e) {
e.printStackTrace();
}
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
public void connect() {
if (isConnected == false) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
try {
connection.connect();
connection.login();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
};
connectionThread.execute();
}
}
public AbstractXMPPConnection getConnection() {
return connection;
}
public void createChatManager()
{
if(chatManagerCreated==false)
{
chatManager=ChatManager.getInstanceFor(connection);
chatManagerCreated=true;
Log.v("TAG", "index=chat manager created");
}
}
public ChatManager getChatManager()
{
return chatManager;
}
public void sendMessage(String message, EntityBareJid jid)
{
if(chatManagerCreated==true)
{
Chat chat = chatManager.chatWith(jid);
try {
chat.send(message);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public boolean getIsConnected(){
return isConnected;
}
public class XMPPConnectionListener implements ConnectionListener{
#Override
public void connected(XMPPConnection connection) {
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
isConnected=true;
createChatManager();
presence = new Presence(Presence.Type.available, "Online", 24, Presence.Mode.available);
try {
connection.sendStanza(presence);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void connectionClosed() {
isConnected=false;
}
#Override
public void connectionClosedOnError(Exception e) {
isConnected=false;
}
#Override
public void reconnectionSuccessful() {
}
#Override
public void reconnectingIn(int seconds) {
}
#Override
public void reconnectionFailed(Exception e) {
}
}
}
Is this problem normal ?
When I put the listener to on the chatManager in the XMPP class, I don't have this problem. But I would like to do work in my activity / in my view, so having the listener here seems to be better.
I need some advice.
Thank you.
Nico.
I am working on Android Chat app based on Smack 4.1.7.
I have created my XMPP related operations on Saperate class said MyXMPP.java.
and in my app's Application class i am initializing MyXMPP class objects.
my problem is, suppose we have user 1 and user 2. if user 1 sends message to user 2 then user 2 can get message but cant reply back. means if user 2 trying to reply then user 1 can not get user 2's reply.
in short if user 1 initiates chatting then, only user 1 can send message. user 2 can not send message to user 1 same Vice versa.
my codes are as below,
MyXMPP.java
public class MyXMPP {
static Context context;
static XMPPTCPConnectionConfiguration.Builder xmppConfig;
static XMPPTCPConnection connection;
static MyXMPP myXMPP = null;
static Chat chat;
Roster roster;
ArrayList<Rosters> rosters;
static ChatManager chatManager;
static Application app;
public static synchronized MyXMPP getInstance(Context c) {
app = (Application) c.getApplicationContext();
context = c;
if (myXMPP == null) {
myXMPP = new MyXMPP();
xmppConfig = XMPPTCPConnectionConfiguration.builder();
xmppConfig.setResource(Constants.RESOURCE);
xmppConfig.setServiceName(Constants.SERVICE_NAME);
xmppConfig.setPort(Constants.PORT);
xmppConfig.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
}
return myXMPP;
}
public static synchronized AbstractXMPPConnection getConnectXMPP() {
try {
xmppConfig.setUsernameAndPassword(Constants.USERNAME, Constants.PASSWORD);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(xmppConfig.build());
connection.setUseStreamManagement(true);
connection.connect().login();
connection.requestSmAcknowledgement();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
return connection;
}
public static ChatManager getChatManager() {
if (chatManager == null) {
chatManager = ChatManager.getInstanceFor(app.connection);
}
return chatManager;
}
public ArrayList<Rosters> getRosters() {
rosters = new ArrayList<>();
roster = Roster.getInstanceFor(app.connection);
if (!roster.isLoaded())
try {
roster.reloadAndWait();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SmackException.NotLoggedInException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
//Get Roster Entry list
Set<RosterEntry> rosterEntries = roster.getEntries();
Debug.e("entry size", "" + rosterEntries.size());
for (final RosterEntry entry : rosterEntries) {
/*
build List<> for roster entry with roster
---or---
if it is in activity or in fragment then add both items (entry,roster) to adapter
*/
Rosters rosterItem = new Rosters();
rosterItem.entry.add(entry);
rosterItem.roster.add(roster);
rosters.add(rosterItem);
}
return rosters;
}
public void initChatManager() {
if (chatManager == null) {
chatManager = getChatManager();
}
chatManager.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
MyXMPP.chat = chat;
if (!createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Debug.e("Chat obj", chat.toString());
if (message != null || !message.getBody().equalsIgnoreCase(null) || !message.getBody().equalsIgnoreCase("")) {
if (message.getBody() == null || message.getBody().equals(null)) {
} else {
Debug.e("Message aala", "" + message.getBody());
}
} else {
Debug.e("message null", "Message Null");
}
}
});
} else {
Debug.e("MY MSG", chat.getParticipant());
}
}
});
}
public void sendMessage(String to, String msg) {
Chat newChat = app.myXMPP.getChatManager().createChat(to, new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
System.out.println("Received message: " + message);
}
});
try {
Message message = new Message();
message.setFrom(connection.getUser());
message.setTo("xyz#myhostaddress.com");
message.setBody("My Message");
newChat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
Debug.e("send msg listener", message.getBody());
}
});
newChat.sendMessage(message);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Application app;
Button btn;
String threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
app.myXMPP.sendMessage("xyz#myhost.com", "hello");
}
});
//Get Application data access
app = (Application) getApplicationContext();
//Establish Connection and Login
new XMPPOperations().execute();
}
class XMPPOperations extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (app.connection == null || !app.connection.isConnected()) {
app.connection = app.myXMPP.getConnectXMPP();
Debug.e("Connection in activity", "" + app.connection.isConnected());
}
app.myXMPP.getRosters();
app.myXMPP.initChatManager();
return null;
}
}
}
Application.java
public class Application extends android.app.Application {
public MyXMPP myXMPP;
public AbstractXMPPConnection connection;
#Override
public void onCreate() {
super.onCreate();
myXMPP = MyXMPP.getInstance(this);
}
#Override
public void onTerminate() {
super.onTerminate();
Presence p = new Presence(Presence.Type.unavailable);
try {
connection.sendStanza(p);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
I have a class extends Application where I initialize some libraries needed by my application.
I want to launch a ProgressDialog from this class to notify user what App is doing.
Is possible launch these elements from Application classes??
Thanks
ps. attach my code
public class ApplicationLoader extends Application implements InitializeDelegate {
public static String TAG = "ApplicationLoader";
private ProgressDialog pd = null;
private InitializeDelegate initializeDelegate = null;
#Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
#Override
public void onCreate() {
super.onCreate();
// LOAD ANDROID LIBRARY //
initializeDelegate = this;
AndroidLibraries androidLibraries = new AndroidLibraries();
androidLibraries(getApplicationContext(), initializeDelegate);
try {
pd = new ProgressDialog(getApplicationContext());
pd.setMessage("Initializing..");
pd.show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void initializingResult(InitializinResult initializingResult) {
Log.i(TAG,""+ initializingResult);
try {
if (pd != null) {
if (pd.isShowing()) {
pd.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Why not?
But don't do any heavy stuff in the UI Thread. You may use a splash screen in conjunction with a progress bar.
I am planning to use MVP pattern for my new Android project. I have done some sample code and I would like to know, have I implemented it correctly? Please give comments on the code and also post your suggestions.
my activity class I am extending it from my BaseView class and I am implementing an interface. this activity simply calls an webservice in a new thread and updates the value in the textview.
public class CougarTestView extends BaseView implements ICougarView,
OnClickListener {
CougarTestPresenter _presenter;
public String activityName = "CougarHome";
/** Called when the activity is first created. */`enter code here`
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, activityName);
setContentView(R.layout.main);
_presenter = new CougarTestPresenter(this);
getSubmitBtn().setOnClickListener(this);
getCallInfoBtn().setOnClickListener(this);
}
private Button getCallInfoBtn() {
return (Button) findViewById(R.id.btn_callinfo);
}
public void setServiceValue(String retVal) {
// TODO Auto-generated method stub
getResultLabel().setText(retVal);
setPbar(false);
// toastMsg(retVal);
}
public void ResetPbar() {
getProgressBtn().setProgress(0);
}
public void setProcessProgress(int progress) {
if (getProgressBtn().getProgress() < 100) {
getProgressBtn().incrementProgressBy(progress);
} else {
setPbar(false);
}
}
private TextView getResultLabel() {
return (TextView) findViewById(R.id.result);
}
private Button getSubmitBtn() {
return (Button) findViewById(R.id.btn_triptype);
}
private ProgressBar getProgressBtn() {
return (ProgressBar) findViewById(R.id.pgs_br);
}
public void setPbar(boolean visible) {
if (!visible) {
getProgressBtn().setVisibility(View.GONE);
} else
getProgressBtn().setVisibility(View.VISIBLE);
}
#Override
public void setHttpResult(String retVal) {
// TODO Auto-generated method stub
setServiceValue(retVal);
}
private void toastMsg(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_triptype: {
try {
_presenter.valueFromService(RequestType.CallInfo, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
default:
setServiceValue("default");
}
}
}
My activity class: in my activity class i am having a textview and a button. when i press the button , it call the webservice to get the data in the presenter class. the presenter class calls the webservice parses the response and sets the value in the textview of the activity.
My presenter class
public class CougarTestPresenter {
ICougarView mIci;
RequestType mRtype;
public String result= "thisi s result i";
Handler mHandle;
public CougarTestPresenter(ICougarView ici) {
mIci = ici;
}
public void valueFromService(RequestType type, int x) throws Exception{
String url = getURLByType(type);
// GetServiceresult service = new GetServiceresult();
// service.execute(url);
Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case Globals.IO_EXPECTION: {
Toast.makeText(mIci.getContext(), msg.toString(),
Toast.LENGTH_LONG).show();
NetworkConnectivityListener connectivityListener = NetworkConnectivityListener
.getInstace();
mHandle = CustomHandler.getInstance(mIci.getContext(),
connectivityListener, mIci);
connectivityListener.registerHandler(mHandle,
Globals.CONNECTIVITY_MSG);
connectivityListener.startListening(mIci.getContext());
mIci.setPbar(false);
}
break;
case Globals.RHAPSODY_EXCEPTION:{
ExceptionInfo exInfo =null;
try {
exInfo = Utility.ParseExceptionData(msg.obj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mIci.setServiceValue(exInfo.Message + exInfo.Type +exInfo.Detail);
// new HandleRhapsodyException(mIsa, exInfo);
}
break;
default: {
Toast.makeText(mIci.getContext(), msg.toString(),
Toast.LENGTH_LONG).show();
mIci.setServiceValue(msg.obj.toString());
}
}
}
};
ServiceResult thread = new ServiceResult(handle, url);
mIci.setPbar(true);
thread.start();
}
public String getURLByType(RequestType type) {
// TODO Auto-generated method stub
switch (type) {
case CallInfo: {
return ("www.gmail.com");
}
case TripType: {
return ("www.google.com");
}
default:
return ("www.cnet.com");
}
}
private class ServiceResult extends Thread {
Handler handle;
String url;
public ServiceResult(Handler handle, String url) {
this.handle = handle;
this.url = url;
}
public void run() {
sendExceptionLog(handle);
}
}
public void sendExceptionLog(Handler handle) {
DebugHttpClient httpClient = new DebugHttpClient();
HttpGet get = new HttpGet(
"https://192.168.194.141/TripService/service1/");
try {
HttpResponse response = httpClient.execute(get);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
// setdvrid.setText(xmlString + " "
// + response.getStatusLine().getStatusCode());
httpClient.getConnectionManager().shutdown();
if (response.getStatusLine().getStatusCode() != 200) {
handle.sendMessage(Message.obtain(handle, Globals.RHAPSODY_EXCEPTION,
xmlString));
result= Utility.ParseExceptionData(xmlString).Message;
}
else
{
handle.sendMessage(Message.obtain(handle, Globals.SERVICE_REPONSE,
response.getStatusLine().getStatusCode()
+ response.getStatusLine().getReasonPhrase()
+ xmlString));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
e.getMessage().toString() + "she"));
} catch (IOException e) {
// TODO Auto-generated catch block
handle.sendMessage(Message.obtain(handle, Globals.IO_EXPECTION, e
.getMessage().toString() + "he"));
} catch (Exception e) {
handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
e.getMessage().toString() + "it"));
}
}
the below interface is implemented in the activity class and the instance of the activity class is sent as interface object to the constructor of the presenter class.
my view interface
public interface ICougarView {
public void setServiceValue(String retVal);
public void setProcessProgress(int progress);
public void setPbar(boolean b);
public void ResetPbar();
public Context getContext();
}
Sorry for the late :)
I've use MVP on Android this way.
Activities are presenters. Every presenter has a link to model(s) (sometimes it is services, sometimes not, depending from the task) and to view(s). I create custom view and set it as the content view for activity.
See:
public class ExampleModel {
private ExampleActivity presenter;
public ExampleModel(ExampleActivity presenter) {
this.presenter = presenter;
}
//domain logic and so on
}
public class ExampleActivity extends Activity {
private ExampleModel model;
private ExampleView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = new ExampleModel(this);
view = new ExampleView(this);
setContentView(view);
}
// different presenter methods
}
public class ExampleView extends LinearLayout {
public ExampleView(Context context) {
super(context);
}
}
Also, I've discussed this topic here.
I should warn you, that Activity shouldn't be considered as the view. We had very bad expirience with it, when we wrote with PureMVC which considered Activity as view component. Activity is excellently suitable for controller/presenter/view model (I've tried all of them, I like MVP the most), it has excellent instrumentation for managing the views (View, Dialog and so on) while it's not a view itself.