How to convert audio to text without stopping - spekit

I have an application that converts audio to text. I wanted that when the recording stops the text and starts again, it continues on the same previous recording and does not start again.
This is my code:
I've searched many threads and couldn't find a solution
My application is based on written voice recording so that the user speaks into the phone’s microphone and the voice is converted into text, but when it stops and starts again in recording, the converted text is recorded from the beginning, so I wanted it to continue on the previous text
getWindow ().addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
returnedText = (EditText) findViewById (R.id.textView1);
progressBar = (ProgressBar) findViewById (R.id.progressBar1);
toggleButton = (ToggleButton) findViewById (R.id.toggleButton1);
Copy = (Button) findViewById (R.id.copy);
Share = (Button) findViewById (R.id.share);
progressBar.setVisibility (View.INVISIBLE);
speech = SpeechRecognizer.createSpeechRecognizer (this);
Log.i (LOG_TAG,"isRecognitionAvailable: " + SpeechRecognizer.isRecognitionAvailable (this));
speech.setRecognitionListener (this);
recognizerIntent = new Intent (RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"ar");
recognizerIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// تغير اللغة
recognizerIntent.putExtra (RecognizerIntent.EXTRA_LANGUAGE,"ar");
recognizerIntent.putExtra (RecognizerIntent.EXTRA_MAX_RESULTS,1);
toggleButton.setOnCheckedChangeListener (new CompoundButton.OnCheckedChangeListener () {
#Override
public void onCheckedChanged ( CompoundButton buttonView,
boolean isChecked ) {
if (isChecked) {
progressBar.setVisibility (View.VISIBLE);
progressBar.setIndeterminate (true);
ActivityCompat.requestPermissions
(Arabick.this,
new String[]{Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_PERMISSION);
} else {
progressBar.setIndeterminate (false);
progressBar.setVisibility (View.INVISIBLE);
speech.stopListening ();
}
}
});
}
#Override
public void onRequestPermissionsResult ( int requestCode,#NonNull String[] permissions,#NonNull int[] grantResults ) {
super.onRequestPermissionsResult (requestCode,permissions,grantResults);
switch (requestCode) {
case REQUEST_RECORD_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
speech.startListening (recognizerIntent);
} else {
Toast.makeText (Arabick.this,"Permission Denied!",Toast
.LENGTH_SHORT).show ();
}
}
// recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ar-SA");
Copy.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick ( View v ) {
// ������ ���� ���� ������� ���� txtText
copy_content = returnedText.getText ().toString ();
ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
clipboard.setText (copy_content);
// ��� ����� ����� ���� ���� ������ ����
Toast.makeText (getApplicationContext (),"تم النسخ ",Toast.LENGTH_SHORT).show ();
}
});
// ����� �� ������� ����
Share.setOnClickListener (new View.OnClickListener () {
#Override
public void onClick ( View v ) {
copy_content = returnedText.getText ().toString ();
Intent sendIntent = new Intent ();
sendIntent.setAction (Intent.ACTION_SEND);
sendIntent.putExtra (Intent.EXTRA_TEXT,copy_content);
sendIntent.setType ("text/plain");
startActivity (Intent.createChooser (sendIntent,"Select the application:"));
}
});
}
#Override
public void onResume () {
super.onResume ();
}
#Override
protected void onPause () {
super.onPause ();
}
#Override
protected void onStop () {
super.onStop ();
if (speech != null) {
speech.destroy ();
Log.i (LOG_TAG,"destroy");
}
}
#Override
public void onBeginningOfSpeech () {
Log.i (LOG_TAG,"onBeginningOfSpeech");
progressBar.setIndeterminate (false);
progressBar.setMax (10);
}
#Override
public void onBufferReceived ( byte[] buffer ) {
Log.i (LOG_TAG,"onBufferReceived: " + buffer);
}
#Override
public void onEndOfSpeech () {
Log.i (LOG_TAG,"onEndOfSpeech");
progressBar.setIndeterminate (true);
toggleButton.setChecked (false);
}
#Override
public void onError ( int errorCode ) {
String errorMessage = getErrorText (errorCode);
Log.d (LOG_TAG,"FAILED " + errorMessage);
returnedText.setText (errorMessage);
toggleButton.setChecked (false);
}
#Override
public void onEvent ( int arg0,Bundle arg1 ) {
Log.i (LOG_TAG,"onEvent");
}
#Override
public void onPartialResults ( Bundle arg0 ) {
Log.i (LOG_TAG,"onPartialResults");
}
#Override
public void onReadyForSpeech ( Bundle arg0 ) {
Log.i (LOG_TAG,"onReadyForSpeech");
}
#Override
public void onResults ( Bundle results ) {
Log.i (LOG_TAG,"onResults");
ArrayList < String > matches = results
.getStringArrayList (SpeechRecognizer.RESULTS_RECOGNITION);
String text = "";
for (String result : matches)
text += result + "\n";
returnedText.setText (text);
}
#Override
public void onRmsChanged ( float rmsdB ) {
Log.i (LOG_TAG,"onRmsChanged: " + rmsdB);
progressBar.setProgress ((int) rmsdB);
}
}

Related

Can't update Item from RecycleView using a Custom Adapter and Listener

I have an updateTask method which opens an alert dialog. I am trying to call this method through a listener in the onBindViewHolder function in my custom adapter.
However my alert dialog does not pop up and while debugging I found out that my update task method is not called.
Please help me understand why.
Thanks
Here is my customAdapter:
public class TasksAdapter extends RecyclerView.Adapter<TasksAdapter.TaskViewHolder> {
private ArrayList<Model> tasks;
private TaskUpdateListener listener;
TasksAdapter(ArrayList<Model> tasks,TaskUpdateListener listener) {
this.tasks = tasks;
this.listener = listener;
}
#Override
public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.retrieved_layout, parent, false);
return new TaskViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TaskViewHolder holder, int position) {
Model task = tasks.get(position);
holder.setDate(task.getDate());
holder.setTask(task.getTask());
holder.setDesc(task.getDescription());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String taskString = task.getTask();
String descString = task.getDescription();
listener.onTaskUpdate(task, position);
}
});
}
#Override
public int getItemCount() {
return tasks.size();
}
public static class TaskViewHolder extends RecyclerView.ViewHolder {
View mView;
public TaskViewHolder(#NonNull View itemView) {
super(itemView);
mView = itemView;
}
public void setTask(String task) {
TextView taskTextView = mView.findViewById(R.id.taskTv);
taskTextView.setText(task);
}
public void setDesc(String desc) {
TextView descTextView = mView.findViewById(R.id.descriptionTv);
descTextView.setText(desc);
}
public void setDate(String date) {
TextView dateTextView = mView.findViewById(R.id.dateTv);
}
}
public interface TaskUpdateListener {
void onTaskUpdate(Model model, int position);
}
}
And here is my HomeActivity:
public class HomeActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference userTasksRef;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String onlineUserID;
private ProgressDialog loader;
private String key = "";
private String task;
private String description;
#Override
public void onBackPressed(){
new AlertDialog.Builder(this)
.setMessage("Are you sure you want exit ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.homeToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Todo List App");
mAuth = FirebaseAuth.getInstance();
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
loader = new ProgressDialog(this);
mUser = mAuth.getCurrentUser();
onlineUserID = mUser.getUid();
database = FirebaseDatabase.getInstance("https://todolist-bbccd-default-rtdb.europe-west1.firebasedatabase.app");
userTasksRef = database.getReference("users").child(onlineUserID).child("tasks");
floatingActionButton = findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addTask();
}
});
}
private void addTask() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View myView = inflater.inflate(R.layout.input_file, null);
myDialog.setView(myView);
final AlertDialog dialog = myDialog.create();
dialog.setCancelable(false);
final EditText task = myView.findViewById(R.id.task);
final EditText description = myView.findViewById(R.id.description);
Button save = myView.findViewById(R.id.saveBtn);
Button cancel = myView.findViewById(R.id.CancelBtn);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mTask = task.getText().toString().trim();
String mDescription = description.getText().toString().trim();
String id = userTasksRef.push().getKey();
String date = DateFormat.getDateInstance().format(new Date());
if (TextUtils.isEmpty(mTask)) {
task.setError("Task Required");
return;
}
if (TextUtils.isEmpty(mDescription)) {
description.setError("Description Required");
return;
} else {
loader.setMessage("Adding your data");
loader.setCanceledOnTouchOutside(false);
loader.show();
Model model = new Model(mTask, mDescription, id, date);
userTasksRef.child(id).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(HomeActivity.this, "Task has been inserted successfully", Toast.LENGTH_SHORT).show();
loader.dismiss();
} else {
String error = task.getException().toString();
Toast.makeText(HomeActivity.this, "Failed: " + error, Toast.LENGTH_SHORT).show();
loader.dismiss();
}
}
});
}
dialog.dismiss();
}
});
dialog.show();
}
#Override
protected void onStart() {
super.onStart();
ArrayList<Model> tasks = new ArrayList<>();
userTasksRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot taskSnapshot : dataSnapshot.getChildren()) {
Model task = taskSnapshot.getValue(Model.class);
tasks.add(task);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Handle errors here
}
});
TasksAdapter.TaskUpdateListener listener = new TasksAdapter.TaskUpdateListener() {
#Override
public void onTaskUpdate(Model model, int position) {
updateTask(model, position);
}
};
TasksAdapter adapter = new TasksAdapter(tasks, listener);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void updateTask(Model task, final int position ) {
AlertDialog.Builder myDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.update_data, null);
myDialog.setView(view);
final AlertDialog dialog = myDialog.create();
final EditText mTask = view.findViewById(R.id.mEditTextTask);
final EditText mDescription = view.findViewById(R.id.mEditTextDescription);
mTask.setText(task.getTask());
mTask.setSelection(task.getTask().length());
mDescription.setText(task.getDescription());
mDescription.setSelection(task.getDescription().length());
Button delButton = view.findViewById(R.id.btnDelete);
Button updateButton = view.findViewById(R.id.btnUpdate);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasktxt = mTask.getText().toString().trim();
String descriptiontxt = mDescription.getText().toString().trim();
String date = DateFormat.getDateInstance().format(new Date());
Model model = new Model(tasktxt, descriptiontxt, key, date);
userTasksRef.child(key).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(HomeActivity.this, "Data has been updated successfully", Toast.LENGTH_SHORT).show();
}else {
String err = task.getException().toString();
Toast.makeText(HomeActivity.this, "update failed "+err, Toast.LENGTH_SHORT).show();
}
}
});
dialog.dismiss();
}
});
}
}

When I invalidate() my data, the onChanged submitList is triggered with 0 items before loadInitial gets the data from firebase

I am using the paging library with Firebase, and set ValueEventListener on the repository to invalidate the data whenever a change happens. The problem is as soon as I trigger invalidate(), the Observer trigger onChanged and Adapter.submitList(items) gets items with 0 size before the new date is loaded from Firebase via loadInitial method on the ItemKeyedDataSource.
The result is that the DIFF_CALLBACK is never called on PagedListAdapter because there is no comparison between the old list and the new items list (0 size) and when the data received it refresh the list like if I used notifyDataSetChanged().
The only solution so far is to delay Adapter.submitList(items) by 5 seconds until all the data is received from Firebase, but it's not a practical solution.
public class UsersRepository {
private final static String TAG = UsersRepository.class.getSimpleName();
// [START declare_database_ref]
private DatabaseReference mDatabaseRef;
private DatabaseReference mUsersRef;
private Boolean isFirstLoaded = true;
public ValueEventListener usersChangesListener;
public UsersRepository() {
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUsersRef = mDatabaseRef.child("users");
isFirstLoaded = true;
Log.d(TAG, "UsersRepository init. isFirstLoaded= " + isFirstLoaded);
}
public void getUsers(Long initialKey, final int size, #NonNull final ItemKeyedDataSource.LoadInitialCallback < User > callback) {
if (initialKey == null) {
Log.d(TAG, "getUsers initialKey= " + initialKey);
mUsersRef.orderByChild("created").limitToFirst(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsers dataSnapshot. getSnapshotKey= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsers usersList.size= " + usersList.size() + " lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadInitialCallback) {
//initial load
/*((ItemKeyedDataSource.LoadInitialCallback)callback)
.onResult(usersList, 0, 14);*/
callback.onResult(usersList);
}
} else {
Log.w(TAG, "getUsers no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
} else {
Log.d(TAG, "getUsers initialKey= " + initialKey);
mUsersRef.orderByChild("created").startAt(initialKey).limitToFirst(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsers dataSnapshot. getSnapshotKey= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsers usersList.size= " + usersList.size() + " lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadInitialCallback) {
//initial load
/*((ItemKeyedDataSource.LoadInitialCallback)callback)
.onResult(usersList, 0, 14);*/
callback.onResult(usersList);
}
} else {
Log.w(TAG, "getUsers no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
}
}
public void getUsersAfter(final Long key, final int size, #NonNull final ItemKeyedDataSource.LoadCallback < User > callback) {
/*if(key == entireUsersList.get(entireUsersList.size()-1).getCreatedLong()){
Log.d(TAG, "getUsersAfter init. afterKey= " + key+ "entireUsersList= "+entireUsersList.get(entireUsersList.size()-1).getCreatedLong());
return;
}*/
Log.d(TAG, "getUsersAfter. AfterKey= " + key);
mUsersRef.orderByChild("created").startAt(key).limitToFirst(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsersAfter dataSnapshot. getSnapshotKey= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsersAfter usersList.size= " + usersList.size() + "lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadCallback) {
//initial After
callback.onResult(usersList);
/*((ItemKeyedDataSource.LoadCallback)callback)
.onResult(usersList);*/
}
} else {
Log.w(TAG, "getUsersAfter no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
//mUsersRef.addValueEventListener(usersListener);
}
public void getUsersBefore(final Long key, final int size, #NonNull final ItemKeyedDataSource.LoadCallback < User > callback) {
Log.d(TAG, "getUsersBefore. BeforeKey= " + key);
/*if(key == entireUsersList.get(0).getCreatedLong()){
return;
}*/
mUsersRef.orderByChild("created").endAt(key).limitToLast(size).addListenerForSingleValueEvent(new ValueEventListener() {#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// [START_EXCLUDE]
if (dataSnapshot.exists()) {
// loop throw users value
List < User > usersList = new ArrayList < >();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
usersList.add(userSnapshot.getValue(User.class));
Log.d(TAG, "getUsersBefore dataSnapshot. getSnapshotKeys= " + userSnapshot.getKey());
}
if (usersList.size() == 0) {
return;
}
Log.d(TAG, "getUsersBefore usersList.size= " + usersList.size() + "lastkey= " + usersList.get(usersList.size() - 1).getCreatedLong());
if (callback instanceof ItemKeyedDataSource.LoadCallback) {
//initial before
callback.onResult(usersList);
/*((ItemKeyedDataSource.LoadCallback)callback)
.onResult(usersList);*/
}
//initial load
/* ((ItemKeyedDataSource.LoadCallback)callback)
.onResult(usersList, 0, usersList.size());*/
} else {
Log.w(TAG, "getUsersBefore no users exist");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
//mUsersRef.addValueEventListener(usersListener);
}
public void usersChanged(final DataSource.InvalidatedCallback InvalidatedCallback) {
final Query query = mUsersRef.orderByChild("created");
usersChangesListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!isFirstLoaded) {
isFirstLoaded = true;
Log.d(TAG, "entireUsersList Invalidated:");
// Remove post value event listener
if (usersChangesListener != null) {
query.removeEventListener(usersChangesListener);
Log.d(TAG, "usersChanged Invalidated removeEventListener");
}
((ItemKeyedDataSource.InvalidatedCallback)InvalidatedCallback).onInvalidated();
}
isFirstLoaded = false;
/*if(entireUsersList.size() > 0){
entireUsersList.clear();
((ItemKeyedDataSource.InvalidatedCallback)onInvalidatedCallback).onInvalidated();
Log.d(TAG, "entireUsersList Invalidated:");
return;
}
if (dataSnapshot.exists()) {
// loop throw users value
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
entireUsersList.add(userSnapshot.getValue(User.class));
}
Log.d(TAG, "entireUsersList size= "+entireUsersList.size()+"dataSnapshot count= "+dataSnapshot.getChildrenCount());
} else {
Log.w(TAG, "usersChanged no users exist");
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
};
query.addValueEventListener(usersChangesListener);
//mUsersRef.addValueEventListener(eventListener);
}
}
public class UsersDataSource extends ItemKeyedDataSource < Long,
User >
public class UsersDataSource extends ItemKeyedDataSource < Long,
User > {
private final static String TAG = UsersDataSource.class.getSimpleName();
private UsersRepository usersRepository;
public UsersDataSource() {
usersRepository = new UsersRepository();
}
#Override
public void addInvalidatedCallback(#NonNull InvalidatedCallback onInvalidatedCallback) {
//super.addInvalidatedCallback(onInvalidatedCallback);
Log.d(TAG, "Callback Invalidated ");
usersRepository.usersChanged(onInvalidatedCallback);
}
#Override
public void loadInitial(#NonNull LoadInitialParams < Long > params, #NonNull LoadInitialCallback < User > callback) {
/*List<User> items = usersRepository.getUsers(params.requestedInitialKey, params.requestedLoadSize);
callback.onResult(items);*/
Log.d(TAG, "loadInitial params key" + params.requestedInitialKey + " " + params.requestedLoadSize);
usersRepository.getUsers(params.requestedInitialKey, params.requestedLoadSize, callback);
//usersRepository.getUsers( 0L, params.requestedLoadSize, callback);
}
#Override
public void loadAfter(#NonNull LoadParams < Long > params, #NonNull LoadCallback < User > callback) {
/*List<User> items = usersRepository.getUsers(params.key, params.requestedLoadSize);
callback.onResult(items);*/
Log.d(TAG, "loadAfter params key " + (params.key + 1));
usersRepository.getUsersAfter(params.key + 1, params.requestedLoadSize, callback);
}
#Override
public void loadBefore(#NonNull LoadParams < Long > params, #NonNull LoadCallback < User > callback) {
/*List<User> items = fetchItemsBefore(params.key, params.requestedLoadSize);
callback.onResult(items);*/
Log.d(TAG, "loadBefore params " + (params.key - 1));
usersRepository.getUsersBefore(params.key - 1, params.requestedLoadSize, callback);
}
#NonNull#Override
public Long getKey(#NonNull User user) {
return user.getCreatedLong();
}
}
public MainFragment()
public MainFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
*/
public static MainFragment newInstance(String param1, String param2) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
//fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
/*if(activity != null){
activity.setTitle(R.string.main_frag_title);
}*/
View fragView = inflater.inflate(R.layout.fragment_main, container, false);
// prepare the Adapter
mUserArrayList = new ArrayList < >();
mProfileAdapter = new UsersAdapter();
// Initiate the viewModel
viewModel = ViewModelProviders.of(this).get(UsersViewModel.class);
// Initiate the RecyclerView
mProfileRecycler = (RecyclerView) fragView.findViewById(R.id.users_recycler);
mProfileRecycler.setHasFixedSize(true);
mProfileRecycler.setLayoutManager(new LinearLayoutManager(mActivityContext));
//viewModel.usersList.observe(this, mProfileAdapter::submitList);
//viewModel.getPagedListObservable().observe(this, new Observer<PagedList<User>>() {
viewModel.usersList.observe(this, new Observer < PagedList < User >> () {#Override
public void onChanged(#Nullable PagedList < User > items) {
System.out.println("onChanged");
if (items != null) {
new java.util.Timer().schedule(
new java.util.TimerTask() {#Override
public void run() {
// your code here
Log.d(TAG, "submitList size" + items.size());
mProfileAdapter.submitList(items);
}
},
5000);
}
}
});
mProfileRecycler.setAdapter(mProfileAdapter);
return fragView;
}
Update:
Well, I found a better solution than delaying submitList for 5 second. I decided to use a while loop until the data is received from firebase database, once items.size() is greater than 0 I stops the loop and submit the list to the adapter.
public class MainFragment extends Fragment {
private final static String TAG = MainFragment.class.getSimpleName();
private RecyclerView mUsersRecycler;
private ArrayList<User> mUserArrayList;
private UsersAdapter mUsersAdapter;
private Context mActivityContext;
private Activity activity;
private UsersViewModel viewModel;
public MainFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
*/
public static MainFragment newInstance(String param1, String param2) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
//fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Initiate viewModel for this fragment instance
viewModel = ViewModelProviders.of(this).get(UsersViewModel.class);
//viewModel.getPagedListObservable().observe(this, new Observer<PagedList<User>>() {
viewModel.usersList.observe(this, new Observer<PagedList<User>>() {
#Override
public void onChanged(#Nullable final PagedList<User> items) {
System.out.println("mama onChanged");
if (items != null ){
// Create new Thread to loop until items.size() is greater than 0
new Thread(new Runnable() {
int sleepCounter = 0;
#Override
public void run() {
try {
while(items.size()==0) {
//Keep looping as long as items size is 0
Thread.sleep(20);
Log.d(TAG, "sleep 1000. size= "+items.size()+" sleepCounter="+sleepCounter++);
if(sleepCounter == 1000){
break;
}
//handler.post(this);
}
//Now items size is greater than 0, let's submit the List
Log.d(TAG, "after sleep finished. size= "+items.size());
if(items.size() == 0 && sleepCounter == 1000){
// If we submit List after loop is finish with 0 results
// we may erase another results submitted via newer thread
Log.d(TAG, "Loop finished with 0 items. Don't submitList");
}else{
Log.d(TAG, "submitList");
mUsersAdapter.submitList(items);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
});
}
}

Sending a tweet from Blackberry -- working in simulator, but not working on device

I am working on Blackberry Twitter integration to tweet a message on twitter.
The app is working fine in simulator but giving exception when I am running it on a device.
Here is the exception I am getting every time I run the app on the device{
OAuth_IO_Exception
I have done some research and saw a solution to set the correct date time on device, but it still is not working.
Here is my code:
import com.kc.twitter.activity.TweetToFriend;
import com.twitterapime.rest.Credential;
import com.twitterapime.xauth.Token;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class TwitterScreen extends MainScreen {
private final String CONSUMER_KEY = "{redected}";
private final String CONSUMER_SECRET = "{redected}";
private final String CALLBACK_URL = "http://kingdomconnectng.net/redirect.php";
private LabelField _labelStutus;
public static OAuthDialogWrapper pageWrapper = null;
private ShowAuthBrowser showAuthBrowserScreen;
private String adminMessage;
public String adminMessages[];
boolean done=false;
Credential c ;
TweetToFriend tw;
public static StoreToken _tokenValue;
public static boolean isTweetPosted=false;
public static boolean isTweeterScreen =false ;
public TwitterScreen(final String adminMessage)
{
this.adminMessage=adminMessage;
isTweeterScreen = true ;
showAuthBrowserScreen = new ShowAuthBrowser();
_tokenValue = StoreToken.fetch();
/*if(_tokenValue.token.equalsIgnoreCase("nothing"))
{*/
showAuthBrowserScreen.doAuth(null);
UiApplication.getUiApplication().pushScreen(showAuthBrowserScreen);
/*}
else
{
final Token t = new Token(_tokenValue.token, _tokenValue.secret,
_tokenValue.userId, _tokenValue.username);
Credential c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, t);
TweetToFriend tw=new TweetToFriend();
boolean done=tw.doTweet(adminMessage, c);
if(done==true){
Dialog.alert("Tweet posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
else{
Dialog.alert("Tweet not posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
}*/
}
class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
{
BrowserField b = new BrowserField();
public ShowAuthBrowser()
{
//if(isTweetPosted==false){
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
//}
_labelStutus = new LabelField("KingdomConnect App" );
//add(_labelStutus );
add(b);
pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,CONSUMER_SECRET,CALLBACK_URL,this);
pageWrapper.setOAuthListener(this);
}
public void doAuth( String pin )
{
try
{
if ( pin == null )
{
pageWrapper.login();
}
else
{
this.deleteAll();
add(b);
pageWrapper.login(pin);
}
}
catch ( Exception e )
{
final String message = "Error loggin Twitter: " + e.getMessage();
Dialog.alert( message );
}
}
public void onAccessDenied(String response ) {
System.out.println("Access denied! -> " + response );
updateScreenLog( "Acceso denegado! -> " + response );
}
public void onAuthorize(final Token token) {
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
final Token myToken = token;
_tokenValue = StoreToken.fetch();
_tokenValue.token = myToken.getToken();
_tokenValue.secret = myToken.getSecret();
_tokenValue.userId = myToken.getUserId();
_tokenValue.username = myToken.getUsername();
_tokenValue.save();
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
try{
deleteAll();
c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, myToken);
tw = new TweetToFriend();
/*done=tw.doTweet("KingdomConnect App: "+adminMessage, c);
if(done == true)
{
Dialog.alert( "Buzz posted successfully." );
close();
}
*/
prepareMessage(adminMessage);
}catch(NullPointerException e){
}catch(Exception e){
}
}
});
}
public void onFail(String arg0, String arg1) {
updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
}
}
//TWEET METHOD
public void tweet(String message){
done=tw.doTweet("KingdomConnect: "+message, c);
/*if(done == true){
Dialog.alert( "Shared successfully." );
close();
} */
}
//PREPARE MESSAGE TO TWEET
public void prepareMessage(String msg){
int charLimit = 120;
int _msgSize = msg.length();
int i=0;
int parts = _msgSize/124;
try {
if(_msgSize > charLimit){
int temp1=0,temp2=charLimit;
while(i<parts+1){
String data = null;
if(i==parts){
data = msg.substring(temp1, _msgSize);
}else{
data = msg.substring(temp1, temp2);
temp1=temp2;
temp2=temp2+charLimit;
}
i++;
tweet(data);
}
Dialog.alert( "Shared successfully." );
}else{
tweet(msg);
//System.out.println("Data:======================"+msg);
}
}catch (Exception e) {
System.out.println("e = "+e);
}
}
private void updateScreenLog( final String message )
{
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
_labelStutus.setText( message );
}
});
}
}

BrowserField and lost connection

I have an app that uses a browserfield to connect to a web-page.
All is working ok and the simulator shows the right page.
If I set the simulator Network Properties to "Out of Coverage" and click on a link in my web-page then I get an exception - in the BrowserFieldConnectionManagerImpl
How can catch this exception so I can take appropriate action?
The app is using BlackBerry SDK
The code is here:
public final class example_Screen extends MainScreen {
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
protected MyBrowserFieldErrorHandler(BrowserField browserField){
super(browserField);
}
public void displayContentError(String url, String errorMessage) {
System.out.println("JERRY: displayContentError" + url);
System.out.println("JERRY: displayContentError" + errorMessage);
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void navigationRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public InputConnection resourceRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
InputConnection connection = null;
return connection;
}
}
/**
* Creates a new example_Screen object
*/
public example_Screen() {
GIFEncodedImage ourAnimation = (GIFEncodedImage) GIFEncodedImage.getEncodedImageResource("2.gif");
AnimatedGIFField _ourAnimation = new AnimatedGIFField(ourAnimation, Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourAnimation);
LabelField _ourLabelField = new LabelField("Updating ...", Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourLabelField);
int anim_ht = _ourAnimation.getPreferredHeight();
int label_ht = _ourLabelField.getPreferredHeight();
EncodedImage ei = EncodedImage.getEncodedImageResource("img/menu.png");
int currentWidthFixed32 = Fixed32.toFP(ei.getWidth());
int currentHeightFixed32 = Fixed32.toFP(ei.getHeight());
int displayWidthFixed32 = Fixed32.toFP(Display.getWidth());
int displayHeightFixed32 = Fixed32.toFP((Display.getHeight() - anim_ht - label_ht));
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, displayWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, displayHeightFixed32);
ei = ei.scaleImage32(scaleXFixed32, scaleYFixed32);
BitmapField bmp = new BitmapField(ei.getBitmap(), Field.FIELD_HCENTER + Field.FIELD_VCENTER);
add(bmp);
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent("http://www.bbc.co.uk");
BrowserFieldListener listener = new BrowserFieldListener() {
public void documentAborted(BrowserField browserField, Document document) {
System.out.println("JERRY: documentAborted");
}
public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document) {
System.out.println("JERRY: documentCreated");
}
public void documentError(BrowserField browserField, Document document) {
System.out.println("JERRY: documentError");
}
public void documentLoaded(BrowserField browserField, Document document) {
System.out.println("JERRY: documentLoaded");
Node node = document.getFirstChild();
String nodeText = node.getTextContent();
int index = -1;
if (nodeText != null) {
String errorText = "Error requesting content for:";
index = nodeText.indexOf(errorText);
}
Screen screen = browserField.getScreen();
try {
synchronized (Application.getEventLock()) {
if (index == -1) {
System.out.println("JERRY: documentLoaded: no error");
int count = screen.getFieldCount();
if (count > 1) {
screen.deleteRange(0, (count-1));
System.out.println("JERRY: documentLoaded: " + (count-1) + " fields deleted");
} else {
System.out.println("JERRY: documentLoaded: only 1 field so none deleted");
}
} else {
System.out.println("JERRY: documentLoaded: error");
}
}
} catch (final Exception ex) {
System.out.println("example_Screen: documentLoaded: exception caught: " + ex.toString());
}
}
public void documentUnloading(BrowserField browserField, Document document) {
System.out.println("JERRY: documentUnloading");
}
public void downloadProgress(BrowserField browserField, ContentReadEvent event) {
System.out.println("JERRY: downloadProgress");
}
};
browserField.addListener(listener);
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler(browserField);
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER, eHandler);
}
}
BrowserField contains a method, addListener() which takes a reference to BrowserFieldListener implementation.
Extend BrowserFieldListener and process errors in methods documentError() and documentAborted() of this implementation.
Then add a reference of your class instance that extends BrowserFieldListener to your browser field via browserField.addListener(browserFieldListener);.
EDIT:
If this does not work, then use BrowserFieldErrorHandler class from RIM API. Build your own error handler and pass its instance to the browserfield configuration.
Below, there's sample code:
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
public void displayContentError(String url, String errorMessage) {
String error = "Error: (url=" + url + "): " + t.getMessage();
Dialog.ask(Dialog.D_OK, error);
logMessage(“BrowserFieldError: “ + error );
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t){
displayContentError(request.getURL(), t.getMessage());
}
}
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler();
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER,eHandler);
I get this sample code from DevCon2010 presentation of BrowserField capabilities. You can get it here: http://dev.tuyennguyen.ca/wp-content/uploads/2011/02/DEV49.pdf

BlackBerry - Programmatically fetching data in calendar

i have invoked blackberry calender from my application
can anyone tell me how to fetch :
date
duration
notes
from the selected date
my code :
MenuItem importCalender = new MenuItem("Import from Calender",100,11)
{
public void run()
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
try
{
EventList list = (EventList)PIM.getInstance().openPIMList(PIM.EVENT_LIST, PIM.READ_WRITE);
Enumeration events = list.items();
BlackBerryEvent e = (BlackBerryEvent) events.nextElement();
Invoke.invokeApplication(Invoke.APP_TYPE_CALENDAR, new CalendarArguments( CalendarArguments.ARG_VIEW_DEFAULT,e) );
}
catch (PIMException e)
{
//e.printStackTrace();
}
}
});
}
};
protected void makeMenu(Menu menu, int instance)
{
menu.add(importCalender);
}
You should register custom menu item for calendar application.
See How To - Add a custom menu item to an existing BlackBerry application
UPDATE
alt text http://img517.imageshack.us/img517/2789/caledar3.jpg
class Scr extends MainScreen {
VerticalFieldManager mManager;
UiApplication mApp;
public Scr() {
mApp = UiApplication.getUiApplication();
mManager = (VerticalFieldManager) this.getMainManager();
MyMenuItem myMenuitem = new MyMenuItem(0);
ApplicationMenuItemRepository.getInstance().addMenuItem(
ApplicationMenuItemRepository.MENUITEM_CALENDAR, myMenuitem);
}
class MyMenuItem extends ApplicationMenuItem {
MyMenuItem(int order) {
super(order);
}
public Object run(Object context) {
if (context instanceof Event) {
Event event = (Event) context;
final String text = "start: "
+ (new Date(event.getDate(Event.START, 0))).toString()
+ "\nend: "
+ (new Date(event.getDate(Event.END, 0))).toString()
+ "\nnote: " + event.getString(Event.NOTE, 0);
String message = "Import event\n" + text;
if (Dialog.YES == Dialog.ask(Dialog.D_YES_NO, message)) {
mApp.invokeLater(new Runnable() {
public void run() {
mApp.requestForeground();
mManager.add(new LabelField(text));
}
});
}
}
return context;
}
public String toString() {
return "Import Event";
}
}
MenuItem importCalender = new MenuItem("Import from Calender", 100, 11) {
public void run() {
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
Invoke.invokeApplication(Invoke.APP_TYPE_CALENDAR,
new CalendarArguments(
CalendarArguments.ARG_VIEW_DEFAULT));
}
});
}
};
protected void makeMenu(Menu menu, int instance) {
menu.add(importCalender);
}
}

Resources