Android ViewModel keeps initialising ArrayList - java

For the last two days I've been trying to use a ViewModel to store an ArrayList. However, every time I access the ViewModel it initialises the ArrayList, removing the data stored inside it.
I've tried including methods in the ViewModel to control initialisation of the ArrayList, but it hasn't helped. Every time the ViewModel is accessed it resets the ArrayList to 'null.'
Why is this happening and how can I stop it?
ViewModel_Quiz.java
import android.arch.lifecycle.ViewModel;
import java.util.ArrayList;
public class ViewModel_Quiz extends ViewModel {
ArrayList<String> checkboxStatus;
public void sendCheckboxStatus(ArrayList<String> arrayList){
checkboxStatus = arrayList;
}
public ArrayList<String> getCheckboxStatus(){
return checkboxStatus;
}
}
FragmentQuiz_Selection.java
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.support.constraint.Group;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
public class FragmentQuiz_Selection extends Fragment implements View.OnClickListener{
private FloatingActionButton fab_start;
//Create member variable for Checkbox loops
private boolean mChecked;
//Create ArrayList for QuizSelection
private ArrayList<String> mQuizSelection = new ArrayList<>();
//Create boolean for Expand/Collapse
//boolean iv_group_instruments = false;
//Create View variable
private View mView;
//Variables for database
private SQLiteDatabase mInstrumentsDB;
private InstrumentsDbHelper instrumentsDb;
//This contains the same data as mQuizSelection. It's used to prepare the database and populate mTotalRows.
private String[] mQuizSelectionArray;
//This is used as part of quizPrep() to populate mTotalRows. This may note need to be a memberVariable.
private int mTotalRows;
//This contains the total number of columns for the user's selection.
private int mTotalColumns;
//This holds all of the column/row pairs for the quiz.
private ArrayList<String> mQuizList = new ArrayList<>();
//This variable is used to interface with MainActivity
private OnQuizStarted mCallback;
//This ArrayList holds the CheckBox status for restoring the user's state
private ArrayList<String> mCheckboxStatus = new ArrayList<>();
public static FragmentQuiz_Selection newInstance() {
FragmentQuiz_Selection fragment = new FragmentQuiz_Selection();
return fragment;
}
//Create an interface to communicate with MainActivity
public interface OnQuizStarted {
void onQuizStarted (ArrayList<String> arrayList);
}
// Connect the interface to MainActivity
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnQuizStarted) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnQuizStarted");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Store views in variable
mView = inflater.inflate(R.layout.fragment_quiz_selection, container, false);
// Set onClickListeners
setOnClickListeners();
//Ensure all Checkboxes are set to 'false'
ViewGroup constraintLayout = (ViewGroup) mView.findViewById(R.id.quiz_menu_layout);
loopCheckboxesFalse(constraintLayout);
//Create onClickListener for 'start' FAButton
fab_start.setOnClickListener(new View.OnClickListener() {
//If you click the FAButton, start the Quiz
#Override
public void onClick(View view) {
//Create variable for ConstraintLayout
ViewGroup constraintLayout = (ViewGroup) mView.findViewById(R.id.quiz_menu_layout);
quizStart(constraintLayout);
}
});
return mView;
}
//Handle actions when the user is returning to the Fragment
#Override
public void onResume() {
super.onResume();
Log.i("LIFECYCLE CHANGE", "Quiz_Selection, onResume has been called!");
//Get mCheckboxStatus from ViewModel
ViewModel_Quiz viewmodel = ViewModelProviders.of(this).get(ViewModel_Quiz.class);
if (viewmodel.getCheckboxStatus() != null && !(viewmodel.getCheckboxStatus().isEmpty())) {
mCheckboxStatus = viewmodel.getCheckboxStatus();
setCheckboxStatus(mCheckboxStatus);
}
//If mChecked is 'true,' show FAButton. If mChecked is 'false,' hide FAButton.
ViewGroup layout = mView.findViewById(R.id.quiz_menu_layout);
mChecked = loopCheckboxesBoolean(layout);
fabButton(mChecked, fab_start);
}
//Handle actions when the user is leaving, but not necessarily destroying, the Fragment
#Override
public void onPause() {
super.onPause();
Log.i("LIFECYCLE CHANGE", "Quiz_Selection, onPause has been called!");
mCheckboxStatus.clear();
recordCheckboxStatus(mCheckboxStatus);
//Send mCheckboxStatus to ViewModel
ViewModel_Quiz viewmodel = ViewModelProviders.of(this).get(ViewModel_Quiz.class);
viewmodel.sendCheckboxStatus(mCheckboxStatus);
}
#Override
public void onClick(View view) {
if (view instanceof CheckBox) {
onCheckboxClicked(view);
} else if (view instanceof ImageView) {
onExpandCollapse(view);
}
}
//METHOD: Set Checkbox status for 'onCreate'
private void setCheckboxStatus (ArrayList<String> arrayList) {
ViewGroup layout = mView.findViewById(R.id.quiz_menu_layout);
int childCount = layout.getChildCount();
//Iterate through the layout's CheckBox views
for (int i = 0; i < childCount; i++) {
View view = layout.getChildAt(i);
//If item is a Checkbox, assign it as true or false
if (view instanceof CheckBox) {
if (arrayList.get(0) == "y") {
((CheckBox) view).setChecked(true);
arrayList.remove(0);
} else if (arrayList.get(0) == "n") {
((CheckBox) view).setChecked(false);
arrayList.remove(0);
}
}
}
}
//METHOD: Store Checkbox status for 'onPause'
private void recordCheckboxStatus (ArrayList<String> arrayList) {
ViewGroup layout = mView.findViewById(R.id.quiz_menu_layout);
int childCount = layout.getChildCount();
//Iterate through the layout's views
for (int i = 0; i < childCount; i++) {
View view = layout.getChildAt(i);
//If item is a Checkbox && Checkbox is 'checked,' add 'y' to the arrayList.
if (view instanceof CheckBox && ((CheckBox) view).isChecked()) {
arrayList.add("y");
//Else if item is a Checkbox && Checkbox is 'not checked,' add 'n' to the arrayList.
} else if (view instanceof CheckBox && !((CheckBox) view).isChecked()){
arrayList.add("n");
//Else if item is not a Checkbox, skip this view and move to the next one
} else {}
}
}
}

You have to use MutableLiveData in yout ViewModel.
import android.arch.lifecycle.ViewModel;
import java.util.ArrayList;
public class ViewModel_Quiz extends ViewModel {
MutableLiveData<Arraylist<String>> checkboxStatus;
public void sendCheckboxStatus(ArrayList<String> arrayList){
checkboxStatus.postValue(arrayList);
}
public ArrayList<String> getCheckboxStatus(){
return checkboxStatus;
}
}

Related

How to know the index of the item of the list, on which the button was clicked

So I am working on a list view, and I want to implement a delete button. But for some reason, whenever I press the delete button on any list item whatsoever, the last item in the list gets deleted automatically. I tried out almost everything, but I am unable to understand how I can know the index of the item where the button was clicked so I can easily just delete that particular item.
This is the code :
// full subtask adapter code
package com.example.taskmasterv3;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class SubtaskAdapter extends ArrayAdapter<subtask> {
private final Context context;
private ArrayList<subtask> values;
public SubtaskAdapter(Context context, ArrayList<subtask> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.subtask_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvSubtaskName);
ImageView ivPri = convertView.findViewById(R.id.ivPri);
ImageView ivTime = convertView.findViewById(R.id.ivTime);
ImageView ivDelete = convertView.findViewById(R.id.ivDelete);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).isPriHigh()) {
ivPri.setImageResource(R.drawable.priority_high);
} else if (values.get(position).isPriMed()) {
ivPri.setImageResource(R.drawable.priority_med);
} else if (values.get(position).isPriLow()) {
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).isTimeMore()) {
ivTime.setImageResource(R.drawable.time_symbol_more);
} else if (values.get(position).isTimeMed()) {
ivTime.setImageResource(R.drawable.time_symbol_med);
} else if (values.get(position).isTimeLess()) {
ivTime.setImageResource(R.drawable.time_symbol_less);
}
// Delete button for subtasks (NOT WORKING)
ivDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SubtaskAdapter.this.remove(SubtaskAdapter.this.getItem(position));
notifyDataSetChanged();
}
});
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public void addANewSubTask(subtask newSubTask){
ArrayList<subtask> newvalues = new ArrayList<>(this.values);
newvalues.add(newSubTask);
this.values = newvalues;
notifyDataSetChanged();
}
}
ivDelete.setOnClickListener(new View.OnClickListener() {
Change that to:
ivDelete.setOnClickListener(new View.OnClickListener() {
ivDelete.setTag(position);
public void onClick(View v) {
Change to:
public void onClick(View v) {
// int position = v.getTag();
int position = (Integer)v.getTag();
Try to use below code :
ivDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
values .remove(position);
notifyDataSetChanged();
//SubtaskAdapter.this.remove(SubtaskAdapter.this.getItem(position));
//notifyDataSetChanged();
}
});

Click on one card view affected another card view value

When I create a custom card view in recycler view and click the increment button counter work properply. But when I crete another cardview then already created card counter value reset to 0. How to solve this issue?
Here's my Main Activity code
package com.example.muhasbaapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.example.muhasbaapp.CustomAdapter.ViewHolder.*;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter mAdapter,countAdapter;
private RecyclerView.LayoutManager layoutManager,layoutManager2;
private static RecyclerView recyclerView,recyclerView2;
private ImageView imageView;
public CustomModel customModel;
public static ArrayList<String> input = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView2=(RecyclerView)findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
recyclerView2.setHasFixedSize(true);
layoutManager2=new LinearLayoutManager(this);
recyclerView2.setLayoutManager(layoutManager2);
recyclerView2.setItemAnimator(new DefaultItemAnimator());
mAdapter= new CustomAdapter(input);
recyclerView2.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.more_action_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { //add action2 kau kat sini
switch (item.getItemId()) {
case R.id.action_item_1:
openCustomDialoge();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void openCustomDialoge() {
final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.user_generated_cards, null);
final EditText editText = (EditText) dialogView.findViewById(R.id.edt_comment);
Button button1 = (Button) dialogView.findViewById(R.id.buttonSubmit);
Button button2 = (Button) dialogView.findViewById(R.id.buttonCancel);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialogBuilder.dismiss();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s=editText.getText().toString();
if (s.isEmpty()){
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
}else {
input.add(s);
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
dialogBuilder.setView(dialogView);
dialogBuilder.show();
}
}
And Here' my Adaptar Class code
package com.example.muhasbaapp;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
public ArrayList<String> values;
final CustomModel customMdl=new CustomModel();
final MainActivity mainActivity=new MainActivity();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView tv;
public View layout;
public TextView counter_value;
public ImageView increment,decrement, deleted;
public int counter;
public ViewHolder(View v) {
super(v);
layout = v;
tv = (TextView) v.findViewById(R.id.textViewName);
counter_value=(TextView) v.findViewById(R.id.counter);
increment=(ImageView)v.findViewById(R.id.increment);
decrement=(ImageView)v.findViewById(R.id.decrement);
deleted=(ImageView)v.findViewById(R.id.delbtn);
}
}
public void add(int position, String item) {
values.add(position, item);
notifyItemInserted(position);
}
public void remove(int position) {
values.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, values.size());
}
// Provide a suitable constructor (depends on the kind of dataset)
public CustomAdapter(ArrayList<String> myDataset) {
this.values = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public CustomAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(
parent.getContext());
View v =
inflater.inflate(R.layout.custom_cards_layout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = values.get(position);
holder.tv.setText(name);
final int[] counter={0};
holder.deleted.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(position);
}
});
holder.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter[0] == 0) {
Toast.makeText(v.getContext(), "Can't add less than 0", Toast.LENGTH_SHORT).show();
} else {
counter[0] -= 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
}
});
holder.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.decrement.setEnabled(true);
counter[0] += 1;
holder.counter_value.setText(String.valueOf(counter[0]));
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return values.size();
}
}
If anyone knows this problem please inform me.
Thanks in advance
Well, I'm seeing some bad practices in your code:
Adapters hosted in main activity must be not static, what do you think if try accessing via recyclerView.getAdapter()
Please remove the next one in your adapter
final MainActivity mainActivity = new MainActivity();
So the problem that you are having is inside your click listener.
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String s = editText.getText().toString();
if (s.isEmpty()) {
Toast.makeText(MainActivity.this, "You can't enter empty spaces", Toast.LENGTH_SHORT).show();
} else {
input.add(s); // <-------------- HERE
recyclerView2.setAdapter(mAdapter);
dialogBuilder.dismiss();
}
}
});
You add the new item to the array, however, the adapter never knows that there is a new item has been added.
Access to the instanced adapter which has been attached to RecyclerView in onCreate() step and update their data.

Recyclerview change item color outside adapter

Currently I'm trying figure out how to change an RecyclerView item color outside adapter. I'm just manipulating the position, and works fine! But I must swipe the page to color update, and I don't know what I should do to fix this problem.
Check my code:
MainActivity.java
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
player_prev = findViewById(R.id.prev);
player_prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((currentPos-1) > 0) {
killMediaPlayer();
initAudio(getApplicationContext(),
RecyclerViewAdapter.mData.get(currentPos - 1).getURL());
currentPos -= 1;
RecyclerViewAdapter.OldselectedPos = RecyclerViewAdapter.selectedPos;
RecyclerViewAdapter.selectedPos = currentPos;
adapter.notifyDataSetChanged();
}
});
...
}
RecyclerViewAdapter.java
package etes.xdda.music;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> implements View.OnClickListener{
MainActivity activity;
static List<mList> mData;
Dialog myDialog;
public static int selectedPos = RecyclerView.NO_POSITION;
public static int OldselectedPos = RecyclerView.NO_POSITION;
private LinearLayout menu_dialog, menu_dialog2;
public static TextView song_detail;
public RecyclerViewAdapter(MainActivity activity, List<mList> mData) {
this.activity = activity;
this.mData = mData;
}
#Override
public void onClick(View view) { }
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(activity).inflate(R.layout.item_list, parent, false);
final MyViewHolder vHolder = new MyViewHolder(v);
// Dialog ini
myDialog = new Dialog(activity);
myDialog.setContentView(R.layout.dialog);
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vHolder.item_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
TextView dialog_name_tv = myDialog.findViewById(R.id.dialog_name_id);
TextView dialog_phone_tv = myDialog.findViewById(R.id.dialog_author_id);
ImageView dialog_contact_img = myDialog.findViewById(R.id.dialog_img);
dialog_name_tv.setText(mData.get(vHolder.getAdapterPosition()).getName());
dialog_phone_tv.setText(mData.get(vHolder.getAdapterPosition()).getPhone());
dialog_contact_img.setImageResource(mData.get(vHolder.getAdapterPosition()).getPhoto());
//Toast.makeText(mContext, "Test click "+String.valueOf(vHolder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
myDialog.show();
}
});
vHolder.menu_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
OldselectedPos = selectedPos;
selectedPos = vHolder.getAdapterPosition();
notifyItemChanged(selectedPos);
notifyItemChanged(OldselectedPos);
menu_dialog = v.getRootView().findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(v.VISIBLE);
menu_dialog2 = v.getRootView().findViewById(R.id.menu_dialog2);
menu_dialog2.setVisibility(v.VISIBLE);
song_detail = v.getRootView().findViewById(R.id.song_detail);
song_detail.setVisibility(v.VISIBLE);
String newName;
newName = mData.get(vHolder.getAdapterPosition()).getName();
if (newName.length() > 42) {
newName = newName.substring(0, 38) + "...";
}
song_detail.setText(newName);
activity.killMediaPlayer();
activity.initAudio(v.getContext(), mData.get(vHolder.getAdapterPosition()).getURL());
activity.setMargins(v.getRootView().findViewById(R.id.viewpager_id), 0,0,0,205);
activity.updateNotificationBar("mzPlay", mData.get(vHolder.getAdapterPosition()).getName());
MainActivity.currentPos = vHolder.getAdapterPosition();
}
});
return vHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv_name.setText(mData.get(position).getName());
holder.tv_author.setText(mData.get(position).getPhone());
holder.img.setImageResource(mData.get(position).getPhoto());
//Toast.makeText(activity, String.valueOf(holder), Toast.LENGTH_LONG).show();
if(selectedPos == position){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else
{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private ImageButton item_play;
private LinearLayout menu_play;
private TextView tv_name;
private TextView tv_author;
private ImageView img;
public MyViewHolder(View itemView) {
super(itemView);
item_play = itemView.findViewById(R.id.info_id);
menu_play = itemView.findViewById(R.id.list_item_id);
tv_name = itemView.findViewById(R.id.name_list);
tv_author = itemView.findViewById(R.id.author_list);
img = itemView.findViewById(R.id.img_music);
}
}
}
Video: https://ntcdn.stream/20181009_2342010.mp4
The problem is: I must swipe the page to item colors be updated, how can I update the colors without page swipe?
Storing andoid classes in static variables is really a very bad practice. You should interact with your adapter the regular way, using a non static field, for example:
//This will go in your onCreate() for example
MyAdapter adapter = new MyAdapter(parameters);
...
adapter.highligtedItemPosition = 10;
adapter.notifyItemChanged(10);
and later in your onBindViewHolder() react according to what background you want set:
if(position == highligtedItemPosition ){
holder.itemView.setBackgroundColor(Color.parseColor("#373737"));
}
else{
holder.itemView.setBackgroundColor(Color.parseColor("#212121"));
}
in this example you must add an integer field:
int highligtedItemPosition;
to your adapter to store the position of the item you want to change the color of.
UPDATE:
You are not calling notifyItemChange() or notifyDataSetChanged() from your activity, so the adapter needs to "wait" for the scrolling action to "see" the changes. You should call notifyItemChange() or notifyDataSetChanged() from your player_prev's OnClickListener instead. So the adapter will reflect the changes immediately.

How can i get the 3 textview from recyclerview and pass it to dialogbox

Im new to android programming so can you provide me the right code.
this is my code. the data is from sqlite. my problem is . How can i get the 3 textview from recyclerview and pass it to dialogbox when clicked? i finally made dialogbox but i can get only the position of the item i want to get all of the three textview data. please help me.
FragmentMeal.java
package inncharge.poy.madrigal.innchargev1.fragments;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.database.DatabaseHelper;
import inncharge.poy.madrigal.innchargev1.adapters.VivzAdapter;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentMeal#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentMeal extends Fragment {
private DatabaseHelper db;
private RecyclerView recyclerView;
private VivzAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentMeal.
*/
// TODO: Rename and change types and number of parameters
public static FragmentMeal newInstance(String param1, String param2) {
FragmentMeal fragment = new FragmentMeal();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentMeal() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
db = new DatabaseHelper(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_meal, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.mealList);
adapter = new VivzAdapter(getActivity(),db.getMealData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int postion) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.custom_dialog);
dialog.show();
final EditText editText = (EditText)dialog.findViewById(R.id.editText_pin);
Button submitButton = (Button)dialog.findViewById(R.id.submit_button);
Button cancelButton = (Button)dialog.findViewById(R.id.cancel_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText.getText().toString();
Toast.makeText(getActivity(), "Pin submitted is : " + text, Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(getActivity(), "onLongClick" + position, Toast.LENGTH_SHORT).show();
}
}));
return view;
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
Log.d("VIVZ", "constructor invoked ");
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("VIVZ","onSingleTapUp " + e);
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null){
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
Log.d("VIVZ", "onLongPress " + e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("VIVZ","onTouchEvent "+ e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View arg1, int arg2);
public void onLongClick(View view, int position);
}
}
VivzAdapter.java
package inncharge.poy.madrigal.innchargev1.adapters;
import android.content.ClipData;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.fragments.FragmentMeal;
import inncharge.poy.madrigal.innchargev1.pojo.Contact;
import inncharge.poy.madrigal.innchargev1.pojo.Information;
/**
* Created by Madrigal on 7/18/2015.
*/
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder> {
private Context context;
private final LayoutInflater inflater;
List<Contact> data = Collections.emptyList();
public VivzAdapter(Context context, List<Contact> data){
this.context=context;
inflater = LayoutInflater.from(context);
this.data=data;
}
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
Log.d("VIVZ","onCreateHolder called ");
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
Log.d("VIVZ", "onBindViewHolder called " + position);
holder.itemId.setText(String.valueOf(current.getId()));
holder.title.setText(current.getName());
holder.email.setText(current.getEmail());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public TextView email;
public TextView itemId;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listTextName);
email = (TextView) itemView.findViewById(R.id.listTextUname);
itemId = (TextView) itemView.findViewById(R.id.listTextId);
}
#Override
public void onClick(View v) {
}
}
}
Slidenerd makes some great videos, he helped me a lot as well when I started.
You might want to reconsider what you're trying to do and approach it differently... Why would you want to pass 3 textview from your UI into a dialog?
This is going to be painful.
Seems like you're going to have to extend DialogFragment (i'm assuming that's what you're using for a dialog, maybe an alert?). Create a static factory method inside the DialogFragment like this...
public class MyDialog extends DialogFragment {
private static tv1, tv2, tv3;
public static MyDialog newInstance(TextView tv1, TextView tv2, TextView tv3){
MyDialog.tv1 = tv1;
MyDialog.tv2 = tv2;
MyDialog.tv3 = tv3;
return new MyDialog();
}
}
Once you have this complete, create this dialog fragment inside that onClick method in the ViewHolder class. Instantiate the DialogFragment by doing this...
MyDialog.newInstance(title,email,itemId).show(getFragmentManager(),"dialog_tag");
Like i said before, it's seems sloppy and is probably error prone. There may be a better way of doing this but this is all I can think of off the top of my head. Let me know how it works out for you.. or perhaps revise your question so we can better help you reach a better solution to what you're trying to do.

Failed Binder Transaction is Ruining Entire Widget

In my widget, I am constantly getting this error:
11-02 09:35:10.613: D/D&D(1557): onCreate called
11-02 09:35:10.933: E/JavaBinder(1557): !!! FAILED BINDER TRANSACTION !!!
11-02 09:35:10.933: D/AppInfoAdapter(1557): top
No matter what I seem to do (I've tried cutting down bitmap sizes, making bitmaps static, commenting out parts of my coding to see where the error was (which didn't help at all by the way)), I always get this error. What this error is causing is that it makes my listView of the users installed applications not show up at all (it's just white space) in a sliding drawer. All my links and other classes work just fine. (But my listView is the center piece and major function of my entire widget.)
I'm at a loss now so I am just going to post the three suspected classes that I've concluded this is steming from (because all the other classes work fine).
Please note that some code is commented out (such as coding for drag and drop functionality because my real device doesn't support honeycomb. I will implement that code when my listView starts working again however)
AppInfoAdapter.java:
package com.example.awesomefilebuilderwidget;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class AppInfoAdapter extends BaseAdapter implements Filterable {
private Context mContext;
private List<PackageInfo> mListAppInfo;
private PackageManager mPackManager;
private List<PackageInfo> originalListAppInfo;
private Filter filter;
public AppInfoAdapter(Context c, List<PackageInfo> listApp,
PackageManager pm) {
mContext = c;
this.originalListAppInfo = this.mListAppInfo = listApp;
mPackManager = pm;
Log.d("AppInfoAdapter", "top");
}
#Override
public int getCount() {
Log.d("AppInfoAdapter", "getCount()");
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
Log.d("AppInfoAdapter", "getItem");
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
Log.d("AppInfoAdapter", "getItemId");
return position;
}
public static Bitmap scaleDownBitmap(Bitmap default_b, int newHeight, Context c) {
final float densityMultiplier = c.getResources().getDisplayMetrics().density;
int h= (int) (100*densityMultiplier);
int w= (int) (h * default_b.getWidth()/((double) default_b.getHeight()));
default_b=Bitmap.createScaledBitmap(default_b, w, h, true);
// TO SOLVE LOOK AT HERE:https://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
return default_b;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// get the selected entry
final PackageInfo entry = (PackageInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
Log.d("AppInfoAdapter", "New layout inflated");
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
final CheckBox addCheckbox = (CheckBox) v
.findViewById(R.id.addCheckbox);
Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");
// set data to display
ivAppIcon.setImageDrawable(entry.applicationInfo.loadIcon(mPackManager));
tvAppName.setText(entry.applicationInfo.loadLabel(mPackManager));
tvPkgName.setText(entry.packageName);
Log.d("AppInfoAdapter", "Data Set To Display");
addCheckbox
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
Drawable icon = null;
try {
icon = pm
.getApplicationIcon(entry.packageName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable default_icon = pm.getDefaultActivityIcon();
if (icon instanceof BitmapDrawable
&& default_icon instanceof BitmapDrawable) {
BitmapDrawable icon_bd = (BitmapDrawable) icon;
Bitmap icon_b = icon_bd.getBitmap();
BitmapDrawable default_bd = (BitmapDrawable) pm
.getDefaultActivityIcon();
Bitmap default_b = default_bd.getBitmap();
if (icon_b == default_b) {
// It's the default icon
scaleDownBitmap(default_b, 100, v.getContext());
Log.d("AppInfoAdapter", "Scale Bitmap Chosen");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
default_b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Log.d("AppInfoAdapter", "Scale Bitmap to Array");
Intent intent = new Intent(v.getContext(), GridView.class);
intent.putExtra("picture", byteArray);
v.getContext().startActivity(intent);
Log.d("AppInfoAdapter", "Intent started to send Bitmap");
}
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<PackageInfo> myFilteredAppList = new ArrayList<PackageInfo>();
constraint = constraint.toString().toLowerCase();
if (constraint.length() == 0) {
myFilteredAppList.addAll(originalListAppInfo);
}
for (PackageInfo appInfo : originalListAppInfo) {
String somefield = appInfo.packageName;
String name = appInfo.packageName;
if (somefield.toLowerCase().contains(
constraint.toString().toLowerCase().toString())
|| (name != null && name.toLowerCase()
.contains(
constraint.toString()
.toLowerCase()
.toString()))) {
myFilteredAppList.add(appInfo);
}
}
results.count = myFilteredAppList.size();
results.values = myFilteredAppList;
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results.values != null) {
mListAppInfo = (List<PackageInfo>) results.values;
notifyDataSetChanged();
}
}
};
}
return filter;
}
}
Drag_and_Drop_App (snippet):
public class Drag_and_Drop_App extends Activity {
private static final int SET_BACKGROUND = 10;
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public AppInfoAdapter adapter;
final SwipeDetector swipeDetector = new SwipeDetector();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// import buttons
Button btnLinkToPersonalize = (Button) findViewById(R.id.btnLinkToPersonalize);
Log.d("D&D", "onCreate called");
// create new adapter
adapter = new AppInfoAdapter(this, (List<PackageInfo>) Utilities.getInstalledApplications(this), getPackageManager());
// load list application
mListAppInfo = (ListView)findViewById(R.id.lvApps);
// set adapter to list view
mListAppInfo.setAdapter(adapter);
// search bar
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
// Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
if (Drag_and_Drop_App.this.adapter == null){
// some print statement saying it is null
Log.d ("msg_error", "adapter_is_null");
}
Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// implement event when an item on list view is selected
mListAppInfo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
}
});
// implement event when an item on list view is selected via long-click
mListAppInfo.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,int pos, long id) {
if (swipeDetector.swipeDetected()){
// do the onSwipe action
} else {
// do the onItemLongClick action
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
Log.d("D&D", "App launched");
}
return true;
}
});
// implement slide event to open up plus button
mListAppInfo.setOnTouchListener(swipeDetector);
mListAppInfo.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
if (swipeDetector.swipeDetected()){
// do the onSwipe action
// TEST TO MAKE SURE SWIPE WORKS
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
} else {
// do the onItemClick action
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
}
}
});
And finally GridView.java:
package com.example.awesomefilebuilderwidget;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class GridView extends Activity { // implements OnItemLongClickListener, OnDragListener{
ArrayList<Integer> drawables = new ArrayList<Integer>();
private BaseAdapter adapter;
private int draggedIndex = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag_and_drop_app);
Log.d("GridView", "onCreate called");
drawables = new ArrayList<Integer>();
drawables.add(R.drawable.pattern1);
drawables.add(R.drawable.pattern2);
android.widget.GridView gridView = (android.widget.GridView) findViewById(R.id.grid_view);
// gridView.setOnItemLongClickListener(this);
gridView.setAdapter(adapter = new BaseAdapter() {
#Override
// Get a View that displays the data at the specified position in
// the data set.
public View getView(int position, View convertView,
ViewGroup gridView) {
// try to reuse the views.
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse
// it
if (view == null) {
view = new ImageView(GridView.this);
}
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap default_b = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
view.setImageBitmap(default_b);
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
#Override
// Get the row id associated with the specified position in the
// list.
public long getItemId(int position) {
return position;
}
#Override
// Get the data item associated with the specified position in the
// data set.
public Object getItem(int position) {
return drawables.get(position);
}
#Override
// How many items are in the data set represented by this Adapter.
public int getCount() {
return drawables.size();
}
});
}
/*#Override
public boolean onItemLongClick(AdapterView<?> gridView, View view,
int position, long row) {
ClipData.Item item = new ClipData.Item((String) view.getTag());
ClipData clipData = new ClipData((CharSequence) view.getTag(),
new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }, item);
view.startDrag(clipData, new View.DragShadowBuilder(view), null, 0);
View trashCan = findViewById(R.id.trash_can);
trashCan.setVisibility(View.VISIBLE);
trashCan.setOnDragListener(GridView.this);
trashCan.setOnDragListener(GridView.this);
draggedIndex = position;
return true;
}
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// Drag has started
// If called for trash resize the view and return true
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.0f);
view.animate().scaleY(1.0f);
return true;
} else // else check the mime type and set the view visibility
if (dragEvent.getClipDescription().hasMimeType(
ClipDescription.MIMETYPE_TEXT_PLAIN)) {
view.setVisibility(View.GONE);
return true;
} else {
return false;
}
case DragEvent.ACTION_DRAG_ENTERED:
// Drag has entered view bounds
// If called for trash can then scale it.
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.5f);
view.animate().scaleY(1.5f);
}
return true;
case DragEvent.ACTION_DRAG_EXITED:
// Drag exited view bounds
// If called for trash can then reset it.
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.0f);
view.animate().scaleY(1.0f);
}
view.invalidate();
return true;
case DragEvent.ACTION_DRAG_LOCATION:
// Ignore this event
return true;
case DragEvent.ACTION_DROP:
// Dropped inside view bounds
// If called for trash can then delete the item and reload the grid
// view
if (view.getId() == R.id.trash_can) {
drawables.remove(draggedIndex);
draggedIndex = -1;
}
adapter.notifyDataSetChanged();
case DragEvent.ACTION_DRAG_ENDED:
// Hide the trash can
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
findViewById(R.id.trash_can).setVisibility(View.GONE);
}
}, 1000l);
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.0f);
view.animate().scaleY(1.0f);
} else {
view.setVisibility(View.VISIBLE);
}
// remove drag listeners
view.setOnDragListener(null);
return true;
}
return false;
}*/
}
Please comment if you notice ANYTHING that doesn't seem right or that is wrong. I have been trying to fix this error for days and have tried the stackoverflow links here, here, here, and others on top of those.
Please help me to fix this error that I keep getting. I'm really at a loss at what to do now...
(Thanks for reading all of this too, I know it was a lot)
Here is my Utilities class:
package com.example.awesomefilebuilderwidget;
import java.util.List;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
public class Utilities {
/*
* Get all installed application on mobile and return a list
* #param c Context of application
* #return list of installed applications
*/
public static List<PackageInfo> getInstalledApplications(Context c) {
return c.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);
}
PackageManager methods, like getInstalledPackages(), can result in a binder transaction error, if the sum total of information being returned is greater than 1MB.
One way to mitigate this is to pass in no flags (e.g., skip PackageManager.GET_ACTIVITIES) to reduce the amount of data in the first call. Then, for those packages where you need the additional detail, call getPackageInfo() to get the details for a specific package. While this does involve multiple IPC round-trips, and therefore is slower, it will help prevent you from blowing out the 1MB-per-transaction limit.
It turned out that I was recieving too much information from the packageManager when I was getting the list of installed applications i.e.
Utilities.getInstalledApplications(this)
In my Utilities class. So then I thought that instead of getting ALL of the installed applications, that I should just get the users installed applications (excluding the system ones that are pointless for my use anyways). Here is the updated class:
public class Utilities {
/*
* Get all installed application on mobile and return a list
* #param c Context of application
* #return list of installed applications
*/
public static List<ResolveInfo> getInstalledApplications(Context c) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return c.getPackageManager().queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
}
Then of course any list with
<PackageInfo>
had to be changed to
<ResolveInfo>
but it worked like a charm!

Categories

Resources