Android: Activity freezes while running code that takes a while to complete - android

The app I am working on takes JSONs from a server and has to interpret them. I have around 6-7 JSONs that are requested.
As such, this is bound to take some time.
This code runs whenever the user types in information to an EditText and clicks a button. After the search button is clicked, the app freezes and will not do anything until all the data is loaded.
I tried having the code like this:
Button button = (Button) findViewById(R.id.search_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(summonerNameET.getWindowToken(), 0);
final CollectUserData c = new CollectUserData();
c.setRegion(region);
c.setSummonerName(summonerNameET.getText().toString());
Runnable r = new Runnable() {
#Override
public void run() {
try {
c.setUpTheJSONs();
updateUI(c);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
};
r.run();
}
});
But it still freezes. Here is the code for setUpTheJSON();
public void setUpTheJSONs() throws IOException, JSONException, URISyntaxException {
jsonSummonerInfo = getJsonSummonerInfo();
if(canIContinue()) {
jsonSummonerStats = getJsonSummaryStats();
//jsonSummonerRankedStats = getJsonRankedStats();
jsonSummonerMatchHistory = getJsonMatchHistory();
jsonSummonerLeagueInfo = getJsonSummonerLeagueInfo();
jsonSummonerRecentGames = getJsonSummonerRecentGames();
}
}
And here is the code for unpdateUI(c);
public void updateUI(CollectUserData c) {
if (c.canIContinue()) {
String league = "";
try {
league = c.getMundaneCurrentLeague();
} catch (JSONException e) {
e.printStackTrace();
}
setLeague(tierIV, league);
try {
summonerNameTV.setText(c.getSummonerName());
} catch (JSONException e) {
e.printStackTrace();
}
try {
tierTV.setText(c.getTier());
} catch (JSONException e) {
e.printStackTrace();
}
try {
leaguePointsTV.setText(c.getLeaguePoints() + "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
winsTV.setText("W: " + c.getWins());
} catch (JSONException e) {
e.printStackTrace();
}
slashTV.setText("/");
try {
lossesTV.setText("L: " + c.getLosses());
} catch (JSONException e) {
e.printStackTrace();
}
try {
lastSeasonRankTV.setText("Season 4: " + c.getRankOfLastSeason());
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameModeGameOneTV.setText(c.getGameType(1));
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameOneChampion.setBackground(c.getChampionPicturePlayed(1));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneKillsTV.setText(c.getKills(1) + "");
} catch (JSONException e) {
e.printStackTrace();
}
gameOneSlashOneTV.setText(" / ");
try {
gameOneDeathsTV.setText(c.getDeaths(1) + "");
} catch (JSONException e) {
e.printStackTrace();
}
gameOneSlashTwoTV.setText(" / ");
try {
gameOneAssistsTV.setText(c.getAssists(1) + "");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameOneGoldTV.setText(c.getGold(1) + " K");
} catch (JSONException e) {
e.printStackTrace();
}
try {
gameOneCSTV.setText(" " + c.getMinionsKilled(1) + " CS");
} catch (JSONException e) {
e.printStackTrace();
}
boolean gameOneWon = true;
try {
gameOneWon = c.isGameWon(1);
} catch (JSONException e) {
e.printStackTrace();
}
if (gameOneWon) {
gameOneTitleBar.setBackgroundColor(Color.parseColor("#d604c429"));
gameOne.setBackgroundColor(Color.parseColor("#4600FF06"));
}
if (!gameOneWon) {
gameOneTitleBar.setBackgroundColor(Color.parseColor("#d6ff0100"));
gameOne.setBackgroundColor(Color.parseColor("#4fff0100"));
}
try {
gameOneItemOneIV.setBackground(c.getItemFromMatchHistory(1, 0, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemTwoIV.setBackground(c.getItemFromMatchHistory(1, 1, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemThreeIV.setBackground(c.getItemFromMatchHistory(1, 2, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemFourIV.setBackground(c.getItemFromMatchHistory(1, 3, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemFiveIV.setBackground(c.getItemFromMatchHistory(1, 4, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
gameOneItemSixIV.setBackground(c.getItemFromMatchHistory(1, 5, getResources()));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Drawable[] tempDrawable = null;
try {
tempDrawable = c.getTeamPlayerChampionIcon(1, 100);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempDrawable != null) {
gameOneTeamOnePlayerOne.setBackground(tempDrawable[0]);
gameOneTeamOnePlayerTwo.setBackground(tempDrawable[1]);
gameOneTeamOnePlayerThree.setBackground(tempDrawable[2]);
gameOneTeamOnePlayerFour.setBackground(tempDrawable[3]);
gameOneTeamOnePlayerFive.setBackground(tempDrawable[4]);
}
Drawable[] tempDrawable2 = null;
try {
tempDrawable2 = c.getTeamPlayerChampionIcon(1, 200);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempDrawable != null) {
gameOneTeamTwoPlayerOne.setBackground(tempDrawable2[0]);
gameOneTeamTwoPlayerTwo.setBackground(tempDrawable2[1]);
gameOneTeamTwoPlayerThree.setBackground(tempDrawable2[2]);
gameOneTeamTwoPlayerFour.setBackground(tempDrawable2[3]);
gameOneTeamTwoPlayerFive.setBackground(tempDrawable2[4]);
}
String[] tempString = null;
try {
tempString = c.getTeamPlayerName(1, 100);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempString != null) {
gameOneTeamOnePlayerOneName.setText(tempString[0]);
gameOneTeamOnePlayerTwoName.setText(tempString[1]);
gameOneTeamOnePlayerThreeName.setText(tempString[2]);
gameOneTeamOnePlayerFourName.setText(tempString[3]);
gameOneTeamOnePlayerFiveName.setText(tempString[4]);
}
String[] tempString2 = null;
try {
tempString2 = c.getTeamPlayerName(1, 200);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (tempString2 != null) {
gameOneTeamTwoPlayerOneName.setText(tempString2[0]);
gameOneTeamTwoPlayerTwoName.setText(tempString2[1]);
gameOneTeamTwoPlayerThreeName.setText(tempString2[2]);
gameOneTeamTwoPlayerFourName.setText(tempString2[3]);
gameOneTeamTwoPlayerFiveName.setText(tempString2[4]);
}
}
}
Anyone know a fix for this?
Thanks ☺

You need to introduce multi threading. The r.run() command needs to be started by another thread.
http://developer.android.com/training/multiple-threads/index.html

You are running the Runnable in the UI Thread and this is why you are getting your UI blocked until it finished.
Try something like this:
Button button = (Button) findViewById(R.id.search_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(summonerNameET.getWindowToken(), 0);
final CollectUserData c = new CollectUserData();
c.setRegion(region);
c.setSummonerName(summonerNameET.getText().toString());
new Thread(new Runnable() {
#Override
public void run() {
try {
c.setUpTheJSONs();
updateUI(c);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}).start();
}
});

Put your downloading files in a separate thread. Use AsyncTask or Java Thread. Just simply.
class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Show progress dialog, if u want
}
#Override
protected Void doInBackground(Void... params) {
//Do all your processing here!
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Return some result to UI
}
}

Related

Multiuserchat InvitationListener Smack: 4.1.0 not getting called

I have already gone through related questions on stack but all in vain. I am not getting callback in Invitation Listener. Any help will be appreciated.
MultiUserChatListener
MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
#Override
public void invitationReceived(XMPPConnection conn, MultiUserChat room, String inviter, String reason, String password, Message message) {
String nickname = AppSharedPereference.getInstance(mContext).getUserName();
try {
mchat.join(nickname);
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
});
}
sendInvitation Method
public void sendInvites(ArrayList<ContactData.Usercontactsdetail> usercontactsdetail) {
try {
for (int i = 0; i < usercontactsdetail.size(); i++) {
String userID = usercontactsdetail.get(i).getContactid();
String user = userID + "#" + connection.getHost();
mchat.invite(user,
userID + "_user");
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}finally {
usercontactsdetail = null;
}
try {
mchat.sendMessage("New group created");
} catch (SmackException.NotConnectedException e1) {
e1.printStackTrace();
}
}

XMPP error reply received from myroom#conference.****/myroom#conference.****: XMPPError: item-not-found - cancel

I am not able to join the room. I have gone through the documentation XMPP Instant Room Error
Here is how i am creating instant room:
try {
UserSearchManager usm = new UserSearchManager(Utils.connection);
List<DomainBareJid> services = usm.getSearchServices();
String roomjid = "myroom#" + services.get(0);
mucJid = JidCreate.entityBareFrom(roomjid);
Log.d(TAG, mucJid.toString());
// Create the nickname.
nickname = Resourcepart.from(roomjid);
Log.d(TAG, nickname.toString());
} catch (XmppStringprepException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
}
// Get the MultiUserChatManager
manager = MultiUserChatManager.getInstanceFor(Utils.connection);
// Get a MultiUserChat using MultiUserChatManager
MultiUserChat muc = manager.getMultiUserChat(mucJid);
// Create the room and send an empty configuration form to make this an instant room
try {
// Prepare a list of owners of the new room
Set<Jid> owners = JidUtil.jidSetFrom(new String[] { "54321#rahul", "12345#rahul" });
muc.create(nickname)
.getConfigFormManager()
.setRoomOwners(owners)
.submitConfigurationForm();
muc.sendConfigurationForm(new Form(DataForm.Type.submit));
muc.join(nickname);
EntityBareJid invitemucJid = JidCreate.entityBareFrom("12345#rahul");
muc.invite(invitemucJid, "testing");
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (MultiUserChatException.MucAlreadyJoinedException e) {
e.printStackTrace();
} catch (MultiUserChatException.MissingMucCreationAcknowledgeException e) {
e.printStackTrace();
} catch (MultiUserChatException.NotAMucServiceException e) {
e.printStackTrace();
} catch (XmppStringprepException e) {
e.printStackTrace();
} catch (MultiUserChatException.MucConfigurationNotSupportedException e) {
e.printStackTrace();
}
The MUC room is getting created successfully. But when i am checking through Invitation Listener and trying to join the room. It is giving error.
The Invitation listener code is as follow:
try {
Resourcepart nickname = Resourcepart.from(room.getRoom().toString());
room.join(nickname);
Log.d(TAG, "room status---> " + room.isJoined());
runOnUiThread(new Runnable() {
#Override
public void run() {
if (room.isJoined()) {
Toast.makeText(FriendListActivity.this, "Joined", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(FriendListActivity.this, "Not joined", Toast.LENGTH_SHORT).show();
}
}
});
} catch (XmppStringprepException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (MultiUserChatException.NotAMucServiceException e) {
e.printStackTrace();
}
Below is screen shot of the stack Trace
As per the documentation it says that the MUC room is locked. But I have created instant room along with default configuration.
Maybe it's a network error, I do somethings wrong if I use Wifi but get corrcet result with cellular network.

Quickblox sample chat Android privacy settings (block or unblock)

in quickblock sample chat, trying to add block and unblock for user 1-1 was unable to include ALL of the desired items .Only one user was adding to list always this is my code
privacyListsManager = QBChatService.getInstance().getPrivacyListsManager();
privacyListsManager.addPrivacyListListener(privacyListListener);
privacyListsManager.setPrivacyListAsActive("public");
QBPrivacyList list_all = null;
try {
list_all = privacyListsManager.getPrivacyList("public");
Log.e("lists", "privacyCheck: " + list_all + list_all.getItems());
privacyListsManager.setPrivacyList(list_all);
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
and on click of block, private void blockUser() {
List<Integer> userIds = qbChatDialog.getOccupants();
Log.e("userid ", "blockUser: " + id);
QBPrivacyList list = new QBPrivacyList();
list.setName("public");
ArrayList<QBPrivacyListItem> items = new ArrayList<QBPrivacyListItem>();
QBPrivacyListItem item1 = new QBPrivacyListItem();
item1.setAllow(false);
item1.setType(QBPrivacyListItem.Type.USER_ID);
item1.setValueForType(String.valueOf(id));
items.add(item1);
list.setItems(items);
try {
privacyListsManager.setPrivacyList(list);
privacyListsManager.setPrivacyListAsDefault("public");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
privacyListListener = new QBPrivacyListListener() {
#Override
public void setPrivacyList(String listName, List<QBPrivacyListItem> listItem){
Log.e("block", "setPrivacyList: " );
}
#Override
public void updatedPrivacyList(String listName) {
Log.e("unblock", "setPrivacyList: " );
}
};
}
The problem is `QBPrivacyList always used to be override with the block click values but I want the previous data to be saved.

How can i save data from multipart/form-data in servlet and save this data to db?

public void saveData(HttpServletRequest request,HttpServletResponse response) throws IOException {
try {
boolean checkMultiPart = ServletFileUpload.isMultipartContent(request);
System.out.println(checkMultiPart);
//fin = request.getInputStream();
Part part = request.getPart("pic");
fin = part.getInputStream();
System.out.println(fin);
writer = response.getWriter();
if(fin != null){
fin.read();
System.out.println("Inside Function");
query = "INSERT INTO SAVEPIC(picID,PIC) VALUES (picIncVal.nextval,?)";
Class.forName(DB_DRIVER);
connection = DriverManager.getConnection(DB_URL, DB_USER,DB_PASSWORD);
connection.setAutoCommit(false);
insertStatement = connection.prepareStatement(query);
insertStatement.setBinaryStream(1, fin, fin.available());
row = insertStatement.executeUpdate();
connection.commit();
System.out.println("Save To Data Base");
}
if (row > 0)
writer.print("SUCCESS");
else
writer.print("FAILED");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (NullPointerException e) {
writer.print("Pic Value is Null");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(fin != null)
fin.close();
if(writer != null)
writer.close();
if (connection != null) {
insertStatement.close();
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
I want to store image which i am sending from android in multipart/form-data. Can any one give me suggestions how can i do it.
By this code only some bits are storing into the db, Not whole image.
Thanks in advance.

Android getOnTouchListener with API version >= 15

I need to know if there has been set an OnTouchListener to a view.
Following code works fine below api level 15.
public static boolean isSetOnTouchListener_v8(View v) {
try {
Class<View> clazz = (Class<View>) Class.forName("android.view.View");
Field f = clazz.getDeclaredField("mOnTouchListener");
f.setAccessible(true);
if (f.get(v) == null) {
return false;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
Now I need the same method for api level 15 and above.
I tried the following code, but it's not working. Does anyone have any suggestions?
public static boolean isSetOnTouchListener_v15(View v) {
try {
Object listenerInfo = getListenerInfo(v);
if (listenerInfo != null) {
Class<? extends Object> clazz = listenerInfo.getClass();
Field f = clazz.getDeclaredField("mOnTouchListener");
f.setAccessible(true);
if (f.get(listenerInfo) == null) return false;
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return true;
}
private static Object getListenerInfo(View v) {
Field f = null;
try {
f = View.class.getDeclaredField("mListenerInfo");
f.setAccessible(true);
return (Object) f.get(v);
} catch (Exception e) {
return null;
}
}

Categories

Resources