So i developed an android news app. A spinner item is available on the toolbar and data reloads according to spinner selection. However, when the data reloads, for some of the items, it directly loads the relevant content but for some others, it loads the previously selected spinner data. Current data for the current item only shows after reloading same spinner data using the swipe refresh functionality which i had implemented. I want the correct data relevant to that selection to load the first time itself without having to refresh all the time.
Below is my MainActivity where all these functions are called.
package com.example.app.activities;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessaging;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="url" //outputs JSON data
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
prefManager = new PrefManager(MainActivity.this);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if (++check > 1) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
//intent.putExtra("NAME_KEY", itemSelected);
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
#Override
public int getCount() {
return pager_number;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).equals(myString)) {
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//TODO DONE
String name = prefManager.spinReadString();
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
//TODO DONE
if (spinConstituency.equals(name))
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
//TODO DONE
prefManager.writeString("" + spinConstID);
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position % 2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
I discovered that from API level 3, one can use the onUserInteraction() on an Activity with a boolean value thereby determining the user's interaction.
Find the documentation in the link below.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
#Override
public void onUserInteraction() {
super.onUserInteraction();
userInteracts = true;
}
The my adjustment goes as thus in the MainActivity.java
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (IsInteracting) {
Intent intent = getIntent(); //MainActivity
String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
//TODO: DONE
prefManager.spinWriteString(itemSelected);
Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
startActivity(intent);
finish();
}
}
Related
I just created my recyclerview to show a cardview when I just filling the required data on AddNewTimerFragment.java. But somehow it wont show the card that contains the data that I've fill in before. I've tried to changes something, but doesn't work.
Code :
MainActivity.java
package com.mobprog.ius.dwasu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private ArrayList<MyListDataTimer> mintervalTimeList = new ArrayList();
private RecyclerView mRecyclerView;
private alarmListAdapter mAdapter;
public boolean isFragmentAddNewAlarmDisplayed = false;
static final String STATE_FRAGMENT = "state_of_fragment";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.textUserName)).setText("Hello " + getSharedPreferences("Dwasu", 0).getString("user", ""));
if (getSharedPreferences("Dwasu", 0) == null || !getSharedPreferences("Dwasu", 0).contains("user")) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
// Create recycler view.
mRecyclerView = findViewById(R.id.recyclerView);
// Create an adapter and supply the data to be displayed.
mAdapter = new alarmListAdapter(getApplicationContext(), mintervalTimeList);
// Connect the adapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
if (savedInstanceState != null)
isFragmentAddNewAlarmDisplayed = savedInstanceState.getBoolean(STATE_FRAGMENT);
Button mnewReminderButton = findViewById(R.id.newReminder);
mnewReminderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(MainActivity.class.getSimpleName(),"Button Clicked");
displayFragment();
}
});
ImageButton mlogOutButton = findViewById(R.id.logOutButton);
findViewById(R.id.logOutButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSharedPreferences("Dwasu", 0).edit().clear().apply();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
// // Get the Drawable custom_progressbar
// Drawable draw = ResourcesCompat.getDrawable(getResources(), R.drawable.progress_bar, null);
// // set the drawable as progress drawable
// ProgressBar.setProgressDrawable(draw);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the state of the fragment (true=open, false=closed).
savedInstanceState.putBoolean(STATE_FRAGMENT, isFragmentAddNewAlarmDisplayed);
super.onSaveInstanceState(savedInstanceState);
}
public void closeFragment(){
// Get the FragmentManager.
FragmentManager fragmentManager = getSupportFragmentManager();
// Check to see if the fragment is already showing.
AddNewTimerFragment simpleFragment = (AddNewTimerFragment) fragmentManager
.findFragmentById(R.id.FragmentContainer_AddNewAlarm);
if (simpleFragment != null) {
// Create and commit the transaction to remove the fragment.
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.remove(simpleFragment).commit();
}
// Set boolean flag to indicate fragment is closed.
isFragmentAddNewAlarmDisplayed = false;
}
public void displayFragment(){
AddNewTimerFragment simpleFragment = AddNewTimerFragment.newInstance();
// Get the FragmentManager and start a transaction.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// Add the SimpleFragment.
fragmentTransaction.add(R.id.FragmentContainer_AddNewAlarm,
simpleFragment).addToBackStack(null).commit();
// Set boolean flag to indicate fragment is open.
isFragmentAddNewAlarmDisplayed = true;
}
}
AddNewTimerFragment.java
package com.mobprog.ius.dwasu;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import org.apache.http.entity.mime.content.StringBody;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import static android.content.Context.MODE_PRIVATE;
public class AddNewTimerFragment extends Fragment {
Button startTime;
Button endTime;
Button meditConfirm_button;
int startHour;
int startMinute;
int endHour;
int endMinute;
int position = 1;
long totalSize = 0;
String value;
ProgressDialog progDailog;
View rootview;
private SharedPreferences mPreferences;
private String sharedPrefFile =
"com.mobprog.ius.dwasu";
public AddNewTimerFragment() {
// Required empty public constructor
}
public static AddNewTimerFragment newInstance() {
return new AddNewTimerFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_new_alarm,
container, false);
rootview = rootView;
/*Shared Pref*/
mPreferences = this.getActivity().getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
SharedPreferences.Editor mPreferencesEditor = mPreferences.edit();
ImageButton mbtnCloseFragment = rootView.findViewById(R.id.btnCloseFragment);
mbtnCloseFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).closeFragment();
}
});
// initiate the edit text
startTime = rootView.findViewById(R.id.startTimePick);
startTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
startTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
startHour = mcurrentTime.get(Calendar.HOUR);
startMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mStartTimePicker;
mStartTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedStartHour, int selectedStartMinute) {
if (selectedStartMinute == 0) {
startTime.setText(selectedStartHour + ":00");
} else if (selectedStartMinute < 10) {
if (selectedStartHour < 10) {
startTime.setText("0" + selectedStartHour + ":0" + selectedStartMinute);
}
} else {
startTime.setText(selectedStartHour + ":" + selectedStartMinute);
}
startHour = selectedStartHour;
}
}, startHour, startMinute, true);//Yes 24 hour time
mStartTimePicker.show();
}
});
endTime = rootView.findViewById(R.id.endTimePick);
endTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
endTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
endHour = mcurrentTime.get(Calendar.HOUR);
endMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mEndTimePicker;
mEndTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedEndHour, int selectedEndMinute) {
if (selectedEndMinute == 0) {
endTime.setText(selectedEndHour + ":00");
} else if (selectedEndMinute < 10) {
if (selectedEndHour < 10) {
endTime.setText("0" + selectedEndHour + ":0" + selectedEndMinute);
}
} else {
endTime.setText(selectedEndHour + ":" + selectedEndMinute);
}
endHour = selectedEndHour;
}
}, endHour, endMinute, true);//Yes 24 hour time
mEndTimePicker.show();
}
});
Spinner spinner = (Spinner) rootView.findViewById(R.id.timeIntervalPick);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.listtimer, R.layout.spinner_support);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.spinner_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String[] valueListTimer = getResources().getStringArray(R.array.valueListTimer);
value = valueListTimer[position];
Log.e("Value of Spinner", value);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
meditConfirm_button = rootView.findViewById(R.id.editConfirm_button);
meditConfirm_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String.valueOf(startHour);
String.valueOf(endHour);
String.valueOf(value);
new MyListDataTimer(String.valueOf(startHour),String.valueOf(endHour),String.valueOf(value),String.valueOf(position));
new UploadAlarmDataToServer().execute();
position++;
}
});
// Inflate the layout for this fragment
return rootView;
}
private class UploadAlarmDataToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progDailog = new ProgressDialog(getContext());
progDailog.setMessage("Menyimpan...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(false);
progDailog.setCanceledOnTouchOutside(false);
progDailog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
String data = null;
try {
data = sendDataTimer();
} catch (Exception e) {
e.printStackTrace();
data = "Gagal";
}
return data;
}
public String sendDataTimer() throws Exception {
URL url = new URL("https://ius.mobile.indoserver.web.id/alarmData.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
entity.addPart("startHour", new StringBody(startHour + ""));
entity.addPart("endHour", new StringBody(endHour + ""));
entity.addPart("intervalWaktu", new StringBody(value + ""));
totalSize = entity.getContentLength();
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.addRequestProperty("Content-length", totalSize + "");
con.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = con.getOutputStream();
entity.writeTo(con.getOutputStream());
os.close();
con.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
#Override
protected void onPostExecute(String result) {
progDailog.dismiss();
if (result != null) {
Log.e("UPLOAD", result);
if (result.equalsIgnoreCase("OK")) {
Toast.makeText(getContext(), "Data Alarm tersimpan", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getContext(), MainActivity.class));
}
}
super.onPostExecute(result);
}
}
}
alarmListAdapter.java
package com.mobprog.ius.dwasu;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedList;
public class alarmListAdapter extends RecyclerView.Adapter<alarmListAdapter.alarmListHolder>{
private final ArrayList<MyListDataTimer> mintervalTimeList;
private LayoutInflater mInflater;
public alarmListAdapter(Context context, ArrayList<MyListDataTimer> mintervalTimeList) {
mInflater = LayoutInflater.from(context);
this.mintervalTimeList = mintervalTimeList;
}
#Override
public alarmListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.alarm_item,
parent, false);
return new alarmListHolder(mItemView, this);
}
#Override
public void onBindViewHolder(alarmListAdapter.alarmListHolder holder, int position) {
final MyListDataTimer myListData = mintervalTimeList.get(position);
holder.mintervalTime.setText(myListData.getIntervalWaktu());
holder.mtimeWork.setText(myListData.getStartHour() +":00 - " + myListData.getEndHour() +":00");
}
#Override
public int getItemCount() {
return mintervalTimeList.size();
}
public class alarmListHolder extends RecyclerView.ViewHolder {
public TextView mintervalTime;
public TextView mtimeWork;
final alarmListAdapter mAdapter;
public alarmListHolder(View itemView, alarmListAdapter adapter) {
super(itemView);
mintervalTime = itemView.findViewById(R.id.intervalTime);
mtimeWork = itemView.findViewById(R.id.timeWork);
this.mAdapter = adapter;
}
}
}
**MyListDataTimer.java**
package com.mobprog.ius.dwasu;
public class MyListDataTimer {
private String startHour;
private String endHour;
private String intervalWaktu;
private String position;
public MyListDataTimer(String startHour, String endHour, String intervalWaktu, String position) {
this.startHour = startHour;
this.endHour = endHour;
this.intervalWaktu = intervalWaktu;
this.position = position;
}
public String getStartHour() {
return startHour;
}
public void setStartHour(String startHour) {
this.startHour = startHour;
}
public String getEndHour() {
return endHour;
}
public void setEndHour(String endHour) {
this.endHour = endHour;
}
public String getIntervalWaktu() {
return intervalWaktu;
}
public void setIntervalWaktu(String intervalWaktu) {
this.intervalWaktu = intervalWaktu;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
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.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}
Currently I'm trying solve a issue. When I open my app, it must show the JSON output data, but the JSON take 1 - 2 seconds to finish the loading, and after that, still not updating the fragment view.
What I've tried:
1 - Using notifyDataSetChanged()
2 - Testing the app on real mobile device
3 - Search so much before create this thread.
Nothing helped me at this moment.
MainActivity.java
package etes.xdda.music;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private DrawerLayout nDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Handler mHandler = new Handler();
private TabLayout tabLayout;
private ViewPager viewPager;
private viewPagerAdapter adapter;
public LinearLayout menu_dialog;
public LinearLayout menu_dialog2;
public TextView song_detail;
public TextView time1;
public TextView time2;
private String player_status = "playing";
private ImageButton player_img;
public static SeekBar seekBar;
public static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDrawerLayout = findViewById(R.id.drawer);
menu_dialog = findViewById(R.id.menu_dialog);
menu_dialog.setVisibility(View.GONE);
menu_dialog2 = findViewById(R.id.menu_dialog2);
menu_dialog2.setVisibility(View.GONE);
song_detail = findViewById(R.id.song_detail);
song_detail.setVisibility(View.GONE);
time1 = findViewById(R.id.time_1);
time2 = findViewById(R.id.time_2);
seekBar = findViewById(R.id.seekBar);
mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
nDrawerLayout.addDrawerListener(mToggle);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
tabLayout = findViewById(R.id.tablayout_id);
viewPager = findViewById(R.id.viewpager_id);
//viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
//setMarginBottom(viewPager, 0);
setMargins(viewPager, 0, 0, 0, 0);
adapter = new viewPagerAdapter(getSupportFragmentManager());
//Add fragments here
adapter.addFragment(new fragmentList(), ""); //Lista de música
adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
adapter.addFragment(new fragmentPlayList(), ""); //Playlist
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if (mediaPlayer != null) {
int CurrentPosition = mediaPlayer.getCurrentPosition();
int Duration = mediaPlayer.getDuration();
int progress = (getProgressPercentage(CurrentPosition, Duration));
seekBar.setProgress(progress);
String m_1;
String s_1;
//Toast.makeText(getApplicationContext(), "Current: " + CurrentPosition + " - Duration: " + mediaPlayer.getDuration(), Toast.LENGTH_LONG).show();
final int minutes_1 = (CurrentPosition / 1000) / 60;
final int seconds_1 = ((CurrentPosition / 1000) % 60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
String m_2;
String s_2;
final int minutes_2 = (Duration / 1000) / 60;
final int seconds_2 = ((Duration / 1000) % 60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
player_img = findViewById(R.id.playorpause);
player_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setMargins(viewPager, 0,0,0,110);
if (player_status == "playing") {
player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
pauseAudio();
mHandler.removeCallbacks(mRunnable);// essencial para economizar bateria;
player_status = "paused";
} else {
player_img.setImageResource(R.drawable.ic_pause_black_24dp);
startAudio();
mHandler.postDelayed(mRunnable, 1000); // essencial para economizar bateria;
player_status = "playing";
}
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
//int _progress = (getProgressPercentage(progress*10000, mediaPlayer.getDuration()));
//Toast.makeText(getApplicationContext(), String.valueOf(_progress), Toast.LENGTH_LONG).show();
//mediaPlayer.seekTo(progress);
int _progress = (progress * mediaPlayer.getDuration())/100;
mediaPlayer.seekTo(_progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
registerReceiver(broadcastReceiver, new IntentFilter("my-permission-response-action"));
registerReceiver(broadcastReceiver2, new IntentFilter("my-permission-response-quit"));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
};
BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
killMediaPlayer();
Toast.makeText(context, "OK2", Toast.LENGTH_LONG).show();
}
};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mToggle.syncState();
}
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
public void initAudio(final Context context, String url) {
if (mediaPlayer == null) {
try {
url = url.replace(" ", "%20");
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
catch (Exception e) {
Toast.makeText(context, "Falha ao iniciar o áudio", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
killMediaPlayer();
updateLayout();
clearNotificationBar();
}
});
seekBar.setMax(100);
mediaPlayer.start();
}
public void updateNotificationBar(String title, String author) {
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
Notification.MediaStyle style = new Notification.MediaStyle();
Bitmap notificationLargeIconBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_play_circle_filled_black_24dp);
Intent intent = new Intent(this, ActionReceiver.class);
intent.putExtra("action","action1");
Intent intent2 = new Intent(this, updateNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setSmallIcon(R.drawable.ic_play_circle_outline_black_40dp)
.setLargeIcon(notificationLargeIconBitmap)
.setContentTitle(title)
.setContentText(author)
.setContentIntent(pendingIntent)
.setDeleteIntent(pendingIntent2)
.setColor(this.getResources().getColor(R.color.colorPrimary))
.setPriority(Notification.PRIORITY_MAX)
//.setOngoing(true) // n vai fechar a notificação
.addAction(R.drawable.ic_skip_previous_black_24dp, "Prev", pendingIntent)
.addAction(R.drawable.ic_pause_black_24dp, "PlayOrPause", pendingIntent)
.addAction(R.drawable.ic_skip_next_black_24dp, "Next", pendingIntent)
.setStyle(style);
notificationManager.notify(0, builder.build());
}
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
clearNotificationBar();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public int getProgressPercentage(long currentDuration, long totalDuration){
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 100);
long totalSeconds = (int) (totalDuration / 100);
// calculando porcentagem
percentage =(((double)currentSeconds)/totalSeconds)*100;
// retornando porcentagem
return percentage.intValue();
}
private void updateLayout() {
try {
menu_dialog.setVisibility(View.GONE);
menu_dialog2.setVisibility(View.GONE);
song_detail.setVisibility(View.GONE);
setMargins(viewPager.findViewById(R.id.viewpager_id), 0,0,0,0);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public static void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
public void clearNotificationBar() {
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
}
}
fragmentList.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
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 fragmentList extends Fragment {
View v;
private RecyclerView myrecyclerview;
private List<mList> lstContact;
private String URL_JSON = "http://ntcdn.stream/audio/";
private JsonArrayRequest ArrayRequest;
private RequestQueue requestQueue ;
public fragmentList() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.list_fragment,container,false);
myrecyclerview = v.findViewById(R.id.list_recyclerview);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter((MainActivity)getActivity(), lstContact);
myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
myrecyclerview.setAdapter(recyclerViewAdapter);
return v;
}
#Override
public void onCreate(#Nullable Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
_JSONcall();
}
public void _JSONcall() {
lstContact = new ArrayList<>();
ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0 ; i<response.length();i++) {
try {
jsonObject = response.getJSONObject(i);
lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
}
catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error 1!",
Toast.LENGTH_LONG).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error 3!",
Toast.LENGTH_LONG).show();
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(ArrayRequest);
}
}
viewPagerAdapter.java
package etes.xdda.music;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class viewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public viewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return lstFragment.get(position);
}
#Override
public int getCount() {
return lstTitles.size();
}
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
public void addFragment(Fragment fragment, String title) {
lstFragment.add(fragment);
lstTitles.add(title);
}
}
Can you help me? I really don't know what I must do to fix this problem and make the system update the view after JSON finish the loading
Solution:
Follow the below steps:
Step1:
Make this: RecyclerViewAdapter recyclerViewAdapter as a Global object so that you can access it throughout the Fragment.
Step2:
Add this line: recyclerviewadapter.notifyDataSetChanged() after the for loop in your onResponse() method.
Try it, Hopefully it should work.
Try to initialize the array list in your fragment where you have declared it
private List<mList> listContact= new ArrayList<>();
and try notifyDataSetChanged(); in your fragment too
Create an instance of your adapter in fragment and
check whether your adapter is null or not.
if(adapter != null){
adapter.notifyDataSetChanged();
} else {
adapter = new Adapter(getContext, listContact);
recyclerView.setAdapter(adapter);
}
I guess i'm implementing the spinner onItemSelected inappropriately.
So i have spinner values loaded from my database. I'm trying to load data according to the spinner selected but the spinner doesn't persist and the id doesn't pass to the activity. It loads a default id of 1 instead of the selected spinner id. So i'm not sure if the spinner id is being passed. How do i check these and correct them?
package com.example.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.firebase.messaging.FirebaseMessaging;
import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.models.Constituency;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import com.squareup.picasso.Picasso;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
public class MainActivity extends AppCompatActivity {
String URL="https://xxx.xxx.xxx/api/get_constituency_index/?api_key="+
Config.API_KEY;
private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set Font
CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/Arkhip_font.ttf")
.setFontAttrId(R.attr.fontPath)
.build());
setContentView(R.layout.activity_main);
view = findViewById(android.R.id.content);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());
myApplication = MyApplication.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
spinnerConstituencyName = new ArrayList<>();
mySpinner = findViewById(R.id.mySpinner);
loadSpinnerData(URL);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
int check = 0;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/
if ( ++check > 1 ){
PrefManager prefManager = new PrefManager(MainActivity.this);
prefManager.writeString("" + spinConstID);
Intent intent = getIntent();
startActivity(intent);
Toast.makeText(getApplicationContext(), mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString() + " Showing", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(pager_number);
navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
viewPager.setCurrentItem(0);
return true;
case R.id.navigation_category:
viewPager.setCurrentItem(1);
return true;
case R.id.navigation_video:
viewPager.setCurrentItem(2);
return true;
case R.id.navigation_favorite:
viewPager.setCurrentItem(3);
return true;
case R.id.navigation_profile:
viewPager.setCurrentItem(4);
return true;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
} else {
navigation.getMenu().getItem(0).setChecked(false);
}
navigation.getMenu().getItem(position).setChecked(true);
prevMenuItem = navigation.getMenu().getItem(position);
if (viewPager.getCurrentItem() == 1) {
toolbar.setTitle(getResources().getString(R.string.title_nav_category));
} else if (viewPager.getCurrentItem() == 2) {
toolbar.setTitle(getResources().getString(R.string.title_nav_video));
} else if (viewPager.getCurrentItem() == 3) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else if (viewPager.getCurrentItem() == 4) {
toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
} else {
toolbar.setTitle(R.string.app_name);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
if (Config.ENABLE_RTL_MODE) {
viewPager.setRotationY(180);
}
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// checking for type intent filter
if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
// now subscribe to global topic to receive app wide notifications
FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);
} else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
// new push notification is received
String message = intent.getStringExtra("message");
Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
}
}
};
Intent intent = getIntent();
final String message = intent.getStringExtra("message");
final String imageUrl = intent.getStringExtra("image");
final long nid = intent.getLongExtra("id", 0);
final String link = intent.getStringExtra("link");
if (message != null) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);
final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setView(mView);
final TextView notification_title = mView.findViewById(R.id.news_title);
final TextView notification_message = mView.findViewById(R.id.news_message);
final ImageView notification_image = mView.findViewById(R.id.news_image);
if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
notification_title.setText(message);
notification_message.setVisibility(View.GONE);
Picasso.with(MainActivity.this)
.load(imageUrl.replace(" ", "%20"))
.placeholder(R.drawable.ic_thumbnail)
.resize(200, 200)
.centerCrop()
.into(notification_image);
alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
intent.putExtra("id", nid);
startActivity(intent);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
notification_title.setText(getResources().getString(R.string.app_name));
notification_message.setVisibility(View.VISIBLE);
notification_message.setText(message);
notification_image.setVisibility(View.GONE);
//Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();
if (!link.equals("")) {
alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(open);
}
});
alert.setNegativeButton(R.string.dialog_dismiss, null);
} else {
alert.setPositiveButton(R.string.dialog_ok, null);
}
}
alert.setCancelable(false);
alert.show();
}
GDPR.updateConsentStatus(this);
}
public class MyAdapter extends FragmentPagerAdapter {
private MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentRecent();
case 1:
return new FragmentCategory();
case 2:
return new FragmentVideo();
case 3:
return new FragmentFavorite();
case 4:
return new FragmentProfile();
}
return null;
}
#Override
public int getCount() {
return pager_number;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem((0), true);
} else {
exitApp();
}
}
public void exitApp() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
private void loadSpinnerData(String url) {
RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.getString("status").equals("ok")){
JSONArray jsonArray=jsonObject.getJSONArray("constituencies");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String spinConstituency=jsonObject1.getString("constituency_name");
spinConstID = jsonObject1.getInt("const_id");
spinnerConstituencyName.add(spinConstituency);
}
}
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
R.layout.custom_spinner_item, spinnerConstituencyName){
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
View view = super.getDropDownView(position, convertView, parent);
TextView tv = (TextView) view;
if(position%2 == 1) {
// Set the item background color
tv.setBackgroundColor(Color.parseColor("#910D3F"));
}
else {
// Set the alternate item background color
tv.setBackgroundColor(Color.parseColor("#41061C"));
}
return view;
}
};
mySpinner.setPrompt("Select Your Constituency");
myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
mySpinner.setAdapter(myAdapter);
//RECEIVE DATA VIA INTENT
Intent i = getIntent();
String name = i.getStringExtra("NAME_KEY");
mySpinner.setSelection(getIndex(mySpinner, name));
}catch (JSONException e){e.printStackTrace();}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Here is the problem (On Spinner Item selection)
Intent intent = getIntent();
startActivity(intent);
Toast.makeText(getApplicationContext(), mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString() + " Showing", Toast.LENGTH_SHORT).show();
finish();
**You are starting current activity as new and finish current activity, it means when you select any of items from spinner it will start a new activity and your on create executed again and again, so please place other logic or you can send your values in your activity using intent.putextra() and check in oncreate for null and if values is not null you can set spinner.setSelected(Your Position). For Fragment You can use
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(ComingSoonFragment.this).attach(ComingSoonFragment.this).commit();
for refresh your fragment and pass your data with bundle and check for null if your bundle is null then use your code for defalt and if not null then set your data according to your id.
**
Thanks
In your spinner inside OnItemSelectedListener use parent.getItemAtPosition(position) to get the correct value
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
//Do your staff here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I'm using Recycle Adapter class and using this to populate the fragments with blog image and description. But when I close the BlogActivity and move to Next Activity then sometimes suddenly app get crashed with error of
java.lang.IllegalArgumentException:You cannot start a load for a destryoed activity at com.bumptech.glide.manager.RequestManagerRetriever.asseertNotDestroyed(RequestManagerRetriver.java:312)
My Recycle adapter classs code is
package com.nepalpolice.cdp;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.android.volley.VolleyLog.TAG;
import static com.nepalpolice.cdp.webfaq.isNetworkStatusAvialable;
public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {
public List<BlogPost> blog_list;
public Context context;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private PopupWindow popWindow;
public BlogRecyclerAdapter(List<BlogPost> blog_list){
this.blog_list = blog_list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
context = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
final String blogPostId = blog_list.get(position).BlogPostId;
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);
String image_url = blog_list.get(position).getImage_url();
String thumbUri = blog_list.get(position).getImage_thumb();
holder.setBlogImage(image_url, thumbUri);
String user_id = blog_list.get(position).getUser_id();
//User Data will be retrieved here...
firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
String userName = task.getResult().getString("name");
String userImage = task.getResult().getString("image");
holder.setUserData(userName, userImage);
} else {
//Firebase Exception
}
}
});
try {
long millisecond = blog_list.get(position).getTimestamp().getTime();
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
holder.setTime(dateString);
} catch (Exception e) {
Toast.makeText(context, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
//Get Likes Count
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(((Main2Activity) context),new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e!=null) {
Log.w(TAG, "listening failed",e);
return;
}
if(!documentSnapshots.isEmpty()){
int count = documentSnapshots.size();
holder.updateLikesCount(count);
} else {
holder.updateLikesCount(0);
}
}
});
//Get Likes
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context),new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e!=null) {
Log.w(TAG, "listening failed",e);
return;
}
if (documentSnapshot.exists()){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
}
else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
}else{
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));
}
}
}
});
//Likes Feature
holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(!task.getResult().exists()){
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
} else {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent commentIntent = new Intent(context, CommentsActivity.class);
context.startActivity(commentIntent);
}
});
}
#Override
public int getItemCount() {
return blog_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView descView;
private ImageView blogImageView;
private TextView blogDate;
private TextView blogUserName;
private CircleImageView blogUserImage;
private ImageView blogLikeBtn;
private TextView blogLikeCount;
private ImageView blogCommentBtn;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
blogLikeBtn = mView.findViewById(R.id.blog_like_btn);
blogCommentBtn = mView.findViewById(R.id.blog_comment_icon);
}
public void setDescText(String descText){
descView = mView.findViewById(R.id.blog_desc);
descView.setText(descText);
}
public void setBlogImage(String downloadUri, String thumbUri){
blogImageView = mView.findViewById(R.id.blog_image);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.image_placeholder);
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).thumbnail(
Glide.with(context).load(thumbUri)
).into(blogImageView);
}
public void setTime(String date) {
blogDate = mView.findViewById(R.id.blog_date);
blogDate.setText(date);
}
public void setUserData(String name, String image){
blogUserImage = mView.findViewById(R.id.blog_user_image);
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
RequestOptions placeholderOption = new RequestOptions();
placeholderOption.placeholder(R.drawable.profile_placeholder);
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
}
public void updateLikesCount(int count){
blogLikeCount = mView.findViewById(R.id.blog_like_count);
blogLikeCount.setText(count + " Likes");
}
}
}
and my MainActivity code is
public class MainActivity extends AppCompatActivity {
private Toolbar mainToolbar;
private FirebaseAuth mAuth;
private FirebaseFirestore firebaseFirestore;
private String current_user_id;
private FloatingActionButton addPostBtn;
private HomeFragment homeFragment;
private BottomNavigationView mainbottomNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle("Central Department of Physics");
mainToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newPostIntent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(newPostIntent);
}
});
mainbottomNav = findViewById(R.id.mainBottomNav);
// FRAGMENTS
homeFragment = new HomeFragment();
replaceFragment(homeFragment);
mainbottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.bottom_action_home :
replaceFragment(homeFragment);
return true;
case R.id.bottom_action_account:
return true;
case R.id.bottom_action_notif:
return true;
default:
return false;
}
}
});
addPostBtn = findViewById(R.id.add_post_btn);
addPostBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newPostIntent = new Intent(Main2Activity.this, NewPostActivity.class);
startActivity(newPostIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if(currentUser == null){
Intent loginIntent = new Intent(Main2Activity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
} else {
current_user_id = mAuth.getCurrentUser().getUid();
firebaseFirestore.collection("Users").document(current_user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
if(!task.getResult().exists()){
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
startActivity(setupIntent);
finish();
}
} else {
String errorMessage = task.getException().getMessage();
Toast.makeText(Main2Activity.this, "Error : " + errorMessage, Toast.LENGTH_LONG).show();
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout_btn:
logOut();
return true;
case R.id.action_settings_btn:
Intent settingsIntent = new Intent(MainActivity.this, SetupActivity.class);
startActivity(settingsIntent);
return true;
default:
return false;
}
}
private void logOut() {
mAuth.signOut();
sendToLogin();
}
private void sendToLogin() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
private void replaceFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, fragment);
fragmentTransaction.commit();
}
}
Here is the complete code https://github.com/akshayejh/PhotoBlog-Android-Blog-App
Check whether your activity is finishing before using Glide. Something like this:
if (!activity.isFinishing()) {
Glide.with(...
}