How to save value Intent inside Calling API? - java

I have a problem for saving value in Intent from calling API, the calling API showing its value, but i can't save it to intent.
this is my Code
Saving in Intent
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent mIntent = new Intent(view.getContext(), KelasOnlineActivity.class);
mIntent.putExtra("link",kelas.get(position).getUrl());
sharedPrefKelas.saveSPString(SharedPrefKelas.SP_ID_Kelas, "");
Call<Kelas> result = mApiInterface.KelasCall(kelas.get(position).getUrl(), sharedPrefManager.getSpIdMember(), sharedPrefManager.getSpLevelMember(), sharedPrefManager.getSpToken());
result.enqueue(new Callback<Kelas>() {
#Override
public void onResponse(Call<Kelas> call, Response<Kelas> response) {
if (response.isSuccessful()) {
Kelas mkelas = response.body();
Log.d("data", "Nyoba Status Kelas: " + mkelas.statuschat);
mIntent.putExtra("Status",mkelas.statuschat);
} else {
Log.i("debug", "cekdata: GA BERHASIL");
}
}
#Override
public void onFailure(Call<Kelas> call, Throwable t) {
Log.e("debug", "onFailure: ERROR > " + t.getMessage());
}
});
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(mIntent);
Getting Intent
Intent intent;
intent = getActivity().getIntent();
url= intent.getStringExtra("link");
status = intent.getStringExtra("Status");
Toast.makeText(getActivity(), url+status, Toast.LENGTH_LONG).show();
i can display url in Toast but not the status, the status showing null,
This is the picture of the problem
Can anyone help me?I am grateful if anyone can solve my problem

You're calling startActivity outside of onResponse callback: in this way, it'll call the new activity surely before onResponse, and surely before the status-save event.
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent mIntent = new Intent(view.getContext(), KelasOnlineActivity.class);
mIntent.putExtra("link",kelas.get(position).getUrl()); //This is outside of onResponse, so it's added correctly
sharedPrefKelas.saveSPString(SharedPrefKelas.SP_ID_Kelas, "");
Call<Kelas> result = mApiInterface.KelasCall(kelas.get(position).getUrl(), sharedPrefManager.getSpIdMember(), sharedPrefManager.getSpLevelMember(), sharedPrefManager.getSpToken());
result.enqueue(new Callback<Kelas>() {
#Override
public void onResponse(Call<Kelas> call, Response<Kelas> response) {
if (response.isSuccessful()) {
Kelas mkelas = response.body();
Log.d("data", "Nyoba Status Kelas: " + mkelas.statuschat);
mIntent.putExtra("Status",mkelas.statuschat);
//You should put them here
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(mIntent);
} else {
Log.i("debug", "cekdata: GA BERHASIL");
}
}
#Override
public void onFailure(Call<Kelas> call, Throwable t) {
Log.e("debug", "onFailure: ERROR > " + t.getMessage());
}
});
//And not here
//mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//view.getContext().startActivity(mIntent);

Try
private String tmp = "";
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent mIntent = new Intent(view.getContext(), KelasOnlineActivity.class);
mIntent.putExtra("link",kelas.get(position).getUrl());
sharedPrefKelas.saveSPString(SharedPrefKelas.SP_ID_Kelas, "");
Call<Kelas> result = mApiInterface.KelasCall(kelas.get(position).getUrl(), sharedPrefManager.getSpIdMember(), sharedPrefManager.getSpLevelMember(), sharedPrefManager.getSpToken());
result.enqueue(new Callback<Kelas>() {
#Override
public void onResponse(Call<Kelas> call, Response<Kelas> response) {
if (response.isSuccessful()) {
Kelas mkelas = response.body();
Log.d("data", "Nyoba Status Kelas: " + mkelas.statuschat);
tmp = mkelas.statuschat;
} else {
Log.i("debug", "cekdata: GA BERHASIL");
}
}
#Override
public void onFailure(Call<Kelas> call, Throwable t) {
Log.e("debug", "onFailure: ERROR > " + t.getMessage());
}
});
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("Status", tmp);
view.getContext().startActivity(mIntent);

Related

Properly send value through many intents

I have tried all the good ole fashion ways of sending data through intents such as getExtra and putExtra. However, this certain piece of information will not travel through intents. The variable is initialized here (driverId):
private void findDriver() {
DatabaseReference drivers = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
GeoFire gfDrivers = new GeoFire(drivers);
GeoQuery geoQuery = gfDrivers.queryAtLocation(new GeoLocation(mLastLocation.getLatitude(),mLastLocation.getLongitude()),radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
if(!Common.isDriverFound){
Common.isDriverFound = true;
Common.driverId = key;
btnPickupRequest.setText("CALL SUB");
Toast.makeText(Home.this,""+key, Toast.LENGTH_SHORT).show();
}
}
I then send the information for driverId when a button is clicked here:
Intent intent = new Intent(Home.this, CallDriver.class);
intent.putExtra("driverId",marker.getSnippet());
intent.putExtra("lat",mLastLocation.getLatitude());
intent.putExtra("lng",mLastLocation.getLongitude());
startActivity(intent);
I then call the information in the text intent like so:
if (driverId != null && !driverId.isEmpty())
if (getIntent() !=null) {
driverId = getIntent().getStringExtra("driverId");
}
sendRequestToDriver(driverId, mService, getBaseContext(), mLastLocation);
}
My send request to driver method is:
public static void sendRequestToDriver(String driverId,final IFCMService mService,final Context context,final Location currentLocation) {
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference(Common.token_tbl);
tokens.orderByKey().equalTo(driverId)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
Token token = postSnapShot.getValue(Token.class);
//String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude()));
String riderToken = FirebaseInstanceId.getInstance().getToken();
Map<String,String> content = new HashMap<>();
content.put("customer", riderToken);
content.put("driverId",driverId);
content.put("lat",String.valueOf(currentLocation.getLatitude()));
content.put("lng",String.valueOf(currentLocation.getLongitude()));
DataMessage dataMessage = new DataMessage(token.getToken(),content);
Log.d(String.valueOf(dataMessage), "here big boy"+dataMessage);
mService.sendMessage(dataMessage).enqueue(new Callback<FCMResponse>() {
#Override
public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
if(response.body().success == 1)
Toast.makeText(context, "Request Sent!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<FCMResponse> call, Throwable t) {
Log.e("Error", t.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Now when I try to receive the information on the intent RateActivity, I get a null value. How can I make sure that the string driverId is properly initialized or the data stays throughout these intents?
try this intent.putExtra("driverId",marker.getSnippet().toString());
intent.putExtra("lat",mLastLocation.getLatitude().toString());
intent.putExtra("lng",mLastLocation.getLongitude().toString());

Messages duplicates twice when a user sends a message [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm building a chat application that sends messages and media files, my problem is that when a user sends a message or a media file it displays twice. But when I close my chat activity and open it again it displays as expected i.e. once.
My Chat Activity
public class ChatActivityy extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
messageSenderID = mAuth.getCurrentUser().getUid();
Rootref = FirebaseDatabase.getInstance().getReference();
UsersRef = FirebaseDatabase.getInstance().getReference("Users");
messageReceiverID = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("visit_user_name").toString();
//Toast.makeText(this, messageReceiverID, Toast.LENGTH_SHORT).show();
//Toast.makeText(this, messageReceiverName, Toast.LENGTH_SHORT).show();
InitializeControllers();
DisplayLastSeen();
GetUserInfo();
userName.setText(messageReceiverName);
SendMessageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
notify = true;
SendMessage();
//MessageInputText.setText("");
}
});
SendFilesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CharSequence[] options = new CharSequence[]
{
"Images",
"Videos",
"Documents",
"Audio",
"Cancel"
};
AlertDialog.Builder builder = new AlertDialog.Builder(ChatActivityy.this);
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
}
});
builder.show();
}
});
apiService = Client.getClient("https://fcm.googleapis.com/").create(APIService.class);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null & data.getData() !=null)
{
loadingBar.setTitle("Sending file");
loadingBar.setMessage("Please wait, your file is sending");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
fileUri = data.getData();
if(checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files");
String messageSenderRef = "Messages/" + messageSenderID + "/" + messageReceiverID;
String messageReceiverRef = "Messages/" + messageReceiverID + "/" + messageSenderID;
DatabaseReference userMessageKeyRef = Rootref.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
final String messagePushID = userMessageKeyRef.getKey();
final StorageReference filepath = storageReference.child(messagePushID + "." + "jpg");
uploadTask = filepath.putFile(fileUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful())
{
throw task.getException();
}
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful())
{
Uri downloadUrl = task.getResult();
myUrl = downloadUrl.toString();
Map messageTextBody = new HashMap();
messageTextBody.put("message", myUrl);
messageTextBody.put("name", fileUri.getLastPathSegment());
messageTextBody.put("type", checker);
messageTextBody.put("from", messageSenderID);
messageTextBody.put("to", messageReceiverID);
messageTextBody.put("messageID", messagePushID);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef + "/" + messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushID, messageTextBody);
Rootref.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
// Toast.makeText(ChatActivityy.this, "Message Sent", Toast.LENGTH_SHORT).show();
} else {
loadingBar.dismiss();
Toast.makeText(ChatActivityy.this, "Message not sent", Toast.LENGTH_SHORT).show();
}
MessageInputText.setText("");
}
});
}
}
});
}
else
{
loadingBar.dismiss();
Toast.makeText(this, "No Image Selected", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onStart() {
super.onStart();
Rootref.child("Messages").child(messageSenderID).child(messageReceiverID)
.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
messagesList.add(messages);
messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendMessage()
{
String messageText = MessageInputText.getText().toString();
if (TextUtils.isEmpty(messageText))
{
Toast.makeText(this, "Enter a Message", Toast.LENGTH_SHORT).show();
}
else {
String messageSenderRef = "Messages/" + messageSenderID + "/" + messageReceiverID;
String messageReceiverRef = "Messages/" + messageReceiverID + "/" + messageSenderID;
DatabaseReference userMessageKeyRef = Rootref.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
String messagePushID = userMessageKeyRef.getKey();
Map messageTextBody = new HashMap();
messageTextBody.put("message", messageText);
messageTextBody.put("type", "text");
messageTextBody.put("from", messageSenderID);
messageTextBody.put("to", messageReceiverID);
messageTextBody.put("messageID", messagePushID);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef + "/" + messagePushID, messageTextBody);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushID, messageTextBody);
Rootref.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
// Toast.makeText(ChatActivityy.this, "Message Sent", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ChatActivityy.this, "Message not sent", Toast.LENGTH_SHORT).show();
}
MessageInputText.setText("");
}
});
final String msg = messageText;
// UsersRef.child(messageSenderID);
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Friends user = dataSnapshot.getValue(Friends.class);
if (notify) {
sendNotification(messageReceiverID, user.getName(), msg);
}
notify = false;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My Adapter
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageViewHolder>
{
private List<Messages> userMessagesList;
private FirebaseAuth mAuth;
private DatabaseReference usersRef;
MessageAdapter(List<Messages> userMessagesList) {
this.userMessagesList = userMessagesList;
}
class MessageViewHolder extends RecyclerView.ViewHolder
{
TextView senderMessageText, receiverMessageText;
ZoomageView senderImage, receiverImage;
ImageView senderMedia, receiverMedia;
public MessageViewHolder(#NonNull View itemView) {
super(itemView);
senderMessageText = (TextView) itemView.findViewById(R.id.sender_message_text);
receiverMessageText = (TextView) itemView.findViewById(R.id.receiver_message_text);
}
}
#NonNull
#Override
public MessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.custom_messages_layout, parent, false);
mAuth = FirebaseAuth.getInstance();
return new MessageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MessageViewHolder messageViewHolder, final int position) {
String messageSenderID = mAuth.getCurrentUser().getUid();
final Messages messages = userMessagesList.get(position);
String fromUserID = messages.getFrom();
String fromMessageType = messages.getType();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(fromUserID);
messageViewHolder.receiverMessageText.setVisibility(View.GONE);
messageViewHolder.senderMessageText.setVisibility(View.GONE);
if (fromMessageType.equals("text")) {
if (fromUserID.equals(messageSenderID)) {
messageViewHolder.senderMessageText.setVisibility(View.VISIBLE);
messageViewHolder.senderMessageText.setBackgroundResource(R.drawable.sender_message);
messageViewHolder.senderMessageText.setTextColor(Color.BLACK);
messageViewHolder.senderMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
} else {
messageViewHolder.receiverMessageText.setVisibility(View.VISIBLE);
messageViewHolder.receiverMessageText.setBackgroundResource(R.drawable.receiver_messages_layout);
messageViewHolder.receiverMessageText.setTextColor(Color.BLACK);
messageViewHolder.receiverMessageText.setText(messages.getMessage() + "\n \n" + messages.getTime() + " - " + messages.getDate());
}
}
if (fromUserID.equals(messageSenderID))
{
messageViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (userMessagesList.get(position).getType().equals("text"))
{
CharSequence[] options = new CharSequence[]
{
"Delete for me",
"Delete for Everyone",
"Copy",
"Cancel"
};
AlertDialog.Builder builder = new AlertDialog.Builder(messageViewHolder.itemView.getContext());
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if (i == 0)
{
deleteSentMessage(position, messageViewHolder);
}
else if (i == 1)
{
deleteMessageForEveryone(position, messageViewHolder);
}
else if (i == 2)
{
ClipboardManager myClipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData myClip = ClipData.newPlainText("label", messageViewHolder.senderMessageText.getText().toString());
myClipboard.setPrimaryClip(myClip);
Toast.makeText(v.getContext(), "Copied to clipboard" , Toast.LENGTH_SHORT ).show();
//setClipboard(mContext, messageViewHolder.senderMessageText.toString());
}
}
});
builder.show();
}
}
#Override
public int getItemCount() {
return userMessagesList.size();
}
}
This might be because you attach a listener in onStart. After you start a new intent, the activity is paused, and then, after the user has added a new message and resumed the old activity, method onStart is called one more time. So at that moment you have two listeners. If the next added message is duplicated three times, then it must be the actual problem. Try moving EventListener to onCreate. Or check if it is already assigned to your directory (Idk if this is possible with the database), if you want to leave it in onStart

Retrofit, TimeoutException

I'm using retrofit authentication, and I have a timeoutexception. I saw many questions, but I can't solve this.
Here's the code
public class FragmentRegistration extends Fragment {
View mainView;
EditText username, email, password, name;
Button button;
ApiClient pentairAPIClient = ApiClient.getInstance();
SupportopObj supportopObj = new SupportopObj();
SupportopObjActivate supportopObjActivate = new SupportopObjActivate();
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mainView = inflater.inflate
(R.layout.registration, container, false);
username = mainView.findViewById(R.id.username);
email = mainView.findViewById(R.id.email);
password = mainView.findViewById(R.id.password);
name = mainView.findViewById(R.id.name);
button = mainView.findViewById(R.id.register);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//String s = name.getText().toString();
//String split[] = s.split(" ");
supportopObj.setFirstName("Tester");
supportopObj.setLastName("Testryan");
supportopObj.setUsername(username.getText().toString());
supportopObj.setEmail(email.getText().toString());
supportopObj.setPassword(password.getText().toString());
supportopObjActivate.setUsername(supportopObj.getUsername());
supportopObjActivate.setEmail(supportopObj.getEmail());
supportopObjActivate.setPassword(supportopObj.getPassword());
supportopObjActivate.setType("generic");
updateApp();
}
});
return mainView;
}
public void updateApp() {
Call<ResponseBody> call = pentairAPIClient.registration(supportopObj);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
activationCall();
} else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error...", Toast.LENGTH_SHORT).show();
}
});
}
public void activationCall() {
Call<ResponseBody> callActive = pentairAPIClient.activation(supportopObjActivate);
callActive.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String data = response.body().string();
JSONObject obj = new JSONObject(data);
String client_id = obj.getString("client_id");
String client_secret = obj.getString("client_secret");
tokenCall(client_id, client_secret);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(), "error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "Error in activation",
Toast.LENGTH_SHORT).show();
}
});
}
public void tokenCall(String client_id, String client_secret) {
Call<ResponseBody> token = pentairAPIClient.get_token("password", client_id, client_secret,
supportopObj.getEmail(), supportopObj.getPassword());
token.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), String.valueOf(response.body()), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Something wrong.....", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getContext(), "You're on failure", Toast.LENGTH_SHORT).show();
}
});
}
}
I have no error in retrofit, I'm doing debugging and I see all the process, so I getting client id and secret successfully, then I'm getting a timeoutexception in the last onfailure(),
#Override
public void onFailure(Call<ResponseBody> call, Throwable t)
{
Toast.makeText(getContext(), "You're onfailure",Toast.LENGTH_SHORT).show();
}
watch the code, that's the last line. How to fix it? The app not crashes, but in debug he drops timeoutexception like this. t={SocketTimeoutException#830038722120}java.net.SocketTimeoutException: timeout . In OkHttpClient the
readTimeout(10, TimeUnit.SECONDS).connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS); all are 10, i tried to set it 100, not helps. Help me. Thanks.

Facebook - Post to wall

I have this code.. The only working here is the Login... I want to achieve the Publish to wall or feed dialog.. I have here the code for the wall post but It still not working.. Any help will be appreciated... I followed this link for my Login
[a link] http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
I am trying to embed the post status in this Login..
public class FacebookActivity extends FragmentActivity {
private Button publishButton;
private String TAG = "FacebookActivity";
private TextView lblEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_activity);
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
authButton.setOnErrorListener(new OnErrorListener(){
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
// TODO Auto-generated method stub
});
// set permission list, Don't forget to add email
authButton.setReadPermissions(Arrays.asList("basic_info","email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i(TAG,"Access Token"+ session.getAccessToken());
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,Response response) {
if (user != null) {
Log.i(TAG,"User ID "+ user.getId());
Log.i(TAG,"Email "+ user.asMap().get("email"));
lblEmail.setText(user.asMap().get("email").toString());
}
}
});
publishButton.setVisibility(View.VISIBLE);
}
else if (state.isClosed()) {
publishButton.setVisibility(View.INVISIBLE);
}
}
});
publishButton = (Button) findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishFeedDialog();
}
});
}
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getActivity().getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
protected ContextWrapper getActivity() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}

Activity and Voice recognition

I have this code:
public class VoiceActivity extends Activity implements OnClickListener {
private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyActivity";
public String str;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button speakButton = (Button) findViewById(R.id.speakButton);
mText = (TextView) findViewById(R.id.textView1);
speakButton.setOnClickListener(this);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
class listener implements RecognitionListener {
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech() {
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB) {
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer) {
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech() {
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error) {
Log.d(TAG, "error " + error);
mText.setText("error " + error);
}
public void onResults(Bundle results) {
str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++) {
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
mText.setText("results: " + str);
}
public void onPartialResults(Bundle partialResults) {
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params) {
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.speakButton) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "com.moc");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
sr.startListening(intent);
}
}
}
How to make an automatic transition to another Activity after recognition voice (press button - say - open next Activity and result in it)? In my example, it says error in line
intent.setClass (this, SecondActivity.class).
Example:
public void onResults(Bundle results) {
str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++) {
Log.d(TAG, "result " + data.get(i));
str += data.get(i);
}
Intent intent = new Intent();
Bundle b = new Bundle();
b.putString("StrID", str);
intent.putExtras(b);
intent.setClass(this, SecondActivity.class);
startActivity(intent);
}
you should relpace the this with VoiceActivity.this , because the this is refering the the listener instance not of the context of your activity :
intent.setClass (VoiceActivity.this, SecondActivity.class);

Categories