Navigation Drawer Method receives NullPointer Exception - java

i am creating an android app that uses a Navigation Drawer. Since i will have more than one Option in the drawer, i had to create a method passing the activity that i want to implement the navigation and the Activity Toolbar.
The problem is, i am receiving a Null Pointer when i declare the NavigatioDrawer method in the activities. let me show you:
HERE IS MY NAVIGATION DRAWER METHOD(WHICH I WILL INSTANTIATE IN THE ACTIVITY):
package studio.brunocasamassa.ajudaaqui.helper;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import studio.brunocasamassa.ajudaaqui.MainActivity;
import studio.brunocasamassa.ajudaaqui.PerfilActivity;
import studio.brunocasamassa.ajudaaqui.R;
import studio.brunocasamassa.ajudaaqui.ConfiguracoesActivity;
import studio.brunocasamassa.ajudaaqui.ChatActivity;
import studio.brunocasamassa.ajudaaqui.GruposActivity;
import studio.brunocasamassa.ajudaaqui.PedidosActivity;
import studio.brunocasamassa.ajudaaqui.SobreActivity;
/**
* Created by bruno on 24/04/2017.
*/
public class NavigationDrawer {
//NAVIGATION DRAWER
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//private static Activity setClasse = new Activity();
private static MainActivity main;
private static User usuario = main.user;
public void createDrawer(final Activity classe, Toolbar toolbar) {
//setClasse = classe;
//Itens do Drawer
PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.menu_pedidos);
PrimaryDrawerItem item2 = new PrimaryDrawerItem().withIdentifier(2).withName(R.string.menu_chats);
PrimaryDrawerItem item3 = new PrimaryDrawerItem().withIdentifier(3).withName(R.string.menu_grupos);
PrimaryDrawerItem item4 = new PrimaryDrawerItem().withIdentifier(4).withName(R.string.menu_perfil);
PrimaryDrawerItem item5 = new PrimaryDrawerItem().withIdentifier(5).withName(R.string.menu_configuracoes);
PrimaryDrawerItem item6 = new PrimaryDrawerItem().withIdentifier(6).withName(R.string.menu_sobre);
// Create the Navigation Drawer AccountHeader
AccountHeader headerResult = new AccountHeaderBuilder()
.withActivity(classe)
.withHeaderBackground(R.color.colorPrimary)
.addProfiles(
new ProfileDrawerItem().withName("User").withEmail("user#example.com").withIcon(usuario.getProfileImageURL())
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
//Definition Drawer
Drawer drawer = new DrawerBuilder()
.withActivity(classe)
.withToolbar(toolbar)
.withAccountHeader(headerResult)
.addDrawerItems(
item1,
new DividerDrawerItem(),//Divisor
item2,
new DividerDrawerItem(),//Divisor
/*DIVISAO COM MENSAGEM new SectionDrawerItem().withName(R.string.section),//Seção*/
item3,
new DividerDrawerItem(),//Divisor
item4,
new DividerDrawerItem(),//Divisor
item5,
new DividerDrawerItem(),//Divisor
item6
//Divisor
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
StartActivity a = new StartActivity() ;
a.verifyActivity(classe, position);
return false;
}
})
.withSelectedItemByPosition(0)
.build();
}
}
class StartActivity extends AppCompatActivity {
public void verifyActivity(Activity classe, int position) {
if (position == 1) {
// HERE I AM TRYING USING DIFFERENT FORMS TO START THE ACTITIVIES
startActivity(new Intent(classe, PedidosActivity.class));
}
if (position == 3) {
startActivity(new Intent(classe, ChatActivity.class));
}
if (position == 5) {
startActivity(new Intent(classe, GruposActivity.class));
}
if (position == 7) {
startActivity(new Intent(classe, PerfilActivity.class));
}
if (position == 9) {
startActivity(new Intent(classe, SobreActivity.class));
}
}
}
HERE IS MY PedidosActivity(i call the navigator here):
package studio.brunocasamassa.ajudaaqui;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import com.facebook.login.LoginResult;
import studio.brunocasamassa.ajudaaqui.helper.NavigationDrawer;
import studio.brunocasamassa.ajudaaqui.helper.PedidosTabAdapter;
import studio.brunocasamassa.ajudaaqui.helper.SlidingTabLayout;
import studio.brunocasamassa.ajudaaqui.helper.User;
/**
* Created by bruno on 24/04/2017.
*/
public class PedidosActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListView listview_nomes;
private ViewPager viewPager;
private SlidingTabLayout slidingTabLayout;
public int posicao;
private LoginResult loginResult;
private MainActivity main;
private User usuario;
private static NavigationDrawer navigator = new NavigationDrawer();
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
toolbar = (Toolbar) findViewById(R.id.toolbar_principal);
toolbar.setTitle(getResources().getString(R.string.menu_pedidos));
//toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimaryDark));
setSupportActionBar(toolbar);
/*
loginResult = MainActivity.lr;
Profile profile = Profile.getCurrentProfile();
System.out.println("PROFILE: "+ profile);
String userid = loginResult.getAccessToken().getUserId();
String name = message(profile);
user.setName(name);*/
usuario = main.user;
System.out.println("USER: " + usuario.getName());
String username = usuario.getName();
loginResult=main.lr;
String userImg = usuario.getProfileImg();
listview_nomes = (ListView) findViewById(R.id.ListContatos);
viewPager = (ViewPager) findViewById(R.id.vp_pagina);
slidingTabLayout = (SlidingTabLayout) findViewById(R.id.stl_tabs);
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this, R.color.colorAccent));
PedidosTabAdapter pedidosTabAdapter = new PedidosTabAdapter(getSupportFragmentManager());
viewPager.setAdapter(pedidosTabAdapter);
slidingTabLayout.setViewPager(viewPager);
navigator.createDrawer(PedidosActivity.this, toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_exit:
//logoutUser();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
If someone could help, it will be very grateful

ITS WORKED, tks #MikeM, it was that what you said. Here is the answer
this method i call inside the Drawer onClickListener;
private void verifyActivity(Activity classe, int position) {
if (position == 1) {
// HERE I AM TRYING USING DIFFERENT FORMS TO START THE ACTITIVIES
classe.startActivity(new Intent(classe, PedidosActivity.class));
}
if (position == 3) {
classe.startActivity(new Intent(classe, ChatActivity.class));
}
if (position == 5) {
classe.startActivity(new Intent(classe, GruposActivity.class));
}
if (position == 7) {
classe.startActivity(new Intent(classe, PerfilActivity.class));
}
if (position == 9) {
classe.startActivity(new Intent(classe, SobreActivity.class));
}
here i call that, for each activity:
NavigationDrawer navigator = new NavigationDrawer();
navigator.createDrawer(PerfilActivity.this, toolbar);

Related

My Base Adapter, List<Song> songlist has a size of 0, instead of 14. It's preventing me from using my imgCoverArt onClick

I have been trying to create a ListView with the PlaylistsAdapter. But whenever I try to click on imgCoverArt, the app crashes, stating that the songlist has a size of 0. I have tried changing the types of the variables and just changing the codes overall. But I just couldn't fix it and I don't know the issue.
Thanks in advance.
This was the error I got:
2020-08-10 03:52:56.720 3091-3091/sg.edu.tp.musicstream E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.musicstream, PID: 3091
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at sg.edu.tp.musicstream.PlaylistsAdapter$1.onClick(PlaylistsAdapter.java:88)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I have tried to include the relevant classes and please let me know if you need anything else.
package sg.edu.tp.musicstream;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import sg.edu.tp.musicstream.util.AppUtil;
public class PlaylistsAdapter extends BaseAdapter {
Context mContext;
LayoutInflater inflater;
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
public PlaylistsAdapter(Context context, List<Song> songlist, Song[] songs)
{
mContext = context;
inflater = LayoutInflater.from(mContext);
this.songs = songs;
this.songlist = songlist;
this.arrayList = new ArrayList<>();
this.arrayList.addAll(songlist);
}
public class ViewHolder
{
ImageButton imgCoverArt;
TextView txtSongTitle;
TextView txtArtist;
ImageButton btnAddToPlaylist;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.playlist_listview, null);
holder.imgCoverArt = convertView.findViewById(R.id.imgCoverArt);
holder.txtSongTitle = convertView.findViewById(R.id.txtSongTitle);
holder.txtArtist = convertView.findViewById(R.id.txtArtist);
holder.btnAddToPlaylist = convertView.findViewById(R.id.btnAddToPlaylist);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgCoverArt.setImageResource(songlist.get(position).getCoverArt());
holder.imgCoverArt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
{
if (songlist.get(position).getId().equals(songs[index].getId())) {
Song song = songs[index];
sendDataToActivity(songs, song);
AppUtil.popMessage(mContext, ""+ songlist.size());
}
}
}
});
holder.txtSongTitle.setText(songlist.get(position).getTitle());
holder.txtArtist.setText(songlist.get(position).getArtist());
if (position >= 10) {
holder.btnAddToPlaylist.setContentDescription("S10" + position);
} else {
holder.btnAddToPlaylist.setContentDescription("S100" + position);
}
return convertView;
}
public void sendDataToActivity(Song[] songs, Song song)
{
// 1. Create a new Intent and specify the source and destination screen/activity.
Intent intent = new Intent(mContext, PlaySongActivity.class);
songlist = HomeFragment.arrayList;
songlist = new ArrayList<>();
// 2. Store the song information into the Intent object to be sent over to the destination screen.
intent.putExtra("id", song.getId());
intent.putExtra("title", song.getTitle());
intent.putExtra("artist", song.getArtist());
intent.putExtra("fileLink", song.getFileLink());
intent.putExtra("coverArt", song.getCoverArt());
intent.putExtra("songs", songs);
intent.putExtra("songlist", (Serializable) songlist);
// 3. Launch the destination screen/activity
mContext.startActivity(intent);
}
public void filter(String charText){
charText = charText.toLowerCase(Locale.getDefault());
songlist.clear();
if (charText.length()==0){
songlist.addAll(arrayList);
}
else {
for (Song song : arrayList){
if (song.getTitle().toLowerCase(Locale.getDefault())
.contains(charText) || song.getArtist().toLowerCase(Locale.getDefault())
.contains(charText)){
songlist.add(song);
}
}
}
notifyDataSetChanged();
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import sg.edu.tp.musicstream.ui.main.SectionsPagerAdapter;
import sg.edu.tp.musicstream.util.AppUtil;
public class HomeActivity extends AppCompatActivity {
private SectionsPagerAdapter sectionsPagerAdapter;
private SongCollection songCollection = new SongCollection();
static Song[] playlistSongs = new Song[14];
static ArrayList<Song> playlist = new ArrayList<>();
private Fragment homeFragment;
private Fragment playlistsFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
homeFragment = new HomeFragment();
playlistsFragment = new PlaylistsFragment();
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
sectionsPagerAdapter.addFragment(homeFragment, "Recommended Songs");
sectionsPagerAdapter.addFragment(playlistsFragment, "Playlist");
viewPager.setAdapter(sectionsPagerAdapter);
}
public void addToPlaylist (View view) {
String songId = view.getContentDescription().toString();
Song song = songCollection.searchById(SongCollection.recommendedSongs, songId);
playlist.add(song);
AppUtil.popMessage(this, "Added " + song.getTitle() + " to playlist!");
playlistSongs[playlist.size()] = song;
sectionsPagerAdapter.removeFragment(playlistsFragment, "Playlist");
sectionsPagerAdapter.addFragment(new PlaylistsFragment(), "Playlist");
ViewPager viewPager = findViewById(R.id.view_pager);
setUpViewPager(viewPager);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
public void removeAll(View view) {
playlist.clear();
PlaylistsFragment.songAdapter.notifyDataSetChanged();
}
}
package sg.edu.tp.musicstream;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.text.TextUtils;
import android.view.MenuItem;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
private PlaylistsAdapter playlistsAdapter;
private ListView listView;
static ArrayList<Song> arrayList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container,false);
for (int index =0; index<SongCollection.recommendedSongs.length; index++) {
arrayList.add(SongCollection.recommendedSongs[index]);
}
listView = view.findViewById(R.id.listView);
playlistsAdapter = new PlaylistsAdapter(getActivity(), arrayList, SongCollection.recommendedSongs);
listView.setAdapter(playlistsAdapter);
setHasOptionsMenu(true);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView)myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
if (TextUtils.isEmpty(s)){
playlistsAdapter.filter("");
listView.clearTextFilter();
}
else {
playlistsAdapter.filter(s);
}
return true;
}
});
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.settings){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
if (id==R.id.logOut){
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
package sg.edu.tp.musicstream;
import java.util.List;
import java.util.Random;
public class SongCollection
{
static Song[] recommendedSongs = new Song[14];
private Song[] playlist1 = new Song[5];
private Song[] playlist2 = new Song[5];
public SongCollection()
{
//Recommended Songs
Song photograph = new Song("S1000", "Photograph", "Ed Sheeran","097c7b735ceb410943cbd507a6e1dfda272fd8a8?cid=null",4.32, R.drawable.photograph);
Song theWayYouLookTonight = new Song("S1001", "The Way You Look Tonight", "Michael Buble","a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",4.39,R.drawable.michael_buble_collection);
Song billieJean = new Song("S1002", "Billie Jean", "Michael Jackson","f504e6b8e037771318656394f532dede4f9bcaea?cid=2afe87a64b0042dabf51f37318616965",4.39,R.drawable.billie_jean);
Song spark = new Song("S1003", "Spark", "TAEYEON","e857ae54599f2cca1703b598cef871664f36e72e?cid=2afe87a64b0042dabf51f37318616965", 3.63, R.drawable.spark);
Song darkside = new Song("S1004", "Darkside", "Alan Walker","2acc534ac733f8868c98e13e4f71917fae2e3ce3?cid=2afe87a64b0042dabf51f37318616965", 3.53, R.drawable.darkside);
Song diamondHeart = new Song("S1005", "Diamond Heart", "Alan Walker","d75c2b8e870acb087872bd49eeb5d6efb37cfc9d?cid=2afe87a64b0042dabf51f37318616965", 4.01, R.drawable.diamond_heart);
Song ocean= new Song("S1006", "Ocean (feat. Khalid)", "Martin Garrix","5ce5ed5600e96f1604aff6b05c0dc35319023a1c?cid=2afe87a64b0042dabf51f37318616965", 3.61, R.drawable.ocean);
Song numb = new Song("S1007", "Numb", "Linkin Park","e6ccf7717f8a167bfea4afc1bf7da1a0cd707fbb?cid=2afe87a64b0042dabf51f37318616965", 3.09, R.drawable.numb);
Song sadForever = new Song("S1008", "Sad Forever", "Lauv","1250fb3bea03aee6da908ea67420ddd954ad812a?cid=2afe87a64b0042dabf51f37318616965", 3.39, R.drawable.sad_forever);
Song kyokiranbu = new Song("S1009", "Kyokiranbu", "GARNiDELiA","ec373ab20f18e1a4a7b19b3abaac3ce605690abd?cid=2afe87a64b0042dabf51f37318616965", 4.32, R.drawable.kyokiranbu);
Song gokurakuJoudo= new Song("S1010", "Gokuraku Joudo", "GARNiDELiA","8924599ac778ebfbac7ddc2e5cc87961f82f736c?cid=2afe87a64b0042dabf51f37318616965", 3.65, R.drawable.gokuraku_joudo);
Song connect = new Song("S1011", "Connect", "ClariS","6692db454109aa077ed25e65df82a06d34017da6?cid=2afe87a64b0042dabf51f37318616965", 4.5, R.drawable.connect);
Song wannabe = new Song("S1012", "WANNABE", "ITZY", "2bae7f42bbae3cd75228d6400e37515b79467928?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.wannabe);
Song icy = new Song("S1013", "ICY", "ITZY", "118a0dea24f229f51ffff23a9d334cf5714dbaf6?cid=2afe87a64b0042dabf51f37318616965", 3.19, R.drawable.icy);
recommendedSongs[0] = photograph;
recommendedSongs[1] = theWayYouLookTonight;
recommendedSongs[2] = billieJean;
recommendedSongs[3] = spark;
recommendedSongs[4] = darkside;
recommendedSongs[5] = diamondHeart;
recommendedSongs[6] = ocean;
recommendedSongs[7] = numb;
recommendedSongs[8] = sadForever;
recommendedSongs[9] = kyokiranbu;
recommendedSongs[10] = gokurakuJoudo;
recommendedSongs[11] = connect;
recommendedSongs[12] = wannabe;
recommendedSongs[13] = icy;
}
In your adapter, you have three different ways of storing the songs:
Song[] songs;
List<Song> songlist;
ArrayList<Song> arrayList;
This is a problem. Pick one type, and use it everywhere.
The adapter is building its logic around the getCount() method:
#Override
public int getCount() {
return songlist.size();
}
Which uses songlist. But your onClick() method uses songs:
#Override
public void onClick(View v) {
for (int index = 0; index < songs.length; index++)
// ...
}
If you change this to use songlist instead, probably the issue will go away.

RecyclerView search filter getting wrong position after filtering result

Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}

Clicking on navigation drawer close itself Android studio

I have implemented navigation drawer on my mobile application and whenever i open the drawer and click on the drawer, the drawer closes itself. It used to work perfectly until I implemented another function and I am puzzled about how I should fix this.
Here's my main activity code. I am unable to navigate using the navigation drawer now.
package com.example.admin.calendlist;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
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.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
DatabaseHelper dbHelper;
ArrayAdapter<String> mAdapter;
ListView lstTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout, R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
dbHelper = new DatabaseHelper(this);
lstTask = (ListView)findViewById(R.id.lstTask);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView nvDrawer = (NavigationView)findViewById(R.id.nav_view);
setupDrawerContent(nvDrawer);
loadTaskList();
}
private void loadTaskList() {
ArrayList<String> taskList = dbHelper.getTaskList();
if(mAdapter==null){
mAdapter = new ArrayAdapter<String>(this, R.layout.row,R.id.task_title,taskList);
lstTask.setAdapter(mAdapter);
}
else{
mAdapter.clear();
mAdapter.addAll(taskList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
{
switch (item.getItemId()) {
case R.id.action_add_task:
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add New Task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
dbHelper.insertNewTask(task);
loadTaskList();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
switch (item.getItemId()) {
case R.id.td:
Intent newIntent = new Intent(this,MainActivity.class);
return true;
}
switch (item.getItemId()) {
case R.id.tt:
Intent newIntent = new Intent(this,Timetable.class);
return true;
}
switch (item.getItemId()) {
case R.id.ep:
Intent newIntent = new Intent(this,EventPage.class);
return true;
}
}
return super.onOptionsItemSelected(item);
}
private void selectItemDrawer(MenuItem item) {
int id = item.getItemId();
if (id ==R.id.ep) {
Intent newItent = new Intent (this, EventPage.class);
startActivity(newItent);
}
else if (id == R.id.td) {
Intent newIntent = new Intent (this,MainActivity.class);
startActivity(newIntent);
}
else if (id == R.id.tt) {
Intent newIntent = new Intent (this,Timetable.class);
startActivity(newIntent);
}
DrawerLayout drawer = findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
private void setupDrawerContent (NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener (new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.listmenu,menu);
Drawable icon =menu.getItem(0).getIcon();
icon.mutate();
icon.setColorFilter(getResources().getColor(android.R.color.black), PorterDuff.Mode.SRC_IN);
return super.onCreateOptionsMenu(menu);
}
public void deleteTask(View view){
View parent = (View)view.getParent();
TextView taskTextView = (TextView)findViewById(R.id.task_title);
String task = String.valueOf(taskTextView.getText());
dbHelper.deleteTask(task);
loadTaskList();
}
}
If you don't want navigation to close with each click, write like this :
NavigationView navigationView = findViewById(R.id.navigationView);
navigationView.bringToFront();
you can use it after switch
switch(id){
}
//Set menuItem checked and title
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
return false;
its obvious in Default drawerlayout on your click it has to be close,if you wana get command on your drawerlayot , hen you have to use custom drawerlayout, or you can add the library, don't forget to import the library manually not in your gradle, then you can edit the library, and chose the functions .
try this Library

Opening an other activity when clicking on an item in a navigation drawer

I got a navigation drawer, and when i click one of the items in it, it should open an other activity. so i made a switch, and don't get any errors. Still when i launch the application it keeps crashing. Need any help i can get!!!
Java is below
package com.gfo.enexis;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.id;
import static android.R.attr.start;
import static android.R.id.edit;
import static android.R.id.list;
import static com.gfo.enexis.R.id.button;
import static com.gfo.enexis.R.id.lv1;
import static com.gfo.enexis.R.id.nav_acount;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.nav_action);
setSupportActionBar(mToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
registerClickCallBack();
OnNavigationItemSelected();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Weet u zeker dat u wilt uitloggen?")
.setPositiveButton("Log uit", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
finish();
//close();
}
})
.setNegativeButton("Nee", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
EditText NotitieEt;
ListView ListNote;
ArrayList<String> lv = new ArrayList<>();
public void NoteAdd(View view) {
ListNote = (ListView) findViewById(lv1);
NotitieEt = (EditText) findViewById(R.id.notitie);
String note1 = NotitieEt.getText().toString();
if (lv.contains(note1)) {
Toast.makeText(this, "Notitie bestaat al", Toast.LENGTH_LONG).show();
} else if (note1 == null || note1.trim().equals("")) {
Toast.makeText(this, "Imput can't be empty", Toast.LENGTH_LONG).show();
} else {
lv.add(note1);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, lv);
ListNote.setAdapter(adapter);
((EditText) findViewById(R.id.notitie)).setText("");
}
}
private void registerClickCallBack() {
ListNote = (ListView) findViewById(lv1);
ListNote.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> paret, View viewClicked, int position, long id) {
lv.remove(position);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, lv);
ListNote.setAdapter(adapter);
}
});
}
MenuItem item;
public boolean OnNavigationItemSelected() {
int id = item.getItemId();
switch (id) {
case R.id.nav_acount:
Intent i = new Intent(MainActivity.this, DashBoard1.class);
startActivity(i);
break;
case R.id.nav_dashboard:
Intent o = new Intent(MainActivity.this, Dashboard2.class);
startActivity(o);
}
return true;
}
}
these are the errors i'm getting:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gfo.enexis/com.gfo.enexis.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int android.view.MenuItem.getItemId()' on a null object reference
and
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int android.view.MenuItem.getItemId()' on a null object reference
You are not initializing the
MenuItem item;
so it's NULL! And i think your are implementing "OnNavigationItemSelected" in the wrong way. Why are you calling "OnNavigationItemSelected();" in "onCreate()" method?
Just follow the official tutorial and you will be ok:
https://developer.android.com/training/implementing-navigation/nav-drawer.html
I think your problem is that you haven't registered the Navigation Drawer in the onCreate().
Use this:
NavigationView navigationView = (NavigationView) findViewById(R.id.yourIdHere);
navigationView.setNavigationItemSelectedListener(this);
Also, to handle navigation drawer clicks, override the method:
onNavigationItemSelected(MenuItem item)

Android Fragment Not Updating Image From Interface

I am trying to update a image from another thread to a fragment via interface. The code does manage to get into the interface but every time it gets to Left_Image.setImageDrawable(Image_Rotated); I keep getting a null pointer exception. If on the on create for the fragment i set a image it works but as soon as it tries to do it for the interface it comes up with the null pointer exception. I used the command isAdded()) to check if the fragment is attached and that keeps coming back as nothing but i cant seem to fix it and have it attached. Here is the code
Fragment:
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.logging.Handler;
public class Augmented_Reality extends PreferenceFragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationVectorSensor;
private Sensor mMagneticSensor;
private final float[] mRotationMatrix = new float[16];
private Boolean MagnetButtonPressed = false;
private Boolean Left;
private Boolean Right;
Boolean Admin_Mode;
boolean Lock = false;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs";
ToggleButton HeadTracker;
TextView Position;
TextView Position_Left;
TextView Position_Right;
ImageView Left_Image;
ImageView Right_Image;
private Image_Packet_Flag Image_Flag;
public final byte Image_Sync_Flag = 0x09;
private Context context;
Activity activity;
public Augmented_Reality() {
Image_Flag = new Image_Packet_Flag();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mRotationVectorSensor, 10000);
mSensorManager.registerListener(this, mMagneticSensor, 10000);
} catch (Exception ex) {
Toast.makeText(getActivity().getApplicationContext(), "failed sensor", Toast.LENGTH_SHORT).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = getActivity();
View rootView = inflater.inflate(R.layout.augmented_reality_view, container, false);
ActionBar actionBar = ((ActionBarActivity) activity).getSupportActionBar();
actionBar.hide();
HeadTracker = (ToggleButton) rootView.findViewById(R.id.HeadTracker);
Left_Image = (ImageView) rootView.findViewById(R.id.lefty);
Right_Image = (ImageView) rootView.findViewById(R.id.righty);
Bitmap icon = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.ytyty);
BitmapDrawable Image = Rotate_Image(icon);
Left_Image.setImageDrawable(Image);
return rootView;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (HeadTracker.isChecked() == true) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(
mRotationMatrix, event.values);
if (mRotationMatrix[2] >= 0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = true;
Right = false;
} else if (mRotationMatrix[2] <= -0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = false;
Right = true;
} else {
Left = false;
Right = false;
}
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
if (event.values[2] >= 390) {
MagnetButtonPressed = true;
} else {
MagnetButtonPressed = false;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public BitmapDrawable Rotate_Image(Bitmap Image) {
Bitmap bitmapOrg = Image;
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
return bmd;
}
public void UpdateImages(Bitmap Image) {
System.out.println("Image Updated");
final BitmapDrawable Image_Rotated = Rotate_Image(Image);
System.out.println("Is Added Result: " + isAdded());
if(isAdded()) {
System.out.println("Fragment Added");
Left_Image.setImageDrawable(Image_Rotated);
Right_Image.setImageDrawable(Image_Rotated);
}
}
}
MainActivity:
package com.example.jaynesh.mobile_robot_interface.Main_Files;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
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.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality;
import com.example.jaynesh.mobile_robot_interface.Fragments.Main_Screen;
import com.example.jaynesh.mobile_robot_interface.Fragments.Settings;
import com.example.jaynesh.mobile_robot_interface.Fragments.Mission_Data;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.DrawerItemCustomAdapter;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.ObjectDrawerItem;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Augmented_Reality_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Main_Screen_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Mission_Data_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Settings_Identifier;
import com.example.jaynesh.mobile_robot_interface.R;
import com.example.jaynesh.mobile_robot_interface.Socket.ClientThread;
public class MainActivity extends ActionBarActivity implements ClientThread.Image_Listener{
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
ClientThread clientThread;
private Augmented_Reality Augmented_Reality_Fragment;
private Main_Screen Main_Screen_Fragment;
private Mission_Data Mission_Data_Fragment;
private Settings Settings_Fragment;
private boolean Socket_Connected = false;
private int Current_Page = 0;
Main_Screen_Identifier MS;
Augmented_Reality_Identifier AR;
Mission_Data_Identifier MD;
Settings_Identifier SF;
Thread serverThread = null;
boolean NewPage = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
MS = new Main_Screen_Identifier();
AR = new Augmented_Reality_Identifier();
MD = new Mission_Data_Identifier();
SF = new Settings_Identifier();
NewPage = true;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[4];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_share, "Main Screen");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_share, "Augment Reality View");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Mission Data");
drawerItem[3] = new ObjectDrawerItem(R.drawable.ic_action_share, "Settings");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
public void OnNewImageListenerBitmap(final Bitmap Image) {
if (Thread.currentThread().getName() == "main") {
Augmented_Reality_Fragment.UpdateImages(Image);
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (Augmented_Reality_Fragment != null) {
Augmented_Reality_Fragment.UpdateImages(Image);
}
}
});
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
SharedPreferences.Editor editor = sharedpreferences.edit();
switch (position) {
case 0:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Main_Screen_Fragment == null) {
Main_Screen_Fragment = new Main_Screen();
}
fragment = Main_Screen_Fragment;
Current_Page = 1;
NewPage = true;
break;
case 1:
editor.putBoolean("Image_Listener", true);
editor.commit();
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
Current_Page = 2;
NewPage = true;
break;
case 2:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Mission_Data_Fragment == null) {
Mission_Data_Fragment = new Mission_Data();
}
fragment = Mission_Data_Fragment;
Current_Page = 3;
NewPage = true;
break;
case 3:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Settings_Fragment == null) {
Settings_Fragment = new Settings();
}
fragment = Settings_Fragment;
Current_Page = 4;
NewPage = true;
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onBackPressed() {
}
}
Thread on which Updated Interface:
if (Listener != null) {
System.out.println("Listener Found");
Image_data = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);
System.out.println("Image Created");
Listener.OnNewImageListenerBitmap(Image_data);
//sendMessage(Image_Flag.to_byte_array(Image_Sync_Flag));
System.out.println("Updated");
}
Ive been stuck on this problem for a while now and im not sure whats going wrong, Any help would be awesome :)
Steve
///////////................\\\\\\
Added Crash log
08-02 01:16:29.997 26346-26346/com.interface E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality.UpdateImages(Augmented_Reality.java:215)
at com.example.jaynesh.mobile_robot_interface.Main_Files.MainActivity$2.run(MainActivity.java:180)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
EDIT: In your case 1, be sure to use the fragment that you had set earlier
You have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
You should have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = Augmented_Reality_Fragment;

Categories