Related
I am developing the chatbot app. I am using the RecycleView to render the chat of user and bot. I have to show the user listview or text response depend upon his query. All is working until my RecyclerView get's scroll. Whenever my RecyclerView gets scroll it changes the item position. I search a lot and applied every solution but not able to solve my issue.
here is my activity.java
public class HomeActivity extends AppCompatActivity implements AIListener,
View.OnClickListener {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
LinearLayoutManager layoutManager;
private ArrayList<Message> messageArrayList;
private EditText inputMessage;
private RelativeLayout btnSend;
Boolean flagFab = true;
PaytmPGService service = null;
Map<String, String> paytmparam = new HashMap<>();
PrefManager prefManager;
private AIService aiService;
AIDataService aiDataService;
AIRequest aiRequest;
Gson gson;
String food_dish = " ";
double price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
inputMessage = findViewById(R.id.editText_ibm);
btnSend = findViewById(R.id.addBtnibm);
recyclerView = findViewById(R.id.recycler_view_ibm);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(this,messageArrayList);
prefManager = new PrefManager(this);
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgCount = mAdapter.getItemCount();
int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (msgCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
final AIConfiguration configuration = new AIConfiguration("cabc4b7b9c20409aa7ffb1b3d5fe1243",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
btnSend.setOnClickListener(this);
inputMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageView fab_img = findViewById(R.id.fab_img_ibm);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length() != 0 && flagFab) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img);
flagFab = false;
} else if (s.toString().trim().length() == 0) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img1);
flagFab = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!inputmessage.equals("")){
new AsyncTask<String, Void, AIResponse>(){
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
try {
return aiDataService.request(request);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}.execute(inputmessage);
}else {
aiService.startListening();
}
inputMessage.setText("");
}
#Override
public void onResult(AIResponse response) {
int itemNumber = 0;
Log.d("dialogeflow response",response.toString());
try {
JSONObject AIResponse = new JSONObject(gson.toJson(response));
Log.d("json response",AIResponse.toString());
final JSONObject result = AIResponse.getJSONObject("result");
JSONArray contexts = result.getJSONArray("contexts");
final JSONObject fulfillment = result.getJSONObject("fulfillment");
if(contexts.length()>0) {
for(int i = 0;i<contexts.length();i++) {
JSONObject context_items = contexts.getJSONObject(i);
JSONObject paramters = context_items.getJSONObject("parameters");
if (paramters.has("Cuisine")) {
prefManager.setCuisinetype(paramters.getString("Cuisine"));
} else if (paramters.has("Restaurants_name")) {
prefManager.setRestaurant_name(paramters.getString("Restaurants_name"));
}
if (paramters.has("number") && !paramters.getString("number").equals("") && paramters.has("Food_Dishes") && !paramters.getString("Food_Dishes").equals("")) {
itemNumber = Integer.parseInt(paramters.getString("number"));
if (itemNumber <= 2 && price !=0) {
price = 300 + (int) (Math.random() * ((1400 - 300) + 1));
} else {
price = 600 + (int) (Math.random() * ((2200 - 600) + 1));
}
food_dish = paramters.getString("Food_Dishes");
}
}
}
final double finalPrice = price;
final int finalItemNumber = itemNumber;
if(!result.getString("resolvedQuery").matches("payment is done successfully")) {
Message usermsg = new Message();
usermsg.setMessage(result.getString("resolvedQuery"));
usermsg.setId("1");
messageArrayList.add(usermsg);
mAdapter.notifyDataSetChanged();
if (fulfillment.has("speech")) {
Log.d("response of speech", fulfillment.getString("speech"));
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
if (fulfillment.getString("speech").matches("Redirecting you to the Pay-Tm site")) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
getpaytm_params((int) price);
}
}, 2000);
} else {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
if (speech.contains("Your total bill is ₹")) {
Log.d("price", String.valueOf(price));
outMessage.setMessage("Please Confirm your order:- \n" +finalItemNumber +" "+food_dish+" from "+prefManager.getRestaurant_name()+" at Flat No: 20,Galaxy Apartment,Airport Authority Colony,Andheri,Mumbai,Maharashtra 400 047 \n Your total bill is ₹"+price+". \n Do you want to pay by Wallet or by PayTm");
}else{
outMessage.setMessage(speech);
}
outMessage.setId("2");
messageArrayList.add(outMessage);
Log.d("messgae",outMessage.getMessage());
mAdapter.notifyDataSetChanged();
}
}, 2000);
}
} else {
final JSONArray msg = fulfillment.getJSONArray("messages");
for (int i = 0; i < msg.length(); i++) {
if (i == 0) {
Message outMessage = new Message();
JSONObject speechobj = msg.getJSONObject(i);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
} else {
final int itemposition = i;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
try {
JSONObject speechobj = msg.getJSONObject(itemposition);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 5000);
}
}
}
}
}else{
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
}
},2000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
btnSend.setBackground(getDrawable(R.drawable.recording_bg));
}
#Override
public void onListeningCanceled() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
#Override
public void onListeningFinished() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
}`
my ChatAdapter.java class
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int BOT = 100;
private int BOT_Restaurant_ListView = 101;
private int USER = 102;
private Activity activity;
private PrefManager prefManager;
private int itemposition = -1;
private int menu_itemposition = -1;
private List<Restaurant_List_Model> restaurant_list;
private ArrayList<Message> messageArrayList;
private RestaurantListViewAdapter restaurantListViewAdapter;
private TextToSpeech tts ;
public ChatAdapter(Activity activity, ArrayList<Message> messageArrayList) {
this.activity = activity;
this.messageArrayList = messageArrayList;
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
prefManager = new PrefManager(activity.getApplicationContext());
setHasStableIds(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview;
if(viewType == BOT){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_view,parent,false);
}else if(viewType == BOT_Restaurant_ListView){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_restaurant_listview,parent,false);
}else {
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg_view,parent,false);
}
return new ViewHolder(itemview);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if(message.getId()!=null && message.getId().equals("2")){
if(message.getMessage().contains("restaurants") || message.getMessage().contains("restaurant")) {
return BOT_Restaurant_ListView;
}else {
return BOT;
}
}else{
return USER;
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int pic_int = 1;
String filename = null;
final Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
if (holder.getItemViewType() == BOT_Restaurant_ListView) {
Log.d("inside bot listview msg", String.valueOf(BOT_Restaurant_ListView ));
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
if(itemposition<holder.getAdapterPosition()){
itemposition = holder.getAdapterPosition();
Log.d("itemposition",String.valueOf(itemposition));
String jsonFileContent;
Log.d("cuisine value", prefManager.getCuisinetype());
if (message.getMessage().contains("restaurants")) {
if(!prefManager.getCuisinetype().equals("") && prefManager.getCuisinetype() != null){
Log.d("restauratn has drawn", "greate");
try {
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
Log.d("cuisine value", prefManager.getCuisinetype());
if(message.getMessage().contains("Here are restaurants near you")){
String [] restaurant_Array ={
"indian","french","mexican","italian"
};
int randomNumber = (int) Math.floor(Math.random()*restaurant_Array.length);
filename = restaurant_Array[randomNumber];
Log.d("filename",filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}else {
filename = prefManager.getCuisinetype().toLowerCase() + "_restaurants";
Log.d("filename", filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}
JSONObject restaurantfile = new JSONObject(jsonFileContent);
JSONArray jsonArray = restaurantfile.getJSONArray("restaurants");
for (int i = 0; i < jsonArray.length(); i++) {
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
JSONObject restaurantList = jsonArray.getJSONObject(i);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(restaurantList.getString("name"));
restaurant_list_obj.setLocation(restaurantList.getString("location"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("restaurant_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(restaurantList.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
prefManager.setCuisinetype("");
pic_int = 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
restaurantListViewAdapter.notifyDataSetChanged();
}
}else if(message.getMessage().contains("Here are some famous food items from "+prefManager.getRestaurant_name()+" restaurant")){
try {
Log.d("menu has draw","greate");
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
Log.d("restaurant name value", prefManager.getRestaurant_name());
jsonFileContent = readFile(R.raw.restaurant_menu);
JSONObject menu_cuisine = new JSONObject(jsonFileContent);
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
if (menu_cuisine.has(prefManager.getRestaurant_name())) {
JSONObject restaurant_menu = menu_cuisine.getJSONObject("Dominos");
Log.d("Chili's American menu", restaurant_menu.toString());
JSONArray menu = restaurant_menu.getJSONArray("menu");
for (int j = 0; j < menu.length(); j++) {
JSONObject menu_obj = menu.getJSONObject(j);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(menu_obj.getString("name"));
restaurant_list_obj.setLocation(menu_obj.getString("cuisine_type"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
//restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(menu_obj.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
restaurantListViewAdapter.notifyDataSetChanged();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
prefManager.setRestaurant_name("");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("user_message",message.getMessage());
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
}else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
((ViewHolder) holder).retaurant_listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
} if(holder.getItemViewType()==BOT) {
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
Log.d("inside bot msg", String.valueOf(BOT));
((ViewHolder) holder).bot_msg.setText(message.getMessage());
if(itemposition<holder.getAdapterPosition()) {
itemposition = holder.getAdapterPosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}if(holder.getItemViewType() == USER) {
((ViewHolder) holder).user_message.setText(message.getMessage());
}
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder.isRecyclable()){
Log.d("inside onViewRecycled","great");
// itemposition = holder.getAdapterPosition();
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
private String readFile(int id) throws IOException
{
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String content = "";
String line;
while ((line = reader.readLine()) != null)
{
content = content + line;
}
return content;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView user_message,bot_msg;
private ListView retaurant_listView;
ViewHolder(View itemView) {
super(itemView);
bot_msg = itemView.findViewById(R.id.bot_message);
user_message = itemView.findViewById(R.id.message);
retaurant_listView = itemView.findViewById(R.id.restaurant_items_list_ibm);
}
}
}
Please help me out with this issue.
In gif, you can see the lower list is swap with the upper list and then return back
Hi I am working on the Udacity Popular movies project. I have to store the movies user chooses in a content provider as his favorites. I have created a content provider and I am fetching the data from it using a cursor loader and displaying it a recycler view when the user chooses the favorites option. My issue is that the data is not being persisted in my app. After I remove the app from my stack and reopen the app the favorites screen is empty. What am I doing wrong?
This is my Main Activity:
public class MainActivity extends AppCompatActivity implements CustomCursorAdapter.CustomCursorAdapterOnClickHandler,ImagesAdapter.ImagesAdapterOnClickHandler,LoaderManager.LoaderCallbacks<Cursor> {
private final String POPULAR_WEBSITE = "https://api.themoviedb.org/3/movie/popular?API_KEY";
private final String RATED_WEBSITE = "https://api.themoviedb.org/3/movie/top_rated?API_KEY";
// private final String RATED_WEBSITE = "https://api.themoviedb.org/3/movie/top_rated?API_KEY";
private ArrayList<String> list = new ArrayList<>();
ImagesAdapter adapter;
TextView errorTextView ;
ProgressBar progressBar;
RecyclerView recyclerView;
Bundle savedState = null;
ArrayList<MoviesClass> moviesClassList = new ArrayList<>();
final String TAG = MainActivity.class.getSimpleName();
CustomCursorAdapter simpleCursorAdapter;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
errorTextView = (TextView)findViewById(R.id.tv_error_message);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
getLoaderManager().initLoader(1,null,this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
simpleCursorAdapter = new CustomCursorAdapter(this,null,this);
recyclerView.setLayoutManager(layoutManager);
adapter = new ImagesAdapter(this);
recyclerView.setAdapter(adapter);
this.runOnUiThread(new Runnable() {
public void run() {
try {
if (NetworkUtility.isOnline()) {
loadData(POPULAR_WEBSITE);
} else {
// Toast.makeText(MainActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,android.R.style.Theme_Material_Light_Dialog_Alert);
// Setting Dialog Title
alertDialog.setTitle(R.string.no_internet_connection);
// Setting Dialog Message
alertDialog.setMessage(R.string.exit);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), R.string.exit_activity, Toast.LENGTH_SHORT).show();
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(),R.string.connection_check, Toast.LENGTH_SHORT).show();
dialog.cancel();
MainActivity.this.recreate();
}
});
// Showing Alert Message
alertDialog.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void loadData(String data) {
showDataView();
new DownloadTask().execute(data);
}
#Override
public void mClick(int position) {
Intent intent = new Intent(this, MovieDetails.class);
MoviesClass currentMovie = moviesClassList.get(position);
intent.putExtra("current movie", currentMovie);
startActivity(intent);
}
private void showDataView() {
errorTextView.setVisibility(View.INVISIBLE);
recyclerView.setVisibility(View.VISIBLE);
}
public void showError() {
errorTextView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.INVISIBLE);
}
#Override
public CursorLoader onCreateLoader(int i, Bundle bundle) {
CursorLoader cursorLoader = new CursorLoader(this,FavouritesContractClass.FavouriteMovies.CONTENT_URI,null,null,null,null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader loader, Cursor o) {
// simpleCursorAdapter = new CustomCursorAdapter(this,o,this);
simpleCursorAdapter.swapCursor(o);
}
#Override
public void onLoaderReset(Loader loader) {
simpleCursorAdapter.swapCursor(null);
}
#Override
public void click(int position) {
}
public class DownloadTask extends AsyncTask<String,Void,ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(ArrayList<String> s) {
progressBar.setVisibility(View.INVISIBLE);
showDataView();
adapter.setAdapterData(s);
// onSaveInstanceState(savedState);
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
String response = null;
ArrayList<String> imagesList = new ArrayList<>();
ArrayList<String> uriList = new ArrayList<>();
if (strings.length == 0)
return null;
try {
response = NetworkUtility.makeHttpRequest(strings[0]);
if (response == null)
Toast.makeText(MainActivity.this, R.string.error_message, Toast.LENGTH_SHORT).show();
moviesClassList = ParseData.getMoviesObject(response);
for(int i =0; i< moviesClassList.size();i++)
Log.i(TAG, moviesClassList.get(0).getmId());
MoviesClass moviesClass = null;
for (int i = 0; i < moviesClassList.size(); i++) {
moviesClass = moviesClassList.get(i);
Log.i("movie name is",moviesClass.getmTitle());
imagesList.add(moviesClass.getmPosterPath());
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendEncodedPath("/image.tmdb.org/t/p/w185")
.appendEncodedPath(imagesList.get(i)).build();
uriList.add(builder.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
return uriList;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.popular_sort:
loadData(POPULAR_WEBSITE);
return true;
case R.id.rated_sort:
loadData(RATED_WEBSITE);
return true;
case R.id.fav_sort:
/*try {
while (cursor.moveToNext()) {
Log.i("url is ", cursor.getString(cursor.getColumnIndex("url")));
list.add(cursor.getString(cursor.getColumnIndex("url")));
}
}finally {
cursor.close();
}*/
recyclerView.setAdapter(simpleCursorAdapter);
simpleCursorAdapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
This my content provider class ;
public class FavouritesContentProvider extends ContentProvider {
public static final int MOVIES = 100;
public static final int MOVIE_ID = 101;
private MovieDbOpenHelper dbOpenHelper;
Cursor cursor;
#Override
public boolean onCreate() {
Context context = getContext();
dbOpenHelper = new MovieDbOpenHelper(context,null,null,1);
return true;
}
public UriMatcher sUriMatcher = buildUriMatcher();
private UriMatcher buildUriMatcher() {
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(FavouritesContractClass.AUTHORITY,FavouritesContractClass.PATH_FAVOURITES,MOVIES);
uriMatcher.addURI(FavouritesContractClass.AUTHORITY,FavouritesContractClass.PATH_FAVOURITES + "/#",MOVIE_ID);
return uriMatcher;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] strings, #Nullable String s, #Nullable String[] strings1, #Nullable String s1) {
SQLiteDatabase sqLiteDatabase = dbOpenHelper.getReadableDatabase();
int match = sUriMatcher.match(uri);
switch (match) {
case MOVIES:
cursor = sqLiteDatabase.query(FavouritesContractClass.FavouriteMovies.TABLE_NAME, strings, s, strings1, null, null, s1);
break;
case MOVIE_ID:
cursor = sqLiteDatabase.query(FavouritesContractClass.FavouriteMovies.TABLE_NAME, strings, s, strings1, null, null, s1);
break;
default:
throw new UnsupportedOperationException("Unknown uri:" + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
int match = sUriMatcher.match(uri);
switch (match) {
case MOVIES:
// directory
return "vnd.android.cursor.dir" + "/" + FavouritesContractClass.AUTHORITY + "/" + FavouritesContractClass.FavouriteMovies.CONTENT_URI;
case MOVIE_ID:
// single item type
return "vnd.android.cursor.item" + "/" + FavouritesContractClass.AUTHORITY + "/" + FavouritesContractClass.FavouriteMovies.CONTENT_URI;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues contentValues) {
SQLiteDatabase sqLiteDatabase = dbOpenHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
Uri returnUri = null;
switch (match) {
case MOVIES:
long id = sqLiteDatabase.insertWithOnConflict(FavouritesContractClass.FavouriteMovies.TABLE_NAME, null, contentValues,SQLiteDatabase.CONFLICT_IGNORE);
if (id > 0)
returnUri = ContentUris.withAppendedId(FavouritesContractClass.FavouriteMovies.CONTENT_URI, id);
else
Toast.makeText(getContext(), "Already exists.", Toast.LENGTH_SHORT).show();
break;
default:
throw new UnsupportedOperationException("Unknown uri" + uri);
}
getContext().getContentResolver().notifyChange(uri,null);
return returnUri;
}
#Override
public int delete(#NonNull Uri uri, #Nullable String s, #Nullable String[] strings) {
return 0;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues contentValues, #Nullable String s, #Nullable String[] strings) {
return 0;
}
}
This is the movie details class:
public class MovieDetails extends AppCompatActivity implements View.OnClickListener {
public final String trailerBaseUri = "https://api.themoviedb.org/3/movie/";
String movieId;
Uri movieFinalUri, movieReviewUri;
ArrayList<MovieTrailerClass> movieTrailersList;
String movieReviewsList;
Uri.Builder builder;
MoviesClass currentMovie;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
TextView title = (TextView) findViewById(R.id.title_tv);
TextView synopsis = (TextView) findViewById(R.id.synopsis_tv);
TextView userRating = (TextView) findViewById(R.id.rating_tv);
TextView date = (TextView) findViewById(R.id.date_tv);
ImageView imageView = (ImageView) findViewById(R.id.poster_thumbnail);
Intent intent = getIntent();
ImageView trailer1 = (ImageView) findViewById(R.id.trailer1);
ImageView trailer2 = (ImageView) findViewById(R.id.trailer2);
trailer1.setOnClickListener(this);
trailer2.setOnClickListener(this);
if (intent.hasExtra("current movie")) {
currentMovie = intent.getParcelableExtra("current movie");
builder = new Uri.Builder();
builder.scheme("http")
.appendEncodedPath("/image.tmdb.org/t/p/w185")
.appendEncodedPath(currentMovie.getmPosterPath()).build();
movieId = currentMovie.getmId();
title.setText(currentMovie.getmTitle());
synopsis.setText(currentMovie.getmSynopsis());
userRating.setText(currentMovie.getmRating() + "/10");
date.setText(currentMovie.getmReleaseDate());
movieFinalUri = Uri.parse(trailerBaseUri).buildUpon().appendPath(movieId).appendPath("videos").appendQueryParameter("api_key", "ebd331efd1f9bec67a9aa215b256ebe1")
.appendQueryParameter("language", "en").build();
Picasso.with(getApplicationContext())
.load(builder.toString())
.placeholder(R.drawable.popcorn_placeholder)
.error(R.drawable.error)
.resize(800, 1000)
.into(imageView);
movieTrailersList = new ArrayList<>();
DownloadTask task = new DownloadTask();
task.execute(movieFinalUri.toString());
movieReviewUri = Uri.parse(trailerBaseUri).buildUpon().appendPath(movieId).appendPath("reviews").appendQueryParameter("api_key", "ebd331efd1f9bec67a9aa215b256ebe1")
.appendQueryParameter("language", "en").build();
ReviewDownloadTask task1 = new ReviewDownloadTask();
task1.execute(movieReviewUri.toString());
// String movieReviewsExtra = getIntent().getStringExtra("movieReviewList");
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.trailer1:
openTrailer(movieTrailersList.get(0).getKey());
break;
case R.id.rating_tv:
Intent intent = new Intent(MovieDetails.this, ReviewActivity.class);
intent.putExtra("movieReviewList", movieReviewsList);
startActivity(intent);
/* case R.id.trailer3:
openTrailer(movieTrailersList.get(2).getKey());
break;*/
}
}
public void openTrailer(String key) {
Uri uri = Uri.parse("https://www.youtube.com/watch?").buildUpon().appendQueryParameter("v", key).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
public void openReview(String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
if(intent.resolveActivity(getPackageManager())!=null) {
intent.setData(uri);
startActivity(intent);
}else
Toast.makeText(this, "Unable to find browser to launch movie trailer!", Toast.LENGTH_SHORT).show();
}
public void markAsFavourite(View view) {
ContentValues contentValues = new ContentValues();
contentValues.put(FavouritesContractClass.FavouriteMovies.MOVIE_URL, builder.toString());
contentValues.put(FavouritesContractClass.FavouriteMovies.MOVIE_ID, movieId);
/*if(checkAlreadyExist()){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
} else {*/
Uri uri = getContentResolver().insert(FavouritesContractClass.FavouriteMovies.CONTENT_URI, contentValues);
if (uri != null) {
Toast.makeText(this, R.string.movie_saved_toast, Toast.LENGTH_SHORT).show();
Log.i("insert successsful", uri.toString());
} else
Log.i("insert not successsful", "suc");
}
class DownloadTask extends AsyncTask<String, Void, ArrayList<MovieTrailerClass>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected ArrayList<MovieTrailerClass> doInBackground(String... strings) {
try {
String response = NetworkUtility.makeHttpRequest(movieFinalUri.toString());
if (response != null) {
JSONObject baseObj = new JSONObject(response);
JSONArray resObject = baseObj.getJSONArray("results");
Gson gson = new Gson();
movieTrailersList = gson.fromJson(resObject.toString(), new TypeToken<List<MovieTrailerClass>>() {
}.getType());
} else {
Toast.makeText(MovieDetails.this, R.string.error_message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return movieTrailersList;
}
}
public class ReviewDownloadTask extends AsyncTask<String, Void, String> {
String response = null;
#Override
protected void onPostExecute(String s) {
Gson gson = new Gson();
ArrayList<MovieReviewResults> movieReviewResults = gson.fromJson(movieReviewsList, new TypeToken<List<MovieReviewResults>>() {
}.getType());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
for (MovieReviewResults movieReviewObject : movieReviewResults) {
TextView textView = new TextView(getApplicationContext());
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity((Gravity.CENTER));
linearLayout.addView(textView);
textView.setText(movieReviewObject.getContent());
TextView textView1 = new TextView(getApplicationContext());
textView1.setGravity((Gravity.CENTER));
textView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView1);
textView1.setText(movieReviewObject.getAuthor());
}
}
#Override
protected String doInBackground(String... strings) {
try {
response = NetworkUtility.makeHttpRequest(strings[0]);
if (response != null) {
JSONObject baseObj = new JSONObject(response);
JSONArray resObject = baseObj.getJSONArray("results");
movieReviewsList = resObject.toString();
} else {
Toast.makeText(MovieDetails.this, R.string.error_message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return movieReviewsList;
}
}
public boolean checkAlreadyExist()
{
String query = "SELECT " + FavouritesContractClass.FavouriteMovies.MOVIE_ID + " FROM " + FavouritesContractClass.FavouriteMovies.TABLE_NAME + " WHERE " + FavouritesContractClass.FavouriteMovies.MOVIE_ID + " = " + movieId;;
MovieDbOpenHelper dbOpenHelper = new MovieDbOpenHelper(getApplicationContext(),null,null,1);
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
Log.i(" ai mger","here");
if (cursor.getCount() > 0)
{
Log.i("fpund","funf");
return true;
}
else
return false;
}
}
You might want to try calling beginTransaction before inserting/updating/deleting, setTransactionSuccessful when you want the changes to be committed and endTransaction to commit the changes. Please see code below (NOTE: I didn't test this code as I'm writing this on a tablet)
You should also take a look at the docs for more information.
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues contentValues) {
SQLiteDatabase sqLiteDatabase = dbOpenHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
Uri returnUri = null;
switch (match) {
case MOVIES:
sqLiteDatabase.beginTransaction();
try {
long id = sqLiteDatabase.insertWithOnConflict(FavouritesContractClass.FavouriteMovies.TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
if (id > 0)
returnUri = ContentUris.withAppendedId(FavouritesContractClass.FavouriteMovies.CONTENT_URI, id);
sqLiteDatabase.setTransactionSuccessful();
} finally {
sqLiteDatabase.endTransaction();
}
break;
default:
throw new UnsupportedOperationException("Unknown uri" + uri);
}
getContext().getContentResolver().notifyChange(uri,null);
return returnUri;
}
We are creating a chat application using openfire, smack. In that there is a chatscreen where users can send and receive messages and media files. For storing messages we are using Realm as local db. I want to show the progress of files during upload of files.
My Upload file code is :
public void firebasestorageMeth(final String msg, final String path, final String filetype, final String mykey, final String otheruserkey, final String username) {
StorageReference riversRef = STORAGE_REFERENCE.child(mykey).child("files").child(GetTimeStamp.timeStampDate());
final String timestampdate = GetTimeStamp.timeStampDate();
final String timestamptime = GetTimeStamp.timeStampTime();
final long id = GetTimeStamp.Id();
ChatMessageRealm cmr = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, msg, mykey, timestamptime, timestampdate, filetype, String.valueOf(id), "0", "",path);
ChatHelper.addChatMesgRealmMedia1(cmr, this, mykey, otheruserkey);
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_STARTING).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
Log.d(TAG, cmr.getChatref()+cmr.getMsgid()+cmr.getMsgstring()+"file path extension upload file" + path);
riversRef.putFile(Uri.fromFile(new File(path)))
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
umpref.setUri(String.valueOf(id), path);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.d(TAG, "file uploaded" + downloadUrl);
ChatMessageRealm cmr = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, msg, mykey, timestamptime, timestampdate, filetype, String.valueOf(id), "1", String.valueOf(downloadUrl),path);
ChatHelper.addChatMesgRealmMedia1(cmr, getApplicationContext(), mykey, otheruserkey);
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_SUCCESS).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmediaurl", String.valueOf(downloadUrl)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", MEDIA_FAILED).putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
exception.printStackTrace();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
int progress = (int) ((100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
sendBroadcast(new Intent().putExtra("reloadchatmediastatus", progress + " ").putExtra("reloadchatmediaid", String.valueOf(id)).putExtra("reloadchatmedialocalurl", path).setAction("reloadchataction"));
}
});
}
The chatadapter code is :
public class ChatAdapter1 extends RecyclerView.Adapter<ChatAdapter1.MyViewHolder> {
ArrayList<ChatMessageRealm> mList = new ArrayList<>();
private Context context;
private UserSession session;
public static final int SENDER = 0;
public static final int RECIPIENT = 1;
String TAG = "ChatAdapter1";
public ChatAdapter1(ArrayList<ChatMessageRealm> list, Context context) {
this.mList = list;
this.context = context;
session = new UserSession(context);
}
#Override
public int getItemViewType(int position) {
if (mList.get(position).getSenderjid().matches(session.getUserKey())) {
return SENDER;
} else {
return RECIPIENT;
}
}
#Override
public int getItemCount() {
return mList.size();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
switch (viewType) {
case SENDER:
View viewSender = inflater.inflate(R.layout.row_chats_sender, viewGroup, false);
viewHolder = new MyViewHolder(viewSender);
break;
case RECIPIENT:
View viewRecipient = inflater.inflate(R.layout.row_chats_receiver, viewGroup, false);
viewHolder = new MyViewHolder(viewRecipient);
break;
}
return (MyViewHolder) viewHolder;
}
#Override
public void onBindViewHolder(final ChatAdapter1.MyViewHolder holder, int position) {
final ChatMessageRealm comment = mList.get(position);
holder.setIsRecyclable(false);
// holder.otherSender_sender.setText(comment.getSenderjid());
holder.otherSender_Timestamp.setText(comment.getSendertime() + "," + comment.getSenderdate());
// holder.status.setVisibility(View.GONE);
switch (comment.getMsgtype()) {
case "text":
// holder.btndown.setVisibility(View.GONE);
String decryptedmsg = comment.getMsgstring();
holder.commentString.setText(decryptedmsg);
// holder.photo.setVisibility(View.GONE);
break;
case "photo":
Glide.clear(holder.imgchat);
holder.imgchat.setVisibility(View.VISIBLE);
holder.progress.setVisibility(View.VISIBLE);
if (getItemViewType(position) == SENDER) {
// holder.btndown.setVisibility(View.GONE);
// holder.btnopen.setVisibility(View.VISIBLE);
try {
Glide.with(context).load(comment.getMsglocalurl()).into(holder.imgchat);
}catch (Exception e){
e.printStackTrace();
}
}
break;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView otherSender_Timestamp, commentString,progress;
public ImageView imgchat;
public Button btndown, btnopen;
public MyViewHolder(View itemView) {
super(itemView);
otherSender_Timestamp = (TextView) itemView.findViewById(R.id.meSender_TimeStamp);
commentString = (TextView) itemView.findViewById(R.id.commentString);
progress = (TextView) itemView.findViewById(R.id.mediaprogress);
imgchat = (ImageView) itemView.findViewById(R.id.imgchat);
btndown = (Button) itemView.findViewById(R.id.btndown);
btnopen = (Button) itemView.findViewById(R.id.btnopen);
}
}
}
ChatActivity code is:
public class ChatActivity extends ToadoBaseActivity {
private EditText typeComment;
private ImageButton sendButton, attachment, takephoto;
Intent intent;
private RecyclerView recyclerView;
DatabaseReference dbChat;
private String otheruserkey;
LinearLayoutManager linearLayoutManager;
private MarshmallowPermissions marshmallowPermissions;
private ArrayList<String> mResults = new ArrayList<>();
private ActionMode actionMode;
UploadFileService uploadFileService;
boolean mServiceBound = false;
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy hh:mm aa");
private ChatAdapter1 mAdapter;
LinkedHashSet<ChatMessageRealm> uniqueStrings = new LinkedHashSet<ChatMessageRealm>();
private ArrayList<ChatMessageRealm> chatList = new ArrayList<>();
private ArrayList<String> chatListIds = new ArrayList<>();
String username, mykey;
private UserSession session;
String receiverToken = "nil";
boolean clicked;
LinearLayout layoutToAdd;
LinearLayout commentView;
private ChildEventListener dbChatlistener;
ImageButton photoattach, videoattach;
Uri videoUri;
public String dbTableKey;
EncryptUtils encryptUtils = new EncryptUtils();
private ImageButton imgdocattach;
private ImageButton locattach;
private LinearLayout spamView;
TextView tvTitle;
ImageView imgprof;
private ArrayList<String> imagesPathList;
private final int PICK_IMAGE_MULTIPLE = 199;
private ProgressBar progressBar;
UserMediaPrefs umprefs;
private Boolean mBounded;
private String TAG = "ChatActivity";
// AbstractXMPPConnection connection;
Realm mRealm;
Boolean chatexists;
private String otherusername;
private String profpic;
private MyXMPP2 myxinstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat1);
session = new UserSession(this);
mykey = session.getUserKey();
// connection = MyXMPP2.getInstance(this,).getConn();
mRealm = Realm.getDefaultInstance();
checkChatRef(otheruserkey);
clicked = false;
layoutToAdd = (LinearLayout) findViewById(R.id.attachmentpopup);
marshmallowPermissions = new MarshmallowPermissions(this);
spamView = (LinearLayout) findViewById(R.id.spamView);
umprefs = new UserMediaPrefs(this);
//get these 2 things from notifications also
intent = getIntent();
otheruserkey = intent.getStringExtra("otheruserkey");
otherusername = intent.getStringExtra("otherusername");
profpic = intent.getStringExtra("profpic");
System.out.println("recevier token chat act oncreate" + otheruserkey);
imgprof = (ImageView) findViewById(R.id.icon_profile);
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvTitle.setText(otherusername);
commentView = (LinearLayout) findViewById(R.id.commentView);
progressBar = (ProgressBar) findViewById(R.id.progress);
typeComment = (EditText) findViewById(R.id.typeComment);
sendButton = (ImageButton) findViewById(R.id.sendButton);
attachment = (ImageButton) findViewById(R.id.attachment);
takephoto = (ImageButton) findViewById(R.id.takephoto);
photoattach = (ImageButton) findViewById(R.id.photoattach);
imgdocattach = (ImageButton) findViewById(R.id.docattach);
videoattach = (ImageButton) findViewById(R.id.videoattach);
locattach = (ImageButton) findViewById(R.id.locationattach);
myxinstance = MyXMPP2.getInstance(ChatActivity.this, getString(R.string.server), mykey);
mAdapter = new ChatAdapter1(chatList, this);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(mAdapter);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(mykey + " chat created " + otheruserkey);
ChatMessageRealm cm = null;
if (!typeComment.getText().toString().matches("")) {
cm = new ChatMessageRealm(mykey + otheruserkey, otheruserkey, typeComment.getText().toString(), mykey, GetTimeStamp.timeStampTime(), GetTimeStamp.timeStampDate(), "text", String.valueOf(GetTimeStamp.Id()), "1");
}
if (cm != null)
myxinstance.sendMessage(cm);
loadData();
typeComment.setText("");
}
});
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (layoutToAdd.getVisibility() == View.VISIBLE)
layoutToAdd.setVisibility(View.GONE);
else
layoutToAdd.setVisibility(View.VISIBLE);
}
});
takephoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
dispatchTakePictureIntent();
} catch (ActivityNotFoundException anfe) {
anfe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
mykey = session.getUserKey();
username = session.getUsername();
loadData();
}
private void loadData() {
Sort sort[] = {Sort.ASCENDING};
String[] fieldNames = {"msgid"};
RealmResults<ChatMessageRealm> shows = mRealm.where(ChatMessageRealm.class).equalTo("chatref", mykey + otheruserkey).findAllSorted(fieldNames, sort);
if (shows.size() > 0) {
Log.d(TAG, shows.size() + "LOAD DATA CALLED " + shows.get(shows.size() - 1).getMsgstring());
for (ChatMessageRealm cm : shows) {
if (!chatList.contains(cm)) {
chatList.add(cm);
}
if (!chatListIds.contains(cm.getMsgid())) {
chatListIds.add(cm.getMsgid());
}
mAdapter.notifyDataSetChanged();
}
mAdapter.notifyDataSetChanged();
recyclerView.scrollToPosition(chatList.size() - 1);
}
}
private void checkChatRef(String otheruserkey) {
RealmQuery<ActiveChats> query = mRealm.where(ActiveChats.class);
query.equalTo("otherkey", otheruserkey);
RealmResults<ActiveChats> result1 = query.findAll();
if (result1.size() == 0) {
chatexists = false;
} else {
chatexists = true;
}
System.out.println(result1.size() + "chat exists chatactivity" + chatexists);
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(this.reloadData, new IntentFilter("reloadchataction"));
}
#Override
protected void onStop() {
super.onStop();
if (reloadData != null)
unregisterReceiver(reloadData);
}
private void dispatchTakePictureIntent() throws IOException {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "request code chatactivity" + requestCode);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
Log.d(TAG, "crop activity");
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
final String imguri = result.getUri().toString();
try {
final File file = createImageFile();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
InputStream in = null;
OutputStream out = null;
try {
in = getContentResolver().openInputStream(Uri.parse(imguri));
out = new FileOutputStream(file);
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
String s = file.getAbsolutePath();
Log.d(TAG, "image cropped uri chatact22" + file.getAbsolutePath());
Intent intent = new Intent(ChatActivity.this, ImageComment.class);
intent.putExtra("URI", s);
intent.putExtra("comment_type", "photo");
startImageComment(intent);
} catch (Exception ex) {
Log.e("Something went wrong.", ex.toString());
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName = "pic-" + GetTimeStamp.timeStamp() + ".jpg";
File image = OpenFile.createFile(this, imageFileName);
// Save a file: path for use with ACTION_VIEW intents
Log.d(TAG, "file createimagefile: " + image.getAbsolutePath());
return image;
}
private void startImageComment(Intent intent) {
Log.d(TAG, "image comment sending" + intent.getStringExtra("URI"));
intent.putExtra("username", username);
intent.putExtra("otheruserkey", otheruserkey);
intent.putExtra("receiverToken", receiverToken);
intent.putExtra("mykey", mykey);
startActivity(intent);
}
BroadcastReceiver reloadData = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getStringExtra("reloadchat") != null) {
Log.d(TAG, " reloading data broadcast receiver" + intent.getStringExtra("reloadchat"));
loadData();
mAdapter.notifyDataSetChanged();
} else if (intent.getStringExtra("reloadchatmediastatus") != null) {
if (intent.getStringExtra("reloadchatmediastatus").matches(MEDIA_STARTING))
loadData();
Log.d(TAG, " reloading data status " + intent.getStringExtra("reloadchatmediastatus"));
Log.d(TAG, " reloading data media id " + intent.getStringExtra("reloadchatmediaid"));
if (!intent.getStringExtra("reloadchatmediastatus").matches(MEDIA_FAILED)) {
final String msgid = intent.getStringExtra("reloadchatmediaid");
String fileprogress = intent.getStringExtra("reloadchatmediastatus");
int ind1 = chatListIds.indexOf(msgid);
Log.d(TAG, ind1 + "chat list broadcast progress " + fileprogress);
Log.d(TAG, "chat list broadcast" + chatListIds.size());
try {
// View ve = linearLayoutManager.findViewByPosition(ind1);
// View v = recyclerView.findViewHolderForAdapterPosition(ind1).itemView;
View v = recyclerView.findViewHolderForLayoutPosition(ind1).itemView;
ChatAdapter1.MyViewHolder holder = (ChatAdapter1.MyViewHolder) recyclerView.getChildViewHolder(v);
holder.commentString.setVisibility(View.VISIBLE);
holder.commentString.setText("file prog " + fileprogress);
mAdapter.notifyDataSetChanged();
Log.d(TAG, holder.getItemViewType() + "," + holder.getLayoutPosition() + "," + holder.commentString.getText().toString() + " VIEW HOLDER? " + v);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (intent.getStringExtra("reloadchatmediaurl") != null)
Log.d(TAG, " reloading data media url " + intent.getStringExtra("reloadchatmediaurl"));
}
};
}
I am trying to update my recyclerview dynamically in the broadcast receiver- reloadData in ChatActivity.
My logs tell me that i am receiving correct data from the sendbroadcast in the UploadFileService, the problem is in following code inside the broadcast receiver on ChatActivity, it is getting correct data but the data is not showing on the recycler view:
try {
View v = recyclerView.findViewHolderForLayoutPosition(ind1).itemView;
ChatAdapter1.MyViewHolder holder = (ChatAdapter1.MyViewHolder) recyclerView.getChildViewHolder(v);
holder.commentString.setVisibility(View.VISIBLE);
holder.commentString.setText("file prog " + fileprogress);
mAdapter.notifyDataSetChanged();
Log.d(TAG, holder.getItemViewType() + "," + holder.getLayoutPosition() + "," + holder.commentString.getText().toString() + " VIEW HOLDER? " + v);
} catch (Exception e) {
e.printStackTrace();
}
I get correct values , such as:
08-03 19:31:25.240 705-705/com.app.toado D/ChatActivity: 0,30,file prog 34 VIEW HOLDER? android.widget.LinearLayout{ff24ae0 V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
08-03 19:31:26.346 705-705/com.app.toado D/ChatActivity: 0,30,file prog 100 VIEW HOLDER? android.widget.LinearLayout{e8a33ce V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
08-03 19:31:26.347 705-705/com.app.toado D/ChatActivity: 0,30,file prog upload success VIEW HOLDER? android.widget.LinearLayout{e8a33ce V.E...... ......I. 0,621-660,1380 #7f1100f2 app:id/message_container}
I have tried using View ve = linearLayoutManager.findViewByPosition(ind1); and View v = recyclerView.findViewHolderForAdapterPosition(ind1).itemView; but they are also not working. Also tried adding notifydatasetchanged to it.
The try catch is also not throwing any error in the logs.
Can someone please help in figuring out why are the changes not showing on the recycler view but are showing in logs?
Are you sure you're updating the RecyclerView's Adapter from the UI Thread? Whenever you try to update the ViewHolder, you have to be certain you're doing so on the UI or it will not behave as expected.
When the modification to the ViewHolder is changed, check that Looper.myLooper().equals(Looper.getMainLooper());. If it returns false, it means you aren't updating on the UI Thread, the necessary place for all graphical updates to be made.
If this is the case, you just need to make sure that you can synchronize your changes on the UI, using Activity.runOnUiThread(Runnable r);.
I'm developing my app, in which storing quotes.
Data about quotes I download from my server.
I want in order to user downloading 10 quotes (at that time data add to local database), and if he scrolled this 10 quotes, new data will be download (again 10).
For example, as in facebook tape (with adding data to local db).
But I also need sync local db with server db.
I do not understand how to combine all this.
Download data - Here I pass the id from which to download from the id from server db.
class DownloadAndParseJson extends AsyncTask<Integer, Void, ArrayList<QuoteObject>> {
interface AsyncResponse {
void processFinish(ArrayList<QuoteObject> output);
}
private AsyncResponse delegate = null;
DownloadAndParseJson(AsyncResponse delegate){
this.delegate = delegate;
}
private static final String TAG = "###" + "DownloadAndParseJson";
#Override
protected ArrayList<QuoteObject> doInBackground(Integer... params) {
Log.i(TAG, "Starting download quotes from " + params[0] + " id");
if (params.length == 0) {
return null;
}
int id = params[0];
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String countriesJsonStr = null;
try {
final String BASIC_URL = "http://*******.com";
final String ID_PARAM = "id";
Uri builtUri = Uri.parse(BASIC_URL).buildUpon()
.appendQueryParameter(ID_PARAM, Integer.toString(id))
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
countriesJsonStr = buffer.toString();
Log.v(TAG, "download end");
} catch (IOException e) {
Log.e(TAG, "Error", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error", e);
}
}
}
Log.i(TAG, "End download quotes");
return getArrayParsedJson(countriesJsonStr);
}
#Override
protected void onPostExecute(ArrayList<QuoteObject> result) {
Log.i(TAG, "Downloaded " + result.size() + " quotes");
delegate.processFinish(result);
}
private ArrayList<QuoteObject> getArrayParsedJson(String jsonStr){
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<QuoteObject>>(){}.getType();
return gson.fromJson(jsonStr, collectionType);
}
}
Working with the database - here Im store Quote objects
public class RealmHelper {
private static final String TAG = "###" + "RealmHelper";
Context context;
public RealmHelper(Context context) {
this.context = context;
}
public void write(ArrayList<QuoteObject> quoteObjectArrayList) {
Realm.init(context);
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
for (QuoteObject quoteObject : quoteObjectArrayList){
realm.copyToRealm(quoteObject);
}
realm.commitTransaction();
}
public ArrayList<QuoteObject> read() {
Realm.init(context);
Realm realm = Realm.getDefaultInstance();
return new ArrayList<>(realm.where(QuoteObject.class).findAll());
}
public void delete() {
Realm.init(context);
Realm realm = Realm.getDefaultInstance();
final RealmResults<QuoteObject> countries = realm.where(QuoteObject.class).findAll();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
countries.deleteAllFromRealm();
Log.i(TAG, "size = " + countries.size());
}
});
}
}
MainActivity
public class MainActivity extends AppCompatActivity
implements DownloadAndParseJson.AsyncResponse{
.
.
RVAdapter adapter;
private ArrayList<QuoteObject> quoteObjectArrayList;
.
.
protected void onCreate(){
.
.
.
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RVAdapter(this, quoteObjectArrayList);
recyclerView.setAdapter(adapter);
}
#Override
public void processFinish(ArrayList<QuoteObject> output) {
if (output.size() != 0) {
quoteObjectArrayList = output;
Log.i(TAG, "processFinish() returned outputArray size " + output.size());
} else
Toast.makeText(this, "Not found quotes", Toast.LENGTH_SHORT).show();
}
RecyclerView.Adapter - To display quotes Im using card view.
class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder>
implements DownloadAndParseJson.AsyncResponse{
private static final String TAG = "###" + "RVAdapter";
private Context context;
private boolean hasMoreItems;
private ArrayList<QuoteObject> quoteObjectArrayList;
RVAdapter(Context context, ArrayList<QuoteObject> quoteObjectArrayList){
this.context = context;
this.hasMoreItems = true;
this.quoteObjectArrayList = quoteObjectArrayList;
Log.i(TAG, "quoteObjectArrayList = " + quoteObjectArrayList.size());
}
private void notifyNoMoreItems(){
hasMoreItems = false;
Toast.makeText(context, "No More Items", Toast.LENGTH_SHORT).show();
}
#Override
public RVAdapter.PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_of_quote, viewGroup, false);
return new PersonViewHolder(view);
}
#Override
public void onBindViewHolder(final RVAdapter.PersonViewHolder holder, int position) {
Log.i(TAG, "Card position = " + position);
if (position == quoteObjectArrayList.size() && hasMoreItems){
new DownloadAndParseJson(this).execute(Integer.parseInt(quoteObjectArrayList.get(position).getId()));
}
holder.contentOfQuote.setText(quoteObjectArrayList.get(position).getQuote());
holder.authorQuote.setText(quoteObjectArrayList.get(position).getAuthor());
holder.ratingBar.setOnRatingChangeListener(new MaterialRatingBar.OnRatingChangeListener() {
#Override
public void onRatingChanged(MaterialRatingBar ratingBar, float rating) {
//ratingBar.setRight(Integer.parseInt(quoteObjectArrayList.get(position).getId()));
}
});
holder.btnShareQuote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, holder.contentOfQuote.getText()
+ "\n" + holder.authorQuote.getText() );
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
});
holder.btnViewComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//View Comments
}
});
}
#Override
public int getItemCount() {
return quoteObjectArrayList.size();
}
#Override
public void processFinish(ArrayList<QuoteObject> output) {
if (output.size() != 0) {
quoteObjectArrayList.addAll(output);
Log.i(TAG, "Total quoteArray Size = " + quoteObjectArrayList.size());
new RealmHelper(context).write(output); // NEED separate throw
} else notifyNoMoreItems();
}
static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView contentOfQuote, authorQuote;
MaterialRatingBar ratingBar;
ImageButton btnViewComment, btnShareQuote;
TextView rating;
public PersonViewHolder(View itemView) {
super(itemView);
this.cardView = (CardView) itemView.findViewById(R.id.cardView);
this.contentOfQuote = (TextView) itemView.findViewById(R.id.contentOfQuote);
this.authorQuote = (TextView) itemView.findViewById(R.id.authorQuote);
this.btnViewComment = (ImageButton) itemView.findViewById(R.id.btnViewComment);
this.btnShareQuote = (ImageButton) itemView.findViewById(R.id.btnShareQuote);
this.ratingBar = (MaterialRatingBar) itemView.findViewById(R.id.ratingBar);
this.rating = (TextView) itemView.findViewById(R.id.txtRating);
}
}
}
Now I need to combine all this.
It should turn out:
To start with the data from local db.
If there is no data - download new (10 quotes).
Else take data from local db until they run out
Download 10 quotes from server bd, add to local and display they.
Or If there is no data Print out about it.
Sync local bd with server.
Help me please.
Thanks.
This would be much easier if you used RealmResults as intended along with RealmChangeListener and Realm's notification system. See the official documentation.
class DownloadAndParseJson extends AsyncTask<Integer, Void, Void> {
DownloadAndParseJson(){
}
private static final String TAG = "###" + "DownloadAndParseJson";
#Override
protected Void doInBackground(Integer... params) {
Log.i(TAG, "Starting download quotes from " + params[0] + " id");
if (params.length == 0) {
return null;
}
int id = params[0];
try {
final List<QuoteObject> quotes = retrofitService.getQuotes(id).execute().body();
if(quotes == null) {
throw new RuntimeException("Download failed");
}
try(Realm realm = Realm.getDefaultInstance()) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.insert(quotes);
}
});
}
} catch (Exception e) {
Log.e(TAG, "Error", e);
return null;
}
Log.i(TAG, "End download quotes");
return null;
}
#Override
protected void onPostExecute(Void ignored) {
}
}
And
class RVAdapter extends RealmRecyclerViewAdapter<QuoteObject, RVAdapter.PersonViewHolder> {
private static final String TAG = "###" + "RVAdapter";
RVAdapter(OrderedRealmCollection<QuoteObject> quotes) {
super(quotes, true);
}
// onCreateViewHolder
// onBindViewHolder
// view holder
}
And
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new RVAdapter(realm.where(QuotesObject.class).findAll()); // <-- RealmResults
recyclerView.setAdapter(adapter);
and some "did download all" kind of logic, although that needs a bit smarter error handling; and "is data being downloaded" so that you don't spam requests when you scrolled down.
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}