AutoCompleteTextField list does not always scroll to top? - autocomplete

The AutoCompleteTextField seems to work exactly as intended until I start backspacing in the TextField. I am not sure what the difference is, but if I type in something like "123 M" then I get values that start with "123 M". If I backspace and delete the M leaving "123 " in the field, the list changes, but it does not scroll to the top of the list.
I should note that everything works fine on the simulator and that I am experiencing this behavior when running a debug build on my iPhone.
EDIT: So this does not only seem to happen when backspacing. This image shows the results I have when typing in an address key by key. In any of the pictures where the list isn't viewable or is clipped, I am able to drag down on the list to get it to then display properly. I have not tried this on an Android device.
EDIT2:
public class CodenameOneTest {
private Form current;
private Resources theme;
private WaitingClass w;
private String[] properties = {"1 MAIN STREET", "123 E MAIN STREET", "12 EASTER ROAD", "24 MAIN STREET"};
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
}
public void start() {
if(current != null) {
current.show();
return;
}
Form form = new Form("AutoCompleteTextField");
form.setLayout(new BorderLayout());
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
protected boolean filter(String text) {
if(text.length() == 0) {
options.removeAll();
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
};
};
Container container = new Container(BoxLayout.y());
container.setScrollableY(true); // If you comment this out then the field works fine
container.add(ac);
form.addComponent(BorderLayout.CENTER, container);
form.show();
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
if(w != null) {
w.actionPerformed(null);
}
w = new WaitingClass();
String[] properties = getProperties(text);
if(Display.getInstance().isEdt()) {
Display.getInstance().invokeAndBlock(w);
}
else {
w.run();
}
return properties;
}
}
catch(Exception e) {
Log.e(e);
}
return null;
}
private String[] getProperties(String text) {
List<String> returnList = new ArrayList<>();
List<String> propertyList = Arrays.asList(properties);
for(String property : propertyList) {
if(property.startsWith(text)) {
returnList.add(property);
}
}
w.actionPerformed(null);
return returnList.toArray(new String[returnList.size()]);
}
class WaitingClass implements Runnable, ActionListener<ActionEvent> {
private boolean finishedWaiting;
public void run() {
while(!finishedWaiting) {
try {
Thread.sleep(30);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
finishedWaiting = true;
return;
}
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
}

I used this code on an iPhone 4s:
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("AutoComplete", new BorderLayout());
if(apiKey == null) {
hi.add(new SpanLabel("This demo requires a valid google API key to be set in the constant apiKey, "
+ "you can get this key for the webservice (not the native key) by following the instructions here: "
+ "https://developers.google.com/places/web-service/get-api-key"));
hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key"));
hi.show();
return;
}
Container box = new Container(new BoxLayout(BoxLayout.Y_AXIS));
box.setScrollableY(true);
for(int iter = 0 ; iter < 30 ; iter++) {
box.add(createAutoComplete());
}
hi.add(BorderLayout.CENTER, box);
hi.show();
}
private AutoCompleteTextField createAutoComplete() {
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
#Override
protected boolean filter(String text) {
if(text.length() == 0) {
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
}
};
ac.setMinimumElementsShownInPopup(5);
return ac;
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
r.addArgument("key", apiKey);
r.addArgument("input", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
String[] res = Result.fromContent(result).getAsStringArray("//description");
return res;
}
} catch(Exception err) {
Log.e(err);
}
return null;
}
I was able to create this issue but not the issue you describe.

Related

Background Service displays a timeout exception after some time in Android 6

This is a service running in the background, no Activity, began operating normally, but After about four hours, there will be a ConnectTimeoutException.
Connect to xxx.xxx.xxx.xxx time out.
This problem occurs in Android 6, I did not find this issue Android 4. When this problem occurs, I have to restart this phone, after which it connects properly for some time. When this problem occurs, other network applications on the phone runs properly.
public class mService extends Service{
Intent intent;
private Handler objHandlerCheckNetwork = new Handler();
private boolean mReflectFlg = false;
private static final int NOTIFICATION_ID = 101;
private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class };
private static final Class<?>[] mStartForegroundSignature = new Class[] { int.class , Notification.class };
private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
private NotificationManager mNM;
private Method mSetForeground;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mSetForegroundArgs = new Object[1];
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
private Runnable mHttpTestRunnable = new Runnable() {
#Override
public void run() {
if (httpTest()){
Log.e(GlobalData.getClassMethodName(),"true");
}else{
Log.e(GlobalData.getClassMethodName(),"false");
}
}
};
private Runnable mTasksCheckNetwork = new Runnable()
{
public void run()
{
Thread httpTestThread = new Thread(mHttpTestRunnable);;
httpTestThread.start();
objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000*30);
}
};
#SuppressLint("NewApi")
#Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE );
try {
mStartForeground = mService.class.getMethod("startForeground" , mStartForegroundSignature);
mStopForeground = mService.class.getMethod("stopForeground" , mStopForegroundSignature);
} catch (NoSuchMethodException e) {
mStartForeground = mStopForeground = null;
}
try {
mSetForeground = getClass().getMethod( "setForeground", mSetForegroundSignature);
} catch (NoSuchMethodException e) {
throw new IllegalStateException( "OS doesn't have Service.startForeground OR Service.setForeground!");
}
Intent intent = new Intent(this,UploadTableDataService.class );
intent.putExtra( "ficationId", NOTIFICATION_ID);
Notification.Builder builder = new Notification.Builder(this);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.gps);
builder.setContentTitle( "test" );
builder.setContentText( "test111" );
Notification notification = builder.getNotification();
startForegroundCompat( NOTIFICATION_ID, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
//startService( new Intent( this, WifiService. class));
//startService( new Intent( this, VoiceService. class));
this.intent = intent;
Log.e(GlobalData.getClassMethodName(),"mService start!");
objHandlerCheckNetwork.postDelayed(mTasksCheckNetwork, 1000);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
try{
objHandlerCheckNetwork.removeCallbacks(mTasksCheckNetwork);
}catch (Exception e) {
Log.d("DEBUG->", "onDestroy error - removeUpdates: ");
}
//stopForegroundCompat( NOTIFICATION_ID);
}
void invokeMethod(Method method, Object[] args) {
try {
method.invoke( this, args);
} catch (InvocationTargetException e) {
// Should not happen.
Log. w("ApiDemos" , "Unable to invoke method" , e);
} catch (IllegalAccessException e) {
// Should not happen.
Log. w("ApiDemos" , "Unable to invoke method" , e);
}
}
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat( int id, Notification notification) {
if ( mReflectFlg) {
// If we have the new startForeground API, then use it.
if ( mStartForeground != null) {
mStartForegroundArgs[0] = Integer. valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod( mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
} else {
if (Build.VERSION. SDK_INT >= 5) {
startForeground(id, notification);
} else {
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mSetForeground, mSetForegroundArgs);
mNM.notify(id, notification);
}
}
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat( int id) {
if ( mReflectFlg) {
// If we have the new stopForeground API, then use it.
if ( mStopForeground != null) {
mStopForegroundArgs[0] = Boolean. TRUE;
invokeMethod( mStopForeground, mStopForegroundArgs);
return;
}
mNM.cancel(id);
mSetForegroundArgs[0] = Boolean. FALSE;
invokeMethod( mSetForeground, mSetForegroundArgs);
} else {
if (Build.VERSION. SDK_INT >= 5) {
stopForeground( true);
} else {
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
mNM.cancel(id);
mSetForegroundArgs[0] = Boolean. FALSE;
invokeMethod( mSetForeground, mSetForegroundArgs);
}
}
}
public static Boolean httpTest() {
HttpClient client= new DefaultHttpClient();;
try {
StringBuilder sb = new StringBuilder();
HttpParams httpParams = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 1000*5);
HttpConnectionParams.setSoTimeout(httpParams, 1000*10);
HttpResponse response = client.execute(new HttpGet("http://www.itnanny.com/default.htm"));
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
}
Log.e(GlobalData.getClassMethodName(),"result:"+sb.toString());
if (sb.toString().indexOf("ok") > -1){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
client.getConnectionManager().shutdown();;
}
return false;
}
}

Arrayadapter only returning the last element

I'm new to android development and right now I'm trying to parse an J SON array into object and then save each object into a array list then display the array list with a array adapter. But, right now I can only get the array adapter to display the last element.
Here is the main class
public class Venue extends Activity {
Venue_Listing venue = new Venue_Listing();
ArrayList<Venue_Listing> venueList;
ListView listview;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.list);
new GetVenus().execute(URL);
venueList = new ArrayList<Venue_Listing>();
}
private class GetVenus extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
String data;
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(Venue.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
protected Boolean doInBackground(String... url) {
try {
HttpGet httppost = new HttpGet(url[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
data = EntityUtils.toString(entity);
}
return true;
}
catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
Venue_Listing_Adapter adapter = new
Venue_Listing_Adapter(getApplicationContext(),R.layout.venue_list_layout, venueList);
try {
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
if (venue != null) {
venue.SET_ID(object.getString("venue_ID"));
venue.SET_NAME(object.getString("name"));
listview.setAdapter(adapter);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
}
This class holds all the J SON parse data
public class Venue_Listing {
private String ID;
private String NAME;
public Venue_Listing() {
}
public Venue_Listing(String ID, String NAME) {
super();
this.ID = ID;
this.NAME = NAME;
}
// setter & getter....
And here is what I have for my array adapter
public class Venue_Listing_Adapter extends ArrayAdapter<Venue_Listing> {
private ArrayList<Venue_Listing> objects;
public Venue_Listing_Adapter(Context context, int resource, ArrayList<Venue_Listing> objects) {
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.venue_list_layout, null);
}
Venue_Listing i = objects.get(position);
if (i != null) {
TextView id = (TextView) v.findViewById(R.id.id);
TextView name = (TextView) v.findViewById(R.id.name);
if (id != null ){
id.setText(i.GET_ID());
}
if (name != null) {
name.setText(i.GET_NAME());
}
}
return v;
}
}
Any help would be appreciated
Thank you
Please print and check the values of 'venueList'.
You have not added values in 'venueList' object.
You need to create 'venue' object every time and add object 'venue' in 'venueList'. Hence you are not getting all items in list view.
The Code may go this way: -
Venue_Listing venue;
try {
JSONArray jarray = new JSONArray(data);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
venue = new Venue_Listing();
if (object != null) {
venue.SET_ID(object.getString("venue_ID"));
venue.SET_NAME(object.getString("name"));
venueList.add(venue);
}
}
Venue_Listing_Adapter adapter = new Venue_Listing_Adapter(getApplicationContext(),R.layout.venue_list_layout, venueList);
listview.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}

Service-Unavailable(503) Error in Smack XEP-0198: Stream Management

I am using below class to enable stream management("urn:xmpp:sm:3") in our ejabberd server(we have latest version of ejabberd). But when I send the Enable packet to server it says Service Unavailable(503). But when I use "yaxim" it works perfectly. Please help me to solve this problem. Thanks.
public class XmppStreamHandler {
public static final String URN_SM_3 = "urn:xmpp:sm:3";
private static final int MAX_OUTGOING_QUEUE_SIZE = 20;
private static final int OUTGOING_FILL_RATIO = 4;
private XMPPConnection mConnection;
private boolean isSmAvailable = false;
private boolean isSmEnabled = false;
private boolean isOutgoingSmEnabled = false;
private long previousIncomingStanzaCount = -1;
private String sessionId;
private long incomingStanzaCount = 0;
private long outgoingStanzaCount = 0;
private Queue<Packet> outgoingQueue;
private int maxOutgoingQueueSize = MAX_OUTGOING_QUEUE_SIZE;
private ConnectionListener mConnectionListener;
public XmppStreamHandler(XMPPConnection connection, ConnectionListener connectionListener) {
mConnection = connection;
mConnectionListener = connectionListener;
startListening();
}
/** Perform a quick shutdown of the XMPPConnection if a resume is possible */
public void quickShutdown() {
if (isResumePossible()) {
mConnection.quickShutdown();
// We will not necessarily get any notification from a quickShutdown, so adjust our state here.
closeOnError();
} else {
mConnection.shutdown();
}
}
public void setMaxOutgoingQueueSize(int maxOutgoingQueueSize) {
this.maxOutgoingQueueSize = maxOutgoingQueueSize;
}
public boolean isResumePossible() {
return sessionId != null;
}
public boolean isResumePending() {
return isResumePossible() && !isSmEnabled;
}
public static void addExtensionProviders() {
addSimplePacketExtension("sm", URN_SM_3);
addSimplePacketExtension("r", URN_SM_3);
addSimplePacketExtension("a", URN_SM_3);
addSimplePacketExtension("enabled", URN_SM_3);
addSimplePacketExtension("resumed", URN_SM_3);
addSimplePacketExtension("failed", URN_SM_3);
}
public void notifyInitialLogin() {
if (sessionId == null && isSmAvailable)
sendEnablePacket();
}
private void sendEnablePacket() {
debug("sm send enable " + sessionId);
if (sessionId != null) {
isOutgoingSmEnabled = true;
// TODO binding
StreamHandlingPacket resumePacket = new StreamHandlingPacket("resume", URN_SM_3);
resumePacket.addAttribute("h", String.valueOf(previousIncomingStanzaCount));
resumePacket.addAttribute("previd", sessionId);
mConnection.sendPacket(resumePacket);
} else {
outgoingStanzaCount = 0;
outgoingQueue = new ConcurrentLinkedQueue<Packet>();
isOutgoingSmEnabled = true;
StreamHandlingPacket enablePacket = new StreamHandlingPacket("enable", URN_SM_3);
enablePacket.addAttribute("resume", "true");
mConnection.sendPacket(enablePacket);
}
}
private void closeOnError() {
if (isSmEnabled && sessionId != null) {
previousIncomingStanzaCount = incomingStanzaCount;
}
isSmEnabled = false;
isOutgoingSmEnabled = false;
isSmAvailable = false;
}
private void startListening() {
mConnection.forceAddConnectionListener(new ConnectionListener() {
public void reconnectionSuccessful() {
}
public void reconnectionFailed(Exception e) {
}
public void reconnectingIn(int seconds) {
}
public void connectionClosedOnError(Exception e) {
if (e instanceof XMPPException &&
((XMPPException)e).getStreamError() != null) {
// Non-resumable stream error
close();
} else {
// Resumable
closeOnError();
}
}
public void connectionClosed() {
previousIncomingStanzaCount = -1;
}
});
mConnection.addPacketSendingListener(new PacketListener() {
public void processPacket(Packet packet) {
// Ignore our own request for acks - they are not counted
if (!isStanza(packet)) {
trace("send " + packet.toXML());
return;
}
if (isOutgoingSmEnabled && !outgoingQueue.contains(packet)) {
outgoingStanzaCount++;
outgoingQueue.add(packet);
trace("send " + outgoingStanzaCount + " : " + packet.toXML());
// Don't let the queue grow beyond max size. Request acks and drop old packets
// if acks are not coming.
if (outgoingQueue.size() >= maxOutgoingQueueSize / OUTGOING_FILL_RATIO) {
mConnection.sendPacket(new StreamHandlingPacket("r", URN_SM_3));
}
if (outgoingQueue.size() > maxOutgoingQueueSize) {
// Log.e(XmppConnection.TAG, "not receiving acks? outgoing queue full");
outgoingQueue.remove();
}
} else if (isOutgoingSmEnabled && outgoingQueue.contains(packet)) {
outgoingStanzaCount++;
trace("send DUPLICATE " + outgoingStanzaCount + " : " + packet.toXML());
} else {
trace("send " + packet.toXML());
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
return true;
}
});
mConnection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
if (isSmEnabled && isStanza(packet)) {
incomingStanzaCount++;
trace("recv " + incomingStanzaCount + " : " + packet.toXML());
} else {
trace("recv " + packet.toXML());
}
if (packet instanceof StreamHandlingPacket) {
StreamHandlingPacket shPacket = (StreamHandlingPacket) packet;
String name = shPacket.getElementName();
if ("sm".equals(name)) {
debug("sm avail");
isSmAvailable = true;
if (sessionId != null)
sendEnablePacket();
} else if ("r".equals(name)) {
StreamHandlingPacket ackPacket = new StreamHandlingPacket("a", URN_SM_3);
ackPacket.addAttribute("h", String.valueOf(incomingStanzaCount));
mConnection.sendPacket(ackPacket);
} else if ("a".equals(name)) {
long ackCount = Long.valueOf(shPacket.getAttribute("h"));
removeOutgoingAcked(ackCount);
trace(outgoingQueue.size() + " in outgoing queue after ack");
} else if ("enabled".equals(name)) {
incomingStanzaCount = 0;
isSmEnabled = true;
mConnection.getRoster().setOfflineOnError(false);
String resume = shPacket.getAttribute("resume");
if ("true".equals(resume) || "1".equals(resume)) {
sessionId = shPacket.getAttribute("id");
}
debug("sm enabled " + sessionId);
} else if ("resumed".equals(name)) {
debug("sm resumed");
incomingStanzaCount = previousIncomingStanzaCount;
long resumeStanzaCount = Long.valueOf(shPacket.getAttribute("h"));
// Removed acked packets
removeOutgoingAcked(resumeStanzaCount);
trace(outgoingQueue.size() + " in outgoing queue after resume");
// Resend any unacked packets
for (Packet resendPacket : outgoingQueue) {
mConnection.sendPacket(resendPacket);
}
// Enable only after resend, so that the interceptor does not
// queue these again or increment outgoingStanzaCount.
isSmEnabled = true;
// Re-notify the listener - we are really ready for packets now
// Before this point, isSuspendPending() was true, and the listener should have
// ignored reconnectionSuccessful() from XMPPConnection.
mConnectionListener.reconnectionSuccessful();
} else if ("failed".equals(name)) {
// Failed, shutdown and the parent will retry
debug("sm failed");
mConnection.getRoster().setOfflineOnError(true);
mConnection.getRoster().setOfflinePresences();
sessionId = null;
mConnection.shutdown();
// isSmEnabled / isOutgoingSmEnabled are already false
}
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
return true;
}
});
}
private void removeOutgoingAcked(long ackCount) {
if (ackCount > outgoingStanzaCount) {
// Log.e(XmppConnection.TAG,
// "got ack of " + ackCount + " but only sent " + outgoingStanzaCount);
// Reset the outgoing count here in a feeble attempt to re-sync. All bets
// are off.
outgoingStanzaCount = ackCount;
}
int size = outgoingQueue.size();
while (size > outgoingStanzaCount - ackCount) {
outgoingQueue.remove();
size--;
}
}
private static void addSimplePacketExtension(final String name, final String namespace) {
ProviderManager.getInstance().addExtensionProvider(name, namespace,
new PacketExtensionProvider() {
public PacketExtension parseExtension(XmlPullParser parser) throws Exception {
StreamHandlingPacket packet = new StreamHandlingPacket(name, namespace);
int attributeCount = parser.getAttributeCount();
for (int i = 0; i < attributeCount; i++) {
packet.addAttribute(parser.getAttributeName(i),
parser.getAttributeValue(i));
}
return packet;
}
});
}
private void debug(String message) {
System.out.println(message);
}
private void trace(String message) {
System.out.println(message);
}
public static class StreamHandlingPacket extends UnknownPacket {
private String name;
private String namespace;
Map<String, String> attributes;
StreamHandlingPacket(String name, String namespace) {
this.name = name;
this.namespace = namespace;
attributes = Collections.emptyMap();
}
public void addAttribute(String name, String value) {
if (attributes == Collections.EMPTY_MAP)
attributes = new HashMap<String, String>();
attributes.put(name, value);
}
public String getAttribute(String name) {
return attributes.get(name);
}
public String getNamespace() {
return namespace;
}
public String getElementName() {
return name;
}
public String toXML() {
StringBuilder buf = new StringBuilder();
buf.append("<").append(getElementName());
// TODO Xmlns??
if (getNamespace() != null) {
buf.append(" xmlns=\"").append(getNamespace()).append("\"");
}
for (String key : attributes.keySet()) {
buf.append(" ").append(key).append("=\"")
.append(StringUtils.escapeForXML(attributes.get(key))).append("\"");
}
buf.append("/>");
return buf.toString();
}
}
/** Returns true if the packet is a Stanza as defined in RFC-6121 - a Message, IQ or Presence packet. */
public static boolean isStanza(Packet packet) {
if (packet instanceof Message)
return true;
if (packet instanceof IQ)
return true;
if (packet instanceof Presence)
return true;
return false;
}
public void queue(Packet packet) {
if (outgoingQueue.size() >= maxOutgoingQueueSize) {
System.out.println("outgoing queue full");
return;
}
outgoingStanzaCount++;
outgoingQueue.add(packet);
}
private void close() {
isSmEnabled = false;
isOutgoingSmEnabled = false;
sessionId = null;
}
}
when I send the Enable packet to server it says Service
Unavailable(503)
Service Unavailable means that the service is unavailable on the server. Does ejabberd support XEP-198? Did you enable it?
You should also consider switching to Smack 4.1.0-alpha, which also runs on Android and comes with Stream Management support. yaxim will soon switch to from it's custom XmppStreamHandler implementation to Smack 4.1.

LoadException with FXML created with Scene Builder 2.0

I got a problem that i absolutly cant solve on my own because i have just started using JAVA FX. I get a nasty javafx.fxml.LoadException: , but i have done exactly like a guide (http://docs.oracle.com/javafx/scenebuilder/1/get_started/jsbpub-get_started.htm), but i cant get my Main to run. This is the console:
ant -f P:\\FXML\\IssueTrackingLite jfxsa-run
init:
deps-jar:
Created dir: P:\FXML\IssueTrackingLite\build
Updating property file: P:\FXML\IssueTrackingLite\build\built-jar.properties
Created dir: P:\FXML\IssueTrackingLite\build\classes
Created dir: P:\FXML\IssueTrackingLite\build\empty
Created dir: P:\FXML\IssueTrackingLite\build\generated-sources\ap-source-output
Compiling 6 source files to P:\FXML\IssueTrackingLite\build\classes
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning
Copying 4 files to P:\FXML\IssueTrackingLite\build\classes
compile:
Detected JavaFX Ant API version 1.3
Launching <fx:jar> task from C:\Program Files\Java\jdk1.8.0\jre\..\lib\ant-javafx.jar
Warning: From JDK7u25 the Codebase manifest attribute should be used to restrict JAR repurposing.
Please set manifest.custom.codebase property to override the current default non-secure value '*'.
Launching <fx:deploy> task from C:\Program Files\Java\jdk1.8.0\jre\..\lib\ant-javafx.jar
jfx-deployment-script:
jfx-deployment:
jar:
Copying 12 files to P:\FXML\IssueTrackingLite\dist\run910302418
jfx-project-run:
Executing P:\FXML\IssueTrackingLite\dist\run910302418\IssueTrackingLite.jar using platform C:\Program Files\Java\jdk1.8.0\jre/bin/java
before ........!
IssueTrackingLiteController.initialize
août 11, 2014 12:24:01 PM issuetrackinglite.Main start
GRAVE: null
javafx.fxml.LoadException:
file:/P:/FXML/IssueTrackingLite/dist/run910302418/IssueTrackingLite.jar!/issuetrackinglite/IssueTrackingLite.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2617)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2595)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3230)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3191)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3164)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3140)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3120)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3113)
at issuetrackinglite.Main.start(Main.java:55)
at com.sun.javafx.application.LauncherImpl$8.run(LauncherImpl.java:837)
at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
at issuetrackinglite.IssueTrackingLiteController.configureTable(IssueTrackingLiteController.java:481)
at issuetrackinglite.IssueTrackingLiteController.initialize(IssueTrackingLiteController.java:119)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 19 more
BUILD STOPPED (total time: 50 minutes 46 seconds)
What does it mean and how can I fix it?
the main class:
package issuetrackinglite;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class Main extends Application {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(Main.class, (java.lang.String[])null);
}
#Override
public void start(Stage primaryStage) {
try {
System.out.println(" before ........!");
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("/issuetrackinglite/IssueTrackingLite.fxml"));
System.out.println(" after .............!");
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Issue Tracking Lite Sample");
primaryStage.show();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
my FXML file is in the same path as Main class.
the class Controller:
package issuetrackinglite;
public class IssueTrackingLiteController implements Initializable {
#FXML
Button newIssue;
#FXML
Button deleteIssue;
#FXML
Button saveIssue;
TableView<ObservableIssue> table;
#FXML
TableColumn<ObservableIssue, String> colName;
#FXML
TableColumn<ObservableIssue, IssueStatus> colStatus;
#FXML
TableColumn<ObservableIssue, String> colSynopsis;
#FXML
ListView<String> list;
#FXML
TextField synopsis;
private String displayedBugId; // the id of the bug displayed in the details section.
private String displayedBugProject; // the name of the project of the bug displayed in the detailed section.
#FXML
Label displayedIssueLabel; // the displayedIssueLabel will contain a concatenation of the
// the project name and the bug id.
#FXML
AnchorPane details;
#FXML
TextArea descriptionValue;
ObservableList<String> projectsView = FXCollections.observableArrayList();
TrackingService model = null;
private TextField statusValue = new TextField();
final ObservableList<ObservableIssue> tableContent = FXCollections.observableArrayList();
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rsrcs) {
assert colName != null : "fx:id=\"colName\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert colStatus != null : "fx:id=\"colStatus\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert colSynopsis != null : "fx:id=\"colSynopsis\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert deleteIssue != null : "fx:id=\"deleteIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert descriptionValue != null : "fx:id=\"descriptionValue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert details != null : "fx:id=\"details\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert displayedIssueLabel != null : "fx:id=\"displayedIssueLabel\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert newIssue != null : "fx:id=\"newIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert saveIssue != null : "fx:id=\"saveIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert synopsis != null : "fx:id=\"synopsis\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert table != null : "fx:id=\"table\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert list != null : "fx:id=\"list\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
System.out.println(this.getClass().getSimpleName() + ".initialize");
configureButtons();
configureDetails();
configureTable();
connectToService();
if (list != null) {
list.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
list.getSelectionModel().selectedItemProperty().addListener(projectItemSelected);
displayedProjectNames.addListener(projectNamesListener);
}
}
/**
* Called when the NewIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void newIssueFired(ActionEvent event) {
final String selectedProject = getSelectedProject();
if (model != null && selectedProject != null) {
ObservableIssue issue = model.createIssueFor(selectedProject);
if (table != null) {
// Select the newly created issue.
table.getSelectionModel().clearSelection();
table.getSelectionModel().select(issue);
}
}
}
/**
* Called when the DeleteIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void deleteIssueFired(ActionEvent event) {
final String selectedProject = getSelectedProject();
if (model != null && selectedProject != null && table != null) {
// We create a copy of the current selection: we can't delete
// issue while looping over the live selection, since
// deleting selected issues will modify the selection.
final List<?> selectedIssue = new ArrayList<Object>(table.getSelectionModel().getSelectedItems());
for (Object o : selectedIssue) {
if (o instanceof ObservableIssue) {
model.deleteIssue(((ObservableIssue) o).getId());
}
}
table.getSelectionModel().clearSelection();
}
}
/**
* Called when the SaveIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void saveIssueFired(ActionEvent event) {
final ObservableIssue ref = getSelectedIssue();
final Issue edited = new DetailsData();
SaveState saveState = computeSaveState(edited, ref);
if (saveState == SaveState.UNSAVED) {
model.saveIssue(ref.getId(), edited.getStatus(),
edited.getSynopsis(), edited.getDescription());
}
// We refresh the content of the table because synopsis and/or description
// are likely to have been modified by the user.
int selectedRowIndex = table.getSelectionModel().getSelectedIndex();
table.getItems().clear();
displayedIssues = model.getIssueIds(getSelectedProject());
for (String id : displayedIssues) {
final ObservableIssue issue = model.getIssue(id);
table.getItems().add(issue);
}
table.getSelectionModel().select(selectedRowIndex);
updateSaveIssueButtonState();
}
private void configureButtons() {
if (newIssue != null) {
newIssue.setDisable(true);
}
if (saveIssue != null) {
saveIssue.setDisable(true);
}
if (deleteIssue != null) {
deleteIssue.setDisable(true);
}
}
// An observable list of project names obtained from the model.
// This is a live list, and we will react to its changes by removing
// and adding project names to/from our list widget.
private ObservableList<String> displayedProjectNames;
// The list of Issue IDs relevant to the selected project. Can be null
// if no project is selected. This list is obtained from the model.
// This is a live list, and we will react to its changes by removing
// and adding Issue objects to/from our table widget.
private ObservableList<String> displayedIssues;
// This listener will listen to changes in the displayedProjectNames list,
// and update our list widget in consequence.
private final ListChangeListener<String> projectNamesListener = new ListChangeListener<String>() {
#Override
public void onChanged(Change<? extends String> c) {
if (projectsView == null) {
return;
}
while (c.next()) {
if (c.wasAdded() || c.wasReplaced()) {
for (String p : c.getAddedSubList()) {
projectsView.add(p);
}
}
if (c.wasRemoved() || c.wasReplaced()) {
for (String p : c.getRemoved()) {
projectsView.remove(p);
}
}
}
FXCollections.sort(projectsView);
}
};
// This listener will listen to changes in the displayedIssues list,
// and update our table widget in consequence.
private final ListChangeListener<String> projectIssuesListener = new ListChangeListener<String>() {
#Override
public void onChanged(Change<? extends String> c) {
if (table == null) {
return;
}
while (c.next()) {
if (c.wasAdded() || c.wasReplaced()) {
for (String p : c.getAddedSubList()) {
table.getItems().add(model.getIssue(p));
}
}
if (c.wasRemoved() || c.wasReplaced()) {
for (String p : c.getRemoved()) {
ObservableIssue removed = null;
// Issue already removed:
// we can't use model.getIssue(issueId) to get it.
// we need to loop over the table content instead.
// Then we need to remove it - but outside of the for loop
// to avoid ConcurrentModificationExceptions.
for (ObservableIssue t : table.getItems()) {
if (t.getId().equals(p)) {
removed = t;
break;
}
}
if (removed != null) {
table.getItems().remove(removed);
}
}
}
}
}
};
// Connect to the model, get the project's names list, and listen to
// its changes. Initializes the list widget with retrieved project names.
private void connectToService() {
if (model == null) {
model = new TrackingServiceStub();
displayedProjectNames = model.getProjectNames();
}
projectsView.clear();
List<String> sortedProjects = new ArrayList<String>(displayedProjectNames);
Collections.sort(sortedProjects);
projectsView.addAll(sortedProjects);
list.setItems(projectsView);
}
// This listener listen to changes in the table widget selection and
// update the DeleteIssue button state accordingly.
private final ListChangeListener<ObservableIssue> tableSelectionChanged =
new ListChangeListener<ObservableIssue>() {
#Override
public void onChanged(Change<? extends ObservableIssue> c) {
updateDeleteIssueButtonState();
updateBugDetails();
updateSaveIssueButtonState();
}
};
private static String nonNull(String s) {
return s == null ? "" : s;
}
private void updateBugDetails() {
final ObservableIssue selectedIssue = getSelectedIssue();
if (details != null && selectedIssue != null) {
if (displayedIssueLabel != null) {
displayedBugId = selectedIssue.getId();
displayedBugProject = selectedIssue.getProjectName();
displayedIssueLabel.setText( displayedBugId + " / " + displayedBugProject );
}
if (synopsis != null) {
synopsis.setText(nonNull(selectedIssue.getSynopsis()));
}
if (statusValue != null) {
statusValue.setText(selectedIssue.getStatus().toString());
}
if (descriptionValue != null) {
descriptionValue.selectAll();
descriptionValue.cut();
descriptionValue.setText(selectedIssue.getDescription());
}
} else {
displayedIssueLabel.setText("");
displayedBugId = null;
displayedBugProject = null;
}
if (details != null) {
details.setVisible(selectedIssue != null);
}
}
private boolean isVoid(Object o) {
if (o instanceof String) {
return isEmpty((String) o);
} else {
return o == null;
}
}
private boolean isEmpty(String s) {
return s == null || s.trim().isEmpty();
}
private boolean equal(Object o1, Object o2) {
if (isVoid(o1)) {
return isVoid(o2);
}
return o1.equals(o2);
}
private static enum SaveState {
INVALID, UNSAVED, UNCHANGED
}
private final class DetailsData implements Issue {
#Override
public String getId() {
if (displayedBugId == null || isEmpty(displayedIssueLabel.getText())) {
return null;
}
return displayedBugId;
}
#Override
public IssueStatus getStatus() {
if (statusValue == null || isEmpty(statusValue.getText())) {
return null;
}
return IssueStatus.valueOf(statusValue.getText().trim());
}
#Override
public String getProjectName() {
if (displayedBugProject == null || isEmpty(displayedIssueLabel.getText())) {
return null;
}
return displayedBugProject;
}
#Override
public String getSynopsis() {
if (synopsis == null || isEmpty(synopsis.getText())) {
return "";
}
return synopsis.getText();
}
#Override
public String getDescription() {
if (descriptionValue == null || isEmpty(descriptionValue.getText())) {
return "";
}
return descriptionValue.getText();
}
}
private SaveState computeSaveState(Issue edited, Issue issue) {
try {
// These fields are not editable - so if they differ they are invalid
// and we cannot save.
if (!equal(edited.getId(), issue.getId())) {
return SaveState.INVALID;
}
if (!equal(edited.getProjectName(), issue.getProjectName())) {
return SaveState.INVALID;
}
// If these fields differ, the issue needs saving.
if (!equal(edited.getStatus(), issue.getStatus())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getSynopsis(), issue.getSynopsis())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getDescription(), issue.getDescription())) {
return SaveState.UNSAVED;
}
} catch (Exception x) {
// If there's an exception, some fields are invalid.
return SaveState.INVALID;
}
// No field is invalid, no field needs saving.
return SaveState.UNCHANGED;
}
private void updateDeleteIssueButtonState() {
boolean disable = true;
if (deleteIssue != null && table != null) {
final boolean nothingSelected = table.getSelectionModel().getSelectedItems().isEmpty();
disable = nothingSelected;
}
if (deleteIssue != null) {
deleteIssue.setDisable(disable);
}
}
private void updateSaveIssueButtonState() {
boolean disable = true;
if (saveIssue != null && table != null) {
final boolean nothingSelected = table.getSelectionModel().getSelectedItems().isEmpty();
disable = nothingSelected;
}
if (disable == false) {
disable = computeSaveState(new DetailsData(), getSelectedIssue()) != SaveState.UNSAVED;
}
if (saveIssue != null) {
saveIssue.setDisable(disable);
}
}
// Configure the table widget: set up its column, and register the
// selection changed listener.
private void configureTable() {
colName.setCellValueFactory(new PropertyValueFactory<ObservableIssue, String>("id"));
colSynopsis.setCellValueFactory(new PropertyValueFactory<ObservableIssue, String>("synopsis"));
colStatus.setCellValueFactory(new PropertyValueFactory<ObservableIssue, IssueStatus>("status"));
// In order to limit the amount of setup in Getting Started we set the width
// of the 3 columns programmatically but one can do it from SceneBuilder.
colName.setPrefWidth(75);
colStatus.setPrefWidth(75);
colSynopsis.setPrefWidth(443);
colName.setMinWidth(75);
colStatus.setMinWidth(75);
colSynopsis.setMinWidth(443);
colName.setMaxWidth(750);
colStatus.setMaxWidth(750);
colSynopsis.setMaxWidth(4430);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setItems(tableContent);
assert table.getItems() == tableContent;
final ObservableList<ObservableIssue> tableSelection = table.getSelectionModel().getSelectedItems();
tableSelection.addListener(tableSelectionChanged);
}
/**
* Return the name of the project currently selected, or null if no project
* is currently selected.
*
*/
public String getSelectedProject() {
if (model != null && list != null) {
final ObservableList<String> selectedProjectItem = list.getSelectionModel().getSelectedItems();
final String selectedProject = selectedProjectItem.get(0);
return selectedProject;
}
return null;
}
public ObservableIssue getSelectedIssue() {
if (model != null && table != null) {
List<ObservableIssue> selectedIssues = table.getSelectionModel().getSelectedItems();
if (selectedIssues.size() == 1) {
final ObservableIssue selectedIssue = selectedIssues.get(0);
return selectedIssue;
}
}
return null;
}
/**
* Listen to changes in the list selection, and updates the table widget and
* DeleteIssue and NewIssue buttons accordingly.
*/
private final ChangeListener<String> projectItemSelected = new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
projectUnselected(oldValue);
projectSelected(newValue);
}
};
// Called when a project is unselected.
private void projectUnselected(String oldProjectName) {
if (oldProjectName != null) {
displayedIssues.removeListener(projectIssuesListener);
displayedIssues = null;
table.getSelectionModel().clearSelection();
table.getItems().clear();
if (newIssue != null) {
newIssue.setDisable(true);
}
if (deleteIssue != null) {
deleteIssue.setDisable(true);
}
}
}
// Called when a project is selected.
private void projectSelected(String newProjectName) {
if (newProjectName != null) {
table.getItems().clear();
displayedIssues = model.getIssueIds(newProjectName);
for (String id : displayedIssues) {
final ObservableIssue issue = model.getIssue(id);
table.getItems().add(issue);
}
displayedIssues.addListener(projectIssuesListener);
if (newIssue != null) {
newIssue.setDisable(false);
}
updateDeleteIssueButtonState();
updateSaveIssueButtonState();
}
}
private void configureDetails() {
if (details != null) {
details.setVisible(false);
}
if (details != null) {
details.addEventFilter(EventType.ROOT, new EventHandler<Event>() {
#Override
public void handle(Event event) {
if (event.getEventType() == MouseEvent.MOUSE_RELEASED
|| event.getEventType() == KeyEvent.KEY_RELEASED) {
updateSaveIssueButtonState();
}
}
});
}
}
}

I am working with facebook game request

I finished working with sending the request with android reading https://developers.facebook.com/docs/howtos/androidsdk/3.0/send-requests/
but i'm having a problem with handling requests.
https://developers.facebook.com/docs/howtos/androidsdk/3.0/app-link-requests/
I think I did what it told me to do, but I can't get the uri and the requestid
they are all null.
I thing the problem is that when I receive a request I can't click the accept button.
It says that the playstore can't find the app. So the request doesn't disappear.
How can I solve the problem?
public class MainActivity extends Activity {
private static final List<String> PERMISSIONS = Arrays
.asList("read_requests");
private Bundle SIS;
private Session.StatusCallback logincallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
updateview();
getp();
loginlogoutbutton.setText("Login");
onSessionStateChange(session, state, exception);
} else {
}
}
};
public void updateview() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
tt.setText(user.getId());
}
}
});
} else
{
tt.setText("Login");
}
}
private Button loginlogoutbutton;
private Button sendrequestbutton;
private Button testbtn;
private TextView tt;
private String app_id = "APP ID";
private String requestId;
public void getp() {
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
return;
}
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS)
.setCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
}
}));
} else {
}
}
#Override
public void onResume() {
super.onResume();
checkforrequest();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SIS = savedInstanceState;
tt = (TextView) findViewById(R.id.tex);
loginlogoutbutton = (Button) findViewById(R.id.loginlogoutbtn);
loginlogoutbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLoginLogout();
}
});
sendrequestbutton = (Button) findViewById(R.id.sendrequest);
sendrequestbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendRequestDialog();
}
});
testbtn = (Button) findViewById(R.id.button1);
testbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
checkforrequest();
}
});
ConfirmLogin(app_id);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
public boolean ConfirmLogin(String iappid) {
app_id = iappid;
Session session = Session.getActiveSession();
boolean dd = true;
if (session == null) {
if (SIS != null) {
session = Session.restoreSession(this, null,
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
// TODO Auto-generated method stub
}
}, SIS);
}
if (session == null) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
dd = true;
} else {
dd = false;
}
}
return dd;
}
public void onClickLoginLogout() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else if (session.isClosed()) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else {
session.closeAndClearTokenInformation();
loginlogoutbutton.setText("Login");
}
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message",
"Learn how to make your Android apps social");
params.putString("data", "{\"badge_of_awesomeness\":\"1\","
+ "\"social_karma\":\"5\"}");
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
} else {
}
} else {
final String requestId = values
.getString("request");
if (requestId != null) {
maketoast(requestId);
} else {
}
}
}
}).build();
requestsDialog.show();
}
public void checkforrequest() {
maketoast("0");
Uri intentUri = this.getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
maketoast("1 : " +requestIdParam);
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
}
}
else
{
maketoast("uri = null");
}
}
public void maketoast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
maketoast("2");
Request request = new Request(Session.getActiveSession(), inRequestId,
null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the
// key/value info
JSONObject dataObject = new JSONObject(
(String) graphObject
.getProperty("data"));
// Get the value for the key -
// badge_of_awesomeness
String badge = dataObject
.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma = dataObject
.getString("social_karma");
// Get the sender's name
JSONObject fromObject = (JSONObject) graphObject
.getProperty("from");
String sender = fromObject
.getString("name");
String title = sender + " sent you a gift";
// Create the text for the alert based on
// the sender
// and the data
message = title + "\n\n" + "Badge: "
+ badge + " Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
maketoast(message);
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
// Check if the user is authenticated and
// an incoming notification needs handling
if (state.isOpened() && requestId != null) {
maketoast("3");
getRequestData(requestId);
requestId = null;
} else if (requestId == null) {
maketoast("4");
}
if (state.isOpened()) {
} else if (state.isClosed()) {
}
}
}
this is the code.