Related
I am developing a peer-to-peer chat app using socket programming in android. The port number of self and IP address and port number of the other peer is given as input and connection is established through socket. I have implemented chat activity using a list-view with custom adapter when the chatting starts, after exchanging some messages, the old message reappears in the list-view and also the order of the sent and the received messages gets spoiled.
I have printed the exchanged message in the logcat of android studio and seems that there is no issue. So what is the reason of the problem ? and What should be the solution?
Here is the Chat Activity
public class ChatActivity extends AppCompatActivity {
String ipAddress,portNo;
//public static String message="";
EditText messageTextView;
TextView responseTextView;
static MessageAdapter mAdapter;
ListView message_List;
ArrayList<Message> messageArray;
EditText portText;
int myport;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
Log.d("STATE",savedInstanceState.toString());
}
setContentView(R.layout.activity_chat);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
String info = bundle.getString("ip&port");
String[] infos = info.split(" ");
ipAddress = infos[0];
portNo = infos[1];
myport = Integer.parseInt(infos[2]);
Log.d("info",ipAddress+" "+portNo+" "+myport);
}
message_List = (ListView) findViewById(R.id.message_list);
messageArray = new ArrayList<Message>();
mAdapter = new MessageAdapter(this, messageArray);
message_List.setAdapter(mAdapter);
messageTextView= (EditText) findViewById(R.id.messageEditText);
//message = messageTextView.getText().toString();
startServer();
}
void startServer(){
Server s = new Server(message_List, messageArray, myport);
s.start();
}
public void sendResponse(View view){
Client c =new Client();
c.execute();
}
public void setView(String s){
String str=responseTextView.getText().toString();
str=str+"\nReceived: "+s;
responseTextView.setText(str);
}
public class Client extends AsyncTask<Void,Void,String> {
String msg = messageTextView.getText().toString();;
#Override
protected String doInBackground(Void... voids) {
try {
String ipadd = ipAddress;
int portr = Integer.parseInt(portNo);
Socket clientSocket = new Socket(ipadd, portr);
OutputStream outToServer =clientSocket.getOutputStream();
PrintWriter output = new PrintWriter(outToServer);
output.println(msg);
output.flush();
clientSocket.close();
}
catch (Exception e) {
e.printStackTrace();
}
return msg;
}
protected void onPostExecute(String result) {
messageArray.add(new Message("Sent: " + result, 0));
message_List.setAdapter(mAdapter);
Log.d("problem","Sent: " + result);
for(Message mssg: messageArray){
String sst = mssg.getMessage();
//Log.d("problem"," "+sst);
}
messageTextView.setText("");
}
}
}
Here is the code of the server
public class Server extends Thread {
ListView messageList;
ArrayList<Message> messageArray;
int port;
public Server(ListView messageList, ArrayList<Message> messageArray, int
port) {
this.messageArray = messageArray;
this.messageList = messageList;
this.port = port;
}
ServerSocket welcomeSocket=null;
#Override
public void run(){
try{
String sentence;
welcomeSocket=new ServerSocket(port);
while (true){
Socket connectionSocket=welcomeSocket.accept();
HandleClient c= new HandleClient();
c.execute(connectionSocket);
}
}
catch(Exception e){
e.printStackTrace();
}
}
public class HandleClient extends AsyncTask<Socket,Void,String>{
String sentence;
#Override
protected String doInBackground(Socket... sockets) {
try {
BufferedReader input = new BufferedReader(new
InputStreamReader(sockets[0].getInputStream()));
sentence = input.readLine();
}
catch(Exception e){
e.printStackTrace();
}
return sentence ;
}
protected void onPostExecute(String result) {
messageArray.add(new Message("Received: " + result, 1));
messageList.setAdapter(mAdapter);
Log.d("problem","Received: " + result);
for(Message mssg: messageArray){
String sst = mssg.getMessage();
//Log.d("problem"," "+sst);
}
}
}
}
Here is my message adapter class
public class MessageAdapter extends BaseAdapter{
Context context;
ArrayList<Message> arr = new ArrayList<>();
public MessageAdapter(Context context,ArrayList<Message> arr) {
this.context = context;
this.arr = arr;
for(Message mssg: arr){
String sst = mssg.getMessage();
Log.d("problem"," "+sst);
}
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int i) {
return arr.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//View listItemView=convertView;
if(convertView==null){
convertView=
LayoutInflater.from(context).inflate(R.layout.message_list,parent,false);
}
Message currentMessage= (Message) getItem(position);
String message=currentMessage.getMessage();
//Log.d("problem"," Current Message: " + message);
if(currentMessage.isSent()){
TextView sent=(TextView) convertView.findViewById(R.id.list_sent);
sent.setText(message);
sent.setVisibility(View.VISIBLE);
//sent.setVisibility(View.VISIBLE);
}
else{
TextView received= (TextView)
convertView.findViewById(R.id.list_received);
received.setText(message);
received.setVisibility(View.VISIBLE);
}
return convertView;
}
}
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.
I am facing the problem to create a new user on ejabberd server but sign in is working fine. i used the github repository (https://github.com/dilicode/LetsChat) for register the new user and chat between two and more users. I search on intenet, i found some way to register those are:
1.add
%% In-band registration
{access, register, [{allow, all}]}.
in access rules in ejabberd server and
2. also add
{mod_register, [
{access_from, register},
...
] ...
it in access rules of ejabberd server.
my sign up activity as follows:
public class SignupActivity extends AppCompatActivity implements OnClickListener, Listener<Boolean> {
private static final int REQUEST_CODE_SELECT_PICTURE = 1;
private static final int REQUEST_CODE_CROP_IMAGE = 2;
private static final String RAW_PHOTO_FILE_NAME = "camera.png";
private static final String AVATAR_FILE_NAME = "avatar.png";
private EditText nameText;
private EditText phoneNumberText;
private EditText passwordText;
private Button submitButton;
private ImageButton uploadAvatarButton;
private File rawImageFile;
private File avatarImageFile;
private SignupTask signupTask;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
nameText = (EditText)findViewById(R.id.et_name);
phoneNumberText = (EditText)findViewById(R.id.et_phone_number);
passwordText = (EditText)findViewById(R.id.et_password);
uploadAvatarButton = (ImageButton)findViewById(R.id.btn_upload_avatar);
submitButton = (Button)findViewById(R.id.btn_submit);
submitButton.setOnClickListener(this);
uploadAvatarButton.setOnClickListener(this);
File dir = FileUtils.getDiskCacheDir(this, "temp");
if (!dir.exists()) {
dir.mkdirs();
}
rawImageFile = new File(dir, RAW_PHOTO_FILE_NAME);
avatarImageFile = new File(dir, AVATAR_FILE_NAME);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if (v == submitButton) {
String phoneNumber = phoneNumberText.getText().toString();
String password = passwordText.getText().toString();
String name = nameText.getText().toString();
if (phoneNumber.trim().length() == 0 || password.trim().length() == 0 ||
name.trim().length() == 0) {
Toast.makeText(this, R.string.incomplete_signup_info, Toast.LENGTH_SHORT).show();
return;
}
signupTask = new SignupTask(this, this, phoneNumber, password, name, getAvatarBytes());
signupTask.execute();
} else if(v == uploadAvatarButton) {
chooseAction();
}
}
private void chooseAction() {
Intent captureImageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rawImageFile));
Intent pickIntent = new Intent(Intent.ACTION_GET_CONTENT);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(pickIntent, getString(R.string.profile_photo));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {captureImageIntent});
startActivityForResult(chooserIntent, REQUEST_CODE_SELECT_PICTURE);
}
#Override
public void onResponse(Boolean result) {
if (result) {
Toast.makeText(this, R.string.login_success, Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
setResult(RESULT_OK);
finish();
}
}
#Override
public void onErrorResponse(Exception exception) {
Toast.makeText(this, R.string.create_account_error, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_CODE_SELECT_PICTURE:
boolean isCamera;
if (data == null) {
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
if (isCamera) {
startCropImage(Uri.fromFile(rawImageFile));
} else {
startCropImage(data == null ? null : data.getData());
}
break;
case REQUEST_CODE_CROP_IMAGE:
Bitmap bitmap = BitmapFactory.decodeFile(avatarImageFile.getAbsolutePath());
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
drawable.setCircular(true);
uploadAvatarButton.setImageDrawable(drawable);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startCropImage(Uri source) {
if (source != null) {
int size = getResources().getDimensionPixelSize(R.dimen.default_avatar_size);
CropImageIntentBuilder cropImage = new CropImageIntentBuilder(size, size, Uri.fromFile(avatarImageFile));
cropImage.setSourceImage(source);
startActivityForResult(cropImage.getIntent(this), REQUEST_CODE_CROP_IMAGE);
}
}
private byte[] getAvatarBytes() {
if (!avatarImageFile.exists()) return null;
InputStream inputStream = null;
try {
inputStream = new FileInputStream(avatarImageFile);
} catch (FileNotFoundException e) {
AppLog.e("avatar file not found", e);
}
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
return output.toByteArray();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (signupTask != null) {
signupTask.dismissDialogAndCancel();
}
}
}
SignupTaskActivity as follows:
public class SignupTask extends BaseAsyncTask<Void, Void, Boolean> {
private String user;
private String name;
private String password;
private byte[] avatar;
private ProgressDialog dialog;
public SignupTask(Listener<Boolean> listener, Context context, String user, String password, String name, byte[] avatar) {
super(listener, context);
this.user = user;
this.name = name;
this.password = password;
this.avatar = avatar;
dialog = ProgressDialog.show(context, null, context.getResources().getString(R.string.signup));
}
#Override
public Response<Boolean> doInBackground(Void... params) {
Context context = getContext();
if (context != null) {
try {
SmackHelper.getInstance(context).signupAndLogin(user, password, name, avatar);
if (avatar != null) {
ImageCache.addAvatarToFile(context, user, BitmapFactory.decodeByteArray(avatar, 0, avatar.length));
}
PreferenceUtils.setLoginUser(context, user, password, name);
return Response.success(true);
} catch(SmackInvocationException e) {
AppLog.e(String.format("sign up error %s", e.toString()), e);
return Response.error(e);
}
}
return null;
}
#Override
protected void onPostExecute(Response<Boolean> response) {
dismissDialog();
super.onPostExecute(response);
}
#Override
protected void onCancelled() {
super.onCancelled();
dismissDialog();
}
public void dismissDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void dismissDialogAndCancel() {
dismissDialog();
cancel(false);
}
}
SmackHelper class as follows:
public class SmackHelper {
private static final String LOG_TAG = "SmackHelper";
private static final int PORT = 5222;
public static final String RESOURCE_PART = "Smack";
private XMPPConnection con;
private ConnectionListener connectionListener;
private Context context;
private State state;
private PacketListener messagePacketListener;
private PacketListener presencePacketListener;
private SmackAndroid smackAndroid;
private static SmackHelper instance;
private SmackContactHelper contactHelper;
private SmackVCardHelper vCardHelper;
private FileTransferManager fileTransferManager;
private PingManager pingManager;
private long lastPing = new Date().getTime();
public static final String ACTION_CONNECTION_CHANGED = "com.mstr.letschat.intent.action.CONNECTION_CHANGED";
public static final String EXTRA_NAME_STATE = "com.mstr.letschat.State";
private SmackHelper(Context context) {
this.context = context;
smackAndroid = SmackAndroid.init(context);
messagePacketListener = new MessagePacketListener(context);
presencePacketListener = new PresencePacketListener(context);
SmackConfiguration.setDefaultPacketReplyTimeout(20 * 1000);
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
ProviderManager.addExtensionProvider(UserLocation.ELEMENT_NAME, UserLocation.NAMESPACE, new LocationMessageProvider());
}
public static synchronized SmackHelper getInstance(Context context) {
if (instance == null) {
instance = new SmackHelper(context.getApplicationContext());
}
return instance;
}
public void setState(State state) {
if (this.state != state) {
Log.d(LOG_TAG, "enter state: " + state.name());
this.state = state;
}
}
public void signupAndLogin(String user, String password, String nickname, byte[] avatar) throws SmackInvocationException {
connect();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("name", nickname);
try {
AccountManager.getInstance(con).createAccount(user, password, attributes);
} catch (Exception e) {
throw new SmackInvocationException(e);
}
login(user, password);
vCardHelper.save(nickname, avatar);
}
public void sendChatMessage(String to, String body, PacketExtension packetExtension) throws SmackInvocationException {
Message message = new Message(to, Message.Type.chat);
message.setBody(body);
if (packetExtension != null) {
message.addExtension(packetExtension);
}
try {
con.sendPacket(message);
} catch (NotConnectedException e) {
throw new SmackInvocationException(e);
}
}
public List<RosterEntry> getRosterEntries() {
List<RosterEntry> result = new ArrayList<RosterEntry>();
Roster roster = con.getRoster();
Collection<RosterGroup> groups = roster.getGroups();
for (RosterGroup group : groups) {
result.addAll(group.getEntries());
}
return result;
}
and finally my menifest file
public UserProfile search(String username) throws SmackInvocationException {
String name = StringUtils.parseName(username);
String jid = null;
if (name == null || name.trim().length() == 0) {
jid = username + "#" + con.getServiceName();
} else {
jid = StringUtils.parseBareAddress(username);
}
if (vCardHelper == null) {
return null;
}
VCard vCard = vCardHelper.loadVCard(jid);
String nickname = vCard.getNickName();
return nickname == null ? null : new UserProfile(jid, vCard);
}
public String getNickname(String jid) throws SmackInvocationException {
VCard vCard = vCardHelper.loadVCard(jid);
return vCard.getNickName();
}
private void connect() throws SmackInvocationException {
if (!isConnected()) {
setState(State.CONNECTING);
if (con == null) {
con = createConnection();
}
try {
con.connect();
}catch (SmackException.NoResponseException er){
Log.e(LOG_TAG,"Norespponse exception");
}
catch(Exception e) {
Log.e(LOG_TAG, String.format("Unhandled exception %s", e.toString()), e);
startReconnectIfNecessary();
throw new SmackInvocationException(e);
}
}
}
#SuppressLint("TrulyRandom")
private XMPPConnection createConnection() {
ConnectionConfiguration config = new ConnectionConfiguration(PreferenceUtils.getServerHost(context), PORT);
SSLContext sc = null;
MemorizingTrustManager mtm = null;
try {
mtm = new MemorizingTrustManager(context);
sc = SSLContext.getInstance("TLS");
sc.init(null, new X509TrustManager[] { mtm }, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (KeyManagementException e) {
throw new IllegalStateException(e);
}
config.setCustomSSLContext(sc);
config.setHostnameVerifier(mtm.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier()));
config.setSecurityMode(SecurityMode.required);
config.setReconnectionAllowed(false);
config.setSendPresence(false);
config.setSecurityMode(SecurityMode.disabled);
List<HostAddress> list = config.getHostAddresses();
boolean data = config.isSendPresence();
return new XMPPTCPConnection(config);
}
public void cleanupConnection() {
if (con != null) {
con.removePacketListener(messagePacketListener);
con.removePacketListener(presencePacketListener);
if (connectionListener != null) {
con.removeConnectionListener(connectionListener);
}
}
if (isConnected()) {
try {
con.disconnect();
} catch (NotConnectedException e) {}
}
}
private void onConnectionEstablished() {
if (state != State.CONNECTED) {
//processOfflineMessages();
try {
con.sendPacket(new Presence(Presence.Type.available));
} catch (NotConnectedException e) {}
contactHelper = new SmackContactHelper(context, con);
vCardHelper = new SmackVCardHelper(context, con);
fileTransferManager = new FileTransferManager(con);
OutgoingFileTransfer.setResponseTimeout(30000);
addFileTransferListener();
pingManager = PingManager.getInstanceFor(con);
pingManager.registerPingFailedListener(new PingFailedListener() {
#Override
public void pingFailed() {
// Note: remember that maybeStartReconnect is called from a different thread (the PingTask) here, it may causes synchronization problems
long now = new Date().getTime();
if (now - lastPing > 30000) {
Log.e(LOG_TAG, "Ping failure, reconnect");
startReconnectIfNecessary();
lastPing = now;
} else {
Log.e(LOG_TAG, "Ping failure reported too early. Skipping this occurrence.");
}
}
});
con.addPacketListener(messagePacketListener, new MessageTypeFilter(Message.Type.chat));
con.addPacketListener(presencePacketListener, new PacketTypeFilter(Presence.class));
con.addConnectionListener(createConnectionListener());
setState(State.CONNECTED);
broadcastState(State.CONNECTED);
MessageService.reconnectCount = 0;
}
}
private void broadcastState(State state) {
Intent intent = new Intent(ACTION_CONNECTION_CHANGED);
intent.putExtra(EXTRA_NAME_STATE, state.toString());
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
public void login(String username, String password) throws SmackInvocationException {
connect();
try {
if (!con.isAuthenticated()) {
con.login(username, password, RESOURCE_PART);
}
onConnectionEstablished();
} catch(Exception e) {
SmackInvocationException exception = new SmackInvocationException(e);
// this is caused by wrong username/password, do not reconnect
if (exception.isCausedBySASLError()) {
cleanupConnection();
} else {
startReconnectIfNecessary();
}
throw exception;
}
}
public String getLoginUserNickname() throws SmackInvocationException {
try {
return AccountManager.getInstance(con).getAccountAttribute("name");
} catch (Exception e) {
throw new SmackInvocationException(e);
}
}
private void processOfflineMessages() {
Log.i(LOG_TAG, "Begin retrieval of offline messages from server");
OfflineMessageManager offlineMessageManager = new OfflineMessageManager(con);
try {
if (!offlineMessageManager.supportsFlexibleRetrieval()) {
Log.d(LOG_TAG, "Offline messages not supported");
return;
}
List<Message> msgs = offlineMessageManager.getMessages();
for (Message msg : msgs) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(msg.getFrom()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, msg.getBody());
context.startService(intent);
}
offlineMessageManager.deleteMessages();
} catch (Exception e) {
Log.e(LOG_TAG, "handle offline messages error ", e);
}
Log.i(LOG_TAG, "End of retrieval of offline messages from server");
}
private ConnectionListener createConnectionListener() {
connectionListener = new ConnectionListener() {
#Override
public void authenticated(XMPPConnection arg0) {}
#Override
public void connected(XMPPConnection arg0) {}
#Override
public void connectionClosed() {
Log.e(LOG_TAG, "connection closed");
}
#Override
public void connectionClosedOnError(Exception arg0) {
// it may be due to network is not available or server is down, update state to WAITING_TO_CONNECT
// and schedule an automatic reconnect
Log.e(LOG_TAG, "connection closed due to error ", arg0);
startReconnectIfNecessary();
}
#Override
public void reconnectingIn(int arg0) {}
#Override
public void reconnectionFailed(Exception arg0) {}
#Override
public void reconnectionSuccessful() {}
};
return connectionListener;
}
private void startReconnectIfNecessary() {
cleanupConnection();
setState(State.WAITING_TO_CONNECT);
if (NetworkUtils.isNetworkConnected(context)) {
context.startService(new Intent(MessageService.ACTION_RECONNECT, null, context, MessageService.class));
}
}
private boolean isConnected() {
return con != null && con.isConnected();
}
public void onNetworkDisconnected() {
setState(State.WAITING_FOR_NETWORK);
}
public void requestSubscription(String to, String nickname) throws SmackInvocationException {
contactHelper.requestSubscription(to, nickname);
}
public void approveSubscription(String to, String nickname, boolean shouldRequest) throws SmackInvocationException {
contactHelper.approveSubscription(to);
if (shouldRequest) {
requestSubscription(to, nickname);
}
}
public void delete(String jid) throws SmackInvocationException {
contactHelper.delete(jid);
}
public String loadStatus() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadStatus();
}
public VCard loadVCard(String jid) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard(jid);
}
public VCard loadVCard() throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
return vCardHelper.loadVCard();
}
public void saveStatus(String status) throws SmackInvocationException {
if (vCardHelper == null) {
throw new SmackInvocationException("server not connected");
}
vCardHelper.saveStatus(status);
contactHelper.broadcastStatus(status);
}
public SubscribeInfo processSubscribe(String from) throws SmackInvocationException {
SubscribeInfo result = new SubscribeInfo();
RosterEntry rosterEntry = contactHelper.getRosterEntry(from);
ItemType rosterType = rosterEntry != null ? rosterEntry.getType() : null;
if (rosterEntry == null || rosterType == ItemType.none) {
result.setType(SubscribeInfo.TYPE_WAIT_FOR_APPROVAL);
result.setNickname(getNickname(from));
} else if (rosterType == ItemType.to) {
result.setType(SubscribeInfo.TYPE_APPROVED);
result.setNickname(rosterEntry.getName());
approveSubscription(from, null, false);
}
result.setFrom(from);
return result;
}
public void sendImage(File file, String to) throws SmackInvocationException {
if (fileTransferManager == null || !isConnected()) {
throw new SmackInvocationException("server not connected");
}
String fullJid = to + "/" + RESOURCE_PART;
OutgoingFileTransfer transfer = fileTransferManager.createOutgoingFileTransfer(fullJid);
try {
transfer.sendFile(file, file.getName());
} catch (SmackException e) {
Log.e(LOG_TAG, "send file error");
throw new SmackInvocationException(e);
}
while(!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
Log.d(LOG_TAG, "send file status: " + transfer.getStatus());
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
throw new SmackInvocationException("send file error, " + transfer.getError());
}
}
private void addFileTransferListener() {
fileTransferManager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(final FileTransferRequest request) {
new Thread() {
#Override
public void run() {
IncomingFileTransfer transfer = request.accept();
String fileName = String.valueOf(System.currentTimeMillis());
File file = new File(FileUtils.getReceivedImagesDir(context), fileName + FileUtils.IMAGE_EXTENSION);
try {
transfer.recieveFile(file);
} catch (SmackException e) {
Log.e(LOG_TAG, "receive file error", e);
return;
}
while (!transfer.isDone()) {
if(transfer.getStatus().equals(Status.refused) || transfer.getStatus().equals(Status.error)
|| transfer.getStatus().equals(Status.cancelled)){
Log.e(LOG_TAG, "receive file error, " + transfer.getError());
return;
}
}
// start service to save the image to sqlite
if (transfer.getStatus().equals(Status.complete)) {
Intent intent = new Intent(MessageService.ACTION_MESSAGE_RECEIVED, null, context, MessageService.class);
intent.putExtra(MessageService.EXTRA_DATA_NAME_FROM, StringUtils.parseBareAddress(request.getRequestor()));
intent.putExtra(MessageService.EXTRA_DATA_NAME_MESSAGE_BODY, context.getString(R.string.image_message_body));
intent.putExtra(MessageService.EXTRA_DATA_NAME_FILE_PATH, file.getAbsolutePath());
intent.putExtra(MessageService.EXTRA_DATA_NAME_TYPE, ChatMessageTableHelper.TYPE_INCOMING_IMAGE);
context.startService(intent);
}
}
}.start();
}
});
}
public void onDestroy() {
cleanupConnection();
smackAndroid.onDestroy();
}
public static enum State {
CONNECTING,
CONNECTED,
DISCONNECTED,
// this is a state that client is trying to reconnect to server
WAITING_TO_CONNECT,
WAITING_FOR_NETWORK;
}
}
but i could not found any progress.please help me out. thanks in advance.
After struggle i found solution of this kind of problem. we need to do server side changes like:
step1:
step2:
step3:
after doing all these steps we will able to register new user on ejabberd server.
i'm trying to save object(saveMOvie) in onSaveinstanceState to restore it on screen rotated when debugging the code using tablet with main and detail fragments are next to each other the value of object (saveMOvie) is null but when using mobile phone with only one fragment on screen the value of object (saveMOvie) doesn't equal null could anyone tell me why ??
MainActivityFragment
public class MainActivityFragment extends Fragment {
Movie moviesStore[];
GridView gridView;
String[] moviesImages;
View rootView;
ImageAdapter imgadpt;
boolean flag;
OnNewsItemSelectedListener onis;
Movie saveMOvie = new Movie();
public interface OnNewsItemSelectedListener {
public void onMovieSelected(Movie movie);
}
public MainActivityFragment() {
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();//3shan myy7slash duplicate
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
onis = (OnNewsItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNewsItemSelectedListener");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.open_settings_activity) {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
//refresh used when there is no connection
} else if (id == R.id.Refresh_activity) {
onStart();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mode = prefs.getString(getString(R.string.key),
getString(R.string.default_value));
if (mode.equals("popular") || mode.equals("top_rated")) {
new FetchMovies().execute(mode);
} else {
if (flag) {
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
FavouriteActivityFragment fav = new FavouriteActivityFragment();
fragmentTransaction.replace(R.id.frag_main, fav);
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
Intent intent = new Intent(getActivity(), FavouriteActivity.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
transaction.commit();
flag = isTablet(getActivity());
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf == null && nf.isConnected() != true) {
Snackbar snackbar = Snackbar
.make(rootView, "Network Not Available", Snackbar.LENGTH_LONG)
.setAction("RECONNECT", new View.OnClickListener() {
#Override
public void onClick(View view) {
onStart();
}
});
snackbar.show();
}
updateMovies();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("movie",saveMOvie);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
onis.onMovieSelected(saveMOvie);
}
setHasOptionsMenu(true);
rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridView);
return rootView;
}
public class FetchMovies extends AsyncTask<String, Void, Movie[]> {
private final String Log_Tag = FetchMovies.class.getSimpleName();
private Movie[] getMovieDataFromJson(String moviesJasonStr)
throws JSONException
{
final String lists = "results";
final String decription = "overview";
final String originalTitle = "original_title";
final String moviePoster = "poster_path";
final String userRating = "vote_average";
final String releaseDate = "release_date";
final String id = "id";
JSONObject moviesJason = new JSONObject(moviesJasonStr);
JSONArray moviesArray = moviesJason.getJSONArray(lists);
// String[] resultStrs = new String[moviesArray.length()];
moviesStore = new Movie[moviesArray.length()];
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject oneMovieInfo = moviesArray.getJSONObject(i);
moviesStore[i] = new Movie();
moviesStore[i].setPlotSynopsis(oneMovieInfo.getString("overview"));
moviesStore[i].setUserRating(oneMovieInfo.getString("vote_average"));
moviesStore[i].setReleaseDate(oneMovieInfo.getString("release_date"));
moviesStore[i].setOriginalTitle(oneMovieInfo.getString("original_title"));
moviesStore[i].setMoviePoster(oneMovieInfo.getString("poster_path"));
moviesStore[i].setId(oneMovieInfo.getString("id"));
}
return moviesStore;
}
#Override
protected Movie[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJasonStr = null;
StringBuilder baseUrl = new StringBuilder("https://api.themoviedb.org/3/movie/");
baseUrl.append(params[0]);
baseUrl.append("?api_key=");
baseUrl.append(BuildConfig.MOVIE_DP_API_KEY);
try {
// URL url = new URL("https://api.themoviedb.org/3/movie/popular?api_key=d51b32efc0520227b7c1c67e0f6417f6");
URL url = new URL(baseUrl.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
moviesJasonStr = buffer.toString();
Log.v(Log_Tag, "movies Jason String :" + moviesJasonStr);
} catch (IOException e) {
Log.e(Log_Tag, "Error ", e);
// Toast.makeText(getActivity(),"there is no internet connection",Toast.LENGTH_LONG).show();
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(Log_Tag, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(moviesJasonStr);
} catch (JSONException e) {
Log.e(Log_Tag, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Movie[] result) {
if (result != null) {
moviesImages = new String[result.length];
for (int i = 0; i < result.length; i++) {
StringBuilder baseUrl = new StringBuilder();
baseUrl.append("http://image.tmdb.org/t/p/w185/");
baseUrl.append(result[i].getMoviePoster());
moviesImages[i] = baseUrl.toString();
}
imgadpt = new ImageAdapter(getActivity(), moviesImages);
gridView.setAdapter(imgadpt);
// if(flag){
// onis.onMovieSelected(moviesStore[0]);}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String posterUrl = (String) imgadpt.getItem(position);
saveMOvie = moviesStore[position];
if (flag) {
onis.onMovieSelected(moviesStore[position]);
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("movie", moviesStore[position]);
startActivity(intent);
}
}
});
} else {
Toast.makeText(getActivity(), "Cannot Fetch Data from api check your internet Connection", Toast.LENGTH_LONG).show();
}
}
}
}
When onCreate(savedInstanceState) is called, check whether savedInstanceState is null, and if not, then getExtras from it (as it's a Bundle).
if (savedInstanceState != null)
savedInstanceState.getParcelable(key)
Then do whatever you'd like with the object.
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}