JSON data is showing null after publishing my app on google play - java

JSON data is showing null after publishing my app on google play, But it shows the data in the emulator while running the non published app sourcecode. The data is coming from the Database online from external server.The json data is visible in the URL, But is shows null in my published app. What could be the reason??.....
PLEASE HELP ME
This is my MainActivity
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class JUR extends AppCompatActivity implements jurAdapter.JURAdapterListener {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView recyclerView2;
private List<JURlist> jurList;
private jurAdapter mAdapter;
private SearchView searchView;
ProgressBar progressBar2;
static {
System.loadLibrary("keys");
}
public native String getJUR();
public native String geturl2();
String getJUR = URLEncoder.encode(getJUR());
String geturl2 = URLEncoder.encode(geturl2());
// url to fetch contacts json
private final String URL = "https://"+geturl2+"/...../"+getJUR;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jur);
progressBar2 = findViewById(R.id.progress2);
progressBar2.setVisibility(View.VISIBLE);
Toolbar toolbar2 = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar2);
// toolbar fancy stuff
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.toolbar_JUR);
recyclerView2 = findViewById(R.id.recycler_view2);
jurList = new ArrayList<>();
mAdapter = new jurAdapter(this, jurList, this);
// white background notification bar
whiteNotificationBar(recyclerView2);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView2.setLayoutManager(mLayoutManager);
recyclerView2.setItemAnimator(new DefaultItemAnimator());
recyclerView2.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));
recyclerView2.setAdapter(mAdapter);
fetchJUR();
}
/**
* fetches json by making http calls
*/
private void fetchJUR() {
JsonArrayRequest request = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response == null) {
Toast.makeText(getApplicationContext(), "Couldn't fetch JURISDICTION Pleas try again.", Toast.LENGTH_LONG).show();
return;
}
List<JURlist> items = new Gson().fromJson(response.toString(), new TypeToken<List<JURlist>>() {
}.getType());
// adding contacts to contacts list
jurList.clear();
jurList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
progressBar2.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
APP.getInstance().addToRequestQueue(request);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close search view on back button pressed
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
private void whiteNotificationBar(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
getWindow().setStatusBarColor(Color.WHITE);
}
}
#Override
public void onJURSelected(JURlist jur) {
Toast.makeText(getApplicationContext(), "Selected: " + jur.getSTATE() + ", " + jur.getZONE(), Toast.LENGTH_LONG).show();
}
}
This is the Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class jurAdapter extends RecyclerView.Adapter<jurAdapter.MyViewHolder>
implements Filterable {
private Context context;
private List<JURlist> JuRlist;
private List<JURlist> JURlistFiltered;
private JURAdapterListener listener;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView STATE, ZONE, COM, DIVI, RANAME, RANGE1;
// public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
STATE = view.findViewById(R.id.STATE);
ZONE = view.findViewById(R.id.ZONE);
COM = view.findViewById(R.id.COM);
DIVI = view.findViewById(R.id.DIVI);
RANAME = view.findViewById(R.id.RANAME);
RANGE1 = view.findViewById(R.id.RANGE1);
// thumbnail = view.findViewById(R.id.thumbnail);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// send selected contact in callback
listener.onJURSelected(JURlistFiltered.get(getAdapterPosition()));
}
});
}
}
public jurAdapter(Context context, List<JURlist> JURLIST, JURAdapterListener listener) {
this.context = context;
this.listener = listener;
this.JuRlist = JURLIST;
this.JURlistFiltered = JURLIST;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent1, int viewType1) {
View itemView = LayoutInflater.from(parent1.getContext())
.inflate(R.layout.jur_item_row, parent1, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
final JURlist jurlist = JURlistFiltered.get(position);
holder.STATE.setText("STATE : "+jurlist.getSTATE()+"\r\n") ;
holder.ZONE.setText("ZONE : "+jurlist.getZONE()+"\r\n");
holder.COM.setText("COMMISSIONERATE NAME : "+jurlist.getCOM()+"\r\n");
holder.DIVI.setText("DIVISION NAME : "+jurlist.getDIVI()+"\r\n");
holder.RANAME.setText("RANGE NAME : "+jurlist.getRANAME()+"\r\n");
holder.RANGE1.setText("RANGE JURISDICTION : \r\n"+jurlist.getRANGE1());
// Glide.with(context)
// .load(contact.getImage())
// .apply(RequestOptions.circleCropTransform())
// .into(holder.thumbnail);
}
#Override
public int getItemCount() {
return JURlistFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
JURlistFiltered = JuRlist;
} else {
List<JURlist> filteredList = new ArrayList<>();
for (JURlist row : JuRlist) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getSTATE().toLowerCase().contains(charString.toLowerCase()) || row.getZONE().toLowerCase().contains(charString.toLowerCase()) || row.getCOM().toLowerCase().contains(charString.toLowerCase()) || row.getDIVI().toLowerCase().contains(charString.toLowerCase()) || row.getRANAME().toLowerCase().contains(charString.toLowerCase()) || row.getRANGE1().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
JURlistFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = JURlistFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
JURlistFiltered = (ArrayList<JURlist>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface JURAdapterListener {
void onJURSelected(JURlist jur);
}
}```
[1]: https://i.stack.imgur.com/vcWmG.jpg

Related

Nothing happens after I click item in recyclerview even after using interface

I have made an android application using java, and I have made a click listener interface but nothing seems to happen and I can't figure out what is wrong with my code. Please help.
Following is the code of my recyclerViewAdapter:
package com.example.ashwamedh.adapter;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.ashwamedh.R;
import com.example.ashwamedh.model.AdminConfirmation;
import com.example.ashwamedh.model.Attendance;
import com.example.ashwamedh.model.Confirmation;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.List;
import java.util.Objects;
public class ManageAttendanceRecyclerViewAdapter extends RecyclerView.Adapter<ManageAttendanceRecyclerViewAdapter.ViewHolder> {
private List<Confirmation> practiceList;
private Context context;
private OnAttendanceClickListener onAttendanceClickListener;
private CollectionReference collectionReference = FirebaseFirestore.getInstance().collection("Users");
public ManageAttendanceRecyclerViewAdapter(List<Confirmation> practiceList, Context context, OnAttendanceClickListener onAttendanceClickListener) {
this.practiceList = practiceList;
this.context = context;
this.onAttendanceClickListener = onAttendanceClickListener;
}
#NonNull
#Override
public ManageAttendanceRecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context)
.inflate(R.layout.manage_attendance_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(#NonNull ManageAttendanceRecyclerViewAdapter.ViewHolder holder, int position) {
Confirmation confirmation = practiceList.get(position);
holder.nameTextView.setText(confirmation.getUsername());
if (confirmation.getRemarkOrReason() == "") {
holder.remarkOrReasonTextView.setText("null");
}else {
holder.remarkOrReasonTextView.setText(confirmation.getRemarkOrReason());
}
if (Objects.equals(confirmation.getConfirmation(), "present")) {
holder.confirmation.setImageResource(R.drawable.ic_baseline_check_24);
} else if (Objects.equals(confirmation.getConfirmation(), "absent")){
holder.confirmation.setImageResource(R.drawable.ic_baseline_close_24);
}
}
#Override
public int getItemCount() {
return practiceList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView nameTextView;
private ImageView confirmation;
private TextView remarkOrReasonTextView;
OnAttendanceClickListener onAttendanceClickListener;
public ViewHolder(#NonNull View itemView, Context ctx) {
super(itemView);
this.onAttendanceClickListener = ManageAttendanceRecyclerViewAdapter.this.onAttendanceClickListener;
context = ctx;
nameTextView = itemView.findViewById(R.id.manage_attendance_name_textview);
confirmation = itemView.findViewById(R.id.manage_attendance_confirmation);
remarkOrReasonTextView = itemView.findViewById(R.id.manage_attendance_remark_reason_textview);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.manage_attendance_row:
Log.d("from recycler view", "onClick: " + "row clicked");
Confirmation confirmation = practiceList.get(getAdapterPosition());
String userId = confirmation.getUserId();
onAttendanceClickListener.OnAttendanceClick(userId);
}
}
}
}
Following is the code of OnAttendanceClickListener:
package com.example.ashwamedh.adapter;
public interface OnAttendanceClickListener {
void OnAttendanceClick(String userId);
}
Following is the code of the activity where the recycler view is used and the interface implemented:
package com.example.ashwamedh;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ashwamedh.adapter.ManageAttendanceRecyclerViewAdapter;
import com.example.ashwamedh.adapter.OnAttendanceClickListener;
import com.example.ashwamedh.model.Confirmation;
import com.example.ashwamedh.util.UserApi;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class ManagePracticeConfirmationActivity extends AppCompatActivity implements OnAttendanceClickListener {
private static final String TAG = "PRACTICE_CONFIRMATION";
private RecyclerView recyclerView;
private BottomNavigationView bottomNavigationView;
private CardView markAttendanceCardView;
private FloatingActionButton presentFab;
private FloatingActionButton absentFab;
private Button updateButton;
private TextView noPracticeTextView;
private ImageButton signOut;
private Boolean isAdmin;
private String attendance;
private ManageAttendanceRecyclerViewAdapter manageAttendanceRecyclerViewAdapter;
private String practiceDate;
private List<Confirmation> practiceList;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference collectionReference = db.collection("Confirmations");
private CollectionReference userCollection = db.collection("Users");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_practice_confirmation);
Objects.requireNonNull(getSupportActionBar()).hide();
practiceList = new ArrayList<>();
recyclerView = findViewById(R.id.manage_attendance_recycler_view);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
markAttendanceCardView = findViewById(R.id.mark_attendance_cardView);
presentFab = findViewById(R.id.present_fab);
absentFab = findViewById(R.id.absent_fab);
updateButton = findViewById(R.id.update_attendance_button);
noPracticeTextView = findViewById(R.id.no_practice_textView);
signOut = findViewById(R.id.signOut_manage_attendance);
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
bottomNavigationView.setSelectedItemId(R.id.manage_practice_confirmation_button);
markAttendanceCardView.setVisibility(View.INVISIBLE);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
attendance = "";
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
Log.d(TAG, "onCreate: " + Calendar.DAY_OF_WEEK);
if (Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| Calendar.getInstance().get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
recyclerView.setVisibility(View.INVISIBLE);
noPracticeTextView.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
noPracticeTextView.setVisibility(View.INVISIBLE);
}
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.council_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, CouncilActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.attendance_button) {
Intent intent = new Intent(ManagePracticeConfirmationActivity.this, BatchmateAttendance.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
return true;
}
if (item.getItemId() == R.id.manage_practice_confirmation_button) {
return true;
}
return false;
}
});
}
#Override
protected void onStart() {
super.onStart();
Date today = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
practiceDate = simpleDateFormat.format(today);
collectionReference.whereEqualTo("practiceDate", practiceDate)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (!queryDocumentSnapshots.isEmpty()) {
for (QueryDocumentSnapshot snapshot : queryDocumentSnapshots) {
Confirmation confirmation = snapshot.toObject(Confirmation.class);
practiceList.add(confirmation);
}
manageAttendanceRecyclerViewAdapter = new ManageAttendanceRecyclerViewAdapter(practiceList,
ManagePracticeConfirmationActivity.this,
ManagePracticeConfirmationActivity.this);
recyclerView.setAdapter(manageAttendanceRecyclerViewAdapter);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
#Override
public void OnAttendanceClick(String userId) {
Log.d(TAG, "OnAttendanceClick: "+ isAdmin);
UserApi userApi = UserApi.getInstance();
isAdmin = Objects.equals(userApi.getUsername(), "ADMIN");
if (isAdmin) {
markAttendanceCardView.setVisibility(View.VISIBLE);
presentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "present";
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
}
});
absentFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
attendance = "absent";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.selected_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
}
});
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Confirmation confirmation = new Confirmation();
confirmation.setUserId(userId);
confirmation.setConfirmation(attendance);
confirmation.setPracticeDate(practiceDate);
if (Objects.equals(attendance, "present")) {
confirmation.setRemarkOrReason("PRESENT ON PRACTICE");
} else if (Objects.equals(attendance, "absent")){
confirmation.setRemarkOrReason("ABSENT ON PRACTICE");
}
SimpleDateFormat documentDateFormat = new SimpleDateFormat("dd_MM_yyyy");
String docDate = documentDateFormat.format(practiceDate);
String docAddress = userId+"_"+docDate;
collectionReference.document(docAddress)
.set(confirmation)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Attendance marked!", Toast.LENGTH_SHORT)
.show();
}
});
attendance = "";
absentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.absent_button_color)));
presentFab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(ManagePracticeConfirmationActivity.this, R.color.present_button_color)));
markAttendanceCardView.setVisibility(View.INVISIBLE);
manageAttendanceRecyclerViewAdapter.notifyDataSetChanged();
}
});
} else {
Toast.makeText(ManagePracticeConfirmationActivity.this, "Only admins can mark attendance!", Toast.LENGTH_SHORT)
.show();
}
}
}
Please help me I am clueless of where is the error
RecyclerView clicks doesn't work like that.
Firstly you should write click event in onBindViewHolder
holder.itemView.setOnClickListener(view -> onAttendanceClickListener.OnAttendanceClick(userId));
Put this code in your onBindViewHolder and you are good to go!
You will receive click events in Activity.

Getting error index out of bound exception in my recyclerview

I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}

Data is not binding to android recyclerview

I am new to android. I am trying to download data using the Github api and display in and infinite scrolling RecyclerView, the JSON data is been parsed, but somehow the data is not been attached to the recyclerview.
Here is the code below:
Developer_RV_Adapter.java
package com.davidshare.githubdevelopers;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by GemShare on 9/6/2017.
*/
public class Developer_RV_Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private OnLoadMoreListener mOnLoadMoreListener;
private boolean isLoading;
private int visibleThreshold = 10;
private int lastVisibleItem, totalItemCount;
private List<Developer> developerList;
Context context;
RecyclerView recyclerView;
public Developer_RV_Adapter(Context context, List<Developer> developerList, RecyclerView recyclerView) {
this.developerList = developerList;
this.context = context;
this.recyclerView = recyclerView;
final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
totalItemCount = linearLayoutManager.getItemCount();
lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
if(!isLoading && totalItemCount<=(lastVisibleItem+visibleThreshold)){
if(mOnLoadMoreListener!=null){
mOnLoadMoreListener.onLoadMore();
}
isLoading = true;
}
}
});
}
public void setmOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener){
this.mOnLoadMoreListener = mOnLoadMoreListener;
}
#Override
public int getItemViewType(int position){
return developerList.get(position) == null? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == VIEW_TYPE_ITEM){
View developerView = LayoutInflater.from(context).inflate(R.layout.developer_list_item, parent, false);
return new DeveloperViewHolder(developerView);
}else if(viewType== VIEW_TYPE_LOADING){
View loadingView = LayoutInflater.from(context).inflate(R.layout.progress_bar_item, parent, false);
return new ProgressViewHolder(loadingView);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Log.w("binder function", "Just entered the binder");
Developer developer = developerList.get(position);
if(holder instanceof DeveloperViewHolder){
DeveloperViewHolder developerViewHolder = (DeveloperViewHolder) holder;
developerViewHolder.gitNameTv.setText(developer.getGitUsername());
Log.w("binder ", developer.getGitProfileUrl());
developerViewHolder.gitUrlTv.setText(developer.getGitProfileUrl());
developerViewHolder.gitPicUrlTv.setText(developer.getGitProfilePicUrl());
Log.w("profile pic", developer.getGitProfilePicUrl());
Picasso.with(developerViewHolder.gitNameTv.getContext()).load(developer.getGitProfilePicUrl()).transform(new RoundedImage(2)).fit().centerCrop().into(developerViewHolder.profilePicImgV);
}else if (holder instanceof ProgressViewHolder) {
ProgressViewHolder loadingViewHolder = (ProgressViewHolder) holder;
loadingViewHolder.loadingProgress.setIndeterminate(true);
}
}
#Override
public int getItemCount() {
return developerList == null ? 0 : developerList.size();
}
public void setLoaded() {
isLoading = false;
}
public class DeveloperViewHolder extends RecyclerView.ViewHolder{
TextView gitNameTv;
TextView gitUrlTv;
ImageView profilePicImgV;
TextView gitPicUrlTv;
public DeveloperViewHolder(final View itemView) {
super(itemView);
gitNameTv = (TextView) itemView.findViewById(R.id.developerName);
gitUrlTv = (TextView) itemView.findViewById(R.id.developerUrl);
profilePicImgV = (ImageView) itemView.findViewById(R.id.developerPic);
gitPicUrlTv = (TextView) itemView.findViewById(R.id.developerPicUrl);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Intent i = new Intent(itemView.getContext(), Profile.class);
i.putExtra("profile_name", gitNameTv.getText().toString());
i.putExtra("profile_url", gitUrlTv.getText().toString());
i.putExtra("profile_pic_url", gitPicUrlTv.getText().toString());
v.getContext().startActivity(i);
}
});
}
}
public static class ProgressViewHolder extends RecyclerView.ViewHolder{
public ProgressBar loadingProgress;
public ProgressViewHolder(View itemView) {
super(itemView);
loadingProgress = (ProgressBar) itemView.findViewById(R.id.loading_progress_bar);
}
}
}
DeveloperList.java
package com.davidshare.githubdevelopers;
import android.app.ProgressDialog;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class DeveloperList extends AppCompatActivity {
List<Developer> developerList;
Developer_RV_Adapter developer_rv_adapter;
Developer developer;
RecyclerView developerRV;
private static final String GIT_BASE_URL = "https://api.github.com/search/users?q=location:";
private static int page = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_developer_list);
developerRV = (RecyclerView) findViewById(R.id.developer_rv);
developerRV.setLayoutManager(new LinearLayoutManager(this));
developerList = new ArrayList<>();
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter = new Developer_RV_Adapter(DeveloperList.this, developerList, developerRV);
developerRV.setAdapter(developer_rv_adapter);
developer_rv_adapter.setmOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
developerList.add(null);
developer_rv_adapter.notifyItemInserted(developerList.size()-1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
}
});
}
the getDevelopersData method uses volley to query the github api and parse the JSON response into a List
public void getDevelopersData(String requestUrl) {
StringRequest jsonSringRequest = new StringRequest(Request.Method.GET, requestUrl, new Response.Listener<String>() {
#Override
public void onResponse(String jsonResponse) {
try {
JSONObject gitJSONOBject = new JSONObject(jsonResponse);
JSONArray gitItemsArray = gitJSONOBject.getJSONArray("items");
for (int i = 0; i < gitItemsArray.length(); i++) {
JSONObject developerObject = gitItemsArray.getJSONObject(i);
developer = new Developer(developerObject.getString("login"),
developerObject.getString("html_url"),
developerObject.getString("avatar_url"));
developerList.add(developer);
Log.w("developer_data ", developer.getGitUsername());
}
Log.w("JSON DATA", "getting the json data");
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Volley error", volleyError.getMessage());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonSringRequest);
}
//get the location and language and the page of the api data you want to load
private String prepareQuery(String language, String location, int page){
this.page++;
String queryUrl = GIT_BASE_URL+location+"+language:"+language+"&page="+page+"&per_page=50";
Log.w("Query URL = > ", queryUrl);
return queryUrl;
}
}
Can anyone help me with this?
try to notify adapter in getDevelopersData() after data add to array list like add this line developer_rv_adapter.notifyDataSetChanged();
Instead of notifyItemInserted() inserted use
notifyItemRangedChanged(fromIndex,toIndex);
This will notify the adapter that some set of data is changed among the whole data and it tells the adapter that adapter should refresh the data and reload it into the recyclerView starting from fromIndex to toIndex as passed into the method.
If all data are changed then use :
notifyDataSetChanged();
if only one dataItem is changed then use :
notifyItemChanged(dataPosition);
Also I think this statment is causing problem.Try to remove this statment and check again.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
developerList.remove(developerList.size()-1);
developer_rv_adapter.notifyItemRemoved(developerList.size());
getDevelopersData(prepareQuery("java", "lagos", page));
developer_rv_adapter.notifyDataSetChanged();
developer_rv_adapter.setLoaded();
}
}, 5000);
The problem was resolved by just adding developer_rv_adapter.notifyDataSetChanged(); just below developerList.add(developer); this notifies the adapter that new items have been added to the list.

filter recyclerview using searchview

Solved , I should use Static for my Models in declerating . thanks all
I just went through this topic filter recycler view using search view and I did all the steps. Now when I search in recycler view it will filter my recycler view but when I press back space and remove a char it wont show the removed items! My recycler view is also empty after the search.
This is my RecyclerView adapter:
package com.webapp.masoud.application.myRecyclerAdapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.webapp.masoud.application.R;
import com.webapp.masoud.application.service.NewsModel;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class myRecyclerAdapter extends RecyclerView.Adapter<myRecyclerAdapter.myRecyclerViewHolder> {
private Context context;
ArrayList<NewsModel> myModels;
public myRecyclerAdapter(Context context, ArrayList<NewsModel> myModels) {
this.context = context;
this.myModels = myModels;
}
#Override
public myRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.channels_layout, parent, false);
return new myRecyclerViewHolder(v);
}
#Override
public void onBindViewHolder(myRecyclerViewHolder holder, int position) {
final NewsModel newsModel = myModels.get(position);
holder.edt_Title.setText(newsModel.title);
holder.edt_Dis.setText(newsModel.discription);
holder.txt_Category.setText(newsModel.category);
Picasso.with(context).load(newsModel.image).into(holder.img_Channel);
holder.btn_Join.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username;
if (newsModel.username.startsWith("#")){
username = "http://telegram.me/" + newsModel.username.substring(1);
}
else{
username = "http://telegram.me/" + newsModel.username;}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(username));
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return myModels.size();
}
public void animateTo(ArrayList<NewsModel> models) {
applyAndAnimateRemovals(models);
applyAndAnimateAdditions(models);
applyAndAnimateMovedItems(models);
}
public void setModels(ArrayList<NewsModel> models) {
myModels = new ArrayList<>(models);
}
public NewsModel removeItem(int position) {
final NewsModel model = myModels.remove(position);
notifyItemRemoved(position);
return model;
}
public void addItem(int position, NewsModel model) {
myModels.add(position, model);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final NewsModel model = myModels.remove(fromPosition);
myModels.add(toPosition, model);
notifyItemMoved(fromPosition, toPosition);
}
private void applyAndAnimateRemovals(ArrayList<NewsModel> newModels) {
for (int i = myModels.size() - 1; i >= 0; i--) {
final NewsModel model = myModels.get(i);
if (!newModels.contains(model)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(ArrayList<NewsModel> newModels) {
for (int i = 0, count = newModels.size(); i < count; i++) {
final NewsModel model = newModels.get(i);
if (!myModels.contains(model)) {
addItem(i, model);
}
}
}
private void applyAndAnimateMovedItems(ArrayList<NewsModel> newModels) {
for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
final NewsModel model = newModels.get(toPosition);
final int fromPosition = myModels.indexOf(model);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
class myRecyclerViewHolder extends RecyclerView.ViewHolder {
private TextView edt_Title;
private TextView edt_Dis;
public TextView txt_Category;
private Button btn_Join;
private CircleImageView img_Channel;
public myRecyclerViewHolder(View itemView) {
super(itemView);
edt_Title = (TextView) itemView.findViewById(R.id.edt_Title);
edt_Dis = (TextView) itemView.findViewById(R.id.edt_Dis);
btn_Join = (Button) itemView.findViewById(R.id.btn_Join);
img_Channel = (CircleImageView) itemView.findViewById(R.id.img_Channel);
txt_Category = (TextView) itemView.findViewById(R.id.txt_Category);
}
}
}
This is my MainActivity.java:
package com.webapp.masoud.application.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Parcelable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.webapp.masoud.application.R;
import com.webapp.masoud.application.myRecyclerAdapter.myRecyclerAdapter;
import com.webapp.masoud.application.service.NewsModel;
import com.webapp.masoud.application.service.APIService;
import com.webapp.masoud.application.service.NewsModelResponse;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
public class MainActivity extends AppCompatActivity {
private SearchView mSearchView;
private MenuItem searchMenuItem;
RecyclerView rv_Channels;
private Parcelable recyclerViewState;
SearchView.OnQueryTextListener myListener;
myRecyclerAdapter myAdapter;
ArrayList<NewsModel> newsModelArrayList;
NewsModelResponse newsModelResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//CalliGraphy
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Vazir.ttf")
.setFontAttrId(R.attr.fontPath)
.build()
);
//Context
setContentView(R.layout.activity_main);
//MY Application
Toolbar myToolbar = (Toolbar) findViewById(R.id.myToolbar);
setSupportActionBar(myToolbar);
final ProgressDialog myProgressDialog = new ProgressDialog(MainActivity.this);
myProgressDialog.setMessage("در حال دریافت لیست کانال ها ، لطفا منتظر بمانید .");
rv_Channels = (RecyclerView) findViewById(R.id.rv_Channels);
final SearchView sv_Channels = (SearchView) findViewById(R.id.sv_Channels);
//My API Service !
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://rapcity1.cf/service/")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<NewsModelResponse> serviceNewsModels = service.getNewsModels();
serviceNewsModels.enqueue(new Callback<NewsModelResponse>() {
#Override
public void onResponse(Call<NewsModelResponse> call, Response<NewsModelResponse> response) {
myProgressDialog.dismiss();
newsModelResponse = response.body();
newsModelArrayList = newsModelResponse.getNewsModels();
myAdapter = new myRecyclerAdapter(MainActivity.this, newsModelArrayList);
LinearLayoutManager myLinearlayoutmanager = new LinearLayoutManager(MainActivity.this);
rv_Channels.setLayoutManager(myLinearlayoutmanager);
recyclerViewState = rv_Channels.getLayoutManager().onSaveInstanceState();//save
rv_Channels.setItemAnimator(new DefaultItemAnimator());
rv_Channels.setAdapter(myAdapter);
}
#Override
public void onFailure(Call<NewsModelResponse> call, Throwable t) {
}
});
//End of API Service
//Search
assert sv_Channels != null;
myListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
final ArrayList<NewsModel> filteredModelList = filter(newsModelArrayList, query);
myAdapter.animateTo(filteredModelList);
rv_Channels.scrollToPosition(0);
return true;
}
};
}
private ArrayList<NewsModel> filter(ArrayList<NewsModel> models, String query) {
// query = query.toLowerCase();
final ArrayList<NewsModel> filteredModelList = new ArrayList<>();
for (NewsModel model : models) {
final String title = model.title;
//final String dis = model.discription;
if (title.contains(query) /*|| dis.contains(query)*/) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
searchMenuItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchMenuItem.getActionView();
mSearchView.setOnQueryTextListener(myListener);
mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
rv_Channels.getLayoutManager().onRestoreInstanceState(recyclerViewState);
return true;
}
});
return true;
}
}
This is my newsModels:
package com.webapp.masoud.application.service;
import java.io.Serializable;
/**
* Created by Master on 4/19/2016.
*/
public class NewsModel implements Serializable {
public String id;
public String title;
public String discription;
public String image;
public String category;
public String username;
public NewsModel(String title, String description,String image,String id,String category,String username) {
this.id = id;
this.title = title;
this.discription = description;
this.image = image;
this.category = category;
this.username=username;
}
public NewsModel() {
}
}
Please help me, thanks. Sorry for my bad English!
I am also using the tutorial and get it done. I just implements my Activity with
implements SearchView.OnQueryTextListener
Also i am using searchview this way.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.close_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
and rest the overrided methods, Not sure although give a try.

Error in onCreate method (FragmentActivity)

Please help! When I'm trying to write onCreate method.
Multiple markers at this line
The method onCreate in type MainActivityParent can only set one of public /
protected / private
Method breakpoint:MainActivityParent [entry] - onCreate(Bundle)
overrides android.support.v4.app.FragmentActivity.onCreate
here:
package com.example.seledkarelease1;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.concurrent.ExecutionException;
import org.apache.http.util.LangUtils;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DialogFragment;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivityParent extends FragmentActivity implements
ConnectionCallbacks, OnConnectionFailedListener,
OnMyLocationButtonClickListener,
NoticeDialogFragment.NoticeDialogListener {
private ChildrenLocations ch;
private Polyline mMutablePolyline;
private boolean isGetting = false;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private String[] menuItems;
private GoogleMap mMap;
private LinkedList<LatLng> locations = new LinkedList<LatLng>();
private
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_parent);
menuItems = getResources().getStringArray(R.array.menu_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, menuItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// mMessageView = (TextView) findViewById(R.id.message_text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void setUpMapIfNeeded() {
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
setUpMap();
}
}
}
private void setUpMap() {
if (locations.size() > 1) {
LatLng[] locs = new LatLng[locations.size()];
locations.toArray(locs);
PolylineOptions opt = new PolylineOptions().add(locs/*locs[locs.length - 2], locs[locs.length - 2]*/);
mMap.addPolyline(opt.color(Color.RED).width(10));
mMap.moveCamera(CameraUpdateFactory
.newLatLng(locs[locs.length - 1]));
}
}
public void showLocation(View view) {
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
if (cd.isConnectingToInternet()) {
Toast.makeText(getApplicationContext(), "Data has been updated!", Toast.LENGTH_SHORT)
.show();
}else{
Toast.makeText(getApplicationContext(), "Please connect to the internet!", Toast.LENGTH_SHORT)
.show();
}
}
public void loadPath(View view) {
TextView tv = (TextView) findViewById(R.id.fileNameField);
try {
FileInputStream fin = openFileInput(tv.getText().toString());
InputStreamReader isr = new InputStreamReader(fin);
BufferedReader buffreader = new BufferedReader(isr);
locations = new LinkedList<LatLng>();
String res = "";
String readString = buffreader.readLine();
while (readString != null) {
res += readString;
readString = buffreader.readLine();
}
isr.close();
Toast.makeText(this, res, Toast.LENGTH_SHORT).show();
setUpMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
if(position==0||position==1)
showNoticeDialog();
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
public void showNoticeDialog() {
DialogFragment dialog = new NoticeDialogFragment();
dialog.show(MainActivityParent.this.getFragmentManager(),
"NoticeDialogFragment");
}
public void onUserSetValue(String name, String pass)
throws InterruptedException, ExecutionException {
isGetting=true;
String res = new Client().execute("8888", name + " " + pass).get();
if (res.equals("-1"))
Toast.makeText(getApplicationContext(), "User was not found",
Toast.LENGTH_SHORT).show();
if (res.equals("1"))
Toast.makeText(getApplicationContext(),
"User was succefully connected", Toast.LENGTH_SHORT).show();
if (res.equals("0"))
Toast.makeText(getApplicationContext(), "Incorrect password",
Toast.LENGTH_SHORT).show();
isGetting=false;
}
/**
* Callback called when disconnected from GCore. Implementation of
* {#link ConnectionCallbacks}.
*/
#Override
public void onDisconnected() {
}
/**
* Implementation of {#link OnConnectionFailedListener}.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
.show();
return false;
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
// TODO Auto-generated method stub
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
}
but at the same method in another class there are not these errors.
You have a empty floating private in your member declaration. remove that.
private LinkedList<LatLng> locations = new LinkedList<LatLng>();
private

Categories

Resources