I want to know something...
What's wrong about my ListView, the problem is when I perform a fast scroll sometimes my application stopped...
In my MainActivity extending the a4 class ----> that extends Activity class:
ArrayList<a> AL;
static ListView LV;
SearchView SV;
Toast TOAST;
TextView TV;
static boolean isEnglish;
private static boolean isSearching, canClear;
static MultiList newAdapter;
LinearLayout NV;
static RelativeLayout.LayoutParams PR;
ImageButton IB;
ImageView IV;
public void closeSearch(View view) {
if (!isSearching) return;
TV.setVisibility(0);
IB.setVisibility(8);
SV.onActionViewCollapsed();
PR.removeRule(9);
isSearching = false;
}
public void d(View view) {
num(true, 5, 0, 8);
}
public void e(View view) {
num(false, 6, 8, 0);
}
public void goInfo(View view) {
co(3);
}
public void goIns(View view) {
co(2);
}
public void goSet(View view) {
co(4);
}
public void goTools(View view) {
co(1);
}
void num(boolean bl, final int n, int n2, int n3) {
int n4 = 0;
isEnglish = bl;
AL = new ArrayList<a>();
newAdapter = new MultiList(this, true, AL);
findViewById(R.id.l1).setVisibility(n2);
findViewById(R.id.l2).setVisibility(n3);
LV.setAdapter(newAdapter);
LV.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> adapterView, View view, int ol, long l) {
rt(n, ol);
}
});
do {
if(bl){
if(n4 >= songs_e.length || n4 >= singers_e.length) return;
AL.add(new a(songs_e[n4], singers_e[n4]));
} else {
if(n4 >= artists.length) return;
AL.add(new a(artists[n4]));
}
++n4;
} while (true);
}
public void onBackPressed() {
if(isSearching) {
closeSearch(isViewed);
} else {
if (b0 < System.currentTimeMillis() - 1600L) {
TOAST = Toast.makeText(this, "Tap again to exit " + app, 0);
TOAST.show();
b0 = System.currentTimeMillis();
return;
} else {
if (TOAST != null) {
TOAST.cancel();
finish();
return;
}
}
}
}
#Override
protected void onCreate(Bundle bundle) {
show(4, R.layout.slist, q + app, 0);
LV = findViewById(R.id.lv);
SV = findViewById(R.id.search);
TV = findViewById(R.id.mytv);
NV = findViewById(R.id.llp);
PR = (RelativeLayout.LayoutParams)SV.getLayoutParams();
IB = findViewById(R.id.search_close);
IV = (ImageView)findViewById((View)SV, "android:id/search_close_btn");
final TextView actv = (TextView)findViewById(SV, "android:id/search_src_text");
actv.setBackgroundColor(-1);
ImageView imageView2 = (ImageView)findViewById((View)SV, "android:id/search_button");
imageView2.setImageResource(R.drawable.ic_search);
imageView2.setBackgroundColor(-12369085);
LV.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> av, View v, int n, long l){
return true;
}
});
IV.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
if(canClear){
actv.setText("");
}
}
});
d(isViewed);
newAdapter.initForMulti(R.layout.abc_listview, R.id.txt1, R.id.txt2, R.id.image, R.drawable.abc_tab);
SV.setLayoutParams(PR);
SV.setQueryHint(" Search songs and artists . . .");
SV.setOnSearchClickListener(new View.OnClickListener(){
public void onClick(View view) {
IV.setImageResource(R.drawable.search_clear_inactive);
TV.setVisibility(8);
canClear = false;
isSearching = true;
IB.setVisibility(0);
PR.addRule(9);
}
});
SV.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
public boolean onQueryTextChange(String string2) {
ArrayList<a> arrayList = new ArrayList<a>();
if(string2.equals((Object)"")) {
IV.setImageResource(R.drawable.search_clear_inactive);
canClear = false;
} else {
IV.setImageResource(R.drawable.search_clear_active);
canClear = true;
}
//Error for Tagalog, text is not for multi
for (a aa : MainActivity.this.AL) {
if (isEnglish && !aa.getFirst().toLowerCase().contains(string2) && !aa.getFirst().toUpperCase().contains(string2) && !aa.getFirst().contains(string2) && !aa.getLast().toLowerCase().contains(string2) && !aa.getLast().toUpperCase().contains(string2) && !aa.getLast().contains(string2) || !isEnglish && !aa.getLast().toLowerCase().contains(string2) && !aa.getLast().toUpperCase().contains(string2) && !aa.getLast().contains(string2)) continue;
arrayList.add(aa);
}
newAdapter.filterResult((ArrayList<a>)arrayList);
return false;
}
public boolean onQueryTextSubmit(String string2) {
return true;
}
});
MusicUtils.playAsset(this, "audios/a.ogg");
IV.setBackgroundColor(-12369085);
super.onCreate(bundle);
}
public void onPause() {
super.onPause();
closeSearch(isViewed);
if (in != 5 && in != 6) {
LV.setVisibility(4);
int n = 0;
do {
if (n >= 10) return;
LV.scrollListBy(-999999999);
++n;
} while (true);
}
}
//onRestart not included because it basically contains setVisibility
final void rt(int n, int n2) {
in = n;
Bundle bundle = new Bundle();
newAdapter.getLC(n2);
bundle.putString("First", newAdapter.list.getFirst());
bundle.putString("Last", newAdapter.list.getLast());
go(new Intent(this, ContProv.class).putExtras(bundle));
}
And for the custom list adapter:
private static Context Context;
private static ArrayList<a> ab;
private static int view, mText, mText1, mText2, mImage, mDrawable;
private static boolean listType;
public a list;
public MultiList(Context c, boolean isMultiText, ArrayList<a> array) {
if(c != null || array != null) {
Context = c;
listType = isMultiText;
ab = array;
}
}
public final void initForMulti(int layout, int text1ID, int text2ID, int imageID, int imageDrawable) {
view = layout;
mText1 = text1ID;
mText2 = text2ID;
mImage = imageID;
mDrawable = imageDrawable;
}
public final void initForNonMulti(int layout, int textID, int imageID, int imageDrawable){
view = layout;
mText = textID;
mImage = imageID;
mDrawable = imageDrawable;
}
public void filterResult(ArrayList<a> arrayList) {
ab = new ArrayList<a>();
ab.addAll((ArrayList<a>)arrayList);
notifyDataSetChanged();
}
public int getCount() {
return ab.size();
}
public Object getItem(int n) {
return null;
}
public long getItemId(int n) {
return 0L;
}
public a getLC(int n) {
return list = ab.get(n);
}
public View getView(int n, View v, ViewGroup vg) {
a newList = getLC(n);
v = View.inflate(Context, view, null);
((ImageView)v.findViewById(mImage)).setImageResource(mDrawable);
if(listType) {
((TextView)v.findViewById(mText1)).setText(newList.getFirst());
((TextView)v.findViewById(mText2)).setText(newList.getLast());
} else ((TextView)v.findViewById(mText)).setText(newList.getText());
return v;
}
Thank you for your help... I will really appreciate it... Also I need tips about the performance of my existing code and please write your answer in java and don't use support libraries cuz I want my application work for android phones below android 5...
Final:
I've found out that the problem is at my list adapter so I edited it into this:
package dn.widget;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import dn.widget.ListAdapter;
import dn.widget.a.a;
import java.util.ArrayList;
public class ListAdapter extends BaseAdapter {
private ArrayList<a> AR;
private static int N, N2, N3, N4, N5, N6;
private boolean LT;
public a L;
public ListAdapter(ArrayList<a> ar, boolean b) {
AR = ar;
LT = b;
}
public void isDual(int n, int n2, int n3, int n4, int n5) {
if (LT) {
N = n;
N3 = n2;
N4 = n3;
N5 = n4;
N6 = n5;
}
}
public void isSingle(int n, int n2, int n3, int n4){
if (!LT) {
N = n;
N2 = n2;
N4 = n3;
N5 = n4;
}
}
public void filterResult(ArrayList<a> ar) {
if(AR != null) {
AR = new ArrayList<a>();
AR.addAll((ArrayList<a>)ar);
notifyDataSetChanged();
}
}
public int getCount() {
return AR.size();
}
public Object getItem(int n) {
return null;
}
public long getItemId(int n) {
return 0L;
}
public a getLC(int n) {
L = AR.get(n);
return L;
}
static class LH {
private ImageView I;
private TextView T, T1, T2;
}
#Override
public View getView(int n, View v, ViewGroup g) {
getLC(n);
final LH h;
if(v == null) {
v = View.inflate(g.getContext(), N, null);
h = new LH();
h.I = v.findViewById(N5);
h.T = v.findViewById(N2);
h.T1 = v.findViewById(N3);
h.T2 = v.findViewById(N4);
h.I.setImageResource(N6);
v.setTag(h);
} else {
h = (LH)v.getTag();
}
if(LT) {
h.T1.setText(L.f());
h.T2.setText(L.l());
} else h.T.setText(L.t());
return v;
}
}
Related
So I am relatively new to programming, and I have been working on this task app, where I want to save the data such as task name and more, given by the user. I am trying to accomplish this using Room. Now, initially, when I tried to do it, the app would crash since I was doing everything on the main thread probably. So, after a little research, I came to AsyncTask, but that is outdated. Now finally I have come across the Executer. I created a class for it, but I am a little unsure as to how I can implement it in my app. This is what I did :
Entity Class :
#Entity (tableName = "subtasks")
public class SubtaskDetails {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "subtaskName")
private String subtasksName;
#ColumnInfo(name = "priority")
private boolean priHigh;
private boolean priMed;
private boolean priLow;
#ColumnInfo(name = "time")
private boolean timeMore;
private boolean timeMed;
private boolean timeLess;
public SubtaskDetails(String subtasksName, boolean priHigh, boolean priMed, boolean priLow, boolean timeMore, boolean timeMed, boolean timeLess){
this.subtasksName = subtasksName;
this.priHigh = priHigh;
this.priMed = priMed;
this.priLow = priLow;
this.timeMore = timeMore;
this.timeMed = timeMed;
this.timeLess = timeLess;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSubtasksName() {
return subtasksName;
}
public void setSubtasksName(String subtasksName) {
this.subtasksName = subtasksName;
}
public boolean isPriHigh() {
return priHigh;
}
public void setPriHigh(boolean priHigh) {
this.priHigh = priHigh;
}
public boolean isPriMed() {
return priMed;
}
public void setPriMed(boolean priMed) {
this.priMed = priMed;
}
public boolean isPriLow() {
return priLow;
}
public void setPriLow(boolean priLow) {
this.priLow = priLow;
}
public boolean isTimeMore() {
return timeMore;
}
public void setTimeMore(boolean timeMore) {
this.timeMore = timeMore;
}
public boolean isTimeMed() {
return timeMed;
}
public void setTimeMed(boolean timeMed) {
this.timeMed = timeMed;
}
public boolean isTimeLess() {
return timeLess;
}
public void setTimeLess(boolean timeLess) {
this.timeLess = timeLess;
}
}
Dao Class:
#Dao
public interface UserDao {
#Query("Select * from subtasks")
List<SubtaskDetails> getSubtaskDetailsList();
#Insert
void insertSubtaskDetails(SubtaskDetails subtaskDetails);
#Update
void updateSubtaskDetails(SubtaskDetails subtaskDetails);
#Delete
void deleteSubtaskDetails(SubtaskDetails subtaskDetails);
}
App Database Class :
#Database(entities = SubtaskDetails.class, exportSchema = false, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static final String DB_NAME = "subtaskdetails_db";
private static AppDatabase instance;
public static synchronized AppDatabase getInstance(Context context){
if (instance == null){
instance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DB_NAME).fallbackToDestructiveMigration().build();
}
return instance;
}
public abstract UserDao subtaskdetailsdao();
}
Executer Class :
public class AppExecutors {
// For Singleton instantiation
private static final Object LOCK = new Object();
private static AppExecutors sInstance;
private final Executor diskIO;
private final Executor mainThread;
private final Executor networkIO;
private AppExecutors(Executor diskIO, Executor networkIO, Executor mainThread) {
this.diskIO = diskIO;
this.networkIO = networkIO;
this.mainThread = mainThread;
}
public static AppExecutors getInstance() {
if (sInstance == null) {
synchronized (LOCK) {
sInstance = new AppExecutors(Executors.newSingleThreadExecutor(),
Executors.newFixedThreadPool(3),
new MainThreadExecutor());
}
}
return sInstance;
}
public Executor diskIO() {
return diskIO;
}
public Executor mainThread() {
return mainThread;
}
public Executor networkIO() {
return networkIO;
}
private static class MainThreadExecutor implements Executor {
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
#Override
public void execute(#NonNull Runnable command) {
mainThreadHandler.post(command);
}
}
}
Where I try to implement it : (I have written a comment where I do it)
public class TaskInfo extends AppCompatActivity {
//Declaring variables
EditText etWorkingHours, etWorkingMinutes, etTaskName, etWorkingMins, etWorkinghrs, etSubtaskName;
Button btnNewSubtask;
Button btnSaveTaskName;
Button btnProceed;
ImageView ivLeft, ivRight;
TextView tvBreakTime;
TextView tvTaskName;
int breaktime = 10;
final int ENTER_SUBTASK = 20;
final int EDIT_SUBTASK = 40;
ListView lvSubtasks;
ArrayList<subtask> subtaskList = new ArrayList<>();
ScrollView scrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_info);
//Connecting XML to JAVA
etWorkingHours = findViewById(R.id.etWorkingHours);
etWorkingMinutes = findViewById(R.id.etWorkingMinutes);
etTaskName = findViewById(R.id.etTaskName);
btnNewSubtask = findViewById(R.id.btnNewSubtask);
ivLeft = findViewById(R.id.ivLeft);
ivRight = findViewById(R.id.ivRight);
tvBreakTime = findViewById(R.id.tvBreakTime);
etWorkinghrs = findViewById(R.id.etWorkingHrs);
etWorkingMins = findViewById(R.id.etWorkingMins);
lvSubtasks = findViewById(R.id.lvSubtasks);
scrollView = findViewById(R.id.scrollView);
btnSaveTaskName = findViewById(R.id.btnSaveTask);
tvTaskName = findViewById(R.id.tvTaskName);
btnProceed = findViewById(R.id.btnProceed);
tvTaskName.setVisibility(View.INVISIBLE);
if (tvTaskName.getText().equals(""))
{
tvTaskName.setClickable(false);
}
else
{
tvTaskName.setClickable(true);
}
// Code for the left right arrows along with break duration
ivRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (breaktime >= 10 && breaktime < 60)
{breaktime += 5;
String time = breaktime + "";
tvBreakTime.setText(time);}
else
{
String time = breaktime + "";
tvBreakTime.setText(time);
}
}
});
ivLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (breaktime > 10 && breaktime <= 60)
{
breaktime -= 5;
String time = breaktime + "";
tvBreakTime.setText(time);}
else
{
String time = breaktime + "";
tvBreakTime.setText(time);
}
}
});
btnNewSubtask.setEnabled(false);
btnSaveTaskName.setEnabled(false);
//save button enabler when task name is written
etTaskName.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) {
btnSaveTaskName.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSaveTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTaskName.setVisibility(View.VISIBLE);
tvTaskName.setText(etTaskName.getText().toString().toUpperCase().trim());
etTaskName.setVisibility(View.GONE);
btnSaveTaskName.setVisibility(View.GONE);
btnNewSubtask.setEnabled(true);
}
});
tvTaskName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tasksname = tvTaskName.getText().toString().trim();
tvTaskName.setText("");
etTaskName.setVisibility(View.VISIBLE);
etTaskName.setText(tasksname);
btnSaveTaskName.setVisibility(View.VISIBLE);
}
});
btnNewSubtask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(TaskInfo.this, SubtaskActivity.class);
startActivityForResult(i2, ENTER_SUBTASK);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
btnProceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etWorkingHours.getText().toString().isEmpty())
{
etWorkingHours.setText("0");
}
if (etWorkingMinutes.getText().toString().isEmpty())
{
etWorkingMinutes.setText("0");
}
if (etWorkinghrs.getText().toString().isEmpty())
{
etWorkinghrs.setText("0");
}
if (etWorkingMins.getText().toString().isEmpty())
{
etWorkingMins.setText("0");
}
int working_hours = Integer.parseInt(etWorkinghrs.getText().toString().trim());
int working_minutes = Integer.parseInt(etWorkingMins.getText().toString().trim());
int without_break_hours = Integer.parseInt(etWorkingHours.getText().toString().trim());
int without_break_minutes = Integer.parseInt(etWorkingMinutes.getText().toString().trim());
if (etWorkingHours.getText().toString().isEmpty() || etWorkingMinutes.getText().toString().isEmpty() || etWorkinghrs.getText().toString().isEmpty() || etWorkingMins.getText().toString().isEmpty())
{
Toast.makeText(TaskInfo.this, "Field cannot be empty, please try again.", Toast.LENGTH_SHORT).show();
}
else
{
if (working_hours != 0)
{
if (working_hours > without_break_hours)
{
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
startActivity(intent);
}
if (working_hours == without_break_hours){
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours < without_break_hours){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (working_hours == 0){
if (without_break_hours == 0)
{
if (working_minutes >= without_break_minutes){
int breaktime = Integer.parseInt(tvBreakTime.getText().toString());
Intent intent = new Intent(TaskInfo.this, TaskSummary.class);
intent.putExtra("working_hours", working_hours);
intent.putExtra("working_minutes", working_minutes);
intent.putExtra("without_break_hours", without_break_hours);
intent.putExtra("without_break_minutes", without_break_minutes);
intent.putExtra("break_duration", breaktime);
startActivity(intent);
}
if (working_minutes < without_break_minutes){
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
if (without_break_hours != 0)
{
Toast.makeText(TaskInfo.this, "Invalid Time Entered", Toast.LENGTH_SHORT).show();
}
}
}
}
});
//Applying the max min thing for which the class InputFilterMinMax is defined
etWorkingHours.setFilters(new InputFilter[]{new InputFilterMinMax("0", "24")});
etWorkingMinutes.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
etWorkinghrs.setFilters(new InputFilter[]{new InputFilterMinMax("0", "24")});
etWorkingMins.setFilters(new InputFilter[]{new InputFilterMinMax("0", "59")});
}
// This is where I try to implement the executer :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ENTER_SUBTASK)
{
if (resultCode == RESULT_OK)
{
SubtaskAdapter adapter = new SubtaskAdapter(this, subtaskList);
assert data != null;
String subtaskName = data.getStringExtra("subtaskName");
boolean priHigh = data.getBooleanExtra("priHigh", false);
boolean priMed = data.getBooleanExtra("priMed", false);
boolean priLow = data.getBooleanExtra("priLow", false);
boolean timeMore = data.getBooleanExtra("timeMore", false);
boolean timeMed = data.getBooleanExtra("timeMed", false);
boolean timeLess = data.getBooleanExtra("timeLess", false);
AppDatabase appDb = AppDatabase.getInstance(this);
AppExecutors.getInstance().diskIO().execute(new Runnable() {
#Override
public void run() {
SubtaskDetails subtaskDetails = new SubtaskDetails(subtaskName,priHigh, priMed, priLow, timeMore, timeMed, timeLess);
appDb.subtaskdetailsdao().insertSubtaskDetails(subtaskDetails);
}
});
lvSubtasks.setAdapter(adapter);
subtask subtask = new subtask(subtaskName, priHigh, priMed, priLow, timeMore, timeMed, timeLess);
subtaskList.add(subtask);
adapter.addANewSubTask(subtask);
}
}
}
// Menu (action bar) code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case (R.id.settings):
startActivity(new Intent(this, SettingsActivity.class));
break;
}
return super.onOptionsItemSelected(item);
}
//Class to make max and min value on the edit text of hours and minutes, so that they cant enter anything more than 24 hours, and 59 minutes
static class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
}
EDIT :
I implemented the code, but I am facing a few issues in the viewmodel class. For eg, the parameter in repository.insertSubtaskDetails(userDao); is userDao, but it actually it requires of type subtaskDetails.. some errors in the todo part as well. this is the code:
package com.example.taskmasterv3;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import java.util.List;
public class ViewModel extends AndroidViewModel {
private Repository repository;
private List<SubtaskDetails> subtaskDetails;
public ViewModel(#NonNull Application application) {
super(application);
repository = new Repository(application);
subtaskDetails = repository.getSubtaskDetails();
}
public void insert(UserDao userDao) {
repository.insertSubtaskDetails(userDao);
}
public void delete(Todo todo) {
repository.deleteSubtaskDetails(userDao);
}
}
First make a Repository class and make an instance of your DAO
public class Repository {
private UserDAO userDAO;
private List<SubtaskDetails> subtaskDetails;
private Executor executor = Executors.newSingleThreadExecutor();
public Repository(Application application){
AppDatabase appDatabase = AppDatabase.getInstance(application);
userDAO = appDatabase.userDAO();
subtaskDetails = userDAO.getSubtaskDetailsList();
}
Then wrap it around your executor
public void insertSubtaskDetails(SubtaskDetails subtaskDetails){
executor.execute(new Runnable() {
#Override
public void run() {
userDAO.insertSubtaskDetails(subtaskDetails);
}
});
}// For inserting
public void deleteSubtaskDetails(SubtaskDetails subtaskDetails){
executor.execute(new Runnable() {
#Override
public void run() {
userDAO.deleteSubtaskDetails(subtaskDetails);
}
});
}// for deleting
Basically just wrap your DAO queries around the executor.
I want to add Different layout between item in my recyclerview, I have 3 item in first layout, and then I add second layout to item number 2, so It should have 4 item right now, (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)-(4FirstLayout), but I realize the position that I choose from my second layout replaced to the position first layout it becomes like this (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)
Iam not sure how to fix it
This is my Adapter
public class AdapterGameReview extends RecyclerView.Adapter{
public static final int TYPE_ITEM = 1;
public static final int TYPE_TOPREVIEWER = 2;
public static final int TYPE_ADSBANNER = 3;
private boolean mWithTopReviewer = true;
private boolean mWithAdsBanner = false;
private Context mContext;
private ArrayList<ModelGameReview> modelGameReviews;
private RecyclerViewClickListener mListener;
public AdapterGameReview(Context mContext, ArrayList<ModelGameReview> modelGameReviews, RecyclerViewClickListener mListener) {
this.mContext = mContext;
this.modelGameReviews = modelGameReviews;
this.mListener = mListener;
}
//Container
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = null;
if (viewType == TYPE_TOPREVIEWER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereviewtopreviewer, null);
return new GameReviewTopReviewerViewHolder(v);
} else if (viewType == TYPE_ADSBANNER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_adsbannerdummy, null);
return new GameReviewAdsBannerViewHolder(v);
} else {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereview, null);
return new GameReviewViewHolder(v, mListener);
}
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof AdapterGameReview.GameReviewTopReviewerViewHolder) {
AdapterGameReview.GameReviewTopReviewerViewHolder gameReviewTopReviewerViewHolder = (AdapterGameReview.GameReviewTopReviewerViewHolder) holder;
/*gameReviewTopReviewerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});*/
}else if (holder instanceof AdapterGameReview.GameReviewAdsBannerViewHolder) {
AdapterFollowSavedGameReviewList.ShowmoreViewHolder showmoreViewHolder = (AdapterFollowSavedGameReviewList.ShowmoreViewHolder) holder;
} else {
final GameReviewViewHolder GameReviewViewHolder = (GameReviewViewHolder) holder;
final ModelGameReview modelGameReviewX = modelGameReviews.get(position);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.mipmap.ic_launcher);
requestOptions.error(R.drawable.bug);
requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
requestOptions.centerCrop();
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = inputFormat.parse(modelGameReviewX.getGamedate());
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence niceDateStr = DateUtils.getRelativeTimeSpanString(date.getTime(), Calendar.getInstance().getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS);
//Set
GameReviewViewHolder.TVGameDate.setText(niceDateStr);
GameReviewViewHolder.TVGameTitle.setText(modelGameReviewX.getGametitle());
GameReviewViewHolder.TVGameDescription.setText(modelGameReviewX.getGamedescription());
Glide.with(mContext).load(modelGameReviewX.getGameimage())
.apply(requestOptions)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
})
.transition(DrawableTransitionOptions.withCrossFade())
.into(GameReviewViewHolder.IMGGameImage);
GameReviewViewHolder.TVSeenCounter.setText(String.valueOf(modelGameReviewX.getSeencounter()));
GameReviewViewHolder.TVCommentCounter.setText(String.valueOf(modelGameReviewX.getCommentcounter()));
GameReviewViewHolder.TVLikeCounter.setText(String.valueOf(modelGameReviewX.getLikecounter()));
if (modelGameReviewX.getIscomment() == 0) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_off);
} else if (modelGameReviewX.getIscomment() == 1) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_on);
}
if (modelGameReviewX.getIslike() == 0) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_off);
} else if (modelGameReviewX.getIslike() == 1) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_on);
}
if (modelGameReviewX.getIsbookmark() == 0) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_off);
GameReviewViewHolder.IMGBookmarkView.setVisibility(View.GONE);
} else if (modelGameReviewX.getIsbookmark() == 1) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_on);
}
GameReviewViewHolder.TVReviewer.setText(modelGameReviewX.getReviewer());
}
}
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
//TYPE_ITEM
public class GameReviewViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView TVGameDate;
TextView TVGameTitle;
TextView TVGameDescription;
ImageView IMGGameImage;
TextView TVSeenCounter;
TextView TVCommentCounter;
TextView TVLikeCounter;
ImageView IMGSeenView;
ImageView IMGCommentView;
ImageView IMGLikeView;
TextView TVReviewer;
ProgressBar ProgressLoadPhoto;
ImageView IMGBookmarkView;
private RelativeLayout ROWGameReviewContainer;
private RecyclerViewClickListener mListener;
public GameReviewViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameTitle = itemView.findViewById(R.id.TV_GameTitle);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
TVSeenCounter = itemView.findViewById(R.id.TV_SeenCounter);
TVCommentCounter = itemView.findViewById(R.id.TV_CommentCounter);
TVLikeCounter = itemView.findViewById(R.id.TV_LikeCounter);
IMGSeenView = itemView.findViewById(R.id.IMG_SeenView);
IMGCommentView = itemView.findViewById(R.id.IMG_CommentView);
IMGLikeView = itemView.findViewById(R.id.IMG_LikeView);
TVReviewer = itemView.findViewById(R.id.TV_Reviewer);
ProgressLoadPhoto = itemView.findViewById(R.id.Progress_LoadPhoto);
IMGBookmarkView = itemView.findViewById(R.id.IMG_BookmarkView);
ROWGameReviewContainer = itemView.findViewById(R.id.ROW_GameReviewContainer);
mListener = listener;
ROWGameReviewContainer.setOnClickListener(this);
IMGCommentView.setOnClickListener(this);
IMGLikeView.setOnClickListener(this);
IMGBookmarkView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ROW_GameReviewContainer:
mListener.onRowGameReviewContainerClick(ROWGameReviewContainer, getAdapterPosition());
break;
case R.id.IMG_CommentView:
mListener.onRowCommentViewClick(IMGCommentView, getAdapterPosition());
break;
case R.id.IMG_LikeView:
mListener.onRowLikeViewClick(IMGLikeView, getAdapterPosition());
break;
case R.id.IMG_BookmarkView:
mListener.onRowBookmarkViewClick(IMGBookmarkView, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowGameReviewContainerClick(View view, int position);
void onRowCommentViewClick(View view, int position);
void onRowLikeViewClick(View view, int position);
void onRowBookmarkViewClick(View view, int position);
}
//TYPE_TOPREVIEWER
public class GameReviewTopReviewerViewHolder extends RecyclerView.ViewHolder{
Button BTNToBeReviewer;
public GameReviewTopReviewerViewHolder(View itemView) {
super(itemView);
BTNToBeReviewer = itemView.findViewById(R.id.BTN_ToBeReviewer);
}
}
//TYPE_ADSBANNER
public class GameReviewAdsBannerViewHolder extends RecyclerView.ViewHolder{
public GameReviewAdsBannerViewHolder(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (mWithTopReviewer && isPositionTopReviewer(position))
return TYPE_TOPREVIEWER;
if (mWithAdsBanner && isPositionAdsBanner(position))
return TYPE_ADSBANNER;
return TYPE_ITEM;
}
public boolean isPositionTopReviewer(int position) {
return position == 1 && mWithTopReviewer;
}
public boolean isPositionAdsBanner(int position) {
return position == getItemCount() - 1 && mWithAdsBanner;
}
public void setWithTopReviewer(boolean value) {
mWithTopReviewer = value;
}
public void setWithAdsBanner(boolean value) {
mWithAdsBanner = value;
}
}
This is My Model
public class ModelGameReview implements Serializable {
private int contentpage;
private String idcontent;
private String gametitle;
private String gamedate;
private String gameimage;
private String gamedescription;
private int seencounter;
private int commentcounter;
private int likecounter;
private int iscomment;
private int islike;
private int isbookmark;
private String reviewer;
private String value;
private String message;
public ModelGameReview(int contentpage, String idcontent, String gametitle, String gamedate, String gameimage, String gamedescription, int seencounter, int commentcounter, int likecounter, int iscomment, int islike, int isbookmark, String reviewer, String value, String message) {
this.contentpage = contentpage;
this.idcontent = idcontent;
this.gametitle = gametitle;
this.gamedate = gamedate;
this.gameimage = gameimage;
this.gamedescription = gamedescription;
this.seencounter = seencounter;
this.commentcounter = commentcounter;
this.likecounter = likecounter;
this.iscomment = iscomment;
this.islike = islike;
this.isbookmark = isbookmark;
this.reviewer = reviewer;
this.value = value;
this.message = message;
}
public int getContentpage() {
return contentpage;
}
public void setContentpage(int contentpage) {
this.contentpage = contentpage;
}
public String getIdcontent() {
return idcontent;
}
public void setIdcontent(String idcontent) {
this.idcontent = idcontent;
}
public String getGametitle() {
return gametitle;
}
public void setGametitle(String gametitle) {
this.gametitle = gametitle;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGameimage() {
return gameimage;
}
public void setGameimage(String gameimage) {
this.gameimage = gameimage;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getSeencounter() {
return seencounter;
}
public void setSeencounter(int seencounter) {
this.seencounter = seencounter;
}
public int getCommentcounter() {
return commentcounter;
}
public void setCommentcounter(int commentcounter) {
this.commentcounter = commentcounter;
}
public int getLikecounter() {
return likecounter;
}
public void setLikecounter(int likecounter) {
this.likecounter = likecounter;
}
public int getIscomment() {
return iscomment;
}
public void setIscomment(int iscomment) {
this.iscomment = iscomment;
}
public int getIslike() {
return islike;
}
public void setIslike(int islike) {
this.islike = islike;
}
public int getIsbookmark() {
return isbookmark;
}
public void setIsbookmark(int isbookmark) {
this.isbookmark = isbookmark;
}
public String getReviewer() {
return reviewer;
}
public void setReviewer(String reviewer) {
this.reviewer = reviewer;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
You have implemented this method wrong
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
It should be something similar
#Override
public int getItemCount() {
int itemCount = modelGameReviews.size();
if(mWithTopReviewer == true){
itemCount++;
}
return itemCount;
}
i am scanning devices from a bluetooth and getting their data from their advertisement,so one of the device gives the data of other devices which is not in ranged from the mobile device,so i specifically filter the data of that device which i wanted to show in recycler view in automatically updating the rssi values.
let's say,
a device A which gives the data of 3 devices B,C,D containing their rssi values continuously,so what i want to show the list of device B,C,D with their rssi values which is changing continuously.
What i have done until now is scan that device "A",and extract the data of B and shown in recyclerview,but when another device i.e C's data comes in the old device i.e B got vanished and so on.
what i want is continuously changing data of B,C,D.
Adapter Class:-
public class ReapeaterDeviceAdapter extends RecyclerView.Adapter<ReapeaterDeviceAdapter.CryptoViewHolder> {
private ArrayList<RepeaterModel> data = new ArrayList<>();;
private Context mCtx;
public class CryptoViewHolder extends RecyclerView.ViewHolder {
private TextView mName, mPrice;
public CryptoViewHolder(View itemView) {
super(itemView);
mName = itemView.findViewById(R.id.txtName);
mPrice = itemView.findViewById(R.id.txtPrice);
}
}
public ReapeaterDeviceAdapter(Context ctx,ArrayList<RepeaterModel> data) {
this.mCtx = ctx;
this.data = data;
}
#Override
public CryptoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.repeater_dev_data,parent, false);
return new CryptoViewHolder(itemView);
}
#Override
public void onBindViewHolder(CryptoViewHolder holder, int position) {
System.out.println("onBinder");
holder.mName.setText(data.get(position).macdev);
holder.mPrice.setText(String.valueOf(data.get(position).rssi));
}
#Override
public void onBindViewHolder(CryptoViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
//System.out.println("onbinder");
super.onBindViewHolder(holder, position, payloads);
} else {
Bundle o = (Bundle) payloads.get(0);
//System.out.println("in keyset");
for (String key : o.keySet()) {
if (key.equals("price")) {
holder.mName.setText(data.get(position).macdev);
holder.mPrice.setText(String.valueOf(data.get(position).rssi));
//holder.mPrice.setTextColor(Color.GREEN);
//this.notifyItemChanged(position);
}
}
}
}
#Override
public int getItemCount() {
return data.size();
}
public ArrayList<RepeaterModel> getData() {
return data;
}
public void setData(ArrayList<RepeaterModel> newData) {
MyDiffUtilCallBack diffCallBack = new MyDiffUtilCallBack(newData, this.data);
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallBack);
//this.setData(newData);
// this.data=newData;
this.data.clear();
// this.data = newData;
this.data.addAll(newData);
diffResult.dispatchUpdatesTo(this);
//this.notifyItemRangeChanged(0, this.getItemCount());
//this.notifyDataSetChanged();
//System.out.println("Here");
}
}
Model Class:-
public String macdev;
public int rssi ;
public int imageid;
public RepeaterModel(String macdev, int rssi, int imageid) {
this.macdev = macdev;
this.rssi = rssi;
this.imageid = imageid;
}
public String getMacdev() {
return macdev;
}
public void setMacdev(String macdev) {
this.macdev = macdev;
}
public int getRssi() {
return rssi;
}
public void setRssi(int rssi) {
this.rssi = rssi;
}
public int getImageid() {
return imageid;
}
public void setImageid(int imageid) {
this.imageid = imageid;
}
#Override
public boolean equals(Object o) {
System.out.println("in equals");
if (this == o) return true;
if (!(o instanceof RepeaterModel)) return false;
RepeaterModel that = (RepeaterModel) o;
return getRssi() == that.getRssi() &&
getImageid() == that.getImageid() &&
getMacdev().equals(that.getMacdev());
}
#Override
public int hashCode() {
return Objects.hash(getMacdev(), getRssi(), getImageid());
}
/*#Override
public int hashCode() {
int result = Integer.valueOf(rssi);
// result = result + (imageid != 0 ? imageid.hashCode() : 0);
result = result + rssi.hashCode();
System.out.println("hash");
return result;
}*/
}
Diffutilcallback :-
ArrayList<RepeaterModel> newList;
ArrayList<RepeaterModel> oldList;
public MyDiffUtilCallBack(ArrayList<RepeaterModel> newList, ArrayList<RepeaterModel> oldList) {
this.newList = newList;
this.oldList = oldList;
}
#Override
public int getOldListSize() {
return oldList != null ? oldList.size() : 0;
}
#Override
public int getNewListSize() {
return newList != null ? newList.size() : 0;
}
#Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
if(newList.get(newItemPosition).getMacdev().equals(oldList.get(oldItemPosition).getMacdev()))
{
// Log.d("itemsame","in same");
return true;
}
else {
// Log.d("itemsame", "not same");
}
return false;
}
#Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition)
{
//System.out.println("in content same");
final RepeaterModel oldRepeater = oldList.get(oldItemPosition);
final RepeaterModel newRepeater = newList.get(newItemPosition);
if(oldRepeater.getRssi()!=(newRepeater.getRssi()))
{
//Log.d("item contenets","content different");
return false;
}
//Log.d("item contenets","content same");
return true;
}
#Nullable
#Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
RepeaterModel newModel = newList.get(newItemPosition);
RepeaterModel oldModel = oldList.get(oldItemPosition);
//System.out.println("getchange");
Bundle diff = new Bundle();
//if (newModel.getMacdev().equals(oldModel.getMacdev()))
//{
//System.out.println("getchange");
if (newModel.getRssi()!=(oldModel.getRssi())) {
diff.putInt("price", newModel.getRssi());
}
if (diff.size() == 0) {
return null;
}
// }
return diff;
//return super.getChangePayload(oldItemPosition, newItemPosition);
}
}```
Activity Class:-
public class RepeaterAdvertise extends AppCompatActivity {
private static BluetoothAdapter mBluetoothAdapter;
private static BluetoothLeScanner mLEScanner;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
private static boolean mScanning;
private static Handler mHandler;
private static final long SCAN_TIMEOUT = 20000;
public DevData data;
public Button cc;
//List<BluetoothDevice> mBluetoothDevice;
RecyclerView recyclerView;
ReapeaterDeviceAdapter reapeaterDeviceAdapter;
ArrayList<RepeaterModel> modelArrayList;// = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repeater_advertise);
modelArrayList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.devdata);
//dummyData();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
reapeaterDeviceAdapter = new ReapeaterDeviceAdapter(RepeaterAdvertise.this, modelArrayList);
recyclerView.setAdapter(reapeaterDeviceAdapter);
mHandler = new Handler();
final Intent intent = getIntent();
data = (DevData) intent.getSerializableExtra(SINGLE_DEV_DATA);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false,data.getMac_address());
}
#Override
protected void onResume() {
super.onResume();
scanLeDevice(true,data.getMac_address());
}
private void scanLeDevice(final boolean enable,String mac) {
if (enable) { // enable set to start scanning
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if(mScanning) {
mScanning = false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//noinspection deprecation
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
invalidateOptionsMenu();
}
}
}, SCAN_TIMEOUT);
mScanning = true;
UUID[] motorServiceArray = {PSoCBleRobotService.getMotorServiceUUID()};
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//noinspection deprecation
mBluetoothAdapter.startLeScan(motorServiceArray, mLeScanCallback);
} else { // New BLE scanning introduced in LOLLIPOP
ScanSettings settings;
List<ScanFilter> filters;
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<>();
//ScanFilter filter = new ScanFilter.Builder().setServiceUuid(PUuid).build();
//ScanFilter filter = new ScanFilter.Builder().setManufacturerData(89,new byte[] {}).build();
ScanFilter filter = new ScanFilter.Builder().setDeviceAddress(mac).build();
filters.add(filter);
if(mLEScanner==null)
{
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
mLEScanner.startScan(filters, settings, mScanCallback);
}
} else { // enable set to stop scanning
if(mScanning) {
mScanning = false;
if (Build.VERSION.SDK_INT < 21) {
//noinspection deprecation
mBluetoothAdapter.stopLeScan(mLeScanCallback);
} else {
mLEScanner.stopScan(mScanCallback);
}
}
}
invalidateOptionsMenu();
}
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run()
{
byte[] haha = scanRecord;
/* if(!mBluetoothDevice.contains(device))
{
//only add new devices
mBluetoothDevice.add(device);
mBleName.add(device.getName());
mBleArrayAdapter.notifyDataSetChanged(); // Update the list on the screen
}*/
}
});
}
};
public static String SbytesToHex(SparseArray<byte[]> bytes) {
StringBuilder builder = new StringBuilder();
byte[] dd = bytes.valueAt(0);
for (byte b: dd)
{
builder.append(String.format("%02x", b));
}
//System.out.println( dd.length);
return builder.toString();
}
public final ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
ScanRecord scanRecord = result.getScanRecord();
// mBluetoothDevice.add(result.getDevice());
SparseArray<byte[]> dataw = scanRecord.getManufacturerSpecificData();
if (dataw.size() > 0) {
//populate_devData(SbytesToHex(dataw));
String data = SbytesToHex(dataw);
ArrayList<RepeaterModel> repeaterModels= new ArrayList<>();
int rssi = Integer.valueOf(data.substring(12, 14), 16) - 256;
repeaterModels.add(new RepeaterModel(data.substring(0, 12), rssi, 1));
insert(repeaterModels);
} else if (false) {
//alertDialog.dismiss();
final Intent intent = new Intent(RepeaterAdvertise.this, ConfigurationView.class);
intent.putExtra(EXTRAS_BLE_ADDRESS, data.getMac_address());
intent.putExtra(EXTRAS_BLE_NAME, data.getName());
intent.putExtra(SINGLE_DEV_DATA, data.getDev_data());
scanLeDevice(false, data.getMac_address());
//mconfig=false;
startActivity(intent);
}
}
};
public void insert(ArrayList<RepeaterModel> rr)
{
modelArrayList.addAll(rr);
reapeaterDeviceAdapter.setData(rr);
}
}
add this line in insert function reapeaterDeviceAdapter.notifyDataSetChanged();
public void insert(ArrayList<RepeaterModel> rr){
modelArrayList.addAll(rr);
reapeaterDeviceAdapter.setData(rr);
reapeaterDeviceAdapter.notifyDataSetChanged();
}
In my application i'm trying to pass an parcelable array list to a sectioned recycler view adapter but inside the add method where we add sections it gives me required string error:
This is my parcelable class:
public class HostBean implements Parcelable {
public static final String EXTRA = ActivityMain.PKG + ".extra";
public static final String EXTRA_POSITION = ActivityMain.PKG + ".extra_position";
public static final String EXTRA_HOST = ActivityMain.PKG + ".extra_host";
public static final String EXTRA_TIMEOUT = ActivityMain.PKG + ".network.extra_timeout";
public static final String EXTRA_HOSTNAME = ActivityMain.PKG + ".extra_hostname";
public static final String EXTRA_BANNERS = ActivityMain.PKG + ".extra_banners";
public static final String EXTRA_PORTSO = ActivityMain.PKG + ".extra_ports_o";
public static final String EXTRA_PORTSC = ActivityMain.PKG + ".extra_ports_c";
public static final String EXTRA_SERVICES = ActivityMain.PKG + ".extra_services";
public static final int TYPE_GATEWAY = 0;
public static final int TYPE_COMPUTER = 1;
public int deviceType = TYPE_COMPUTER;
public int isAlive = 1;
public int position = 0;
public int responseTime = 0; // ms
public String ipAddress = null;
public String hostname = null;
public String hostsection = null;
public String hardwareAddress = NetInfo.NOMAC;
public String nicVendor = "Unknown";
public String os = "Unknown";
public HashMap<Integer, String> services = null;
public HashMap<Integer, String> banners = null;
public ArrayList<Integer> portsOpen = null;
public ArrayList<Integer> portsClosed = null;
public HostBean() {
// New object
}
public HostBean(Parcel in) {
// Object from parcel
readFromParcel(in);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(deviceType);
dest.writeInt(isAlive);
dest.writeString(ipAddress);
dest.writeString(hostname);
dest.writeString( hostsection );
dest.writeString(hardwareAddress);
dest.writeString(nicVendor);
dest.writeString(os);
dest.writeInt(responseTime);
dest.writeInt(position);
dest.writeMap(services);
dest.writeMap(banners);
dest.writeList(portsOpen);
dest.writeList(portsClosed);
}
private void readFromParcel(Parcel in) {
deviceType = in.readInt();
isAlive = in.readInt();
ipAddress = in.readString();
hostname = in.readString();
hardwareAddress = in.readString();
nicVendor = in.readString();
os = in.readString();
hostsection=in.readString();
responseTime = in.readInt();
position = in.readInt();
services = in.readHashMap(null);
banners = in.readHashMap(null);
portsOpen = in.readArrayList(Integer.class.getClassLoader());
portsClosed = in.readArrayList(Integer.class.getClassLoader());
}
#SuppressWarnings("unchecked")
public static final Creator CREATOR = new Creator() {
public HostBean createFromParcel(Parcel in) {
return new HostBean(in);
}
public HostBean[] newArray(int size) {
return new HostBean[size];
}
};
}
This is my simple adapter class:
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private ArrayList<HostBean> mData;
final HostBean host = new HostBean();
public void add(HostBean s,int position) {
position = position == -1 ? getItemCount() : position;
host.hostsection=s;
mData.add(position,s); //at this line of code i'm getting error
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView mac;
public final TextView vendor;
public final TextView ip;
public SimpleViewHolder(View view) {
super(view);
ip = (TextView) view.findViewById(R.id.ip);
mac = (TextView) view.findViewById(R.id.mac);
vendor = (TextView) view.findViewById(R.id.vendor);
}
}
public SimpleAdapter(Context context, List<HostBean> data) {
mContext = context;
if (data != null)
mData = new ArrayList<HostBean>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.list_host, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.ip.setText( (CharSequence) mData.get(position) );
holder.mac.setText( "" );
holder.vendor.setText( "" );
}
#Override
public int getItemCount() {
return mData.size();
}
}
This is my simple sectioned recyclerview adapter class:
public class SimpleSectionedRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final Context mContext;
private static final int SECTION_TYPE = 0;
private boolean mValid = true;
private int mSectionResourceId;
private int mTextResourceId;
private LayoutInflater mLayoutInflater;
private RecyclerView.Adapter mBaseAdapter;
private SparseArray<Section> mSections = new SparseArray<Section>();
public SimpleSectionedRecyclerViewAdapter(Context context, int sectionResourceId, int textResourceId,
RecyclerView.Adapter baseAdapter) {
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mSectionResourceId = sectionResourceId;
mTextResourceId = textResourceId;
mBaseAdapter = baseAdapter;
mContext = context;
mBaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onChanged() {
mValid = mBaseAdapter.getItemCount()>0;
notifyDataSetChanged();
}
#Override
public void onItemRangeChanged(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeChanged(positionStart, itemCount);
}
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeInserted(positionStart, itemCount);
}
#Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
mValid = mBaseAdapter.getItemCount()>0;
notifyItemRangeRemoved(positionStart, itemCount);
}
});
}
public static class SectionViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public SectionViewHolder(View view, int mTextResourceid) {
super(view);
title = (TextView) view.findViewById(mTextResourceid);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int typeView) {
if (typeView == SECTION_TYPE) {
final View view = LayoutInflater.from(mContext).inflate(mSectionResourceId, parent, false);
return new SectionViewHolder(view,mTextResourceId);
}else{
return mBaseAdapter.onCreateViewHolder(parent, typeView -1);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder sectionViewHolder, int position) {
if (isSectionHeaderPosition(position)) {
((SectionViewHolder)sectionViewHolder).title.setText(mSections.get(position).title);
}else{
mBaseAdapter.onBindViewHolder(sectionViewHolder,sectionedPositionToPosition(position));
}
}
#Override
public int getItemViewType(int position) {
return isSectionHeaderPosition(position)
? SECTION_TYPE
: mBaseAdapter.getItemViewType(sectionedPositionToPosition(position)) +1 ;
}
public static class Section {
int firstPosition;
int sectionedPosition;
CharSequence title;
public Section(int firstPosition, CharSequence title) {
this.firstPosition = firstPosition;
this.title = title;
}
public CharSequence getTitle() {
return title;
}
}
public void setSections(Section[] sections) {
mSections.clear();
Arrays.sort(sections, new Comparator<Section>() {
#Override
public int compare(Section o, Section o1) {
return (o.firstPosition == o1.firstPosition)
? 0
: ((o.firstPosition < o1.firstPosition) ? -1 : 1);
}
});
int offset = 0; // offset positions for the headers we're adding
for (Section section : sections) {
section.sectionedPosition = section.firstPosition + offset;
mSections.append(section.sectionedPosition, section);
++offset;
}
notifyDataSetChanged();
}
public int positionToSectionedPosition(int position) {
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).firstPosition > position) {
break;
}
++offset;
}
return position + offset;
}
public int sectionedPositionToPosition(int sectionedPosition) {
if (isSectionHeaderPosition(sectionedPosition)) {
return RecyclerView.NO_POSITION;
}
int offset = 0;
for (int i = 0; i < mSections.size(); i++) {
if (mSections.valueAt(i).sectionedPosition > sectionedPosition) {
break;
}
--offset;
}
return sectionedPosition + offset;
}
public boolean isSectionHeaderPosition(int position) {
return mSections.get(position) != null;
}
#Override
public long getItemId(int position) {
return isSectionHeaderPosition(position)
? Integer.MAX_VALUE - mSections.indexOfKey(position)
: mBaseAdapter.getItemId(sectionedPositionToPosition(position));
}
#Override
public int getItemCount() {
return (mValid ? mBaseAdapter.getItemCount() + mSections.size() : 0);
}
}
This is how is initialize the arraylist:
hosts = new ArrayList<HostBean>();
This is my activity code for setting adapter to recyclerview:
RecyclerView list =findViewById(R.id.output);
list.setHasFixedSize( true );
list.setLayoutManager( new LinearLayoutManager( this ) );
list.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));
SimpleAdapter mAdapter = new SimpleAdapter(this,hosts);
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0,"Know Devices"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5,"Unknown Devices"));
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(this,R.layout.section,R.id.section_text,mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
list.setAdapter( mSectionedAdapter );
Your mData is an ArrayList<>. Therefore you can not pass key, value for that. You can only pass one param, either key or value. List is not a map.
private ArrayList<HostBean> mData;
mData.add(position,s); // Can not do this
If you want a key value relationship, then use HashMap like this.
private HashMap<Integer, HostBean> mData;
I need to carry my int value from one method to another, but I didnt find any solution. One method counts number of objects and the number needs to be "delivered" to another and check, if the count equals to something.
Do you have any idea, how to do it?
Check my codes below:
#Override
protected void onPostExecute(Void result) {
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.countInBackground(callcount = new CountCallback(){
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
//I need to export int count from "done" method to another
} else {
}
}
});
}
And the secont method, which has to recieve that value and use it:
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//i need to set int count from method above here
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter - threshold) {
updateData();
}
}
Whole code:
public class Fragment1 extends Fragment {
static ListView mListView;
static AnimalAdapter mAdapter;
static ProgressBar mProgressBar;
static EditText mEditText;
static LayoutInflater inflater;
CountCallback callcount;
int g_count = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.animalsfrag, container, false);
mListView = (ListView)rootView.findViewById(R.id.animal_list);
View header = getActivity().getLayoutInflater().inflate(R.layout.header, null);
header.setPadding(2, 8, 4, 2);
mListView.setVisibility(View.INVISIBLE);
mListView.requestFocus();
mListView.addHeaderView(header);
View footie = getActivity().getLayoutInflater().inflate(R.layout.footer, null);
mListView.addFooterView(footie);
footie.setVisibility(View.INVISIBLE);
mProgressBar = (ProgressBar) rootView.findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.VISIBLE);
RemoteDataTask task = new RemoteDataTask();
task.execute();
return rootView;
}
public void updateData() {
mListView = (ListView)getView().findViewById(R.id.animal_list);
final ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.setCachePolicy(CachePolicy.NETWORK_ONLY);
query.orderByAscending("animal");
query.setLimit(mListView.getCount() + 5);
Log.v("updateData", "uploading data from Parse.com");
query.findInBackground(new FindCallback<Animal>() {
#Override
public void done(List<Animal> animals, ParseException error) {
if(animals != null){
mAdapter.clear();
mProgressBar = (ProgressBar) getView().findViewById (R.id.loading_animals);
mProgressBar.setVisibility(View.INVISIBLE);
RelativeLayout footie = (RelativeLayout) getView().findViewById(R.id.footerview);
footie.setVisibility(View.VISIBLE);
mAdapter.clear();
for (int i = 0; i < animals.size(); i++) {
mAdapter.add(animals.get(i));
}
}
}
}); }
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute(); }
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
ParseQuery<Animal> query = ParseQuery.getQuery(Animal.class);
query.countInBackground(callcount = new CountCallback(){
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
if (mListView.getCount() == count) {
Log.v("all loaded", "executed");
g_count=count;
}
} else {
// The request failed
}
}
});
Log.v("onpostexecute", "executing");
mListView = (ListView) getView().findViewById(R.id.animal_list);
if(mListView.getCount() == 0){
updateData();
}
mEditText = (EditText) getView().findViewById(R.id.search_animal);
mAdapter = new AnimalAdapter(getActivity(), new ArrayList<Animal>());
mListView.setVisibility(View.VISIBLE);
mListView.setTextFilterEnabled(true);
mListView.setAdapter(mAdapter);
mListView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter
- threshold){
updateData();
Log.v("count", "count is" + g_count);
}
}
if (SCROLL_STATE_TOUCH_SCROLL == scrollState) {
View currentFocus = getActivity().getCurrentFocus();
if(currentFocus != null) {
currentFocus.clearFocus();
}
}
}
});
mEditText.addTextChangedListener(new TextWatcher(){
#Override
public void afterTextChanged(Editable s) {}
#Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
System.out.println("Text ["+s+"]");
mAdapter.getFilter().filter(s.toString());
}
});
}
}
}
I'd be glad for any advice.
Thanks in advance.
If you are not calling function from another then you need to create a global variable.
Declare a variable just after your class declaration i.e.
int g_count = 0;
then in
public void done(int count, ParseException e) {
if (e == null) {
Log.v("count is" + count, "count is");
g_count=count;
}
Then in second fucntion
public void onScrollStateChanged(AbsListView view, int scrollState) {
int count=g_count; \\you dont really need to declare this, just use g_count
int threshold = 1;
int counter = mListView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (mListView.getLastVisiblePosition() >= counter - threshold) {
updateData();
}
}