Update TAB 2 Recyclerview When Data Added in TAB 1's RecyclerView - java

I have kind of to-do app. In profile activity, there are 2 tabs.
To-do and Done. In Tab 1, user can check as "done" of their "to-do". In this case, I want to update TAB 2's recyclerview.
I tried several things, but didn't work. Here is TAB 1 codes, it's almost same as TAB 2.
TAB 1 Class
public class Tab_Profile_1 extends Fragment {
private RecyclerView recyclerView_tab_todo;
private List<Model_ListItem> itemList;
private Adapter_Profile_ToDo adapter_profile_toDo;
SharedPreferences mSharedPref;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_tab_1, container, false);
//TO-DO
//
recyclerView_tab_todo = view.findViewById(R.id.recyclerView_tab_todo);
//
fetchUserToDo();
return view;
}
public void fetchUserToDo() {
itemList = new ArrayList<>();
//First Settings
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getContext());
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchUserToDo(session_user_id);
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
itemList = response.body();
adapter_profile_toDo = new Adapter_Profile_ToDo(getContext(), itemList);
recyclerView_tab_todo.setHasFixedSize(true);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView_tab_todo.setLayoutManager(layoutManager);
recyclerView_tab_todo.setAdapter(adapter_profile_toDo);
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}}
TAB 1 RecyclerView Adapter
public class Adapter_Profile_ToDo extends RecyclerView.Adapter {
private Context context;
private List<Model_ListItem> itemList;
private String url_extension_images = URL_Extension.url_extension_images;
SharedPreferences mSharedPref;
ProgressDialog progressDialog;
View view;
public Adapter_Profile_ToDo(Context context, List<Model_ListItem> itemList) {
this.context = context;
this.itemList = itemList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_profile_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(context).load(url_extension_images + itemList.get(position).getItem_image()).into(holder.imageView_profile_todo);
holder.textView_profile_todo_name.setText(itemList.get(position).getItem_name());
holder.textView_profile_todo_desc.setText(itemList.get(position).getItem_description());
holder.layout_profile_todo_detail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//detail
}
});
holder.layout_profile_todo_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getRootView().getContext(), R.style.AlertStyle);
builder.setTitle("\"" + itemList.get(position).getItem_name() + "\"" + "\n");
builder.setIcon(R.drawable.ic_bookmark);
builder.setPositiveButton("YAPTIM", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
addDone("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNegativeButton("SİL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showProgressDialog();
deleteUserToDo("" + itemList.get(position).getItem_id(), position);
}
});
builder.setNeutralButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView_profile_todo;
TextView textView_profile_todo_name, textView_profile_todo_desc;
LinearLayout layout_profile_todo_detail, layout_profile_todo_add;
public ViewHolder(View itemView) {
super(itemView);
imageView_profile_todo = itemView.findViewById(R.id.imageView_profile_todo);
textView_profile_todo_name = itemView.findViewById(R.id.textView_profile_todo_name);
textView_profile_todo_desc = itemView.findViewById(R.id.textView_profile_todo_desc);
layout_profile_todo_detail = itemView.findViewById(R.id.layout_profile_todo_detail);
layout_profile_todo_add = itemView.findViewById(R.id.layout_profile_todo_add);
}
}
public void deleteUserToDo(final String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = api_service.deleteUserToDo(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Silindi!", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
});
}
public void addDone(String listId, final int clicked) {
mSharedPref = PreferenceManager.getDefaultSharedPreferences(context);
String session_user_id = mSharedPref.getString("session_user_id", "");
API_Service apiService = Client.getRetrofitInstance().create(API_Service.class);
Call<Response_Success> call = apiService.addDone(session_user_id, listId);
call.enqueue(new Callback<Response_Success>() {
#Override
public void onResponse(Call<Response_Success> call, Response<Response_Success> response) {
if (response.code() == 200) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
if (response.body().getSuccess().matches("true")) {
Toast.makeText(context, "Eklendi", Toast.LENGTH_SHORT).show();
itemList.remove(itemList.get(clicked));
notifyItemRemoved(clicked);
notifyItemRangeChanged(clicked, itemList.size());
} else {
Toast.makeText(context, "Bilinmeyen bir hata oluştu!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<Response_Success> call, Throwable t) {
}
});
}
public void showProgressDialog() {
progressDialog = new ProgressDialog(view.getRootView().getContext());
progressDialog.setMessage("Yükleniyor");
progressDialog.setCancelable(false);
progressDialog.show();
}
}

If i'm reading this correctly, you have two tabs and a backend database that stores the to do items and their state? To get the second list to update, you just need to do the same thing that you're doing in your first list, and update the adapter's data set and notify that the data set changed. How you trigger this action in your second tab is really the question.
You can either use an interface and have your adapter notify your activity that recycler view 1 had an action on it, and you can then tell adapter 2 to update its data. You can either pass back the data and only notify one row, or you could notify the entire data set. If you're doing this all service based, you could just reload the recycler view from the service and it will have the new data.
I think all you need to figure out is how you want to notify tab 2 that it needs to update its data. My recommendation is:
public interface AdapterInterface
{
void itemCompleted(Item hereIsTheItemThatNeedsToBeAddedTo2);
}
Then inside your adapter have a property with getters/setters such as:
private AdapterInterface adapterInterfaceListener;
Inside your Fragment/Activity implement AdapterInterface and implement the itemCompleted function.
And then set your adapter.setAdapterInterfaceLisetener to that function that you implemented. Then inside your adapter when the user clicks the checkbook to mark it as done, you can call the adapterInterfaceListener.itemCompleted() function, and it will send that information to your Fragment/Activity. From there you can give that new data to adapter2, or recall the API, however you want to get the new data.
Does this help?

Related

recyclerview item click listener with sqlite java

I would like to get data from the box which click on on the recycler view to go into a another activity to display.
I have tried to flow this video https://www.youtube.com/watch?v=7GPUpvcU1FE&t=399s&ab_channel=PracticalCoding i dont understand at 6:16.
Also https://www.youtube.com/watch?v=VQKq9RHMS_0&ab_channel=Stevdza-San i cannot get the data to pass to the new activity.
Main code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staff_home);
DB=new mainTextDBHelper(this);
recyclerView=findViewById(R.id.recyclerview);
Title=new ArrayList<>();
description=new ArrayList<>();
radiogroup=new ArrayList<>();
adapter=new recyclerviewAdapter(this,Title,description,radiogroup,listener);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
displaydata();
setOnClickListner();
private void setOnClickListner() {
listener=new recyclerviewAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent intent=new Intent(getApplicationContext(),cardviewclickon.class);
intent.putExtra("Title",Title.get(position));
startActivity(intent);
}
};
}
private void displaydata() {
Cursor cursor=DB.getdata();
if(cursor.getCount()==0){
Toast.makeText(staff_home.this,"No Entry Exists", Toast.LENGTH_SHORT).show();
return;
}else{
while(cursor.moveToNext())
{
Title.add(cursor.getString(1));
description.add(cursor.getString(2));
radiogroup.add(cursor.getString(3));
}
}
}
recyclerview Adapter code
public class recyclerviewAdapter extends RecyclerView.Adapter<recyclerviewAdapter.MyViewHolder>{
private Context context;
private ArrayList Title_id,description_id,radiogroup_id;
private RecyclerViewClickListener listener;
public recyclerviewAdapter(Context context, ArrayList title_id, ArrayList description_id, ArrayList radiogroup_id,RecyclerViewClickListener listener) {
this.context = context;
Title_id = title_id;
this.description_id = description_id;
this.radiogroup_id = radiogroup_id;
this.listener=listener;
}
#NonNull
#Override
public recyclerviewAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.userentry,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull recyclerviewAdapter.MyViewHolder holder, int position) {
holder.Title_id.setText(String.valueOf(Title_id.get(position)));
holder.description_id.setText(String.valueOf(description_id.get(position)));
holder.radiogroup_id.setText(String.valueOf(radiogroup_id.get(position)));
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(context,cardviewclickon.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return Title_id.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView Title_id,description_id,radiogroup_id;
CardView cardView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
Title_id=itemView.findViewById(R.id.textTitle);
description_id=itemView.findViewById(R.id.textdescription);
radiogroup_id=itemView.findViewById(R.id.textsrverity);
cardView=itemView.findViewById(R.id.card);
new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onClick(view,getAdapterPosition());
}
};
}
#Override
public void onClick(View view) {
listener.onClick(view,getAdapterPosition());
}
}
public interface RecyclerViewClickListener{
void onClick(View v,int position);
}
}
If you want to pass data from one activity to other you can use PutExtra() method of the Intent class As I can see you are doing everything pretty much well but you have to catch these extra from the class you are passing like:- I want to pass data from recyclerView to CardViewClass I can do it like:-
In RecyclerView.java file:-
public void sendDataAndOpen(String title) {
Intent intent = new Intent(getApplicationContext(), CardViewClass.class);
intent.putExtraString("Title",Title); // You can use putExtra to put any datatype
startActivity(intent);
}
In CardViewClass.java file (Lets catch our passing data):-
public void onCreate(...) {
....
String title = getIntent().getExtraString("Title") // You can also use ExtraPut and // Must use Same Id
// Use data as you want
.....
}

Load next item of reyclerview when user clicks on next button, having error in this

I am making an android app in which i have reyclerview whenever user clicks on recyclerview items then he is navigating to next activity and in next activity data will be shown. It is working but now i am adding next and previous button in it. Whenever next button will be clicked then next reycler items'data should be shown and same with previous button.
But i am getting error in this. It is my code.
RecylerAdapter:
public class ContentViewRecyclerAdapter extends RecyclerView.Adapter<ContentViewRecyclerAdapter.ViewHolder>{
ArrayList<ContentModel>contentModels;
Context context;
public ContentViewRecyclerAdapter(ArrayList<ContentModel> contentModels, Context context) {
this.contentModels = contentModels;
this.context = context;
}
#NonNull
#Override
public ContentViewRecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ContentViewRecyclerAdapter.ViewHolder holder, final int position) {
holder.textView.setText(contentModels.get(position).getContent());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ContentViewActivity.class);
i.putExtra("valuecontent", contentModels.get(position).getContent());
i.putExtra("position", position);
i.putParcelableArrayListExtra("contentmodels", contentModels);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return contentModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.contentText);
}
}
}
ModelClass:
public class ContentModel implements Parcelable {
String content;
public ContentModel(String content) {
this.content = content;
}
protected ContentModel(Parcel in) {
content = in.readString();
}
public static final Creator<ContentModel> CREATOR = new Creator<ContentModel>() {
#Override
public ContentModel createFromParcel(Parcel in) {
return new ContentModel(in);
}
#Override
public ContentModel[] newArray(int size) {
return new ContentModel[size];
}
};
public String getContent() {
return content;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(content);
}
}
ContentViewActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_view);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView_content);
next = findViewById(R.id.next);
prev = findViewById(R.id.prev);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.backbtncntent);
sharebtn = findViewById(R.id.sharebtn);
copybtn = findViewById(R.id.copy);
contentModels = new ArrayList<>();
contentModels.clear();
contentModels = getIntent().getParcelableArrayListExtra("contentmodels");
final String valuecontent = getIntent().getStringExtra("valuecontent");
position = getIntent().getIntExtra("position",0);
textView.setText((Integer) contentModels.get(position));
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ContentViewActivity.this, HomeActivity.class);
startActivity(i);
}
});
sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hey Read Some Interesting Content");
intent.putExtra(android.content.Intent.EXTRA_TEXT, valuecontent);
startActivity(Intent.createChooser(intent, "Share Via"));
}
});
copybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setClipboard(ContentViewActivity.this,textView.getText().toString());
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position =(position+1)%contentModels.size();
textView.setText((Integer) contentModels.get(position));
}
});
prev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position =(position-1)%contentModels.size();
textView.setText((Integer) contentModels.get(position));
}
});
}
private void setClipboard(Context context, String text) {
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
Toast.makeText(ContentViewActivity.this, "Copied to Clipboard", Toast.LENGTH_SHORT).show();
clipboard.setPrimaryClip(clip);
}
}
}
The error i am getting:
Caused by: java.lang.ClassCastException: example.example1.shayariapp.Models.ContentModel cannot be cast to java.lang.Integer
at example.example1.shayariapp.Acitivties.ContentViewActivity.onCreate(ContentViewActivity.java:54)
at android.app.Activity.performCreate(Activity.java:7227)
at android.app.Activity.performCreate(Activity.java:7218)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2941)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3066) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1764) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:202) 
at android.app.ActivityThread.main(ActivityThread.java:6962) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888) 
Please please help me to solve this issue. Please
It is located here:
textView.setText((Integer) contentModels.get(position));
You are trying to parse ContentModel item into Integer.
You are doing this 3 times. Inside onCreate() and inside ClickListeners for next and prev.

Trying to call method from MainActivity in Another Activity it is me leading to error

I have Recycler ListView which I show in MainActivity and the first item it is as selected, I have done to click for another items but the last stays clicked and when I try to take this recycler view to show me in next Activity it doesn't work.
The first item it is selected but I have a click method which when click an image makes as selected but when I click a new image this works but the first item stays as selected so continues for others images. I want only a image to be selected.
I don't want to write twice the same code.
Is it good if I have a class only for this method which I can use everytime I want.
The id of recycler view list it is the same on both xml's.
If you have any suggestion for my question please let me know.
This is the adapter for the RecyclerView.
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder>{
private int selectedItem;
private ArrayList<Integer> mImages = new ArrayList<>();
private ArrayList<String> mSearchUrl = new ArrayList<>();
private Context mContext;
public ListViewAdapter(ArrayList<Integer> images, ArrayList<String> SearchUrl, Context context) {
mImages = images;
mContext = context;
mSearchUrl = SearchUrl;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.s_engine_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
selectedItem = 0;
if (selectedItem == i) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
}
Glide.with(mContext).load(mImages.get(i))
.into(viewHolder.image);
viewHolder.searchUrl.setText(mSearchUrl.get(i));
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.image.setBackgroundColor(Color.parseColor("#30000000"));
selectedItem = i;
}
});
}
#Override
public int getItemCount() {
return mImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView searchUrl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.ivEngine);
searchUrl = itemView.findViewById(R.id.ivEngineText);
}
}
}
This is the method in MainActivity.class
public void intSearch() {
mImages.add(R.drawable.s_bing);
mSearchUrl.add("https://www.bing.com/search?q=");
mImages.add(R.drawable.s_google);
mSearchUrl.add("https://www.google.com/search?q=");
mImages.add(R.drawable.s_yahoo);
mSearchUrl.add("www.yahoo.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
mImages.add(R.drawable.amazon_white256);
mSearchUrl.add("www.amazon.com");
initRecyclerView();
}
private void initRecyclerView() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.lvEngines);
recyclerView.setLayoutManager(layoutManager);
ListViewAdapter adapter = new ListViewAdapter(mImages, mSearchUrl, this);
recyclerView.setAdapter(adapter);
}
This is the button which takes to another activity.
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = searchPlugin.getText().toString();
Cursor data = mDatabaseHelper.getData();
AddHistory(newEntry);
getFragmentRefreshListener().onRefresh();
Intent intent = new Intent(MainActivity.this, ActivitySearchEngine.class);
intent.putExtra("name", newEntry);
intent.putExtra("test", mSearchUrl.get(0));
startActivityForResult(intent, 2);
}
});
This is the another activity
public class ActivitySearchEngine extends Activity implements
SwipeRefreshLayout.OnRefreshListener {
public ImageView mHome;
public EditText searchPlugin;
public WebView webView;
Button btnSearch;
public ImageButton clearSearch, exitButton;
public ImageView favIcon;
public ProgressBar loadIcon;
String text;
SwipeRefreshLayout refreshLayout;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
private String selectedSearchUrl;
RecyclerView mListView;
MainActivity mainActivity = new MainActivity();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
mHome = findViewById(R.id.imgBtnHome);
searchPlugin = findViewById(R.id.etSearch);
webView = findViewById(R.id.webView);
clearSearch = findViewById(R.id.btnClearSearch);
btnSearch = findViewById(R.id.btnSearch);
favIcon = findViewById(R.id.imgViewFavIcon);
loadIcon = findViewById(R.id.progressBarIcon);
exitButton = findViewById(R.id.imgBtnStopLoad);
refreshLayout = findViewById(R.id.refreshLayout);
mListView = findViewById(R.id.lvEngines);
refreshLayout.setOnRefreshListener(this);
mDatabaseHelper = new DatabaseHelper(this);
mainActivity.intSearch(); // Here it is the error
Activity.ActivitySearchEngine}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
Intent receivedIntent = getIntent();
selectedName = receivedIntent.getStringExtra("name");
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedSearchUrl = receivedIntent.getStringExtra("test");
searchPlugin.setText(selectedName);
loadIcon.setVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("www.bing.com/search?=" + selectedName);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
favIcon.setImageBitmap(icon);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadIcon.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.GONE);
}
public void onPageFinished(WebView view, String url) {
try {
if (loadIcon.getVisibility() == View.VISIBLE) {
loadIcon.setVisibility(View.GONE);
favIcon.setVisibility(View.VISIBLE);
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
exitButton.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onRefresh();
}
});
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
searchPlugin.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) {
}
#Override
public void afterTextChanged(Editable s) {
processButtonByTextLength();
}
});
mHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText(null);
finish();
}
});
clearSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchPlugin.setText("");
}
});
public void processButtonByTextLength() {
String inputText = searchPlugin.getText().toString();
if(inputText.length() > 0) {
btnSearch.setVisibility(View.VISIBLE);
mHome.setVisibility(View.GONE);
clearSearch.setVisibility(View.VISIBLE);
favIcon.setVisibility(View.VISIBLE);
loadIcon.setVisibility(View.GONE);
exitButton.setVisibility(View.GONE);
} else if(inputText.length() == 0) {
btnSearch.setVisibility(View.GONE);
mHome.setVisibility(View.VISIBLE);
clearSearch.setVisibility(View.GONE);
}
}
#Override
public void onRefresh() {
webView.reload();
refreshLayout.setRefreshing(false);
}
}
This is the photo with RecyclerView at MainActivity.class
Photo of another Activity

Firebase and Android - Chat Message and OnClickListener

I learn Firebase and I found this project: https://github.com/firebase/FirebaseUI-Android/tree/0.3.1/codelabs/chat
I'm trying to expand this project for setOnClickListener method.
I would like to click on every item of this chat message(chat listview) and see
this in another activity.
For example: I have this chat in: ChatMessageActivity. And I would like show this in ChatMessageDetailsActivity.
Like this:
private Firebase firebaseRef;
private static final String FIREBASE_URL = "https://my-project.firebaseio.com/chat";
FirebaseListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_message);
Firebase.setAndroidContext(this);
firebaseRef = new Firebase(FIREBASE_URL);
final EditText mText = (EditText) findViewById(R.id.messageText);
Button sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = mText.getText().toString();
ChatMessage message = new ChatMessage("Android User", text);
firebaseRef.push().setValue(message);
mText.setText("");
}
});
final ListView listView = (ListView) this.findViewById(R.id.list);
listAdapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class,
android.R.layout.two_line_list_item, firebaseRef) {
#Override
protected void populateView(View v, ChatMessage model, int position) {
((TextView)v.findViewById(android.R.id.text1)).setText(model.getName());
((TextView)v.findViewById(android.R.id.text2)).setText(model.getText());
}
};
listView.setAdapter(listAdapter);
firebaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) { }
public void onChildRemoved(DataSnapshot dataSnapshot) { }
public void onChildMoved(DataSnapshot dataSnapshot, String s) { }
public void onCancelled(FirebaseError firebaseError) { }
});
}
#Override
public View getView(View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if ( row == null || (row.getTag() == null)) {
holder = new ViewHolder();
holder.chatName = (TextView) row.findViewById(R.id.detsName);
holder.chatText = (TextView) row.findViewById(R.id.detsText);
row.setTag(holder);
}else {
holder = (ViewHolder) row.getTag();
}
holder.chatName.setText(holder.chatMessage.getName());
holder.chatText.setText(holder.chatMessage.getText());
final ViewHolder finalHolder = holder;
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ChatMessage.this, ChatMessageDetails.class);
startActivity(i);
}
});
return row;
}
public class ViewHolder {
ChatMessage chatMessage;
TextView chatName;
TextView chatText;
}
#Override
protected void onDestroy() {
super.onDestroy();
listAdapter.cleanup();
}
}
But getView(at the bottom) method doesn't work. I had this in my old project without Firebase and internet connection. It worked. But now I'm trying to implement this in Chat Project but without positive results.
Is in Firebase some inside method to do this?
Does somebody has some preposition how to develop this listView with SetOnClickListener method with Firebase in AndroidStudio?

Getting indexOutOfBoundsException while trying to fetch data from parse

I am trying to fetch some data from parse, but my app is getting crashed every time due to this error: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at com.abc.xyz.AcceptARequest$1$1.done(AcceptARequest.java:157)
Here's AcceptARequest.java(in which I'm fetching data from parse) file's code :
public class AcceptARequest extends Fragment{
private OnFragmentInteractionListener mListener;
public List<ListContentAAR> listContentAARs;
public RecyclerView recyclerView;
ImageView hPicAccept;
TextView hDescriptionAccept, currentCoordinatesTagAccept, currentLatAccept, currentLngAccept, post_date, post_time, posted_by;
String hDescriptionAcceptS, currentCoordinatesTagAcceptS, currentLatAcceptS, currentLngAcceptS, post_dateS, post_timeS, posted_byS;
Button btn_accept, btn_share;
LinearLayout latContainerAccept, lngContainerAccept, dateTimeContainer;
ParseQuery<ParseObject> query;
String hDescription, cLat, cLng;
public AcceptARequest() {
// 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);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_accept_a_request, container, false);
listContentAARs = new ArrayList<>();
hPicAccept = (ImageView) rootView.findViewById(R.id.h_pic_accept);
hDescriptionAccept = (TextView) rootView.findViewById(R.id.h_description_accept);
currentCoordinatesTagAccept = (TextView) rootView.findViewById(R.id.currentCoordinatesTagAccept);
currentLatAccept = (TextView) rootView.findViewById(R.id.currentLatAccept);
currentLngAccept = (TextView) rootView.findViewById(R.id.currentLngAccept);
btn_accept = (Button) rootView.findViewById(R.id.btn_accept);
btn_share = (Button) rootView.findViewById(R.id.btn_share);
latContainerAccept = (LinearLayout) rootView.findViewById(R.id.latContainerAccept);
lngContainerAccept = (LinearLayout) rootView.findViewById(R.id.lngContainerAccept);
dateTimeContainer = (LinearLayout) rootView.findViewById(R.id.date_time_container);
post_date = (TextView) rootView.findViewById(R.id.post_date);
post_time = (TextView) rootView.findViewById(R.id.post_time);
posted_by = (TextView) rootView.findViewById(R.id.posted_by);
hDescriptionAcceptS = hDescriptionAccept.getText().toString();
currentCoordinatesTagAcceptS = currentCoordinatesTagAccept.getText().toString();
currentLatAcceptS = currentLatAccept.getText().toString();
currentLngAcceptS = currentLngAccept.getText().toString();
post_dateS = post_date.getText().toString();
post_timeS = post_time.getText().toString();
posted_byS = posted_by.getText().toString();
currentCoordinatesTagAccept.setVisibility(View.INVISIBLE);
currentLatAccept.setVisibility(View.INVISIBLE);
currentLngAccept.setVisibility(View.INVISIBLE);
latContainerAccept.setVisibility(View.INVISIBLE);
lngContainerAccept.setVisibility(View.INVISIBLE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
query = ParseQuery.getQuery("HomelessDetails");
query.whereEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
query.addDescendingOrder("createdAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
currentCoordinatesTagAccept.setVisibility(View.VISIBLE);
currentLatAccept.setVisibility(View.VISIBLE);
currentLngAccept.setVisibility(View.VISIBLE);
latContainerAccept.setVisibility(View.VISIBLE);
lngContainerAccept.setVisibility(View.VISIBLE);
hDescriptionAcceptS = list.get(1).getString("hDescription");
hDescriptionAccept.setText(hDescriptionAcceptS);
currentLatAcceptS = list.get(1).getString("hLatitude");
currentLatAccept.setText(currentLatAcceptS);
currentLngAcceptS = list.get(1).getString("hLongitude");
currentLngAccept.setText(currentLngAcceptS);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(e.getMessage());
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}, 1000);
recyclerView = (RecyclerView) rootView.findViewById(R.id.accept_request_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Button btnAccept = (Button) view.findViewById(R.id.btn_accept);
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.request_accepted_txt);
builder.setPositiveButton("Navigate me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "Navigating you to the needy...", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The help-request has been rejected.", Toast.LENGTH_LONG).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
Button btnShare = (Button) view.findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// share the help-request here.
}
});
}
#Override
public void onLongClick(View view, int position) {
}
}));
initializeAdapter();
return rootView;
}
private void initializeAdapter(){
RVAdapterAAR adapter = new RVAdapterAAR(listContentAARs);
recyclerView.setAdapter(adapter);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public void itemClicked(View view, int position) {
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent 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.getChildPosition(child));
}
super.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.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
I don't know what's going wrong here.
Please let me know.
Please cooperate if question seems to be badly formatted, I'm still learning to post good questions.
You are trying to access the ArrayList which does not have any element in it. SO list.get(1) won't work.
Make sure that your ArrayList is getting populated correctly.
#Hammad:
The error that you are getting is because of the array list that you are using does not contain any elements/objects in it.
You need to populate the arraylist using list.Add()(or based on your preference) method.

Categories

Resources