Recyclerview Adapter not refreshing - java

I have a mind-boggling problem I can't seem to solve.
The data in my RecyclerView is not updating, and after an entire day of debugging, I can't find the problematic code. The API returns the correct data, and I parse the correct data in a wallItemList which I pass to the Adapter.
How It Should Behave
After changing the language setting to either one of the 2 (English or Dutch), the items in my Recyclerview should update with it and the title of the element should change to the translated string.
What I Have Tried
Creating a refresh function inside the adapter, and update the wallItemList manually by passing the created wallItemList from the MainActivity and calling notifyDataSetChanged()
Calling notifyDataSetChanged() before, in and after the OnClickListener in the MyRecyclerViewAdapter
Setting the item in onBindViewHolder in the MyRecyclerViewAdapter
Strangely enough, when logging the language of the wallItem just before adapter.setOnItemClickListener in populateRecyclerView(), the language is right. But when I get the string from the object in MyRecyclerViewAdapter's onBindViewHolder, it shows the wrong language.
Here is my MainActivity.java:
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private List<WallItem> WallItemList;
private RecyclerView mRecyclerView;
private MyRecyclerViewAdapter adapter;
private ProgressBar progressBar;
// LifeCycle variables
private String JSONResults = "";
final static private String JSON_KEY_RESULTS = "";
final static private String WALL_ITEM_LIST_KEY = "";
// SharedPrefences variables
private String APIUrlPreferenceString = "";
private String langPreferenceString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
// Setup shared preferences
setupSharedPreferences();
// Load the recyclerView
loadRecyclerView(savedInstanceState);
}
private void setLanguageSettings(String lang)
{
//create a string for country
String country = "";
if(lang.equals("en"))
{
country = "EN";
}
else if(lang.equals("nl"))
{
country = "NL";
}
//use constructor with country
Locale locale = new Locale(lang, country);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
private void setupSharedPreferences()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
APIUrlPreferenceString = sharedPreferences.getString(getString(R.string.pref_api_url_key), getString(R.string.pref_api_url_def_value));
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
// Language settings
if(sharedPreferences.getBoolean(getString(R.string.pref_lang_check_key), true))
{
// Use device settings
setLanguageSettings(Resources.getSystem().getConfiguration().locale.getLanguage());
langPreferenceString = Resources.getSystem().getConfiguration().locale.getLanguage();
}
else
{
// Use preference settings
setLanguageSettings(sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en)));
langPreferenceString = sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en));
}
}
private void loadRecyclerView(Bundle savedInstanceState)
{
// Lifecycle event to preserve data to prevent repeating API calls
if(savedInstanceState != null && savedInstanceState.containsKey(WALL_ITEM_LIST_KEY) && savedInstanceState.containsKey(JSON_KEY_RESULTS))
{
progressBar.setVisibility(View.GONE);
// Set again in order to preserve state on future rotations
JSONResults = savedInstanceState.getString(JSON_KEY_RESULTS);
// Set wallItemList again in order to preserve state on future rotations
WallItemList = savedInstanceState.getParcelableArrayList(WALL_ITEM_LIST_KEY);
populateRecyclerView();
}
else
{
// First execution
new DownloadTask().execute();
}
}
public class DownloadTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean result;
String blindWallResults;
try {
// Error fix, because NetworkUtils.buildUrl returns null when failing
if(null == NetworkUtils.buildUrl(APIUrlPreferenceString))
return false;
// Get response from API
blindWallResults = NetworkUtils.getResponseFromHttpUrl(NetworkUtils.buildUrl(APIUrlPreferenceString));
// Send to parser
JSONResults = blindWallResults;
parseResult(blindWallResults);
result = true;
} catch (IOException e) {
e.printStackTrace();
result = false;
}
// When failed
return result;
}
#Override
protected void onPostExecute(Boolean result) {
progressBar.setVisibility(View.GONE);
// If succeeded
if (result) {
populateRecyclerView();
// Show toast when data has been loaded for the first time
Toast.makeText(MainActivity.this, getString(R.string.json_toast_data_loaded), Toast.LENGTH_SHORT).show();
} else {
// If failed make toast
Toast.makeText(MainActivity.this, getString(R.string.json_toast_data_failed), Toast.LENGTH_SHORT).show();
}
}
}
/**
* Populates recyclerView and adds OnItemClickListener
*/
private void populateRecyclerView()
{
WallItem w = WallItemList.get(0);
adapter = new MyRecyclerViewAdapter(MainActivity.this, WallItemList);
mRecyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(WallItem item) {
// Function to start new activity
Class detailActivity = DetailActivity.class;
// Create intent
Intent startDetailActivityIntent = new Intent(MainActivity.this, detailActivity);
// Add object to intent
startDetailActivityIntent.putExtra("detailWallItem", (Parcelable)item);
// Start activity
startActivity(startDetailActivityIntent);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save instances of existing objects
outState.putString(JSON_KEY_RESULTS, JSONResults);
outState.putParcelableArrayList(WALL_ITEM_LIST_KEY, (ArrayList<? extends Parcelable>) this.WallItemList);
}
/**
* Parses JSON result
*
* #param result
*/
private void parseResult(String result) {
WallItemList = new ArrayList<>();
try {
JSONArray mJsonArray = new JSONArray(result);
// Loop through JSON array
for (int i = 0; i < mJsonArray.length(); i++) {
// Get picture URI fragment from JSON
String pictureURIFragment = mJsonArray.getJSONObject(i)
.getJSONArray("images").getJSONObject(0)
.getString("url");
// Load images into String
JSONArray JSONImageArray = mJsonArray.getJSONObject(i)
.getJSONArray("images");
// Create array for wallItem
String[] imageArray = new String[JSONImageArray.length()];
// Loop through JSONArray
for(int x = 0; x < JSONImageArray.length(); x++)
{
String pictureURLFragment = JSONImageArray.getJSONObject(x).getString("url");
// Built picture
URL pictureURL = NetworkUtils.builtPictureUrl(pictureURLFragment.toLowerCase());
imageArray[x] = java.net.URLDecoder.decode(pictureURL.toString());
}
// Built picture
URL pictureURL = NetworkUtils.builtPictureUrl(pictureURIFragment.toLowerCase());
String cleanPictureUrl = java.net.URLDecoder.decode(pictureURL.toString());
// add wall item to the list
WallItem item = new WallItem();
// Set fields of wallItem
item.setThumbnail(cleanPictureUrl);
item.setTitle(mJsonArray.getJSONObject(i).getString("author"));
item.setPhotographer(mJsonArray.getJSONObject(i).getString("photographer"));
item.setAddress(mJsonArray.getJSONObject(i).getString("address"));
item.setMaterial(mJsonArray.getJSONObject(i).getJSONObject("material").getString(langPreferenceString));
item.setDescription(mJsonArray.getJSONObject(i).getJSONObject("description").getString(langPreferenceString));
item.setImgURLArray(imageArray);
// Add wallItem to list
WallItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.api_url_settings_item)
{
Intent startSettingsActivity = new Intent(this, SettingsActivity.class);
startActivity(startSettingsActivity);
return true;
}
return super.onOptionsItemSelected(item);
}
private void getDeviceLanguage()
{
Log.d("HERE", Locale.getDefault().getLanguage());
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals(getString(R.string.pref_api_url_key)))
{
// Update String again
APIUrlPreferenceString = sharedPreferences.getString(getString(R.string.pref_api_url_key), getString(R.string.pref_api_url_def_value));
new DownloadTask().execute();
}
if(key.equals(getString(R.string.pref_lang_check_key)))
{
// 1. If true, use system language.
// 2. if System language != en or nl, use default language: en.
// 3. if false, make selectable
}
if(key.equals(getString(R.string.pref_lang_list_key)) || key.equals(getString(R.string.pref_lang_check_key)))
{
// Language settings
if(sharedPreferences.getBoolean(getString(R.string.pref_lang_check_key), true))
{
// Use device settings
setLanguageSettings(Resources.getSystem().getConfiguration().locale.getLanguage());
langPreferenceString = Resources.getSystem().getConfiguration().locale.getLanguage();
}
else
{
// Use preference settings
setLanguageSettings(sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en)));
langPreferenceString = sharedPreferences.getString(getString(R.string.pref_lang_list_key), getString(R.string.pref_lang_label_en));
}
// Reload data after executing new Download task
new DownloadTask().execute();
this.recreate();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
protected void onDestroy() {
super.onDestroy();
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
}
}
Here is my MyRecyclerViewAdapter.java
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
private List<WallItem> wallItemList;
private Context mContext;
private OnItemClickListener onItemClickListener;
public MyRecyclerViewAdapter(Context context, List<WallItem> wallItemList) {
this.wallItemList = wallItemList;
this.mContext = context;
WallItem w = wallItemList.get(0);
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null);
CustomViewHolder viewHolder = new CustomViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) {
final WallItem wallItem = wallItemList.get(i);
//Download image using picasso library
if (!TextUtils.isEmpty(wallItem.getThumbnail())) {
// Load image into imageView
Picasso.with(mContext).load(wallItem.getThumbnail())
.error(R.drawable.placeholder)
.placeholder(R.drawable.placeholder)
.into(customViewHolder.imageView);
}
//Setting text view title
customViewHolder.textView.setText(Html.fromHtml(wallItem.getMaterial()));
// Set OnClickListener to wallItem
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClickListener.onItemClick(wallItem);
}
};
customViewHolder.imageView.setOnClickListener(listener);
customViewHolder.textView.setOnClickListener(listener);
}
// Overwrite to return
#Override
public int getItemCount() {
return (null != wallItemList ? wallItemList.size() : 0);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
protected ImageView imageView;
protected TextView textView;
public CustomViewHolder(View view) {
super(view);
this.imageView = (ImageView) view.findViewById(R.id.thumbnail);
this.textView = (TextView) view.findViewById(R.id.title);
}
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
}
My apologies for posting all the code but I can't identify the crucial points and don't have enough experience to pinpoint where it's going wrong. If anyone could help you would it would be greatly appreciated!

I suggest you to initialize and set the adapter in onCreate() method with an empty array of WallItems.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(MainActivity.this, new ArrayList<WallItem>());
mRecyclerView.setAdapter(adapter);
progressBar = (ProgressBar) findViewById(R.id.progress_bar);
// Setup shared preferences
setupSharedPreferences();
// Load the recyclerView
loadRecyclerView(savedInstanceState);
}
To update the list of items, I normally have a setItems method inside my adapter that updates the list and calls notifyDataSetChanged()
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.CustomViewHolder> {
...
public void setItems(List<WallItem> items) {
this.wallItemList = wallItemList;
notifyDataSetChanged();
}
}
Your populateRecyclerView method then should call the setItems method to update the new list of items.
private void populateRecyclerView()
{
WallItem w = WallItemList.get(0);
adapter.setItems(WallItemList);
adapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(WallItem item) {
// Function to start new activity
Class detailActivity = DetailActivity.class;
// Create intent
Intent startDetailActivityIntent = new Intent(MainActivity.this, detailActivity);
// Add object to intent
startDetailActivityIntent.putExtra("detailWallItem", (Parcelable)item);
// Start activity
startActivity(startDetailActivityIntent);
}
});
}
I didn't test, buy this is how I normally use RecyclerView.

Related

Stop animation of Recyclerview when load more data

i'm tying to load more data each time user reached at the bottom of Recyclerview by get data of next page , using this :
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(1) && isEnd) {
page++;
isEnd = false;
new fetchData().execute(page);
}
}
});
And everything works fine , but i have a problem with animation , each time i load more data Recyclerview disappears and shows.
here's my rest of code :
public class fetchData extends AsyncTask<Integer, List<Wallpaper>, List<Wallpaper>> {
Document doc = null;
ArrayList<Wallpaper> urls = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Wallpaper> doInBackground(Integer... integers) {
try {
doc = Jsoup.connect(URLSource+"/page/" + integers[0]).get();
} catch (IOException e) {
e.printStackTrace();
}
Elements newsHeadlines = doc.select(".thumbnail");
for (Element headline : newsHeadlines) {
String thumb = headline.select("img").attr("src");
String title = headline.select("img").attr("alt");
Wallpaper wallpaperInfo = new Wallpaper();
URL = URL.replace("/wallpapers/", "/walls/");
wallpaperInfo.setThumbnails(URL);
wallpaperInfo.setTitle(title);
urls.add(wallpaperInfo);
}
return urls;
}
#Override
protected void onPostExecute(List<Wallpaper> wallpapers) {
super.onPostExecute(wallpapers);
setAdapterForRecyclerView(wallpapers);
isEnd = true;
}
}
private void setAdapterForRecyclerView(List<Wallpaper> wallpapers) {
if (myAdapter == null) {
myAdapter = new MyAdapter(wallpapers, getActivity(), new RecyclerViewClickListener() {
#Override
public void onClick(View view, Wallpaper wallpaper) {
Intent intent = new Intent(getActivity(), FullScreen.class);
intent.putExtra("img", wallpaper.getThumbnails());
if (wallpaper.getTitle().isEmpty()) {
intent.putExtra("title", "Unknown");
} else {
intent.putExtra("title", wallpaper.getTitle());
}
startActivity(intent);
/* TODO: FULLSCREEN ACTIVITY HERE*/
}
#Override
public void onClick(View view, Category categories) {
}
});
recyclerView.setAdapter(myAdapter);
} else {
myAdapter.getItems().addAll(wallpapers);
myAdapter.notifyDataSetChanged();
}
progressbar.setVisibility(View.GONE);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(1) && isEnd) {
page++;
isEnd = false;
new fetchData().execute(page);
}
}
});
}
hope you guys help me to stop this animation , i just want to load more data without any animation
i think that your problem is in the calling of setAdapterForRecyclerView as there you may create new adapter instance and set this new adapter to the recyclerview again which lead to this behavior.
i recommend to append the new list of wallpapers objects to the recyclerview list then call notifydatasetchanged

Recycleview's onClick and put extra

Please help! i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!
this my code , somebody tell my wrongs:):
AdapterFish.java
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;
// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when ViewHolder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_fish, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
public Context getActivity() {
return activity;
}
public void setActivity(Context activity) {
this.activity = activity;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView company;
TextView name;
TextView family;
TextView id;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
company= (TextView) itemView.findViewById(R.id.company);
name = (TextView) itemView.findViewById(R.id.name);
family = (TextView) itemView.findViewById(R.id.family);
id = (TextView) itemView.findViewById(R.id.id);
itemView.setOnClickListener(this);
}
// Click event for all items
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
final String ItemId = id.getText().toString().trim();
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", ItemId);
context.startActivity(intent);
}
}}
ShowSingleRecordActivity.java (Receiving ID)
public class ShowSingleRecordActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_single_record);
COMPANY = (TextView)findViewById(R.id.ncompany);
NAME = (TextView)findViewById(R.id.nname);
FAMILY=(TextView)findViewById(R.id.nfamily);
GENDER =(TextView)findViewById(R.id.ngender);
EMAIL1= (TextView)findViewById(R.id.nemail1);
EMAIL2= (TextView)findViewById(R.id.nemail2);
PHONE= (TextView)findViewById(R.id.nphone);
FAX = (TextView)findViewById(R.id.nfax);
TELLFAX = (TextView)findViewById(R.id.ntellfax);
MOBILE = (TextView)findViewById(R.id.nmobile);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ID");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("company",CompanyHolder );
intent.putExtra("name", NameHolder);
intent.putExtra("family",FamilyHolder );
intent.putExtra("gender",GenderHolder );
intent.putExtra("email1",Email1Holder );
intent.putExtra("email2",Email2Holder );
intent.putExtra("phone",PhoneHolder );
intent.putExtra("fax",FaxHolder );
intent.putExtra("tellfax",TellfaxHolder );
intent.putExtra("mobile",MobileHolder );
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(ShowSingleRecordActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
CompanyHolder = jsonObject.getString("company");
NameHolder = jsonObject.getString("name");
FamilyHolder= jsonObject.getString("family");
GenderHolder= jsonObject.getString("gender");
Email1Holder = jsonObject.getString("email1");
Email2Holder = jsonObject.getString("email2");
PhoneHolder = jsonObject.getString("phone");
FaxHolder = jsonObject.getString("fax");
TellfaxHolder = jsonObject.getString("tellfax");
MobileHolder = jsonObject.getString("mobile");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
COMPANY.setText(CompanyHolder);
NAME.setText(NameHolder);
FAMILY.setText(FamilyHolder);
GENDER.setText(GenderHolder);
EMAIL1.setText(Email1Holder);
EMAIL2.setText(Email2Holder);
PHONE.setText(PhoneHolder);
FAX.setText(FaxHolder);
TELLFAX.setText(TellfaxHolder);
MOBILE.setText(MobileHolder);
}
}
and Searching.java
public class searching extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
SearchView searchView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searching);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(searching.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.company = json_data.getString("company");
fishData.name = json_data.getString("name");
fishData.family = json_data.getString("family");
fishData.id = json_data.getString("id");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(searching.this, data);
mRVFish.setAdapter(mAdapter);
mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Try this
#Override
public void onClick(View v) {
DataFish newCurrent=data.get(getAdapterPosition());
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
final String ItemId = newCurrent.id;
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", ItemId);
context.startActivity(intent);
}
hopefully this will work .. but what exactly is your problem ? is it detecting the clicked value or passing ID to new Activity?
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.setTag(current); //<--added
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
DataFish clickedData = (DataFish) v.getTag(); //<-- pull data from tag
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", clickedData.id);
context.startActivity(intent);
}
});
}
Try with following code hope so it will be working.
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;
// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when ViewHolder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_fish, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
//final String ItemId = id.getText().toString().trim();
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", current.id);
context.startActivity(intent);
}
});
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
public Context getActivity() {
return activity;
}
public void setActivity(Context activity) {
this.activity = activity;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView company;
TextView name;
TextView family;
TextView id;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
company= (TextView) itemView.findViewById(R.id.company);
name = (TextView) itemView.findViewById(R.id.name);
family = (TextView) itemView.findViewById(R.id.family);
id = (TextView) itemView.findViewById(R.id.id);
itemView.setOnClickListener(this);
}
// Click event for all items
#Override
public void onClick(View v) {
}
}}
ShowSingleRecordActivity.java (Receiving ID)
public class ShowSingleRecordActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_single_record);
COMPANY = (TextView)findViewById(R.id.ncompany);
NAME = (TextView)findViewById(R.id.nname);
FAMILY=(TextView)findViewById(R.id.nfamily);
GENDER =(TextView)findViewById(R.id.ngender);
EMAIL1= (TextView)findViewById(R.id.nemail1);
EMAIL2= (TextView)findViewById(R.id.nemail2);
PHONE= (TextView)findViewById(R.id.nphone);
FAX = (TextView)findViewById(R.id.nfax);
TELLFAX = (TextView)findViewById(R.id.ntellfax);
MOBILE = (TextView)findViewById(R.id.nmobile);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getExtra("ID");
System.out.println("TempItem=============>"+TempItem )
//Calling method to filter Student Record and open selected record.
if(null != TempItem){
HttpWebCall(TempItem);
}else{
Toast.makeText(context, "Item ID is not get from list", Toast.LENGTH_SHORT).show();
}
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("company",CompanyHolder );
intent.putExtra("name", NameHolder);
intent.putExtra("family",FamilyHolder );
intent.putExtra("gender",GenderHolder );
intent.putExtra("email1",Email1Holder );
intent.putExtra("email2",Email2Holder );
intent.putExtra("phone",PhoneHolder );
intent.putExtra("fax",FaxHolder );
intent.putExtra("tellfax",TellfaxHolder );
intent.putExtra("mobile",MobileHolder );
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(ShowSingleRecordActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
CompanyHolder = jsonObject.getString("company");
NameHolder = jsonObject.getString("name");
FamilyHolder= jsonObject.getString("family");
GenderHolder= jsonObject.getString("gender");
Email1Holder = jsonObject.getString("email1");
Email2Holder = jsonObject.getString("email2");
PhoneHolder = jsonObject.getString("phone");
FaxHolder = jsonObject.getString("fax");
TellfaxHolder = jsonObject.getString("tellfax");
MobileHolder = jsonObject.getString("mobile");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
COMPANY.setText(CompanyHolder);
NAME.setText(NameHolder);
FAMILY.setText(FamilyHolder);
GENDER.setText(GenderHolder);
EMAIL1.setText(Email1Holder);
EMAIL2.setText(Email2Holder);
PHONE.setText(PhoneHolder);
FAX.setText(FaxHolder);
TELLFAX.setText(TellfaxHolder);
MOBILE.setText(MobileHolder);
}
}
Replace this line in ShowSingleRecordActivity
TempItem = getIntent().getStringExtra("ID");
to
TempItem = getIntent().getExtras().getString("ID");

What method to add in NearablesDemoActivity.java

I'm working on a project for Shoe sticker using estimote sticker and facing some problems. I'm using android studio for my project
I have error at dbRow = stickerdb.getResult(currentNearable.identifier("065473d63cd9d687"));
It says Method call expected
The error log:
Error:(96, 52) error: cannot find symbol method identifier(String)
public class NearablesDemoActivity extends BaseActivity {
private static final String TAG = NearablesDemoActivity.class.getSimpleName();
private Nearable currentNearable;
private BeaconManager beaconManager;
private String scanId;
TextView Desc; //description
Spinner spinnerDropDown; //for size available
String[] size = {
}; //for size available
Spinner spinnerDropDown2; //for colours available
String[] colour = {
}; //for colours available
TextView COO; //For country of origin
TextView SM; //For Shoe Model
TextView Price; //For price
Button btnRating; //for button
private Database_sticker stickerdb;
Sresult dbRow;
#Override
protected int getLayoutResId() {
return R.layout.nearable_demo;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearable_demo);
currentNearable = getIntent().getExtras().getParcelable(ListNearablesActivity.EXTRAS_NEARABLE);
displayCurrentNearableInfo();
beaconManager = new BeaconManager(this);
ArrayAdapter<String> adapter= new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item ,size); //for size available
spinnerDropDown.setAdapter(adapter);
ArrayAdapter<String> adapter1= new ArrayAdapter<>(this,android.R.layout.simple_spinner_dropdown_item ,colour); //for colours available
spinnerDropDown2.setAdapter(adapter1);
toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_action_navigation_arrow_back);
toolbar.setTitle(getTitle());
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
btnRating=(Button)findViewById(R.id.rd);
btnRating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent pageforRatingBar = new Intent(getApplicationContext(), RatingBar_main.class);
startActivity(pageforRatingBar);
}
});
stickerdb = new Database_sticker(this);
// dbRow = stickerdb.getResult(1);//currentNearable.identifier()
dbRow = stickerdb.getResult(currentNearable.identifier("065473d63cd9d687"));
dbRow.getSa();
dbRow.getDesc();
dbRow.getCoo();
dbRow.getId();
dbRow.getPrice();
dbRow.getSm();
}
#Override
protected void onResume() {
super.onResume();
beaconManager.setNearableListener(new BeaconManager.NearableListener() {
#Override
public void onNearablesDiscovered(List<Nearable> nearables) {
updateCurrentNearable(nearables);
displayCurrentNearableInfo();
}
});
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
scanId = beaconManager.startNearableDiscovery();
}
});
}
#Override
protected void onStop() {
beaconManager.disconnect();
super.onStop();
}
private void displayCurrentNearableInfo() {
Desc = (TextView) findViewById(R.id.textview1); //for description
// Get reference of SpinnerView from layout/nearable_demo.xml
spinnerDropDown = (Spinner) findViewById(R.id.spinner1); //For size available
spinnerDropDown2 = (Spinner) findViewById(R.id.spinner2);//for colours available
COO = (TextView) findViewById(R.id.textview2);//for country of origin
SM = (TextView) findViewById(R.id.textview3); //for shoe model
Price = (TextView) findViewById(R.id.textview4); //for price
}
private void updateCurrentNearable(List<Nearable> nearables) {
for (Nearable nearable : nearables) {
if (nearable.equals(currentNearable)) {
currentNearable = nearable;
}
}
}
}
You're calling an identifier method on an object of the Nearable class. There is no such method in this class:
http://estimote.github.io/Android-SDK/JavaDocs/com/estimote/sdk/Nearable.html
There is, however, an identifier property, and that's the one you need to use:
http://estimote.github.io/Android-SDK/JavaDocs/com/estimote/sdk/Nearable.html#identifier
In other words, this line:
dbRow = stickerdb.getResult(currentNearable.identifier("065473d63cd9d687"));
… needs to become:
dbRow = stickerdb.getResult(currentNearable.identifier);

How to sort ArrayList in descending order

Ok i have one list with movies and there i have some image, title, ratings, genres and year in one row for every item in listView. And now i'm trying to sort these movies by name, rating and year. I have followed this tutorial, but i have stucked here:
#Override
public void onClick(View view) {
if(view.getTag().equals(TAG_SORT_NAME)){
adapter.getItem();
}
if(view.getTag().equals(TAG_SORT_RATING)){
}
if(view.getTag().equals(TAG_SORT_YEAR)){
}
}
I don't know what should i passed there for getItem and in his tutorial he is using fragments and i'm not. Here is my activity:
public class ListaPreporuka extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener
, SortListener{
// Log tag
private static final String TAG = ListaPreporuka.class.getSimpleName();
// Movies json url
private static final String url = "http://www.nadji-ekipu.org/wp-content/uploads/2015/07/movies.txt";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
private CustomListAdapter adapter;
private static final String TAG_SORT_NAME = "sortName";
private static final String TAG_SORT_RATING = "sortRating";
private static final String TAG_SORT_YEAR = "sortYear";
private static String Year = "year";
private static String Rating = "rating";
private static String Title = "title";
private static String bitmap = "thumbnailUrl";
private static String opis = "opis";
private static String urlMovie = "url";
private MediaPlayer mp_off;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_preporuka);
// Toolbabr settings
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setLogo(R.drawable.ic_horor_filmovi_ikonica);
Intent newActivity2=new Intent();
setResult(RESULT_OK, newActivity2);
mp_off = MediaPlayer.create(this, R.raw.button_click_off);
final MediaPlayer mp_on = MediaPlayer.create(this, R.raw.button_click_on);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setIcon(R.drawable.ic_horor_filmovi_ikonica);
pDialog.setMessage("Učitavanje...");
pDialog.setCancelable(false);
pDialog.show();
listView = (ListView) findViewById(R.id.list);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create
* As animation won't start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
if (AppStatus.getInstance(this).isOnline()) {
Log.v("Home", "############################You are online!!!!");
} else {
setContentView(R.layout.no_connection);
Toast t = Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT);
t.show();
Log.v("Home", "############################You are not online!!!!");
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String opisFilma = ((TextView) view.findViewById(R.id.opis))
.getText().toString();
String urlFilm = ((TextView) view.findViewById(R.id.url))
.getText().toString();
String ocena = String.valueOf(movieList.get(position).getRating());
String godina = String.valueOf(movieList.get(position).getYear());
bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
Intent intent = new Intent(ListaPreporuka.this, MoviesSingleActivity.class);
intent.putExtra(Title, name);
intent.putExtra(opis, opisFilma);
intent.putExtra("images", bitmap);
intent.putExtra(Rating, ocena);
intent.putExtra(Year, godina);
intent.putExtra(urlMovie, urlFilm);
mp_on.start();
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
});
buildFAB();
}
private void buildFAB(){
// Declare icon for FAB
ImageView icon = new ImageView(this);
icon.setImageResource(R.drawable.ic_halloween);
// Build FAB
FloatingActionButton actionButton = new FloatingActionButton.Builder(this)
.setContentView(icon)
.build();
// Declare icons for SubAction Buttons
ImageView iconSortName = new ImageView(this);
iconSortName.setImageResource(R.drawable.ic_halloween);
ImageView iconSortRating = new ImageView(this);
iconSortRating.setImageResource(R.drawable.ic_halloween);
ImageView iconSortYear = new ImageView(this);
iconSortYear.setImageResource(R.drawable.ic_halloween);
// Set the background for all Sub buttons
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
// Build the Sub Buttons
SubActionButton buttonSortName = itemBuilder.setContentView(iconSortName).build();
SubActionButton buttonSortRating = itemBuilder.setContentView(iconSortRating).build();
SubActionButton buttonSortYear = itemBuilder.setContentView(iconSortYear).build();
buttonSortName.setTag(TAG_SORT_NAME);
buttonSortRating.setTag(TAG_SORT_RATING);
buttonSortYear.setTag(TAG_SORT_YEAR);
buttonSortName.setOnClickListener(this);
buttonSortRating.setOnClickListener(this);
buttonSortYear.setOnClickListener(this);
// add the sub buttons to the main floating action button
FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this)
.addSubActionView(buttonSortName)
.addSubActionView(buttonSortRating)
.addSubActionView(buttonSortYear)
.attachTo(actionButton)
.build();
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies(){
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
movieList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setOpis(obj.getString("opis"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
movie.setUrl(obj.getString("url"));
// Genre is json array
final JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
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.
if (item.getItemId() == android.R.id.home) {
finish();
mp_off.start();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
return true;
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
mp_off.start();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
#Override
public void onClick(View view) {
if(view.getTag().equals(TAG_SORT_NAME)){
adapter.getItem();
}
if(view.getTag().equals(TAG_SORT_RATING)){
}
if(view.getTag().equals(TAG_SORT_YEAR)){
}
}
#Override
public void onSortByName() {
}
#Override
public void onSortByRating() {
}
#Override
public void onSortByYear() {
}
}
You should sort your movieList, assuming Movie contains genre String field, below is some quick example to sort it:
Comparator<Movie> comparator = new Comparator<Movie>() {
#Override
public int compare(Movie movie, Movie t1) {
return movie.genre.compareTo(t1.genre);
}
};
// ordered by genre
Collections.sort(movieList, comparator);
// Reverse order by genre
Collections.sort(movieList, Collections.reverseOrder(comparator));

How to pass value from recyclerview item to another activity

I'm trying to pass the value in recyclerview item to another activity when we click the recyclerview item. Here I use the OnItemTouchListener.
I retrieve data from JSON and parse it into ArrayList. I save 5 parameters. Title, ID, Rating, ReleaseDate, urlPoster, but right now i only show 2 parameters, Title, and image from urlposter.
I want to pass the other parameters to another activity, but i can't find out how to do that.
There's another question similar like this (Values from RecyclerView item to other Activity), but he uses OnClick, not OnItemTouch, and he do that in the ViewHolder. I read somewhere in the internet that it's not the right thing to do.
Here's my code
public class Tab1 extends Fragment {
private static final String ARG_PAGE = "arg_page";
private static final String STATE_MOVIES = "state movies";
private TextView txtResponse;
private String passID;
// Progress dialog
private ProgressDialog pDialog;
//private String urlJsonArry = "http://api.androidhive.info/volley/person_array.json";
private String urlJsonArry = "http://api.themoviedb.org/3/movie/popular?api_key=someapikeyhere";
private String urlJsonImg = "http://image.tmdb.org/t/p/w342";
// temporary string to show the parsed response
private String jsonResponse = "";
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
private ArrayList<Movies> movies = new ArrayList<Movies>();
public Tab1() {
// Required empty public constructor
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(STATE_MOVIES, movies);
}
public static Tab1 newInstance(int pageNumber){
Tab1 myFragment = new Tab1();
Bundle arguments = new Bundle();
arguments.putInt(ARG_PAGE, pageNumber);
myFragment.setArguments(arguments);
return myFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
}
/**
* Method to make json object request where json response starts wtih {
* */
private void makeJsonObjectRequest() {
showpDialog();
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlJsonArry, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
try {
JSONArray result = response.getJSONArray("results");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < result.length(); i++){
JSONObject jsonObject = result.getJSONObject(i);
String id = jsonObject.getString("id");
String originalTitle = jsonObject.getString("original_title");
String releaseDate = jsonObject.getString("release_date");
String rating = jsonObject.getString("vote_average");
String urlThumbnail = urlJsonImg + jsonObject.getString("poster_path");
//jsonResponse = "";
jsonResponse += "ID: " + id + "\n\n";
jsonResponse += "Title: " + originalTitle + "\n\n";
jsonResponse += "Release Date: " + releaseDate + "\n\n";
jsonResponse += "Rating: " + rating + "\n\n";
}
//Toast.makeText(getActivity(),"Response = "+jsonResponse,Toast.LENGTH_LONG).show();
parseResult(response);
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(),"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});
// Adding request to request queue
VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//txtResponse = (TextView) getActivity().findViewById(R.id.txtResponse);
//makeJsonArrayRequest();
// Calling the RecyclerView
mRecyclerView = (RecyclerView) getActivity().findViewById(R.id.recycler_view_movie);
mRecyclerView.setHasFixedSize(true);
// The number of Columns
mLayoutManager = new GridLayoutManager(getActivity(),2);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MovieAdapter(getActivity(),movies);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), mRecyclerView, new ClickListener() {
#Override
public void onMovieClick(View view, int position) {
Toast.makeText(getActivity(), "Kepencet " + position, Toast.LENGTH_SHORT).show();
**//what to do here?**
}
#Override
public void onMovieLongClick(View view, int position) {
Toast.makeText(getActivity(),"Kepencet Lama "+position,Toast.LENGTH_LONG).show();
}
}));
makeJsonObjectRequest();
if (savedInstanceState!=null){
movies=savedInstanceState.getParcelableArrayList(STATE_MOVIES);
mAdapter.notifyDataSetChanged();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.tab_1, container, false);
return view;
}
private void parseResult(JSONObject response) {
try {
JSONArray arrayMovies = response.getJSONArray("results");
if (movies == null) {
movies = new ArrayList<Movies>();
}
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovies = arrayMovies.getJSONObject(i);
Movies item = new Movies();
item.setTitle(currentMovies.optString("original_title"));
item.setRating(currentMovies.optString("vote_average"));
item.setReleaseDate(currentMovies.optString("release_date"));
item.setId(currentMovies.optString("id"));
item.setUrlThumbnail(urlJsonImg+currentMovies.optString("poster_path"));
movies.add(item);
mAdapter.notifyDataSetChanged();
//Toast.makeText(getActivity(),"Movie : "+movies,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector mGestureDetector;
private ClickListener mClickListener;
public RecyclerTouchListener(final Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.mClickListener = clickListener;
mGestureDetector = 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.onMovieLongClick(child,recyclerView.getChildAdapterPosition(child));
}
super.onLongPress(e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child!=null && mClickListener!=null && mGestureDetector.onTouchEvent(e)){
mClickListener.onMovieClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener{
public void onMovieClick(View view, int position);
public void onMovieLongClick(View view, int position);
}
}
any help would be appreciated. Thanks!
You need to add those other two values to a bundle in the intent. So something like this:
Intent intent = new Intent(getActivity(), YourNextActivity.class);
intent.putExtra("movie_id_key", movies.get(position).getId); //you can name the keys whatever you like
intent.putExtra("movie_rating_key", movies.get(position).getRating); //note that all these values have to be primitive (i.e boolean, int, double, String, etc.)
intent.putExtra("movie_release_date_key", movies.get(position).getReleaseDate);
startActivity(intent)
And in your new activity just do this to retrieve:
String id = getIntent().getExtras().getString("movie_id_key");
Add them as extras in the intent with which you start the activity:
Intent intent = new Intent(currentActivity, targetActivity);
// Sree was right in his answer, it's putExtra, not putStringExtra. =(
intent.putExtra("title", title);
// repeat for ID, Rating, ReleaseDate, urlPoster
startActivity(intent);
then pull them out in the onCreate of the other activity with
Intent startingIntent = getIntent();
String title = startingIntent.getStringExtra("title"); // or whatever.
In response to the comment below:
I'm not 100% sure how you implemented it, but it looks like you have onclick handlers that pass a position and a view reference, right? Adapt it as you like, but basically...:
public void onClick(View v, int position){
Movie m = movies.get(position);
Intent intent = new Intent(v.getContext(), AnotherActivity.class);
intent.putExtra("my_movie_foo_key", m.getFoo());
intent.putExtra("my_movie_bar_key", m.getBar());
// etc.
v.getContext().startActivity(intent);
}
As long as you have a valid context reference (and they couldn't click on a view without a valid context), you can start an activity from wherever you like.

Categories

Resources