I am developing an Android app. Please see the Java code below. Can you please explain why textView doesn't update at specific lines in code but updates at others. I have them commented in the code.
I have updated the code see below.
The idea is to get a facebook profile from a server. When profiling_status equals 2 means that the profile is not ready, so I'll just ping the server until I get profiling_status != 2..
I tried the progress dialog thingy but gave up cause I put my activity in a thread, but then I couldn't get some information because I should have run it in nonUIThread.. Tried that but I failed and I lost patience.. so decided that while I ping the server I should just print "Loading profile. Please wait." No mess, no fuss! Only as said, textView doesn't update. Interestingly enough.. System.out.println("Here"); gets executed. I am running it only on AVD at the moment cause the server is not on the wireless network so I can't use a mobile phone to test it.
public class SelectionFragment extends Fragment {
private ProfilePictureView profilePictureView;
private TextView userNameView;
private UiLifecycleHelper uiHelper;
private static final int REAUTH_ACTIVITY_CODE = 100;
private TextView textView;
private String username = null;
Context context;
JSONObject json = null;
JSONObject json_facebook = null;
int time = 0;
int time_interval = 3000;
int profiling_status = 2;
String logincode;
String usermessage = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void deleteProfile() throws JSONException {
IDThiefHTTPRequest.deleteProfile();
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
//Facebook logout
Session session2 = Session.getActiveSession();
if (session2 != null) {
session2.close();
}
else {
session2 = new Session(context);
Session.setActiveSession(session2);
session2.close();
}
}
private String readRiskScoreArray(JSONArray json_riskscore) throws NumberFormatException, JSONException{
//get the risk score with only two digits
double risk_score = Double.valueOf(json_riskscore.get(0).toString());
String risk_score2digits = new DecimalFormat("##.##").format(risk_score);
String usermessage = "Your risk score is: ";
usermessage = usermessage + risk_score2digits;
usermessage = usermessage + " which is ranked as: ";
usermessage = usermessage + json_riskscore.get(2).toString();
JSONArray json_reasons = json_riskscore.getJSONArray(1);
for (int i = 0; i < json_reasons.length(); i++){
JSONArray json_reason = json_reasons.getJSONArray(i);
JSONArray json_reasondetails = json_reason.getJSONArray(1);
usermessage = usermessage + "\n\nReason: ";
usermessage = usermessage + json_reasondetails.get(0);
usermessage = usermessage + "\n\nIDThief suggests you to: ";
usermessage = usermessage + json_reasondetails.get(1);
usermessage = usermessage + "\n\nFix it through this link:\n";
usermessage = usermessage + json_reasondetails.get(2);
}
return usermessage;
}
private void displayProfileInfo() throws JSONException {
Session session = Session.getActiveSession();
if (session.isOpened()) {
System.out.println(session.getAccessToken());
}
if (username != null) {
System.out.println("Login stage: Getting profile info for user:" + username);
logincode = username + "!" + session.getAccessToken();
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
System.out.println(json.toString(4));
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
if (profiling_status == 2) {
try {
while (profiling_status == 2 && time < 100000) {
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText("Loading profile. Please wait.");
System.out.println("Here");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = IDThiefHTTPRequest.makeLoginHTTPRequest(logincode);
json_facebook = json.getJSONObject("facebook");
//profiling_status
profiling_status = Integer.valueOf(json_facebook.get("profiling_status").toString());
}
if (time >= 100000) {
System.out.println("Time is out");
textView.setText("Server is not responding. Please try again later.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
JSONArray json_riskscore = json_facebook.getJSONArray("risk_score");
System.out.println(json_riskscore.toString(4));
usermessage = readRiskScoreArray(json_riskscore);
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.NO_GRAVITY);
textView.setText(usermessage);
}
else System.out.println("username is null");
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection,
container, false);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button deletebutton = (Button) view.findViewById(R.id.ImageButton2);
deletebutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
deleteProfile();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Button button = (Button) view.findViewById(R.id.ImageButton1);
textView = (TextView) view.findViewById(R.id.profiletext);
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setMovementMethod(LinkMovementMethod.getInstance());
button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try {
displayProfileInfo();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
// Check for an open session
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
return view;
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
username = user.getUsername();
//System.out.println("Log in=====================================");
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
makeMeRequest(session);
}
else if (session != null && session.isClosed()) {
textView.setTextColor(Color.GRAY);
textView.setGravity(Gravity.CENTER);
textView.setText("Press Get profile info button to process your risk of identity theft");
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
}
I thing your username is a string . Normally it will be so use !username.equals() dont use != in string comparison. that code may not get executed
if (username != null || !username.equals("")) {
//to do
}
Try out as below to compare the string do not use == use equalsIgnoreCase() or equals() method.
if (profiling_status.equalsIgnoreCase("2")) {
//would not update here either
try {
while (profiling_status.equalsIgnoreCase("2") && time < 100000) {
textView.setText("Loading profile. Please wait.");
try {
Thread.sleep(time_interval);
time += time_interval;
} catch (InterruptedException e) {
e.printStackTrace();
}
Related
I am new to parse ,i am able to store data to its database and also to retrieve some information like object-id from database but when I try to send push notification i usually get the above mentioned error.Query which i am using to send push notification with object-id corresponding to the given Friend-id.
public class MainActivity extends Activity {
private RadioButton genderFemaleButton;
private RadioButton genderMaleButton;
private Button getObjectId,sndpush;
private EditText ageEditText, frndidEditText, objectidEditText;
private RadioGroup genderRadioGroup;
private String FrndTextString, ageTextString, objectid;
private ParseObject sid;
public static final String GENDER_MALE = "male";
public static final String GENDER_FEMALE = "female";
protected static final String ParseIntallation = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(this, "c7fOlMSS4S8rxI53m0u49maP1Kab8PWVWSNwVu3s", "0xOUq1uoDb2NIi1jYZHWANZ9PP4X4W7vDfcA1UOw");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.saveInBackground();
// Track app opens.
ParseAnalytics.trackAppOpened(getIntent());
getObjectId = (Button) findViewById(R.id.get_button);
genderFemaleButton = (RadioButton) findViewById(R.id.gender_female_button);
genderMaleButton = (RadioButton) findViewById(R.id.gender_male_button);
ageEditText = (EditText) findViewById(R.id.age_edit_text);
genderRadioGroup = (RadioGroup) findViewById(R.id.gender_radio_group);
frndidEditText = (EditText) findViewById(R.id.frndid_edit_text);
sndpush = (Button) findViewById(R.id.send_push);
sndpush.setEnabled(true);
sndpush.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JSONObject obj;
try {
obj =new JSONObject();
obj.put("alert","erwerwe");
obj.put("action","com.parse.pushnotifications.UPDATE_STATUS");
obj.put("customdata","My string");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
query.whereEqualTo("objectId",objectidEditText.getText().toString() );
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
// vk
objectidEditText = (EditText) findViewById(R.id.objectid_edit_text);
getObjectId.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getObjectId();
}
});
}
#Override
public void onStart() {
super.onStart();
// Display the current values for this user, such as their age and gender.
displayUserProfile();
refreshUserProfile();
}
// Save the user's profile to their installation.
public void saveUserProfile(View view) {
ageTextString = ageEditText.getText().toString();
FrndTextString = frndidEditText.getText().toString();
if (ageTextString.length() > 0) {
sid.put("age",
Integer.valueOf(ageTextString));
}
if (FrndTextString.length() > 0) {
sid.put("FriendId",
FrndTextString);
}
if (ageTextString.length() > 0) {
ParseInstallation.getCurrentInstallation().put("age", Integer.valueOf(ageTextString));
}
if (FrndTextString.length() > 0) {
ParseInstallation.getCurrentInstallation().put("FriendId", Integer.valueOf(FrndTextString));
}
if (genderRadioGroup.getCheckedRadioButtonId() == genderFemaleButton
.getId()) {
sid.put("gender",
GENDER_FEMALE);
} else if (genderRadioGroup.getCheckedRadioButtonId() == genderMaleButton
.getId()) {
sid.put("gender",
GENDER_MALE);
} else {
sid.remove("gender");
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ageEditText.getWindowToken(), 0);
sid.saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast toast = Toast.makeText(
getApplicationContext(),
R.string.alert_dialog_success,
Toast.LENGTH_SHORT);
toast.show();
} else {
e.printStackTrace();
Toast toast = Toast.makeText(
getApplicationContext(),
R.string.alert_dialog_failed,
Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
// Get the user's Id from parse.com.
#SuppressWarnings({ "rawtypes", "unchecked" })
public void getObjectId() {
#SuppressWarnings("rawtypes")
ParseQuery query = new ParseQuery("sid");
query.whereEqualTo("FriendId", FrndTextString);
query.getFirstInBackground(new GetCallback() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("objectId", "The getFirst request failed.");
} else {
String objectid = object.getObjectId();
objectidEditText.setText(objectid);
sndpush.setEnabled(true);
Log.d("objectId", "Retrieved the object.");
}
}
});
}
// Refresh the UI with the data obtained from the current ParseInstallation
// object.
private void displayUserProfile() {
sid =ParseInstallation.create("sid");
String gender = sid.getString(
"gender");
int age = ParseInstallation.getCurrentInstallation().getInt("age");
if (gender != null) {
genderMaleButton.setChecked(gender.equalsIgnoreCase(GENDER_MALE));
genderFemaleButton.setChecked(gender
.equalsIgnoreCase(GENDER_FEMALE));
} else {
genderMaleButton.setChecked(false);
genderFemaleButton.setChecked(false);
}
if (age > 0) {
ageEditText.setText(Integer.valueOf(age).toString());
}
}
private void refreshUserProfile() {
ParseInstallation.getCurrentInstallation().refreshInBackground(
new RefreshCallback() {
#Override
public void done(ParseObject object, ParseException e) {
if (e == null) {
displayUserProfile();
}
}
});
}
}
Please help me in solving this issue as I googled a lot but haven’t found anything good solution.Any help will be appreciated.
Thanks.
I have a listView that is supposed to accept a shared message and image where the image is placed within the ImageView. This feature works for just the first message, but once an image is shared, each message received after that initial one becomes a copy of that same image even though the blank image placeholder was already set, which is just a one pixel black png:
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
An example is below:
The green textbox is the recipient. They have recieved a shared image from the yellow textbox. The yellow textbox then simply sends a normal message and I have set another image as a placeholder for normal messages: holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
The same previously shared image takes precedence. I have used notifyDataSetChanged() so as to allow for the updating the adapter so that it would recognize not to use the same image, but to no avail.
How can I reformulate this class so that the image shared is only displayed with the proper message and not copied into each subsequent message?
The ArrayAdapter class:
public class DiscussArrayAdapter extends ArrayAdapter<OneComment> {
class ViewHolder {
TextView countryName;
ImageView sharedSpecial;
LinearLayout wrapper;
}
private TextView countryName;
private ImageView sharedSpecial;
private MapView locationMap;
private GoogleMap map;
private List<OneComment> countries = new ArrayList<OneComment>();
private LinearLayout wrapper;
private JSONObject resultObject;
private JSONObject imageObject;
String getSharedSpecialURL = null;
String getSharedSpecialWithLocationURL = null;
String specialsActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecial/";
String specialsLocationActionURL = "http://" + Global.getIpAddress()
+ ":3000/getSharedSpecialWithLocation/";
String JSON = ".json";
#Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public DiscussArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.countries.size();
}
private OneComment comment = null;
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.message_list_item, parent, false);
holder = new ViewHolder();
holder.wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
holder.countryName = (TextView) row.findViewById(R.id.comment);
holder.sharedSpecial = (ImageView) row.findViewById(R.id.sharedSpecial);
// Store the ViewHolder as a tag.
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
Log.v("COMMENTING","Comment is " + countries.get(position).comment);
//OneComment comment = getItem(position);
holder.countryName.setText(countries.get(position).comment);
// Initiating Volley
final RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
// Check if message has campaign or campaign/location attached
if (countries.get(position).campaign_id == "0" && countries.get(position).location_id == "0") {
holder.sharedSpecial.setImageResource(R.drawable.image_share_empty_holder);
Log.v("TESTING", "It is working");
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id != "0") {
// If both were shared
getSharedSpecialWithLocationURL = specialsLocationActionURL + countries.get(position).campaign_id + "/" + countries.get(position).location_id + JSON;
// Test Campaign id = 41
// Location id = 104
// GET JSON data and parse
JsonObjectRequest getCampaignLocationData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialWithLocationURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignLocationData);
} else if (countries.get(position).campaign_id != "0" && countries.get(position).location_id == "0") {
// Just the campaign is shared
getSharedSpecialURL = specialsActionURL + countries.get(position).campaign_id + JSON;
// Test Campaign id = 41
// GET JSON data and parse
JsonObjectRequest getCampaignData = new JsonObjectRequest(Request.Method.GET, getSharedSpecialURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Parse the JSON:
try {
resultObject = response.getJSONObject("shared");
} catch (JSONException e) {
e.printStackTrace();
}
// Get and set image
Picasso.with(getContext()).load("http://" + Global.getIpAddress() + ":3000" + adImageURL).into(holder.sharedSpecial);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
);
requestQueue.add(getCampaignData);
// Location set to empty
}
// If left is true, then yellow, if not then set to green bubble
holder.countryName.setBackgroundResource(countries.get(position).left ? R.drawable.bubble_yellow : R.drawable.bubble_green);
holder.wrapper.setGravity(countries.get(position).left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
}
The messaging class that sends normal messages only but can receive image messages and set to the adapter:
public class GroupMessaging extends Activity {
private static final int MESSAGE_CANNOT_BE_SENT = 0;
public String username;
public String groupname;
private Button sendMessageButton;
private Manager imService;
private InfoOfGroup group = new InfoOfGroup();
private InfoOfGroupMessage groupMsg = new InfoOfGroupMessage();
private StorageManipulater localstoragehandler;
private Cursor dbCursor;
private com.example.feastapp.ChatBoxUi.DiscussArrayAdapter adapter;
private ListView lv;
private EditText editText1;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.message_activity);
lv = (ListView) findViewById(R.id.listView1);
adapter = new DiscussArrayAdapter(getApplicationContext(), R.layout.message_list_item);
lv.setAdapter(adapter);
editText1 = (EditText) findViewById(R.id.editText1);
sendMessageButton = (Button) findViewById(R.id.sendMessageButton);
Bundle extras = this.getIntent().getExtras();
group.userName = extras.getString(InfoOfGroupMessage.FROM_USER);
group.groupName = extras.getString(InfoOfGroup.GROUPNAME);
group.groupId = extras.getString(InfoOfGroup.GROUPID);
String msg = extras.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
setTitle("Group: " + group.groupName);
// Retrieve the information
localstoragehandler = new StorageManipulater(this);
dbCursor = localstoragehandler.groupGet(group.groupName);
if (dbCursor.getCount() > 0) {
// Probably where the magic happens, and keeps pulling the same
// thing
int noOfScorer = 0;
dbCursor.moveToFirst();
while ((!dbCursor.isAfterLast())
&& noOfScorer < dbCursor.getCount()) {
noOfScorer++;
}
}
localstoragehandler.close();
if (msg != null) {
// Then friends username and message, not equal to null, recieved
adapter.add(new OneComment(true, group.groupId + ": " + msg, "0", "0"));
adapter.notifyDataSetChanged();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancel((group.groupId + msg).hashCode());
}
// The send button
sendMessageButton.setOnClickListener(new OnClickListener() {
CharSequence message;
Handler handler = new Handler();
public void onClick(View arg0) {
message = editText1.getText();
if (message.length() > 0) {
// When general texting, the campaign and location will always be "0"
// Only through specials sharing is the user permitted to change the campaign and location to another value
adapter.add(new OneComment(false, imService.getUsername() + ": " + message.toString(), "0", "0"));
adapter.notifyDataSetChanged();
localstoragehandler.groupInsert(imService.getUsername(), group.groupName,
group.groupId, message.toString(), "0", "0");
// as msg sent, will blank out the text box so can write in
// again
editText1.setText("");
Thread thread = new Thread() {
public void run() {
try {
// JUST PUTTING "0" AS A PLACEHOLDER FOR CAMPAIGN AND LOCATION
// IN FUTURE WILL ACTUALLY ALLOW USER TO SHARE CAMPAIGNS
if (imService.sendGroupMessage(group.groupId,
group.groupName, message.toString(), "0", "0") == null) {
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
// showDialog(MESSAGE_CANNOT_BE_SENT);
}
});
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),
R.string.message_cannot_be_sent,
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
thread.start();
}
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
int message = -1;
switch (id) {
case MESSAGE_CANNOT_BE_SENT:
message = R.string.message_cannot_be_sent;
break;
}
if (message == -1) {
return null;
} else {
return new AlertDialog.Builder(GroupMessaging.this)
.setMessage(message)
.setPositiveButton(R.string.OK,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked OK so do some stuff */
}
}).create();
}
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(groupMessageReceiver);
unbindService(mConnection);
ControllerOfGroup.setActiveGroup(null);
}
#Override
protected void onResume() {
super.onResume();
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(MessagingService.TAKE_GROUP_MESSAGE);
registerReceiver(groupMessageReceiver, i);
ControllerOfGroup.setActiveGroup(group.groupName);
}
// For receiving messages form other users...
public class GroupMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extra = intent.getExtras();
//Log.i("GroupMessaging Receiver ", "received group message");
String username = extra.getString(InfoOfGroupMessage.FROM_USER);
String groupRId = extra.getString(InfoOfGroupMessage.TO_GROUP_ID);
String message = extra
.getString(InfoOfGroupMessage.GROUP_MESSAGE_TEXT);
// NEED TO PLACE INTO THE MESSAGE VIEW!!
String received_campaign_id = extra.getString(InfoOfGroupMessage.CAMPAIGN_SHARED);
String received_location_id = extra.getString(InfoOfGroupMessage.LOCATION_SHARED);
// NEED TO INTEGRATE THIS INTO LOGIC ABOVE, SO IT MAKES SENSE
if (username != null && message != null) {
if (group.groupId.equals(groupRId)) {
adapter.add(new OneComment(true, username + ": " + message, received_campaign_id, received_location_id));
localstoragehandler
.groupInsert(username, groupname, groupRId, message, received_campaign_id, received_location_id);
Toast.makeText(getApplicationContext(), "received_campaign: " + received_campaign_id +
" received_location:" + received_location_id, Toast.LENGTH_LONG).show();
received_campaign_id = "0";
received_location_id = "0";
} else {
if (message.length() > 15) {
message = message.substring(0, 15);
}
Toast.makeText(GroupMessaging.this,
username + " says '" + message + "'",
Toast.LENGTH_SHORT).show();
}
}
}
}
;
// Build receiver object to accept messages
public GroupMessageReceiver groupMessageReceiver = new GroupMessageReceiver();
#Override
protected void onDestroy() {
super.onDestroy();
if (localstoragehandler != null) {
localstoragehandler.close();
}
if (dbCursor != null) {
dbCursor.close();
}
}
}
I have gone through your code and this is common problem with listview that images starts repeating itself. In your case I think you have assigned image to Imageview every if and else if condition but if none of the condition satisfy it uses the previous image.
I would suggest to debug the getview method and put break points on the setImageResource. I use volley for these image loading and it has a method called defaultImage so that if no url is there the image is going to get the default one. So add that default case and see if it works.
If any of the above point is not clear feel free to comment.
I want to get Facebook friends list in my android application (friend picker not required).I have followed the the procedure describe on Facebook application development
I have also run the samples , but confused to get the friends list. your suggestions will be appreciated.
you can get friend list with this code
String returnString = null;
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
for(int i=0;i<jArray.length();i++){
Log.i("log_tag","User Name: "+json_data.getString("name")+
", user_id: "+json_data.getString("id"));
returnString += "\n\t" + jArray.getJSONObject(i);
};
flist.setText(returnString);
progressDialog.dismiss();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
I get just name and id , if you want get different things,
public class MainActivity extends FragmentActivity implements OnClickListener {
private static final String LOGTAG = "MainActivity";
private List<GraphUser> tags;
private Button pickFriendsButton;
Button locationtoast;
private ProfilePictureView profilePictureView;// 2
private LoginButton fb_loginBtn;// loginbtn
private TextView userName, userName2, userName3, userName4, text;
private UiLifecycleHelper uiHelper;
// private Button pickFriendsButton;
Button btnlogin;
String Name;
String Id;
String lastname;
String firstname;
String getUsername;
String get_gender;
GraphPlace location;
String profileid;
String birthday;
String get_email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationtoast = (Button) findViewById(R.id.location_button);
locationtoast.setOnClickListener(this);
btnlogin = (Button) findViewById(R.id.profile_view);
btnlogin.setOnClickListener(this);
profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);// 3
text = (TextView) findViewById(R.id.text);
userName = (TextView) findViewById(R.id.user_name);
fb_loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
pickFriendsButton = (Button) findViewById(R.id.add_friend);
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
pickFriendsButton.setEnabled(enableButtons);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
private void onClickPickFriends() {
final FriendPickerFragment fragment = new FriendPickerFragment();
setFriendPickerListeners(fragment);
showPickerFragment(fragment);
}
private void showPickerFragment(FriendPickerFragment fragment) {
fragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> pickerFragment,
FacebookException error) {
String text = getString(R.string.exception,
error.getMessage());
Toast toast = Toast.makeText(MainActivity.this, text,
Toast.LENGTH_SHORT);
toast.show();
}
});
}
private void setFriendPickerListeners(
final FriendPickerFragment fragment) {
fragment.setOnDoneButtonClickedListener(new FriendPickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(
PickerFragment<?> pickerFragment) {
onFriendPickerDone(fragment);
}
});
}
private void onFriendPickerDone(FriendPickerFragment fragment) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
String results = "";
List<GraphUser> selection = fragment.getSelection();
tags = selection;
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = getString(R.string.no_friends_selected);
}
// showAlert("fghjklkbvbn", results);
showAlert(getString(R.string.you_picked), results);
}
private void showAlert(String title, String message) {
new AlertDialog.Builder(MainActivity.this).setTitle(title)
.setMessage(message)
.setPositiveButton(R.string.ok, null).show();
}
});
fb_loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
// Intent intent = new Intent(this, ValuesShow.class);
// startActivity(i);
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
profilePictureView.setProfileId(user.getId());// 4
userName.setText("Hello , " + user.getName()
+ "\n you logged In Uaar Alumni ");
// userName2.setText("frstname"+ user.getFirstName());
// userName3.setText("address"+user.getBirthday());
// userName4.setText("texr"+user.getLocation());
get_email = (String) user.getProperty("email");
Name = user.getName();
Id = user.getId();
lastname = user.getLastName();
firstname = user.getFirstName();
getUsername = user.getUsername();
location = user.getLocation();
get_gender = (String) user.getProperty("gender");
// birthday=user.getBirthday();
// profileid=user.getId();
// profilePictureView.setProfileId(Id.getId());
// text.setText(Name + " \n " + Id + "\n" + firstname +
// "\n"
// + lastname + "\n" + getUsername + "\n" + get_gender);
// profilePicture=user.getId();
} else {
userName.setText("You are not logged");
}
}
});
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
text.setText("");
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = null;
switch (v.getId()) {
// case R.id.fb_login_button:
case R.id.location_button:
i = new Intent(this, LocationGet.class);
break;
// i=new Intent (this,Main_menu.class);
// break;
case R.id.profile_view:
i = new Intent(this, ValuesShow.class);
Log.d(Name, "" + Name);
i.putExtra("Name", Name);
i.putExtra("get_gender", get_gender);
i.putExtra("lastname", lastname);
i.putExtra("firstname", firstname);
i.putExtra("Id", Id);
i.putExtra("birthday", birthday);
i.putExtra("get_email", get_email);
// i.putExtra("profileid",profileid);
break;
}
// profilePictureView.setProfileId(user.getId());
// Intent intent = new Intent(this, ValuesShow.class);
// intent.getBooleanExtra("location", location);
Log.d(lastname, "" + lastname);
Log.d(get_gender, "" + get_gender);
// Log.d(LOGTAG,"Name value name....");
startActivity(i);
}
}
I'm using quickblox sdk group chat.
This is my code. But I still wrong. Can anybody guide me, please?
UserListForGroupActivity.java
public class UserListForGroupActivity extends Activity implements QBCallback {
private ListView usersList;
private ProgressDialog progressDialog;
private Button btnChat;
private SimpleAdapter usersAdapter;
private ArrayList<Friend_Users> friends= new ArrayList<Friend_Users>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list_for_group);
usersList = (ListView) findViewById(R.id.usersList);
btnChat=(Button)findViewById(R.id.btnstartGroupChat);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading fiends list");
progressDialog.show();
// ================= QuickBlox ===== Step 4 =================
// Get all users of QB application.
QBUsers.getUsers(this);
}
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
if (progressDialog != null) {
progressDialog.dismiss();
}
// Cast 'result' to specific result class QBUserPagedResult.
QBUserPagedResult pagedResult = (QBUserPagedResult) result;
final ArrayList<QBUser> users = pagedResult.getUsers();
System.out.println(users.toString());
// Prepare users list for simple adapter.
ArrayList<Map<String, String>> usersListForAdapter = new ArrayList<Map<String, String>>();
for (QBUser u : users) {
Map<String, String> umap = new HashMap<String, String>();
umap.put("userLogin", u.getLogin());
umap.put("chatLogin", QBChat.getChatLoginFull(u));
usersListForAdapter.add(umap);
}
// Put users list into adapter.
usersAdapter = new SimpleAdapter(this, usersListForAdapter,
android.R.layout.simple_list_item_multiple_choice,
new String[]{"userLogin", "chatLogin"},
new int[]{android.R.id.text1, android.R.id.text2});
usersList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
usersList.setAdapter(usersAdapter);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SparseBooleanArray checked= usersList.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
// Item position in adapter
int position = checked.keyAt(i);
// Add sport if it is checked i.e.) == TRUE!
if (checked.valueAt(i))
{
QBUser friendUser = users.get(position);
String login, password;
int id;
id=friendUser.getId();
login=friendUser.getLogin();
password=friendUser.getPassword();
friends.add(new Friend_Users(id,login, password));
}
}
Friend_Users_Wrapper wrapper= new Friend_Users_Wrapper(friends);
Log.e("UserListForGroupAcitvity friend list pass intent=>", friends.size()+ friends.get(0).getLogin());
Bundle extras = getIntent().getExtras();
Intent intent=new Intent(UserListForGroupActivity.this, GroupChatActivity.class);
intent.putExtra("friends", wrapper);
intent.putExtras(extras);
startActivity(intent);
}
});
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Error(s) occurred. Look into DDMS log for details, " +
"please. Errors: " + result.getErrors()).create().show();
}
}
#Override
public void onComplete(Result result, Object context) { }
}
GroupChatActivity.java
public class GroupChatActivity extends Activity {
private EditText messageText;
private TextView meLabel;
private TextView friendLabel;
private ViewGroup messagesContainer;
private ScrollView scrollContainer;
private QBUser me;
private GroupChatController groupChatController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
// Load QBUser objects from bundle (passed from previous activity).
Bundle extras = getIntent().getExtras();
Friend_Users_Wrapper wrapper= (Friend_Users_Wrapper) getIntent().getSerializableExtra("friends");
ArrayList<Friend_Users> friendArray= wrapper.getFriend_Users();
me = new QBUser();
me.setId(extras.getInt("myId"));
me.setLogin(extras.getString("myLogin"));
me.setPassword(extras.getString("myPassword"));
System.out.println("user login =>"+extras.getString("myLogin"));
QBUser friends= new QBUser();
for (Friend_Users friend_Users : friendArray) {
friends.setId(friend_Users.getId());
friends.setLogin(friend_Users.getLogin());
friends.setPassword(friend_Users.getPassword());
}
// UI stuff
messagesContainer = (ViewGroup) findViewById(R.id.messagesContainer);
scrollContainer = (ScrollView) findViewById(R.id.scrollContainer);
Button sendMessageButton = (Button) findViewById(R.id.sendButton);
sendMessageButton.setOnClickListener(onSendMessageClickListener);
messageText = (EditText) findViewById(R.id.messageEdit);
// ================= QuickBlox ===== Step 5 =================
// Get chat login based on QuickBlox user account.
// Note, that to start chat you should use only short login,
// that looks like '17744-1028' (<qb_user_id>-<qb_app_id>).
String chatLogin = QBChat.getChatLoginShort(me);
// Our current (me) user's password.
String password = me.getPassword();
if (me != null && friends != null) {
// ================= QuickBlox ===== Step 6 =================
// All chat logic can be implemented by yourself using
// ASMACK library (https://github.com/Flowdalic/asmack/downloads)
// -- Android wrapper for Java XMPP library (http://www.igniterealtime.org/projects/smack/).
groupChatController = new GroupChatController(chatLogin, password);
groupChatController.setOnMessageReceivedListener(onMessageReceivedListener);
// ================= QuickBlox ===== Step 7 =================
// Get friend's login based on QuickBlox user account.
// Note, that for your companion you should use full chat login,
// that looks like '17792-1028#chat.quickblox.com' (<qb_user_id>-<qb_app_id>#chat.quickblox.com).
// Don't use short login, it
String friendLogin = QBChat.getChatLoginFull(friends);
groupChatController.startChat(friendLogin);
}
}
private void sendMessage() {
if (messageText != null) {
String messageString = messageText.getText().toString();
groupChatController.sendMessage(messageString);
messageText.setText("");
showMessage(me.getLogin() + " (me) : "+messageString, true);
}
}
private GroupChatController.OnMessageReceivedListener onMessageReceivedListener = new GroupChatController.OnMessageReceivedListener() {
#Override
public void onMessageReceived(final Message message) {
String messageString = message.getBody();
showMessage(messageString, false);
}
};
private void showMessage(String message, boolean leftSide) {
final TextView textView = new TextView(GroupChatActivity.this);
textView.setTextColor(Color.BLACK);
textView.setText(message);
int bgRes = R.drawable.left_message_bg;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
if (!leftSide) {
bgRes = R.drawable.right_message_bg;
params.gravity = Gravity.RIGHT;
}
textView.setLayoutParams(params);
textView.setBackgroundResource(bgRes);
runOnUiThread(new Runnable() {
#Override
public void run() {
messagesContainer.addView(textView);
// Scroll to bottom
if (scrollContainer.getChildAt(0) != null) {
scrollContainer.scrollTo(scrollContainer.getScrollX(), scrollContainer.getChildAt(0).getHeight());
}
scrollContainer.fullScroll(View.FOCUS_DOWN);
}
});
}
private View.OnClickListener onSendMessageClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
};
}
GroupChatController.java
public class GroupChatController {
// Get QuickBlox chat server domain.
// There will be created connection with chat server below.
public static final String CHAT_SERVER = QBChat.getChatServerDomain();
private XMPPConnection connection;
private ConnectionConfiguration config;
private Chat chat;
// Multi-User Chat
private MultiUserChat muc2;
private String chatLogin;
private String password;
private String friendLogin;
private ChatManager chatManager;
public GroupChatController(String chatLogin, String password) {
this.chatLogin = chatLogin;
this.password = password;
}
public void startChat(String buddyLogin) {
this.friendLogin = buddyLogin;
new Thread(new Runnable() {
#Override
public void run() {
// Chat action 1 -- create connection.
Connection.DEBUG_ENABLED = true;
config = new ConnectionConfiguration(CHAT_SERVER);
connection = new XMPPConnection(config);
try {
connection.connect();
connection.login(chatLogin, password);
// Chat action 2 -- create chat manager.
chatManager = connection.getChatManager();
// Chat action 3 -- create chat.
chat = chatManager.createChat(friendLogin, messageListener);
// Set listener for outcoming messages.
chatManager.addChatListener(chatManagerListener);
// Muc 2
if(connection != null){
muc2 = new MultiUserChat(connection, "2389_chat1#muc.chat.quickblox.com");
// Discover whether user3#host.org supports MUC or not
// The room service will decide the amount of history to send
muc2.join(chatLogin);
muc2.invite(friendLogin, "Welcome!");
Log.d("friendLogin ->",friendLogin);
// Set listener for outcoming messages.
//chatManager.addChatListener(chatManagerListener);
muc2.addMessageListener(packetListener);
addListenerToMuc(muc2);
//chat1#muc.chat.quickblox.com
}
Message message = new Message(friendLogin + "#muc.chat.quickblox.com");
message.setBody("Join me for a group chat!");
message.addExtension(new GroupChatInvitation("2389_chat1#muc.chat.quickblox.com"));
connection.sendPacket(message);
} catch (XMPPException e) {
e.printStackTrace();
}
}
}).start();
}
/*** muc */
private void addListenerToMuc(MultiUserChat muc){
if(null != muc){
muc.addMessageListener(new PacketListener() {
#Override
public void processPacket(Packet packet) {
Log.i("processPacket", "receiving message");
}
});
}
}
PacketListener packetListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
Message message = (Message)packet;
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
e.printStackTrace();
}
//System.out.println("got message " + message.toXML());
}
};
private PacketInterceptor packetInterceptor = new PacketInterceptor() {
#Override
public void interceptPacket(Packet packet) {
System.out.println("Sending message: " + packet.toString());
Message message = muc2.createMessage();
message.setBody("Hello from producer, message " +
" ");
try {
muc2.sendMessage(message);
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
/***/
private ChatManagerListener chatManagerListener = new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
// Set listener for incoming messages.
chat.addMessageListener(messageListener);
muc2.addMessageListener(packetListener);
}
};
public void sendMessage(String message) {
try {
if (chat != null) {
chat.sendMessage(message);
}
if (muc2 != null) {
muc2.sendMessage(message);
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
private MessageListener messageListener = new MessageListener() {
#Override
public void processMessage(Chat chat, Message message) {
// 'from' and 'to' fields contains senders ids, e.g.
// 17792-1028#chat.quickblox.com/mac-167
// 17744-1028#chat.quickblox.com/Smack
String from = message.getFrom().split("#")[0];
String to = message.getTo().split("#")[0];
System.out.println(String.format(">>> Message received (from=%s, to=%s): %s",
from, to, message.getBody()));
if (onMessageReceivedListener != null) {
onMessageReceivedListener.onMessageReceived(message);
}
}
};
public static interface OnMessageReceivedListener {
void onMessageReceived(Message message);
}
// Callback that performs when device retrieves incoming message.
private OnMessageReceivedListener onMessageReceivedListener;
public OnMessageReceivedListener getOnMessageReceivedListener() {
return onMessageReceivedListener;
}
public void setOnMessageReceivedListener(OnMessageReceivedListener onMessageReceivedListener) {
this.onMessageReceivedListener = onMessageReceivedListener;
}
}
public void startChat(String buddyLogin) {
...
List<String> usersLogins= new ArrayList<String>();
for(String userLogin: usersLogins){
muc2.invite(userLogin, "Welcome!");
}
...
}
In my app i have a spinner with two items ..i have to choose the item an do action accordingly
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String Comment = edittext.getText().toString();
String choose = spinner.getSelectedItem()
.toString();
if (Comment != null && Comment.equalsIgnoreCase("")){
post(Comment,choose);
getActivity().finish();
}else{
showToast("Please enter you comment!");
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
} catch (Exception e) {
e.printStackTrace();
getActivity().finish();
}
}
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
-----------------> if(spinner.getSelectedItem().toString().equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
private void publishStory(Bundle postParams,final String comments,final String choose) {
Session session = Session.getActiveSession();
if (session != null){
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Request.Callback callbackRequest= new Request.Callback() {
public void onCompleted(Response response) {
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else
new fbUtils(activity).share(Data, comments, response.getError(),choose);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
};
Request request = new Request(session, Constants.fb.fbId + "/comments", postParams,
HttpMethod.POST, callbackRequest);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
the issue is the post() is not executing when clicking the dailogbutton its going into else part, i want to execute the if condition in post() method, Any help is appreciated
As you are getting the value from the spinner. The value may not be updated one .
You should use item-selected listeners.
String result="";
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
// Your variable should update here
result = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Now use that value in onPost method as:
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
Log.v("TEST",spinner.getSelectedItem().toString());
-----------------> if(result.equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
Try like this:
private Spinner status;
status = (Spinner) findViewById(R.id.status);
final ArrayList<Simplestatus> statusList = new ArrayList<Simplestatus>();
Simplestatus tempstatus = new Simplestatus();
tempstatus.setSimpleStatusName("ZERO");
tempstatus.setSimpleStatusValue("0");
Simplestatus tempstatus1 = new Simplestatus();
tempstatus1.setSimpleStatusName("ONE");
tempstatus1.setSimpleStatusValue("1");
statusList.add(tempstatus);
statusList.add(tempstatus1);
SpinnerAdapter stateAdaptor = new SpinnerAdapter(SettingActivity.this,statusList);
// stateList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
status.setAdapter(stateAdaptor);
status.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
changeStatus(statusList.get(position));
selected = statusList.get(position).getsimpleStatusName();
System.out.println("selected"+selected);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
public class Simplestatus
{
private String simpleStatusName;
private String simpleStatusValue;
public String getSimpleStatusName()
{
return simpleStatusName;
}
public void setSimpleStatusName(String simpleStatusName)
{
this.simpleStatusName = simpleStatusName;
}
public String getsimpleStatusValue()
{
return simpleStatusValue;
}
public void setsimpleStatusValue(String simpleStatusValue)
{
this.simpleStatusValue = simpleStatusValue;
}
}