Search focusable null pointer exception [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi i did everything about the search query and have no problem in errors but i keep getting a running time error of nullpointerexception
java src code below
package com.developer.bunamay.mplayer;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends Activity {
String LOG_CLASS = "MainActivity";
public static final PlayUtils PlayerController = PlayUtils.getInstance();
CustomAdapter customAdapter = null;
private MediaFileAdapter mediaFileAdapter = null;
public static final int PICK_FOLDER_REQUEST = 8;
static TextView playingSong;
Button btnPlayer;
static Button btnPause, btnPlay, btnNext, btnPrevious;
Button btnStop;
LinearLayout mediaLayout;
static LinearLayout linearLayoutPlayingSong;
ListView mediaListView;
SeekBar seekBar;
TextView textBufferDuration, textDuration;
static ImageView imageViewAlbumArt;
static Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
init();
}
private void init() {
getViews();
setListeners();
playingSong.setSelected(true);
seekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
if (PlayerConstants.SONGS_LIST.size() <= 0) {
PlayerConstants.SONGS_LIST = PlayUtils.listOfSongs(getApplicationContext());
}
setListItems();
}
private void setListItems() {
customAdapter = new CustomAdapter(this, R.layout.custom_list, PlayerConstants.SONGS_LIST);
mediaListView.setAdapter(customAdapter);
mediaListView.setFastScrollEnabled(true);
}
private void getViews() {
playingSong = (TextView) findViewById(R.id.textNowPlaying);
btnPlayer = (Button) findViewById(R.id.btnMusicPlayer);
mediaListView = (ListView) findViewById(R.id.listViewMusic);
mediaLayout = (LinearLayout) findViewById(R.id.linearLayoutMusicList);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
linearLayoutPlayingSong = (LinearLayout) findViewById(R.id.linearLayoutPlayingSong);
seekBar = (SeekBar) findViewById(R.id.seekBar);
btnStop = (Button) findViewById(R.id.btnStop);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
imageViewAlbumArt = (ImageView) findViewById(R.id.imageViewAlbumArt);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
}
private void setListeners() {
mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
Log.d("TAG", "TAG Tapped INOUT(IN)");
PlayerConstants.SONG_PAUSED = false;
PlayerConstants.SONG_NUMBER = position;
boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (!isServiceRunning) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
startService(i);
} else {
PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
}
updateUI();
changeButton();
Log.d("TAG", "TAG Tapped INOUT(OUT)");
}
});
btnPlayer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
startActivity(i);
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.playControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.pauseControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.nextControl(getApplicationContext());
}
});
btnPrevious.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Controls.previousControl(getApplicationContext());
}
});
btnStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MusicService.class);
stopService(i);
linearLayoutPlayingSong.setVisibility(View.GONE);
}
});
imageViewAlbumArt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, AudioPlayerActivity.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
boolean isServiceRunning = PlayUtils.isServiceRunning(MusicService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
} else {
linearLayoutPlayingSong.setVisibility(View.GONE);
}
changeButton();
PlayerConstants.SEEKBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(PlayUtils.getDuration(i[0]));
textDuration.setText(PlayUtils.getDuration(i[1]));
seekBar.setProgress(i[2]);
}
};
} catch (Exception e) {
}
}
#SuppressWarnings("deprecation")
public static void updateUI() {
try {
MediaItem data = PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER);
playingSong.setText(data.getTitle() + " " + data.getArtist() + "-" + data.getAlbum());
Bitmap albumArt = PlayUtils.getAlbumart(context, data.getAlbumId());
if (albumArt != null) {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
imageViewAlbumArt.setBackgroundDrawable(new BitmapDrawable(PlayUtils.getDefaultAlbumArt(context)));
}
linearLayoutPlayingSong.setVisibility(View.VISIBLE);
} catch (Exception e) {
}
}
public static void changeButton() {
if (PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
public static void changeUI() {
updateUI();
changeButton();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Intent about = new Intent(MainActivity.this, About.class);
startActivity(about);
break;
case R.id.action_exit:
finish();
break;
}
int id = item.getItemId();
// get music from specific folder
if (id == R.id.folder_music) {
Intent intent = new Intent(this, FolderPickerActivity.class);
startActivityForResult(intent, PICK_FOLDER_REQUEST);
return true;
}
// search songs by title
if (id == R.id.action_search_title) {
PlayerController.SEARCH_TYPE = "TITLE";
return true;
}
// search songs by artist
if (id == R.id.action_search_artist) {
PlayerController.SEARCH_TYPE = "ARTIST";
return true;
}
// search songs by album
if (id == R.id.action_search_album) {
PlayerController.SEARCH_TYPE = "ALBUM";
return true;
}
if (id == R.id.action_sort_title) {
MediaFileComparator.sortByTitle(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_album) {
MediaFileComparator.sortByAlbum(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_artist) {
MediaFileComparator.sortByArtist(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
if (id == R.id.action_sort_duration) {
MediaFileComparator.sortByDuration(PlayerController.SONGS_LIST);
MediaFileAdapter mediaAdapter = (MediaFileAdapter) mediaListView.getAdapter();
mediaAdapter.notifyDataSetChanged();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
// init menu items for search
MenuItem itemSearchTitle = menu.findItem(R.id.action_search_title);
MenuItem itemSearchAlbum = menu.findItem(R.id.action_search_album);
MenuItem itemSearchArtist = menu.findItem(R.id.action_search_artist);
SearchView searchViewTitle = (SearchView) itemSearchTitle.getActionView();
SearchView searchViewAlbum = (SearchView) itemSearchAlbum.getActionView();
SearchView searchViewArtist = (SearchView) itemSearchArtist.getActionView();
searchViewTitle.setFocusable(true);
searchViewAlbum.setFocusable(true);
searchViewArtist.setFocusable(true);
// init searchable info for each menu item
searchViewTitle.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewTitle.setQueryHint("title...");
searchViewTitle.setIconified(true);
searchViewAlbum.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewAlbum.setQueryHint("album...");
searchViewAlbum.setIconified(true);
searchViewArtist.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchViewArtist.setQueryHint("artist...");
searchViewArtist.setIconified(true);
// set textChangeListeners for each type of search
final SearchView.OnQueryTextListener textChangeListenerTitle = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerAlbum = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
SearchView.OnQueryTextListener textChangeListenerArtist = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
if (!TextUtils.isEmpty(newText)) {
mediaFileAdapter.getFilter().filter(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
};
// apply listeners to searchViews
searchViewTitle.setOnQueryTextListener(textChangeListenerTitle);
searchViewAlbum.setOnQueryTextListener(textChangeListenerAlbum);
searchViewArtist.setOnQueryTextListener(textChangeListenerArtist);
return super.onCreateOptionsMenu(menu);
}
}
I keep getting the error on
searchViewTitle.setFocusable(true);
and the here is the logcat displaying the error
07-31 18:12:18.047 2066-2066/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.developer.bunamay.mplayer, PID: 2066
java.lang.NullPointerException
at com.developer.bunamay.mplayer.MainActivity.onCreateOptionsMenu(MainActivity.java:300)
at android.app.Activity.onCreatePanelMenu(Activity.java:2538)
at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:800)
at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:543)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
07-31 18:12:18.051 587-599/? W/ActivityManager: Force finishing activity com.developer.bunamay.mplayer/.MainActivity
THANKS!!

ActionView of itemSearchTitle is null at this moment.

Related

Activity Reloads with Previous Selected Data Bug

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();
}
}

Reload Data on Spinner itemSelected

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) {
}
});

Android: why my onResume() DialogInterface keeps looping non stop?

May I ask why my onResume() DialogInterface keeps looping non stop? I have reference the onResume() from this website: http://pulse7.net/android/android-delete-sms-message-from-inbox-in-android/
#Override
protected void onResume() {
super.onResume(); int i=0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if(i==0) {
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMain_txt.this);
builder.setMessage("This app is not set as your default messaging app. Do you want to set it as default?")
.setCancelable(false)
.setTitle("Alert!")
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#TargetApi(19)
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);
dialog.dismiss();
}
});
builder.show();
i++;}
}
}
But when I add this part of the code, the DialogInterface for "setPositiveButton" keeps looping non-stop. I am trying to set my application to become the default message application, so I will be able to delete messages. As now it is not set to become the default application, I am unable to delete any messages successfully. Any help will be deeply appreciated. Thanks in advance.
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
import android.provider.Telephony;
import com.example.apple.qs.Activity.db.Constant;
import com.example.apple.qs.Activity.db.DatabaseHandler_txt;
import com.example.apple.qs.Activity.fragment.ContactFragment;
import com.example.apple.qs.Activity.fragment.FragmentAdapter;
import com.example.apple.qs.Activity.fragment.MessageFragment;
import com.example.apple.qs.Activity.db.model.Message;
import com.example.apple.qs.Activity.db.Store.ContactStore;
import com.example.apple.qs.Activity.db.Store.MessageStore;
import java.util.ArrayList;
import com.example.apple.qs.Activity.R;
import java.util.List;
public class ActivityMain_txt extends AppCompatActivity {
private ActionBarDrawerToggle mDrawerToggle;
private Toolbar toolbar;
private DrawerLayout drawerLayout;
public static MessageFragment f_message;
private ContactFragment f_contact;
public FloatingActionButton fab;
private Toolbar searchToolbar;
private boolean isSearch = false;
private ViewPager viewPager;
private DatabaseHandler_txt db;
public ContactStore contacsStore;
public MessageStore messageStore;
public static List<Message> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_txt);
setupDrawerLayout();
db = new DatabaseHandler_txt(getApplicationContext());
toolbar = (Toolbar) findViewById(R.id.toolbar_viewpager);
searchToolbar = (Toolbar) findViewById(R.id.toolbar_search);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ActivityNewMessage_txt.class);
startActivity(i);
}
});
//initToolbar();
prepareActionBar(toolbar);
contacsStore = new ContactStore(getApplicationContext());
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
closeSearch();
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0) {
fab.show();
} else {
fab.hide();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// for system bar in lollipop
Window window = this.getWindow();
if (Constant.getAPIVerison() >= 5.0) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimaryDark));
}
}
private void setupViewPager(ViewPager viewPager) {
FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager());
if (f_message == null) {
f_message = new MessageFragment();
}
if (f_contact == null) {
f_contact = new ContactFragment();
}
adapter.addFragment(f_message, "MESSAGE");
adapter.addFragment(f_contact, "CONTACT");
viewPager.setAdapter(adapter);
}
private void prepareActionBar(Toolbar toolbar) {
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(getResources().getColor(isSearch ? android.R.color.darker_gray : R.color.colorPrimary));
}
if (!isSearch) {
settingDrawer();
}
}
private void settingDrawer() {
mDrawerToggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close ) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Set the drawer toggle as the DrawerListener
drawerLayout.setDrawerListener(mDrawerToggle);
}
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView view = (NavigationView) findViewById(R.id.nav_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
actionDrawerMenu(menuItem.getItemId());
return true;
}
});
}
private void actionDrawerMenu(int itemId) {
switch (itemId) {
case R.id.nav_notif:
Intent i = new Intent(getApplicationContext(), ActivityNotificationSettings_txt.class);
startActivity(i);
break;
case R.id.nav_rate:
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
break;
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("About");
builder.setMessage(getString(R.string.about_text));
builder.setNeutralButton("OK", null);
builder.show();
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (!isSearch) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(isSearch ? R.menu.menu_search_toolbar_txt : R.menu.menu_main_txt, menu);
if (isSearch) {
//Toast.makeText(getApplicationContext(), "Search " + isSearch, Toast.LENGTH_SHORT).show();
final SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView();
search.setIconified(false);
if (viewPager.getCurrentItem() == 0) {
search.setQueryHint("Search message...");
} else {
search.setQueryHint("Search contact...");
}
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter(s);
} else {
f_contact.mAdapter.getFilter().filter(s);
}
return true;
}
});
search.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
closeSearch();
return true;
}
});
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_search: {
isSearch = true;
searchToolbar.setVisibility(View.VISIBLE);
prepareActionBar(searchToolbar);
supportInvalidateOptionsMenu();
return true;
}
case android.R.id.home:
closeSearch();
return true;
case R.id.action_refresh: {
if(viewPager.getCurrentItem()==0){
new RefreshMessage().execute("");
}else{
new RefreshContact().execute("");
}
}
default:
return super.onOptionsItemSelected(item);
}
}
private void closeSearch() {
if (isSearch) {
isSearch = false;
if (viewPager.getCurrentItem() == 0) {
f_message.mAdapter.getFilter().filter("");
} else {
f_contact.mAdapter.getFilter().filter("");
}
prepareActionBar(toolbar);
searchToolbar.setVisibility(View.GONE);
supportInvalidateOptionsMenu();
}
}
private ChangeObserver changeObserver;
// wil update only when there a change
private class ChangeObserver extends ContentObserver {
public ChangeObserver() {
super(new Handler());
}
#Override
public void onChange(boolean selfChange) {
try{
if(!loadRunning) {
loadRunning = true;
changeLoad = new ChangeLoad();
changeLoad.execute("");
}
}catch (Exception e){
}
}
}
private ChangeLoad changeLoad;
private boolean loadRunning = false;
private class ChangeLoad extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
messageStore.update();
return null;
}
#Override
protected void onPostExecute(String s) {
loadRunning = false;
messageList = messageStore.getAllconversation();
f_message.bindView();
super.onPostExecute(s);
}
}
public class RefreshMessage extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_message.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(100);
messageStore = new MessageStore(ActivityMain_txt.this);
messageList = messageStore.getAllconversation();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_message.onStopRefreshLoading();
super.onPostExecute(s);
}
}
private class RefreshContact extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
f_contact.onRefreshLoading();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
Thread.sleep(10);
db.truncateDB();
contacsStore = new ContactStore(getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
f_contact.onStopRefreshLoading();
super.onPostExecute(s);
}
}
String myPackageName= getPackageName();
#Override
protected void onResume() {
super.onResume(); int i=0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
if(i==0) {
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMain_txt.this);
builder.setMessage("This app is not set as your default messaging app. Do you want to set it as default?")
.setCancelable(false)
.setTitle("Alert!")
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#TargetApi(19)
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);
dialog.dismiss();
}
});
builder.show();
i++;}
}
}
}
}
You are using the variable i as a flag, but whenever you open your app the value of i will be 0 again. You should store your flag in a persistent database. Either use SQLite to set i or use any other method like create a file when the user says yes to your question and then check if the file exists or not. If you don't understand what I've told you, I can send you some code snippets.
OK, I assume you are using i as a flag to check if user has set your app as default or not, so I suggest you to use SharedPreferences to store the value of i so that later on you can check the value of i in a better manner. Add the following code in your onResume function:
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
Instead of i++ use:
editor.putInt(i, 1);
editor.commit();
And to check if i==0 use:
int check =sharedprferences.getInt(i);
if(check == 0) {...........}

Android cannot be referenced from a static context

I'm a beginner on Android and this is the first I'm creating an app named GeoQuiz which basically has a few questions and the user has to click true/false or request the answer with the cheat button.I'm getting this one line of error related with a non-static an a static context in line 138,what am I doing wrong? I'm trying that every time i click on the button cheat, it open the other window that is under a different .xml file and in an another java class
package com.example.fusion.geoquiz;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
import android.content.Intent;
import android.content.Intent;
import java.util.*;
import static com.example.fusion.geoquiz.R.string.correct_toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private ImageButton mPrevButton;
private ProgressBar mProgress;
private Button mCheatButton;
private int mProgressStatus = 0;
private TextView mQuestionTextView;
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private int checker = 0;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
private void disablePrev(){
if(mCurrentIndex== 0){
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(false);
}
else{
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
mPrevButton.setEnabled(true);
}
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
checker++;
if(checker >0) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
//mProgressStatus=checker;
//mProgress.setProgress(mProgressStatus);
disablePrev();
}
} else {
messageResId = R.string.incorrect_toast;
checker = 0;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
disablePrev();
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
updateQuestion();
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(false);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
}
});
mNextButton = (ImageButton) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mPrevButton = (ImageButton) findViewById(R.id.prev_button);
disablePrev();
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurrentIndex != 0){
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
mQuestionTextView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checker==1) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
disablePrev();
}
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
}
});
disablePrev();
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#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_quiz, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is the class for the cheat class and cheatButton
package com.example.fusion.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Button;
import android.widget.ImageButton;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.widget.TextView;
import android.util.Log;
/**
* Created by fusion on 1/21/2015.
*/
public class cheatActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
}
}
Replace
Intent intent = new Intent(QuizActivity.this, cheatActivity.startActivity(intent));
with
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
See the docs for more details..
Not sure what you're doing there, but you need to reference the other activity class. Simply calling startActivity is enough, because it will be implicitly called from QuizActivity.this.
Intent intent = new Intent(QuizActivity.this, cheatActivity.class);
startActivity(intent);
To save you from future errors choose one activity class that you will be using either Activity or ActionBarActivity. The latter is from the support package.

Menu buttons work, Soft buttons not working. Same Code basically

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;
}
}
}

Categories