I have a problem with admob ads.
The banner ad seems to work fine but the Interstitial is not loading.
I have tried various solutions, generating different ad unit id's and trying admob test ids.
QuoteActivity.java
package com.axdev.thequotesgarden;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
public class QuoteActivity extends ActionBarActivity implements
TextToSpeech.OnInitListener {
private int ID;
private String mode,fav,text;
private Quote qte;
private DataBaseHandler db;
private ArrayList<Quote> myList = new ArrayList<Quote>();
private TextView textAuth,textQuote;
private ImageView imgIcon;
private ImageButton btnNext,btnPrevious;
private TextToSpeech tts;
private RoundImage roundedImage;
private AdView adView;
private InterstitialAd interstitial;
SharedPreferences sharedPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
db = new DataBaseHandler(this);
textAuth = (TextView) findViewById(R.id.textAuth);
textQuote = (TextView) findViewById(R.id.textQuote);
imgIcon = (ImageView) findViewById(R.id.imgcon);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnPrevious = (ImageButton) findViewById(R.id.btn_prev);
Typeface fontQuote = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Light.ttf");
Typeface fontAuth = Typeface.createFromAsset(getAssets(),
"fonts/Roboto-Italic.ttf");
textQuote.setTypeface(fontQuote);
textQuote.setTextSize(18);
textAuth.setTypeface(fontAuth);
ID = getIntent().getExtras().getInt("id");
mode = getIntent().getExtras().getString("mode");
if(mode.equals("qteday")){
qte = db.getQuote(ID);
btnNext.setVisibility(View.GONE);
btnPrevious.setVisibility(View.GONE);
}
else {
myList = (ArrayList<Quote>) getIntent().getSerializableExtra("array");
qte = myList.get(ID);}
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID < (myList.size() - 1)) {
ID++;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ID > 0) {
ID--;
qte = myList.get(ID);
textAuth.setText(qte.getName());
textQuote.setText(qte.getQuote());
checkPicure();
}
}
});
fav = qte.getFav();
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuote);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
if(mode.equals("qteday")){
tts = new TextToSpeech(this, this);
speakOut();
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId(getResources().getString(R.string.interstitial_ad_unit_id));
AdRequest adRequest2 = new AdRequest.Builder().build();
interstitial.loadAd(adRequest2);
interstitial.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
displayInterstitial();
}
});
}
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void checkPicure(){
boolean isExist = false;
InputStream imageStream = null;
try {
imageStream = getAssets().open("authors/"+qte.getFileName()+".jpg");
isExist =true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isExist != false){
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
roundedImage = new RoundImage(theImage);
imgIcon.setImageDrawable(roundedImage );
}
else {
Bitmap bm = BitmapFactory.decodeResource(getResources(),R.mipmap.author);
roundedImage = new RoundImage(bm);
imgIcon.setImageDrawable(roundedImage);
}
}
public void doShare() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Quote");
intent.putExtra(Intent.EXTRA_TEXT,
qte.getQuote() + " - " + qte.getName());
QuoteActivity.this.startActivity(Intent.createChooser(intent,
getResources().getString(R.string.share)));
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Locale loc = new Locale("en", "UK");
tts.setLanguage(loc);
tts.setSpeechRate((float) 0.8);
speakOut();
} else {
Log.e("TTS", "Initilization Failed");
}
}
private void speakOut() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Boolean speaker = sharedPrefs.getBoolean("prefSpeaker", true);
if (speaker.equals(true)) {
text = qte.getQuote() + "\n" + qte.getName();
if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
else {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, 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.menu_quote, menu);
if (fav.equals("0")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.not_fav);
}
if (fav.equals("1")) {
menu.findItem(R.id.action_favorite).setIcon(R.mipmap.fav);
}
;
return true;
}
#TargetApi(11)
private void copyToClipBoard(String qte) {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(qte);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("text", qte);
clipboard.setPrimaryClip(clip);
}
}
#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.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
case R.id.action_share:
doShare();
break;
case R.id.copy:
String text = qte.getQuote() + "- " + qte.getName();
copyToClipBoard(text);
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.copy_msg),
Toast.LENGTH_LONG).show();
break;
case R.id.action_favorite:
if (qte.getFav().equals("0")) {
qte.setFav("1");
db.updateQuote(qte);
item.setIcon(R.mipmap.fav);
} else if (qte.getFav().equals("1")) {
qte.setFav("0");
db.updateQuote(qte);
item.setIcon(R.mipmap.not_fav);
}
}
return true;
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
QuotesActivity.java
package com.axdev.thequotesgarden;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import java.util.ArrayList;
import java.util.List;
public class QuotesActivity extends ActionBarActivity {
private ArrayList<Quote> imageArry = new ArrayList<Quote>();
private QuotesListAdapter adapter;
private String Activitytype;
private DataBaseHandler db;
private ListView dataList;
private int count;
private ImageView noQuotes;
private AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quotes);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
db = new DataBaseHandler(this);
noQuotes = (ImageView)findViewById(R.id.NoQuotes);
adapter = new QuotesListAdapter(this, R.layout.quote_items, imageArry);
dataList = (ListView) findViewById(R.id.quotesList);
Button btnLoadMore = new Button(this);
btnLoadMore.setBackgroundResource(R.drawable.btn_green);
btnLoadMore.setText(getResources().getText(R.string.btn_LoadMore));
btnLoadMore.setTextColor(0xffffffff);
Activitytype = getIntent().getExtras().getString("mode");
if (Activitytype.equals("isCategory")) {
String categoryValue = getIntent().getExtras()
.getString("category");
List<Quote> contacts = db.getQuotesByCategory(categoryValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
}
if (Activitytype.equals("isAuthor")) {
String authorValue = getIntent().getExtras().getString("name");
List<Quote> contacts = db.getQuotesByAuthor(authorValue);
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
}
if (Activitytype.equals("isFavorite")) {
actionBar.setTitle(getResources().getText(R.string.title_activity_favorites));
List<Quote> contacts = db.getFavorites();
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
if (imageArry.isEmpty()){
noQuotes.setVisibility(View.VISIBLE);
}
}
if (Activitytype.equals("allQuotes")) {
List<Quote> contacts = db.getAllQuotes(" LIMIT 50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
;
dataList.addFooterView(btnLoadMore);
}
dataList.setAdapter(adapter);
dataList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
Intent i = new Intent(getApplicationContext(),
QuoteActivity.class);
Quote srr = imageArry.get(position);
i.putExtra("id",position);
i.putExtra("array", imageArry);
i.putExtra("mode", "");
startActivity(i);
}
});
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Starting a new async task
new loadMoreListView().execute();
}
});
adView = new AdView(this);
adView.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
adView.setAdSize(AdSize.BANNER);
LinearLayout layout = (LinearLayout) findViewById(R.id.layAdsQuotes);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
private class loadMoreListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// Before starting background task
// Show Progress Dialog etc,.
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
count += 50;
List<Quote> contacts = db.getAllQuotes(" LIMIT "+count+ ",50");
for (Quote cn : contacts) {
imageArry.add(cn);
}
int currentPosition = dataList.getFirstVisiblePosition();
adapter = new QuotesListAdapter(QuotesActivity.this, R.layout.quote_items, imageArry);
dataList.setSelectionFromTop(currentPosition + 1, 0);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
}
}
#Override
public void onBackPressed()
{
finish();
super.onBackPressed(); // optional depending on your needs
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quotes, 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.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
}
return true;
}
}
The simplest answer is that mode is not equal to "qteday"
if(mode.equals("qteday")){
Unless that is true, the interstitial will never be loaded.
Related
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();
}
}
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 tried everything possible but couldn't try to figure out how to update images to glide whenever my json is updated
MY android app initally loads images from json using glide for firsttime after that it only load images from cache.It doesnot load images that are updated on server till i delete the app and reinstall it
I tried using diskCacheStrategy(DiskCacheStrategy.NONE) and .skipMemoryCache(true) but nothing happened
Glide.with(mContext).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.thumbnail);
This is my code GalleryAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import java.util.List;
import com.bumptech.glide.signature.StringSignature;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.model.Image;
/**
* Created by Sagunesh on 31/03/16.
*/
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {
private List<Image> images;
private Context mContext;
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView thumbnail;
public MyViewHolder(View view) {
super(view);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
}
}
public GalleryAdapter(Context context, List<Image> images) {
mContext = context;
this.images = images;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.gallery_thumbnail, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Image image = images.get(position);
Glide.with(mContext).load(image.getMedium())
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.thumbnail);
}
#Override
public int getItemCount() {
return images.size();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private GalleryAdapter.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final GalleryAdapter.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
Here is the code of MainActivity.java
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.dailysolutions.sn.R;
import com.dailysolutions.sn.adapter.GalleryAdapter;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdView;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.android.gms.ads.AdRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.dailysolutions.sn.app.AppController;
import com.dailysolutions.sn.model.Image;
import com.google.android.gms.ads.InterstitialAd;
import java.util.ArrayList;
public class MainActivity extends BaseActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "https://www.freesabkuch.com/api_mehndi/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;
private AdView mAdView;
InterstitialAd interstitial;
// Our created menu to use
private Menu mymenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
checkConnectivity();
//advertisement
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
// Prepare the Interstitial Ad
interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
interstitial.loadAd(adRequest);
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
// Call displayInterstitial() function
displayInterstitial();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public void onResume() {
// Start or resume the game.
super.onResume();
displayInterstitial();
}
#Override
public void onStart() {
super.onStart();
displayInterstitial();
}
private void fetchImages() {
pDialog.setMessage("Downloading....");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
image.setName(object.getString("name"));
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTimestamp(object.getString("timestamp"));
images.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
#Override
public void onBackPressed() {
exit();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id){
case R.id.home:
Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.share:
Toast.makeText(getApplicationContext(),"Share",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch(Exception e) {
//e.toString();
}
case R.id.trash:
Toast.makeText(getApplicationContext(),"Drawer Closed",Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawers();
break;
case R.id.logout:
exit();
}
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
tv_email.setText("Daily Solutions");
drawerLayout = (DrawerLayout)findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
private void checkConnectivity(){
if(ConnectionHelper.isConnectedOrConnecting(getApplicationContext())) {
hideErrorsBar(true);
}else {
//hideErrorsBar(false);
Intent Intent = new Intent(MainActivity.this,NoInternet.class);
startActivity(Intent);
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Add our menu
getMenuInflater().inflate(R.menu.menu_main, menu);
// We should save our menu so we can use it to reset our updater.
mymenu = menu;
//
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
// Do animation start
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
item.setActionView(iv);
new UpdateTask(this).execute();
return true;
}
return super.onOptionsItemSelected(item);
}
public void resetUpdating()
{
// Get our refresh item from the menu
MenuItem m = mymenu.findItem(R.id.action_refresh);
if(m.getActionView()!=null)
{
// Remove the animation.
m.getActionView().clearAnimation();
m.setActionView(null);
}
}
}
You can use Signature for invalidating cache and load image from network. Try
Glide.with(Fragment/context)
.load(imagePath)
.signature(new StringSignature(yourVersion))
.into(ImageView);
Just pass new StringSignature(System.currentTimeMillis()+"") to the signature so that it will load the image from network every time
You could also try setting Signatures
As per the glide documentation on caching
Try this
Glide.with(context)
.load(url) .
signature(new StringSignature(System.currentTimeMillis()))
.into(imageView);
Check here for more details
Well everyone thanks a lot for help :)
I resolved this problem by disabling cache of volley library that was causing the issue but anyway thanks for help :)
//disabling caching for url
AppController.getInstance().getRequestQueue().getCache().remove(url);
The image moves perfectly the first time into its place i.e detail activity image view and also returns perfectly back to the main activity but when I click the same image next time the transition animation moves the image to an incorrect (too high) offset in the detail activity and once the animation completes the image will appear to "warp" into the correct position.
Here is my DetailActivity.java file:
package com.akshitjain.popularmovies;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
postponeEnterTransition();
}
ImageView backdropImageView = (ImageView) findViewById(R.id.detail_image_view);
final ImageView posterImageView = (ImageView) findViewById(R.id.detail_poster);
TextView overviewTextView = (TextView) findViewById(R.id.overview_text_view);
TextView releaseDateTextView = (TextView) findViewById(R.id.release_date);
TextView userRatingTextView = (TextView) findViewById(R.id.user_rating);
TextView genreTextView = (TextView) findViewById(R.id.genre);
genreTextView.setText("");
Genre genreObject = new Genre();
String genreName;
Intent intent = getIntent();
if (intent != null && intent.hasExtra(Constants.MOVIE_OBJECT_PARCELABLE_EXTRA)) {
Movies movies = intent.getParcelableExtra(Constants.MOVIE_OBJECT_PARCELABLE_EXTRA);
int[] genre;
genre = movies.genre;
for (int i = 0; i < genre.length; ++i) {
genreName = genreObject.getGenreName(genre[i]);
genreTextView.append(genreName);
if (i < genre.length - 1) {
genreTextView.append(", ");
}
}
setTitle(movies.originalTitle);
Picasso.with(getApplicationContext())
.load((Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_LARGE).trim() + movies.backdropPath)
.into(backdropImageView);
Picasso.with(getApplicationContext())
.load((Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_SMALL).trim() + movies.posterPath)
.into(posterImageView, new Callback() {
#Override
public void onSuccess() {
posterImageView.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
posterImageView.getViewTreeObserver().removeOnPreDrawListener(this);
startPostponedEnterTransition();
}
return true;
}
}
);
}
#Override
public void onError() {
}
}
);
overviewTextView.setText(movies.overview);
releaseDateTextView.setText(movies.releaseDate);
userRatingTextView.setText(movies.userRating);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detail, 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.
int id = item.getItemId();
switch (id) {
case android.R.id.home:
supportFinishAfterTransition();
return true;
case R.id.action_settings:
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this.
posterImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Picasso.with(getApplicationContext())
.load((Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_SMALL).trim() + movies.posterPath)
.into(posterImageView, new Callback() {
#Override
public void onSuccess() {
startPostponedEnterTransition();
}
#Override
public void onError() {
}
});
}
}
Title says it all, Im new to SQL and trying to change the selection the user makes but placing buttons in the screen and not use the MENU button. Seems like the buttons aren't instantiated but the code looks right to me...what am i missing??
package com.example.worldcountriesbooks;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ViewCountry extends Activity implements OnClickListener{
private long rowID;
private TextView nameTv;
private TextView capTv;
private TextView codeTv;
private TextView newEt;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.view_country);
Button a = (Button)findViewById(R.id.editbutton);
Button b = (Button)findViewById(R.id.deletebutton);
a.setOnClickListener(this);
b.setOnClickListener(this); //Set them up right here...
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(CountryList.ROW_ID);
}
private void setUpViews() {
nameTv = (TextView) findViewById(R.id.nameText);
capTv = (TextView) findViewById(R.id.capText);
codeTv = (TextView) findViewById(R.id.codeText);
newEt = (TextView)findViewById(R.id.newText);
}
#Override
protected void onResume()
{
super.onResume();
new LoadContacts().execute(rowID);
}
private class LoadContacts extends AsyncTask<Long, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this);
#Override
protected Cursor doInBackground(Long... params)
{
dbConnector.open();
return dbConnector.getOneContact(params[0]);
}
#Override
protected void onPostExecute(Cursor result)
{
super.onPostExecute(result);
result.moveToFirst();
// get the column index for each data item
int nameIndex = result.getColumnIndex("name");
int capIndex = result.getColumnIndex("cap");
int codeIndex = result.getColumnIndex("code");
int newIndex = result.getColumnIndex("newb");
nameTv.setText(result.getString(nameIndex));
capTv.setText(result.getString(capIndex));
codeTv.setText(result.getString(codeIndex));
newEt.setText(result.getString(newIndex));
result.close();
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.view_country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("newb", newEt.getText());
startActivity(addEditContact);
return true;
case R.id.deleteItem:
deleteContact();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteContact()
{
AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DatabaseConnector dbConnector =
new DatabaseConnector(ViewCountry.this);
AsyncTask<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#Override
protected Object doInBackground(Long... params)
{
dbConnector.deleteContact(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
public void onClick(View arg0) {
switch (arg0.getId())
{
case R.id.editItem:
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("newb", newEt.getText());
startActivity(addEditContact);
break;
case R.id.deleteItem:
deleteContact();
break;//finish them up here and they do nothing...
}
}
}
Now the menu buttons work great so not sure whats up...Thanks for looking
The menu buttons work great because the switch statement for it is proper.
Your onClick is not working properly however. This is because The cases are for different ids than what the buttons provide. You want R.id.editbutton and R.id.deletebutton instead.
Your method should look like:
public void onClick(View arg0) {
switch (arg0.getId())
{
case R.id.editbutton: //updated
Intent addEditContact =
new Intent(this, AddEditCountry.class);
addEditContact.putExtra(CountryList.ROW_ID, rowID);
addEditContact.putExtra("name", nameTv.getText());
addEditContact.putExtra("cap", capTv.getText());
addEditContact.putExtra("code", codeTv.getText());
addEditContact.putExtra("newb", newEt.getText());
startActivity(addEditContact);
break;
case R.id.deletebutton: //updated
deleteContact();
break;
}
}
}