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);
Related
I have successfully uploaded the media in the firebase but i'm unable to retrieve it. apparently it shows that the media_problem is pointing to a null object. below is my code.
This is my code to retrieve:
this.view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "TOO FAST! TRY AGAIN", Toast.LENGTH_LONG);
try {
Dash_agri.this.firestore.collection("problems").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
public void onComplete( Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
Dash_agri.this.records.clear();
Iterator it = ((QuerySnapshot) task.getResult()).iterator();
while (it.hasNext()) {
QueryDocumentSnapshot document = (QueryDocumentSnapshot) it.next();
Dash_agri.this.single_ID = document.getId();
Dash_agri.this.single_name = (String) document.get("NAME_problems");
Dash_agri.this.single_phone = (String) document.get("PHONE_problems");
Dash_agri.this.single_description = (String) document.get("DESCRIPTION_problems");
Dash_agri.this.single_URL = (String) document.get("MEDIA_problems");
String view_media = "Touch to view media";
new SpannableString(view_media).setSpan(new ClickableSpan() {
public void onClick(View widget) {
Toast.makeText(Dash_agri.this.getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
}
}, 0, 9, 33);
Dash_agri.this.record_id.add(Dash_agri.this.single_ID);
ArrayList<String> arrayList = Dash_agri.this.records;
StringBuilder sb = new StringBuilder();
sb.append("QUERY#");
sb.append(Dash_agri.this.single_ID);
sb.append(" by ");
sb.append(Dash_agri.this.single_name);
sb.append("\n");
sb.append(Dash_agri.this.single_description);
sb.append("\n\n");
sb.append(view_media);
arrayList.add(sb.toString());
}
}
}
});
} catch (Exception e) {
Toast.makeText(Dash_agri.this.getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
}
Dash_agri.this.listView.setAdapter(new ArrayAdapter<>(Dash_agri.this.getApplicationContext(), R.layout.simple_list_item_1, Dash_agri.this.records));
}
});
This is my code to upload:
public class Upload extends AppCompatActivity {
private static final int PICK_MEDIA_REQUEST = 1;
String MEDIA_url;
String NAME;
String PHONE;
long TIME_ID = System.currentTimeMillis();
String USER_ID;
TextView file;
FirebaseAuth firebaseAuth;
FirebaseFirestore firestore;
Button img;
EditText prob;
ProgressBar progressBar;
StorageReference storageReference;
Button upld;
/* access modifiers changed from: private */
public Uri uri;
Button vid;
/* access modifiers changed from: protected */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == -1 && data != null && data.getData() != null) {
this.uri = data.getData();
this.file.setText(this.uri.getPath());
}
}
/* access modifiers changed from: protected */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView((int) R.layout.activity_upload);
this.firebaseAuth = FirebaseAuth.getInstance();
this.firestore = FirebaseFirestore.getInstance();
this.storageReference = FirebaseStorage.getInstance().getReference();
this.prob = (EditText) findViewById(R.id.editTextProblem_upload);
this.file = (TextView) findViewById(R.id.textViewFile_upload);
this.img = (Button) findViewById(R.id.buttonImage_upload);
this.vid = (Button) findViewById(R.id.buttonVideo_Upload);
this.upld = (Button) findViewById(R.id.buttonUpload_upload);
this.progressBar = (ProgressBar) findViewById(R.id.progressBar_upload);
this.progressBar.setVisibility(View.VISIBLE);
this.img.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction("android.intent.action.GET_CONTENT");
Upload.this.startActivityForResult(intent, 1);
}
});
this.vid.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction("android.intent.action.GET_CONTENT");
startActivityForResult(intent, 1);
}
});
try {
this.upld.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (prob.getText().toString().isEmpty() || file.getText().toString().equals("No file selected")) {
Toast.makeText(getApplicationContext(), "Please write your problem and upload a file!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
upload_file_also(uri);
USER_ID = firebaseAuth.getCurrentUser().getUid();
TIME_ID = System.currentTimeMillis();
firestore.collection("users").document(USER_ID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
NAME = documentSnapshot.getString("NAME_");
PHONE = documentSnapshot.getString("PHONE_");
}
});
NAME = NAME == null ? "null" : NAME;
PHONE = PHONE == null ? "null" : PHONE;
if (!NAME.equals("null") && !PHONE.equals("null")) {
CollectionReference collection = firestore.collection("problems");
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(TIME_ID);
DocumentReference documentReference = collection.document(String.valueOf(sb.toString()));
Map<String, Object> user_problems = new HashMap<>();
user_problems.put("DESCRIPTION_problems", prob.getText().toString());
user_problems.put("NAME_problems", NAME);
user_problems.put("PHONE_problems", PHONE);
user_problems.put("MEDIA_problems", Upload.this.MEDIA_url);
documentReference.set(user_problems).addOnSuccessListener(new OnSuccessListener<Void>() {
public void onSuccess(Void aVoid) {
Toast.makeText(Upload.this.getApplicationContext(), "Successfully uploaded", Toast.LENGTH_SHORT).show();
Upload.this.startActivity(new Intent(Upload.this.getApplicationContext(), Dash_farmer.class));
Upload.this.finish();
}
});
}
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
/* access modifiers changed from: private */
public void upload_file_also(Uri fileUri) {
StorageReference storageReference2 = this.storageReference;
StringBuilder sb = new StringBuilder();
sb.append("ProbID-");
sb.append(this.TIME_ID);
final StorageReference sr = storageReference2.child(String.valueOf(sb.toString()));
sr.putFile(fileUri).addOnSuccessListener((OnSuccessListener<TaskSnapshot>) new OnSuccessListener<TaskSnapshot>() {
public void onSuccess(TaskSnapshot taskSnapshot) {
sr.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
public void onSuccess(Uri uri) {
Upload.this.MEDIA_url = uri.toString();
Upload.this.progressBar.setVisibility(View.VISIBLE);
Upload.this.upld.setText("TAP AGAIN TO UPLOAD MEDIA");
}
});
}
});
}
}
I'm unable to find why this isn't working. Please put a light on where this is going wrong.
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);
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
The app is about making a simple survey with checkboxes. The checkbox values come from REST Api as list like ["option1", "option2"...]
I will post selected checkboxes as also a list. All set and working except for removing unselected items. How can I get and remove 'unselected' data from list?
(User may make changes) I tried with List and HashMap, couldn't make it. Thanks in advance!
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList= new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String,String> map = new HashMap<>();
Button button_send;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout)findViewById(R.id.linear_checkbox);
button_send= (Button)findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(cevapList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(MainActivity.this, "LIST: "+"\n"+ checkedList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList){
textList = answerList;
for(j=0; j<textList.size(); j++){
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b==true){
Toast.makeText(MainActivity.this, ""+cb.getText()+" selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
secilenlerList.add(cb.getText().toString());
}else{
Toast.makeText(MainActivity.this, ""+cb.getText()+" unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Update your code its working fine. You didn't make changes when user unselect any check box item.
public class MainActivity extends AppCompatActivity {
LinearLayout linear_checkbox;
List<String> answerList = new ArrayList<>();
List<String> checkedList = new ArrayList<>();
Map<String, String> map = new HashMap<>();
Button button_send;
int j;
private ArrayList<String> secilenlerList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
linear_checkbox = (LinearLayout) findViewById(R.id.linear_checkbox);
button_send = (Button) findViewById(R.id.button_send);
//
answerList.add("Photography");
answerList.add("Music");
answerList.add("Skateboard");
listChoices(answerList);
button_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "LIST: " + "\n" + secilenlerList.toString(), Toast.LENGTH_SHORT).show();
//Toast.makeText(MainActivity.this, ""+map.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void listChoices(List<String> textList) {
textList = answerList;
secilenlerList = new ArrayList<>();
for (j = 0; j < textList.size(); j++) {
final CheckBox cb = new CheckBox(getApplicationContext());
cb.setText(textList.get(j));
cb.setTextColor(Color.parseColor("#E7740D"));
linear_checkbox.addView(cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean ischecked) {
if (ischecked) {
Toast.makeText(MainActivity.this, "" + cb.getText() + " selected", Toast.LENGTH_SHORT).show();
String key = String.valueOf(j);
//map.put(key,cb.getText().toString());
if (!secilenlerList.contains(cb.getText().toString()))
secilenlerList.add(cb.getText().toString());
} else {
if (secilenlerList.contains(cb.getText().toString()))
secilenlerList.remove(cb.getText().toString());
Toast.makeText(MainActivity.this, "" + cb.getText() + " unselected", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
I need to put a 30sec timer in my otp verfication page after 30secs timer should be gone and the keyboard should pop up. what needs to be done??
Below are my java files.
SignUpFragment.java
SignUpActivity activity;
/**
* Declaring Variables for Views
*/
TextView SignupAlreadyMember;
EditText SignUpName, SignUpEmail,referCode;
Button SignUpRegister;
VirtualApplication virtualApplication;
// Progress dialog
private ProgressDialog pDialog;
public SignUpFragment() {
}
#Override
public void onAttach(Activity activit) {
super.onAttach(activit);
this.activity = (SignUpActivity) activit;
virtualApplication = (VirtualApplication) activity.getApplicationContext();
}
int bodyId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
bodyId = getArguments().getInt("output");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sign_up, container, false);
activity.setTempTitle("signup");
inItViews(view);
SignUpRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RegisterUser();
// showVerifyMobileScreen(123);
}
});
SignUpEmail.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
RegisterUser();
}
return false;
}
});
SignupAlreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gotoLoginScreen();
}
});
return view;
}
private void gotoLoginScreen() {
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
activity.finish();
}
public boolean validCellPhone(String number) {
return Patterns.PHONE.matcher(number).matches();
}
private void RegisterUser() {
String email = SignUpEmail.getText().toString().trim();
String name = SignUpName.getText().toString().trim();
String code=referCode.getText().toString().trim();
if (email.isEmpty() ||!SystemUtil.isValidMobile(email)) {
SignUpEmail.setError("Enter Mobile number here");
return;
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", name);
jsonObject.put("phone_number", email);
jsonObject.put("body_id", bodyId);
jsonObject.put("referral_code",code);//referral_code
TelephonyManager tm = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
jsonObject.put("imei", SystemUtil.getIMEINumber(activity, tm)) ;
} catch (JSONException e) {
e.printStackTrace();
}
SignUpRegister.setEnabled(false);
requestForRegistration(jsonObject);
}
private void requestForRegistration(JSONObject jsonObject) {
showpDialog();
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, AppConstants.REGISTER_URL, jsonObject, this, this);
customJSONObjectRequest.setTag("Register");
customJSONObjectRequest.setRetryPolicy(new DefaultRetryPolicy(5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
customJSONObjectRequest.setShouldCache(true);
requestQueue.add(customJSONObjectRequest);
//
}
private void showVerifyMobileScreen(int userId) {
VerificationFragment verificationFragment = new VerificationFragment();
Bundle bundle = new Bundle();
bundle.putInt("userId", userId);
bundle.putString("mobile", SignUpEmail.getText().toString().trim());
verificationFragment.setArguments(bundle);
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, verificationFragment).commit();
}
private void inItViews(View view) {
TextView SignUPHeader = (TextView) view.findViewById(R.id.SignUPHeader);
TextView Signupmessage= (TextView) view.findViewById(R.id.Signupmessage);
Signupmessage.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUPHeader.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignupAlreadyMember = (TextView) view.findViewById(R.id.SignupAlreadyMember);
SignupAlreadyMember.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpName = (EditText) view.findViewById(R.id.SignUpName);
SignUpName.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpEmail = (EditText) view.findViewById(R.id.SignUpEmail);
SignUpEmail.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpRegister = (Button) view.findViewById(R.id.SignUpRegister);
SignUpRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
referCode = (EditText) view.findViewById(R.id.referCode);
referCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
SignUpRegister.setEnabled(true);
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
SystemUtil.sysOut("register::::: " + jsonObject.toString());
if (JSONUtil.readBoolean(jsonObject, "status")) {
int userId = JSONUtil.readInt(jsonObject, "user_id");
showVerifyMobileScreen(userId);
}else{
SignUpRegister.setEnabled(true);
}
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
}
VerificationFragment.Java
SignUpActivity activity;
TextView verifyTitleOne, verifyTitleTwo, verifyChnageNumber, verificationResend;
EditText SignUpMobile, VerficationCode;
Button VerificationRegister;
int userId;
String mobile;
boolean isResend;
public VerificationFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
userId = bundle.getInt("userId");
mobile = bundle.getString("mobile");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_verfication, container, false);
activity.setTempTitle("details");
inItViews(view);
SignUpMobile.setText("" + mobile);
VerificationRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!VerficationCode.getText().toString().trim().isEmpty()) {
Toast.makeText(activity, "Verifying", Toast.LENGTH_LONG).show();
showpDialog();
getDefaultData();
} else {
VerficationCode.setError("Enter Code");
}
}
});
verificationResend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isResend) {
isResend = true;
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject, AppConstants.RESEND_OTP_URL);
}else
Toast.makeText(activity,"Please Wait",Toast.LENGTH_SHORT).show();
}
});
// setvalues();
return view;
}
private void setvalues() {
VerficationCode.setText("51692");
VerificationRegister.performClick();
}
private void getDefaultData() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_id", userId);
jsonObject.put("token", VerficationCode.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
requestServer(jsonObject,AppConstants.VERIFY_NUMBER_URL);
}
private void requestServer(JSONObject jsonObject, String url) {
RequestQueue requestQueue = CustomVolleyRequestQueue.getInstance(activity).getRequestQueue();
final CustomJSONObjectRequest customJSONObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, url, jsonObject, this, this);
customJSONObjectRequest.setTag("verify");
requestQueue.add(customJSONObjectRequest);
}
private void gotoSelectSizesPage(JSONObject jsonObject) {
Bundle bundle = new Bundle();
bundle.putString("output", jsonObject.toString());
DoneFragment homeKitFragment = new DoneFragment();
homeKitFragment.setArguments(bundle);
activity.setTempTitle("");
activity.getSupportFragmentManager().beginTransaction().replace(R.id.fragment, homeKitFragment).commit();
}
private void inItViews(View view) {
verifyTitleOne = (TextView) view.findViewById(R.id.verifyTitleOne);
verifyTitleOne.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyTitleTwo = (TextView) view.findViewById(R.id.verifyTitleTwo);
verifyTitleTwo.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verifyChnageNumber = (TextView) view.findViewById(R.id.verifyChnageNumber);
verifyChnageNumber.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
verificationResend = (TextView) view.findViewById(R.id.verificationResend);
verificationResend.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
SignUpMobile = (EditText) view.findViewById(R.id.SignUpMobile);
SignUpMobile.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerficationCode = (EditText) view.findViewById(R.id.VerficationCode);
VerficationCode.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
VerificationRegister = (Button) view.findViewById(R.id.VerificationRegister);
VerificationRegister.setTypeface(Typefaces.get(activity, AppConstants.FONT_ROBOT_REGULAR));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get("pdus");
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], "3gpp");
smsMessageStr = smsMessage.getMessageBody().toString();
// String address = smsMessage.getOriginatingAddress();
/*smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";*/
}
VerficationCode.setText("" + stripNonDigits(smsMessageStr));
VerificationRegister.performClick();
}
}
};
private ProgressDialog pDialog;
private void showpDialog() {
pDialog = ProgressDialog.show(activity, null, null);
final Drawable d = new ColorDrawable(Color.TRANSPARENT);
pDialog.getWindow().setBackgroundDrawable(d);
pDialog.setContentView(R.layout.loader);
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
public static String stripNonDigits(
final CharSequence input) {
final StringBuilder sb = new StringBuilder(
input.length());
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (c > 47 && c < 58) {
sb.append(c);
}
}
return sb.toString();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (SignUpActivity) activity;
activity.registerReceiver(broadcastReceiver, new IntentFilter(
AppConstants.BROADCAST_ACTION_SMS));
}
#Override
public void onDetach() {
super.onDetach();
activity.unregisterReceiver(broadcastReceiver);
}
#Override
public void onErrorResponse(VolleyError volleyError) {
hidepDialog();
}
#Override
public void onResponse(JSONObject jsonObject) {
hidepDialog();
isResend=false;
if (jsonObject.has("message"))
Toast.makeText(activity, JSONUtil.readString(jsonObject, "message"), Toast.LENGTH_LONG).show();
if (JSONUtil.readBoolean(jsonObject, "status") &&jsonObject.has("user_data")) {
gotoSelectSizesPage(jsonObject);
}
}
}