So here is the link of the application:-Nearpeer-Offline messenger
So After integrating firebase, sometimes while i am restarting this application i got stuck at first activity (mainactivity), its hang and after 10-20 sec later, error comes "application not responding" and app closes.
I already ask question before here :- link
But didn't get good response response.
Here i am providing an MainActivity code:-
package com.nearpeer.app;
/**
*
* Wifi-Direct based multi-user chat application
*
*/
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.analytics.FirebaseAnalytics;
/**
* The app's main entry point. Holds 2 fragments: {#link ChatSearchScreenFrag} and {#link ChatHistoryScreenFrag}.
* The 1st fragment offers to scan for new chat groups and users. The 2nd offers to view chat history.
*/
public class MainScreenActivity extends FragmentActivity implements ActionBar.TabListener
{
private AlertDialog mDialog=null;
private OnClickListener AlertCheckBoxClickListener=null; //used to handle check-box click events for a dialog
SectionsPagerAdapter mSectionsPagerAdapter; //adapter for the tab view. Contains all the frags
ViewPager mViewPager; //a layout widget in which each child view is a separate page (a separate tab) in the layout.
//both fragment will initialize these references when they're created:
public ChatHistoryScreenFrag mHistoryFrag = null;
public ChatSearchScreenFrag mSearchFrag = null;
boolean isServiceStarted = false;
boolean wasWifiDialogShown = false;
static int mDisplayedFragIndex = 0;
public static long ChatRoomAccumulatingSerialNumber=0;
public static String UniqueID=null;
public static String UserName = ":>~"; //setting a default user name
static boolean isToNotifyOnNewMsg = false; //defines if notifications should be shown on arrival of new messages
static int RefreshPeriodInMs = 30000; //defines the peer refresh period
private boolean mIsRunForTheFirstTime=false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
//FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
/*Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
try {
InitializeTabHandlerAndAdapter();
if (!isServiceStarted && ChatSearchScreenFrag.mService == null) {
startService(new Intent(this, LocalService.class));
isServiceStarted = true;
}
getPrefs(); //get the shared prefs
//Happens only when the app is run for the very 1st time on a device
if (MainScreenActivity.UniqueID == null) {
UserName = new String(Secure.getString(getContentResolver(), Secure.ANDROID_ID)); //get a unique id
UniqueID = new String(UserName);
}//if
//Remove the title bar for out entire app
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
toast.show();
}
}//end of onCreate()
#Override
protected void onResume()
{
super.onResume();
//check if this activity was launched by the b-cast receiver after a wifi shutdown
try {
boolean isToDisplayWifiDialog = getIntent()
.getBooleanExtra(Constants.WIFI_BCAST_RCVR_WIFI_OFF_EVENT_INTENT_EXTRA_KEY, false);
if (isToDisplayWifiDialog && !wasWifiDialogShown) {
new EnableWifiDirectDialog().show(getSupportFragmentManager(), "MyDialog"); //show a dialog
wasWifiDialogShown = true;
}
//if this app is run for the very 1st time, we want to launch the settings activity first.
if (mIsRunForTheFirstTime) {
//launch the preferences activity
startActivity(new Intent(this, QuickPrefsActivity.class));
mIsRunForTheFirstTime = false;
}
}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
toast.show();
}
}
#Override
protected void onPause()
{
super.onPause();
savePrefs(); //save the preferences
}//end of onPause()
private void InitializeTabHandlerAndAdapter()
{
// Set up the action bar (enable tab display).
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the two
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
#Override
//if a tab was changed by a swipe gesture
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position); //update the tab bar to match the selected page
mDisplayedFragIndex=position; //update the index of the currently displayed frag
if (position==1) //if the view has moved to the history fragment:
{
mHistoryFrag.loadHistory(); //reload the history list view
}
invalidateOptionsMenu();
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}//for
}//end of InitializeTabHandlerAndAdapter()
/**
* Used to modify menu item according to the app's state
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
//Check wifi state.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(mWifi.isConnected()||wifi.isWifiEnabled()) {
ChatSearchScreenFrag.mIsWifiDirectEnabled = true;
}
//if the wifi-direct is disabled, we want to disable the chat room creation option
menu.getItem(0).setEnabled(ChatSearchScreenFrag.mIsWifiDirectEnabled);
//if this menu is opened when the chat search is active:
if (mDisplayedFragIndex==0)
{
//hide the 'delete history option:
menu.findItem(R.id.action_delete_all_history).setVisible(false);
}
else //history frag is active:
{
//show the 'delete history option:
menu.findItem(R.id.action_delete_all_history).setVisible(true);
menu.findItem( R.id.clear_ignore_list).setVisible(false);
}
return true;
}
#SuppressLint("HandlerLeak")
Handler FirstTimeMenuUpdater = new Handler()
{
#Override
public void handleMessage(Message msg)
{
MainScreenActivity.this.invalidateOptionsMenu();
}
};
/**
* Called only once when the app starts
*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen_menu, menu);
FirstTimeMenuUpdater.sendEmptyMessageDelayed(0, 500);
return true;
}//end of onCreateOptionsMenu()
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_settings://setting was clicked
{
startActivity(new Intent(this, QuickPrefsActivity.class));
break;
}
case R.id.action_create_new_chat_room: //exit app was clicked
{
mDialog =CreatePublicChatCreationDialog();
mDialog.show();
AlertCheckBoxClickListener= new OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog dialog = MainScreenActivity.this.mDialog;
EditText ed = (EditText) dialog.findViewById(R.id.choosePassword);
boolean b= !ed.isEnabled();
ed.setEnabled(b);
}
};
CheckBox ch = (CheckBox) mDialog.findViewById(R.id.checkBoxSetPassword);
ch.setOnClickListener(AlertCheckBoxClickListener);
break;
}
case R.id.clear_ignore_list: //exit app was clicked
{
if (mSearchFrag!=null)
mSearchFrag.ClearIgnoredUsersList();
break;
}
case R.id.feedback: //exit app was clicked
{
startActivity(new Intent(this, FeedbackActivity.class));
break;
}
case R.id.about: //exit app was clicked
{
startActivity(new Intent(this, AboutusActivity.class));
break;
}
case R.id.action_exit: //exit app was clicked
{
kill();
break;
}
case R.id.action_delete_all_history: //delete all history was clicked
{
mHistoryFrag.DeleteAllHistory();
break;
}
}//switch
return true;
}//end of onOptionsItemSelected()
#Override
public void onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction)
{
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}//end of onTabSelected()
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
/**
* A FragmentPagerAdapter that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
Fragment fragment=null; //will hold the relevant fragment to be returned
switch (position)
{
case 0:
fragment = new ChatSearchScreenFrag(); //create a new chat search fragment
break;
case 1:
fragment = new ChatHistoryScreenFrag(); //create a new history display fragment
break;
}
return fragment;
}//end of getItem()
#Override
public int getCount()
{
return 2; // Show 2 total pages.
}
//Returns the title for each tab
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.main_screen_tab1_title).toUpperCase(l);
case 1:
return getString(R.string.main_screen_tab2_title).toUpperCase(l);
}
return null;
}
}//end of class
/**
* Called when the refresh button in the chat search fragment is clicked
*/
public void onRefreshButtonClicked (View v)
{
mSearchFrag.onRefreshButtonClicked(v); //call the frag's method
}//end of onRefreshButtonClicked()
/**
* Reads the saved preferences
*/
protected void getPrefs()
{
SharedPreferences prefs = getPreferences(0);
ChatRoomAccumulatingSerialNumber = prefs.getLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, 0);
UserName = prefs.getString(Constants.SHARED_PREF_USER_NAME, null);
UniqueID = prefs.getString(Constants.SHARED_PREF_UNIQUE_ID, null);
isToNotifyOnNewMsg = prefs.getBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, false);
RefreshPeriodInMs = prefs.getInt(Constants.SHARED_PREF_REFRESH_PERIOD, 10000);
mIsRunForTheFirstTime = prefs.getBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, true);
}//end of getPrefs(){
/**
* Saved the shared preferences
*/
protected void savePrefs()
{
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, ChatRoomAccumulatingSerialNumber); //save to current SN
editor.putString(Constants.SHARED_PREF_USER_NAME, UserName);
editor.putString(Constants.SHARED_PREF_UNIQUE_ID, UniqueID);
editor.putBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, isToNotifyOnNewMsg);
editor.putInt(Constants.SHARED_PREF_REFRESH_PERIOD, RefreshPeriodInMs);
editor.putBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, false);
editor.commit();
}//end of savePrefs()
/**
* Calls the kill() method of {#link ChatSearchScreenFrag}, resets all static variables,
* calls the system's garbage collector and finishes.
*/
public void kill(){
savePrefs();
mSearchFrag.kill(); //close the entire app (service and welcome socket)
//we'de like to reset all static variables in our app:
ChatActivity.mIsActive=false;
ChatActivity.mMsgsWaitingForSendResult=null;
ChatSearchScreenFrag.mService=null;
ChatSearchScreenFrag.mIsWifiDirectEnabled=false;
ChatSearchScreenFrag.mIsConnectedToGroup=false;
ChatSearchScreenFrag.mManager = null;
ChatSearchScreenFrag.mChannel = null;
LocalService.mNotificationManager=null;
//Indicates to the VM that it would be a good time to run the garbage collector
System.gc();
finish(); //close this activity
}//kill()
private AlertDialog CreatePublicChatCreationDialog()
{
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.public_chat_creation_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Create A New Room")
.setView(textEntryView)
.setIcon(R.drawable.settings_icon)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
boolean isPassword=false;
String password="";
String roomName=null;
EditText ed = (EditText) mDialog.findViewById(R.id.choosePassword);
//gets password if exists
isPassword= ed.isEnabled();
if(isPassword){password=ed.getText().toString();}
//gets rooms name
ed = (EditText) mDialog.findViewById(R.id.chooseRoomsName);
roomName=ed.getText().toString();
//if the room's name is invalid:
if(roomName==null || roomName.length()<1){
// pop alert dialog and reload this dialog
new AlertDialog.Builder(MainScreenActivity.this)
.setTitle("Missing name error")
.setMessage("A room must have a name")
//yes button setter
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {mDialog.show();}})//setPositive
.setOnCancelListener(new OnCancelListener(){
public void onCancel(DialogInterface dialog){mDialog.show();}})
.show();
//end of alert dialog
}//if
else{//there is a room name
//the room is ready to be created
//call the service and create a new public chat room
if (password.equalsIgnoreCase(""))
password=null;
ChatSearchScreenFrag.mService.CreateNewHostedPublicChatRoom(roomName,password);
}//else
}//onClick dialog listener
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
}).create();
}//end of ShowPublicChatCreationDialog()
}//end of class
Though it is commercial application but i have to share this because this issue must be solve by any how.
Here is the log cat what i got while stucking at screen:-
logcat
Related
I am writing a mobile application and have attached a popup menu to an ImageButton through that button's OnClick method.
menu_lilac.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showPopup(view);
}
});
I am trying to make it so pressing the menu item redirects to the relevant Activity (in the switch statement at the end).
The error I get is Error:(23, 8) error: MainActivity is not abstract and does not override abstract method onMenuItemClick(MenuItem) in OnMenuItemClickListener.
public void showPopup(View view) {
PopupMenu popup = new PopupMenu(this, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.mainmenu, popup.getMenu());
MenuItem item = (MenuItem) popup.getMenu();
popup.show();
//Intent to Tasks Activity
final Intent toTasks = new Intent(this, TasksActivity.class);
//Intent to Distractions Activity
final Intent toDist = new Intent(this, DistractionsActivity.class);
//Intent to Settings Activity
final Intent toSett = new Intent(this, SettingsActivity.class);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.Home:
return true;
case R.id.Tasks:
startActivity(toTasks);
return true;
case R.id.Distractions:
startActivity(toDist);
return true;
case R.id.Settings:
startActivity(toSett);
return true;
default:
return false;
}
}
});
}
What am I doing wrong? I tried initialising the OnMenuItemClickListener in a different way such as
PopupMenu.OnMenuItemClickListener listener = PopupMenu.OnMenuItemClickListener(){
}
but listener is never used and the app crashes when any of the menu buttons are pressed.
Full MainActivity class:
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.NumberPicker;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;
public class MainActivity extends Activity implements PopupMenu.OnMenuItemClickListener {
//Creation of used objects
//Button, Button, TextView, Handler, AlarmManager, NumberPicker, Pending Intent
//Context, TextView, Button
Button startButton;
Button stopButton;
TextView timerValue;
Handler customHandler = new Handler();
NumberPicker interval_length;
PendingIntent pending_intent;
Context context;
TextView checker;
ImageButton menu_lilac;
Intent toDist;
Intent toSett;
Intent toTasks;
//Creation of variables
long timeInMilliseconds = 0L;
long updatedTime = 0L;
long startTime = 0L;
int picked_value;
private static int minValueInterval = 1;
private static int maxValueInterval = 60;
int final_interval;
//On create function initialises the layout
#Override
protected void onCreate(Bundle savedInstanceState) {
//Creation of main GUI layout
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
}
#Override
protected void onStart() {
super.onStart();
//Initialise number picker
interval_length = (NumberPicker) findViewById(R.id.interval_length);
//Set minimum value (minutes)
interval_length.setMinValue(minValueInterval);
//Set maximum value (minutes)
interval_length.setMaxValue(maxValueInterval);
//Set currently displayed value (minutes)
interval_length.setValue(20);
//Initialise listener to listen for a value change on the number picker
interval_length.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
//Replace variable picked_value with the new value of the number picker
picked_value = interval_length.getValue() - 1;
}
});
//Initialise timerValue text box
timerValue = (TextView) findViewById(R.id.timerValue);
//Initialise start button
startButton = (Button) findViewById(R.id.startButton);
//Initialise instance of stop button
stopButton = (Button) findViewById(R.id.stopButton);
//Initialise instance of menu button
menu_lilac = (ImageButton) findViewById(R.id.menu_lilac);
//Initialise checker text box
checker = (TextView) findViewById(R.id.checker);
//Menu button onClickListener
menu_lilac.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showPopup(view);
}
});
//Start button OnClickListener
startButton.setOnClickListener(new View.OnClickListener() {
//On start begin counting up in milliseconds.
//Reset timer every time Start button is pressed.
public void onClick(View view) {
timerValue.setText("00:00");
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
//Set text box to print a message displaying when the alarm is for
checker.setText("The alarm has been set for " + picked_value + " minutes from now!");
//Make pop-up toast notification
Toast.makeText(context,"Alarm on!", Toast.LENGTH_LONG).show();
}
});
//Calculation of picked interval length (from minutes) to milliseconds
final_interval = picked_value * 60 * 1000;
if (timerValue.equals(picked_value+":00")) {
alarm_manager.set(AlarmManager.RTC_WAKEUP, timeInMilliseconds, pending_intent);
}
//Initialise Stop button OnClickListener
stopButton.setOnClickListener(new View.OnClickListener() {
//On click stop updating timer thread and reset value to 00:00
public void onClick(View view) {
customHandler.removeCallbacks(updateTimerThread);
timerValue.setText("00:00");
//print message to notify user of alarm being cancelled
checker.setText("The alarm has been cancelled!");
//Make toast notification to say alarm cancelled
Toast.makeText(context,"Alarm off!", Toast.LENGTH_LONG).show();
}
});
}
//Creates a runnable to update the timer
private Runnable updateTimerThread = new Runnable() {
public void run() {
//Takes time in milliseconds from the system clock
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeInMilliseconds;
//Converts milliseconds to seconds and minutes
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
//Updates timerValue to the formatted 00:00 (minutes:seconds)
timerValue.setText(String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
public Runnable showPopup(View view) {
PopupMenu popup = new PopupMenu(this, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.mainmenu, popup.getMenu());
MenuItem item = (MenuItem) popup.getMenu();
popup.show();
//Intent to Tasks Activity
final Intent toTasks = new Intent(this, TasksActivity.class);
//Intent to Distractions Activity
final Intent toDist = new Intent(this, DistractionsActivity.class);
//Intent to Settings Activity
final Intent toSett = new Intent(this, SettingsActivity.class);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.Home:
return true;
case R.id.Tasks:
startActivity(toTasks);
return true;
case R.id.Distractions:
startActivity(toDist);
return true;
case R.id.Settings:
startActivity(toSett);
return true;
default:
return false;
}
}
});
}
}
Fixed! I removed the "implements PopupMenu.OnMenuItemClickListener" from my class declaration and re-did the PopupMenu all over again. This time I used if statements instead of a switch statement and instead of calling MenuInflater I just used inflate() on popup.
These are the needed imports:
import android.view.MenuItem;
import android.widget.PopupMenu;
My class declaration:
public class MainActivity extends Activity {
These are my intents:
//Intent to Tasks Activity
final Intent toTasks = new Intent(this, TasksActivity.class);
//Intent to Distractions Activity
final Intent toDist = new Intent(this, DistractionsActivity.class);
//Intent to Settings Activity
final Intent toSett = new Intent(this, SettingsActivity.class);
And this is my popup menu.
//Menu button onClickListener
menu_lilac.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//create instance of PopupMenu
PopupMenu popup = new PopupMenu(getApplicationContext(), view);
//inflate menu with layout mainmenu
popup.inflate(R.menu.mainmenu);
popup.show();
//Set on click listener for the menu
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId()== R.id.Home){
Toast.makeText(context, "At home!", Toast.LENGTH_LONG).show();
}
if (item.getItemId() == R.id.Tasks){
startActivity(toTasks);
}
if (item.getItemId() == R.id.Distractions){
startActivity(toDist);
}
if (item.getItemId() == R.id.Settings){
startActivity(toSett);
}
return false;
}
});
}
});
I don't see reason why you actually implement interface PopupMenu.OnMenuItemClickListener in your activity, but if there is reason, you must implement methods of that interface.
So basically you must have implementation of that method in MainActivity:
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
Also hopefully you use Android Studio. It should say you about error and if you will put pointer on error and click "ALT+ENTER" you will see Implement methods item in menu, clicking on which will solve that problem.
May be helpful for late visitors
public class MainActivity extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
ImageButton mainMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainMenu = findViewById(R.id.ibtn_menu);
mainMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showMenu(view);
}
});
}
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
// This activity implements OnMenuItemClickListener
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.main_menue);
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_day_view_about: {
Toast.makeText(MainActivity.this,"Clicked on the action", Toast.LENGTH_LONG).show();
return true;
}
}
return true;
}
}
My problem was that I implemented wrong OnMenuItemClickListener,
I needed:
PopupMenu.OnMenuItemClickListener
and I had:
MenuItem.OnMenuItemClickListener
I have been struggling with an issue in a note application i have been building with the help of a tutorial series. I just created a dialog allowing the user to change the category of a note but the new category is lost whenever the orientation is changed. as instructed by tutorial i override onSavedInstance to save information first but for some reason is not solved code below:
package com.workingprogess.notebook;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
public class NoteEditFragment extends Fragment {
private ImageButton noteCatButton;
private EditText title;
private EditText message;
private Button saveButton;
private Note.Category savedButtonCategory;
private AlertDialog categoryDialogObject;
private AlertDialog confirmDialogObject;
private static final String MODIFIED_CATEGORY="Modified Category";
public NoteEditFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(savedInstanceState!=null){
savedButtonCategory = (Note.Category) savedInstanceState.get(MODIFIED_CATEGORY);
}
//grab layout and assign to view so that we may access widgets
View fragmentLayout = inflater.inflate(R.layout.fragment_note_edit, container, false);
//grab widget references
title = (EditText) fragmentLayout.findViewById(R.id.editNoteTitle);
message = (EditText) fragmentLayout.findViewById(R.id.editMessage);
noteCatButton = (ImageButton) fragmentLayout.findViewById(R.id.editNoteButton);
saveButton = (Button) fragmentLayout.findViewById(R.id.saveNoteButton);
//populate with note data
Intent intent = getActivity().getIntent();
title.setText(intent.getExtras().getString(MainActivity.NOTE_TITLE_EXTRA));
message.setText(intent.getExtras().getString(MainActivity.NOTE_MESSAGE_EXTRA));
if(savedButtonCategory !=null){
Log.d("not null","the new image should be carried over");
noteCatButton.setImageResource(Note.categoryToDrawable(savedButtonCategory));
} else {
Note.Category noteCat = (Note.Category) intent.getSerializableExtra(MainActivity.NOTE_CATEGORY_EXTRA);
savedButtonCategory = noteCat;
noteCatButton.setImageResource(Note.categoryToDrawable(noteCat));
Log.e("null","pull from intent" );
}
//set onclick listeners
buildCategoryDialog();
noteCatButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
categoryDialogObject.show();
}
});
buildConfirmDialog();
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialogObject.show();
}
});
// Inflate the layout for this fragment
return fragmentLayout;
}
//save info before orientation change.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d("save","info is saved");
savedInstanceState.putSerializable(MODIFIED_CATEGORY, savedButtonCategory);
}
//build pop uo dialog to change note info
private void buildCategoryDialog(){
final String[] categories = new String[]{"Personal","Technical","Quote","Finance"};
final AlertDialog.Builder categoryBuilder = new AlertDialog.Builder(getActivity());
categoryBuilder.setTitle("Choose Note Type");
categoryBuilder.setSingleChoiceItems(categories, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int item) {
switch (item){
case 0:
savedButtonCategory= Note.Category.PERSONAL;
noteCatButton.setImageResource(R.drawable.p_icon);
break;
case 1:
savedButtonCategory=Note.Category.TECHNICAL;
noteCatButton.setImageResource(R.drawable.t_icon);
break;
case 2:
savedButtonCategory=Note.Category.QUOTE;
noteCatButton.setImageResource(R.drawable.q_icon);
break;
case 3:
savedButtonCategory=Note.Category.FINANCE;
noteCatButton.setImageResource(R.drawable.f_icon );
break;
}
categoryDialogObject.cancel();
}
});
categoryDialogObject=categoryBuilder.create();
}
private void buildConfirmDialog(){
final AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(getActivity());
confirmBuilder.setTitle("are you sure?");
confirmBuilder.setMessage("are you sure you want to save this note");
confirmBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("Save Note","Note title " + title.getText()+ "Note message "
+ message.getText()+" note category" + savedButtonCategory);
Intent intent = new Intent(getActivity(),MainActivity.class);
startActivity(intent);
}
});
confirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
savedButtonCategory=Note.Category.TECHNICAL;
}
});
confirmDialogObject = confirmBuilder.create();
}
}
Open your application Manifest file and for particular activity, add this code:
<activity
android:name=".MainActivity" //Activity where the problem is occuring
android:configChanges="screenLayout|orientation|screenSize">
Its better to add this "android:configChanges" to every activity to maintain data state even if orientation changes.
Have you checked if onSaveInstanceState is actually getting called? This callback will only be called if the Activity holding the fragment is getting destroyed. So, first check if your Activity is getting destroyed or not.
I am working on an assignment for school, the instructions are to create a Bookmark app with two activities, one named BookNote which must be a List Activity and another called ManageActivity.
BookNote is to populate the List Activity on startup with data read from a file, if no file is present an example bookmark is created. Bookmarks can be added, edited, and deleted, but all typing must be done in ManageActivity. Whenever Booknote handles the data returned from ManageActivity it should alter the list.
The code I have now has comments showing my intentions for each function, but my current problem is that everytime I return to BookNote from ManageActivity, the app crashes with the error "Attempt to invoke virtual method 'void android.widget.ArrayAdapter.insert(java.lang.Object, int)' on a null object reference" when attempting to add or insert a new bookmark object into the ArrayAdapter.
BookNote Activity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class BookNote extends ListActivity{
private ArrayAdapter<Bookmark> adapter;
private final String FILENAME = "bookmarks.txt";
public String title = "EMPTY", url = "EMPTY", note = "EMPTY";
public String bookmarkClicked ="";
public int listViewID = 0;
public boolean intentListener = false;
public boolean addBookmarkClicked = false;
/*When activity is called, list is populated by readData(), addBookmarkClicked is reset to false, intentLister is changed to true if returning from ManageActivity,
if intentListener is true, addBookmarkClicked will be changed to true if AddBookmark is clicked from the BookNote menubar, a bookmark object will be created with information
passed back from ManageActivity, and if addBookmarkClicked is true, the bookmark object will be added to the end of the list, otherwise it will be inserted in the same
list element from which was chosen to edit.*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
addBookmarkClicked = false;
intentListener = false;
intentListener = getIntent().getBooleanExtra("listen", false);
if(intentListener == true) {
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
title = getIntent().getExtras().getString("title");
url = getIntent().getExtras().getString("url");
note = getIntent().getExtras().getString("note");
listViewID = getIntent().getExtras().getInt("listViewID");
Bookmark bookmark = new Bookmark(title,url,note);
Toast.makeText(getApplicationContext(), "Intent return: True", Toast.LENGTH_SHORT).show();
if(addBookmarkClicked == true) {
addBookmark(bookmark);
}
else {
insertBookmark(bookmark, listViewID);
}
//writeData();
}
}
//When list item is clicked, fill bookmarkClicked with values in list item, record item position, and call gotoManageActivity() to pass information to ManageActivity.
public void onListItemClick(ListView listView, View view, int position, long id) {
ListView myListView = getListView();
Object itemClicked = myListView.getAdapter().getItem(position);
Toast.makeText(getApplicationContext(), "Item clicked: " + itemClicked + "\nItem ID: " + id,Toast.LENGTH_SHORT).show();
bookmarkClicked = itemClicked.toString();
listViewID = position;
gotoManageActivity();
}
//reads data when app runs and fills arrayadapter and list with items saved to bookmarks.txt
private ArrayList<Bookmark> readData(){
ArrayList<Bookmark> bookmarks = new ArrayList<>();
try {
FileInputStream fis = openFileInput(FILENAME);
Scanner scanner = new Scanner(fis);
if (scanner.hasNext()){
String titleScan = scanner.nextLine();
String urlScan = scanner.nextLine();
String noteScan = scanner.nextLine();
Bookmark bookmark = new Bookmark(titleScan, urlScan, noteScan);
bookmarks.add(bookmark);
}else{
Bookmark bookmark = new Bookmark("Example Title", "Example URL", "Example Note");
bookmarks.add(bookmark);
}
scanner.close();
} catch (FileNotFoundException e) {
}
return bookmarks;
}
//If addBookmark menu item is clicked, this will be called to add a bookmark to the end of the ArrayAdapter.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
//writeData();
}
//If a list item is clicked, any edits will be inserted back into the ArrayAdapter in the same position of the item clicked.
private void insertBookmark(Bookmark bookmark, int listViewID){
adapter.insert(bookmark,listViewID);
//writeData();
}
//Calls ManageActivity and reports information about app.
public void gotoManageActivity(){
Intent manageIntent = new Intent(this, ManageActivity.class);
Bundle extras = new Bundle();
extras.putString("bookmark", bookmarkClicked);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
extras.putInt("listViewID", listViewID);
manageIntent.putExtras(extras);
startActivity(manageIntent);
}
#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_book_note, 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_add) {
addBookmarkClicked = true;
gotoManageActivity();
return true;
}
return super.onOptionsItemSelected(item);
}
}
ManageActivity
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ManageActivity extends AppCompatActivity {
private String title = "EMPTY", url = "EMPTY", note = "EMPTY";
private boolean listener = true;
private boolean addBookmarkClicked = false;
/* When activity starts, check for addBookmarkClicked status, create book */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_layout);
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
String bookmarkString = "";
bookmarkString = getIntent().getExtras().getString("bookmark");
if(bookmarkString != null && bookmarkString.length() > 0) {
if (bookmarkString.length() != 0) {
String[] stringArray = bookmarkString.split("\\n");
title = stringArray[0];
url = stringArray[1];
note = stringArray[2];
updateTextViews();
}
}
else {
updateTextViews();
}
}
#Override
public void onBackPressed(){
Intent bookNoteIntent = new Intent(this, BookNote.class);
startActivity(bookNoteIntent);
Bundle extras = new Bundle();
extras.putString("title", title);
extras.putString("url", url);
extras.putString("note", note);
extras.putBoolean("listen", listener);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
bookNoteIntent.putExtras(extras);
startActivity(bookNoteIntent);
}
public void editButtonCall(View view){
showNoteDialog();
showURLDialog();
showTitleDialog();
}
public void webButton(View view){
if(url.length() != 0 && url != "EMPTY"){
}
}
public void updateTextViews(){
TextView titleTextView = (TextView) findViewById(R.id.titleTV);
TextView urlTextView = (TextView) findViewById(R.id.urlTV);
TextView noteTextView = (TextView) findViewById(R.id.noteTV);
titleTextView.setText("Title: " + title);
urlTextView.setText("URL: " + url);
noteTextView.setText("Note: " + note);
}
//Show dialog and editText for user to assign title to bookmark.
public void showTitleDialog(){
AlertDialog.Builder titleBuilder = new AlertDialog.Builder(this);
titleBuilder.setTitle("Enter Title");
final EditText titleET = new EditText(this);
titleET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
titleBuilder.setView(titleET);
titleBuilder.setPositiveButton("Add", newDialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
title = titleET.getText().toString();
updateTextViews();
}
});
titleBuilder.show();
}
//Show dialog and editText for user to assign note to bookmark.
public void showNoteDialog(){
AlertDialog.Builder noteBuilder = new AlertDialog.Builder(this);
noteBuilder.setTitle("Enter Note");
final EditText noteET = new EditText(this);
noteET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
noteBuilder.setView(noteET);
noteBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
note = noteET.getText().toString();
updateTextViews();
}
});
noteBuilder.show();
}
//Show dialog and editText for user to assign url to bookmark.
public void showURLDialog(){
AlertDialog.Builder urlBuilder = new AlertDialog.Builder(this);
urlBuilder.setTitle("Enter URL");
final EditText urlET = new EditText(this);
urlET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
urlBuilder.setView(urlET);
urlBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
url = urlET.getText().toString();
updateTextViews();
}
});
urlBuilder.show();
}
}
You are declaring a global and a local instance of adapter. In onCreate() method of BookNote Activity, remove the local instance. Change
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
to
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
You are not setting xml file which contains
book_layout.xml
<ListView android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_layout);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
in my NavigationDrawerFragment.java
i have this code
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String header = listDataHeader.get(groupPosition);
Category child = listDataChild.get(header).get(childPosition);
// child.name to get the name
// child.id to get the id
//Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();
selectItem(1);
return false;
}
});
after i click the child, i set selectItem to 1
the selectItem(1) will go to MainActivity.java
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance())
.commit();
}
}
my question is how to pass the child.name and child.id from NavigationDrawerFragment.java to MainActivity.java then pass to CategoryFragment?
or any other solution to pass the child.name and child.id to CategoryFragment.
COMPLETE CODE
NavigationDrawerFragment.java
package com.example.administrator.mosbeau;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "categories_id";
private static final String TAG_NAME = "categories_name";
JSONArray categories = null;
public NavigationDrawerFragment() {
}
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<Category>> listDataChild;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
/*mDrawerListView = (ListView) fragmentView.findViewById(R.id.listView);
//mDrawerListView = (ListView) inflater.inflate(
//R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_home),
getString(R.string.title_category),
getString(R.string.title_myaccount),
getString(R.string.title_referafriend),
getString(R.string.title_about),
getString(R.string.title_privacypocity),
getString(R.string.title_shippingterms),
getString(R.string.title_contactus),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);*/
// get the listview
expListView = (ExpandableListView) fragmentView.findViewById(R.id.lvExp);
// preparing list data
//prepareListData();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getData();
} else {
selectItem(100);
}
return fragmentView;
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/categories.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
/*Toast.makeText(getActivity(),
"Group Clicked " + listDataHeader.get(groupPosition),
Toast.LENGTH_SHORT).show();*/
if(groupPosition == 1){
return false;
} else {
selectItem(groupPosition);
return true;
}
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
String header = listDataHeader.get(groupPosition);
Category child = listDataChild.get(header).get(childPosition);
// child.name to get the name
// child.id to get the id
Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();
//selectItem(1);
return false;
}
});
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void prepareListData(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
categories = jsonObj.getJSONArray(TAG_RESULTS);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<Category>>();
// Adding group data
listDataHeader.add("HOME");
listDataHeader.add("CATEGORY");
listDataHeader.add("MY ACCOUNT");
listDataHeader.add("REFER A FRIEND");
listDataHeader.add("ABOUT");
listDataHeader.add("PRIVACY POLICY");
listDataHeader.add("SHIPPING TERMS");
listDataHeader.add("CONTACT US");
List<Category> CATEGORY = new ArrayList<Category>();
for(int i=0;i<categories.length();i++){
JSONObject c = categories.getJSONObject(i);
Category category = new Category();
category.name = c.getString(TAG_NAME);
category.id = c.getString(TAG_ID);
CATEGORY.add(category);
}
listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data
} catch (JSONException e) {
e.printStackTrace();
}
}
/*
* Preparing the list data
*/
/*private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding group data
listDataHeader.add("HOME");
listDataHeader.add("CATEGORY");
listDataHeader.add("MY ACCOUNT");
listDataHeader.add("REFER A FRIEND");
listDataHeader.add("ABOUT");
listDataHeader.add("PRIVACY POLICY");
listDataHeader.add("SHIPPING TERMS");
listDataHeader.add("CONTACT US");
// Adding child data
List<String> CATEGORY = new ArrayList<String>();
CATEGORY.add("Category 1");
CATEGORY.add("Category 2");
CATEGORY.add("Category 3");
CATEGORY.add("Category 4");
CATEGORY.add("Category 5");
listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data
}*/
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
MainActivity.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detectconnection = new Seocnd(this);
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 0){
fragmentManager.beginTransaction()
.replace(R.id.container, HomeFragment.newInstance())
.commit();
}
else if (position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance())
.commit();
}
else if (position == 2){
fragmentManager.beginTransaction()
.replace(R.id.container, AccountFragment.newInstance())
.commit();
}
else if (position == 3){
fragmentManager.beginTransaction()
.replace(R.id.container, ReferFragment.newInstance())
.commit();
}
else if (position == 4){
fragmentManager.beginTransaction()
.replace(R.id.container, AboutFragment.newInstance())
.commit();
}
else if (position == 5){
fragmentManager.beginTransaction()
.replace(R.id.container, PolicyFragment.newInstance())
.commit();
}
else if (position == 6){
fragmentManager.beginTransaction()
.replace(R.id.container, TermsFragment.newInstance())
.commit();
}
else if (position == 7){
fragmentManager.beginTransaction()
.replace(R.id.container, ContactusFragment.newInstance())
.commit();
}
else if (position == 100){
fragmentManager.beginTransaction()
.replace(R.id.container, NointernetFragment.newInstance())
.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_home);
break;
case 2:
mTitle = getString(R.string.title_category);
break;
case 3:
mTitle = getString(R.string.title_login);
break;
case 4:
mTitle = getString(R.string.title_register);
break;
case 5:
mTitle = getString(R.string.title_myaccount);
break;
case 6:
mTitle = getString(R.string.title_referafriend);
break;
case 7:
mTitle = getString(R.string.title_about);
break;
case 8:
mTitle = getString(R.string.title_privacypocity);
break;
case 9:
mTitle = getString(R.string.title_shippingterms);
break;
case 10:
mTitle = getString(R.string.title_contactus);
break;
case 100:
mTitle = getString(R.string.title_nointernet);
break;
}
}
#SuppressWarnings("deprecation")
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance() {
CategoryFragment fragment = new CategoryFragment();
return fragment;
}
public CategoryFragment () {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
update your selectitem() and onNavigationDrawerItemSelected methods to accept two more arguments i.e child.id and child.name
private void selectItem(int position,String id,String name) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position,id,name);
}
}
pass child.id and child.name in selectItem() method so which in turn will call onNavigationDrawerItemSelected() method implemented in MainActivity.
Now in MainActivity, pass the values to the fragment using Bundle
here
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance(id,name))
.commit();
you will also need to update to CategoryFragment.newInstance(String,String) to accept the arguments
Updating code to 'setText' in 'edittext'
In your 'CategoryFragment' 'newInstance' method pass data in bundle like below
CategoryFragment categoryfragment = new CategoryFragment()
Bundle bundle = new Bundle()
bundle.putStringExtra("id",id)
bundle.putStringExtra("name",name)
categoryfragment.setArguements(bundle)
return categoryfragment
Now in onCreateView of Categoryfragment get this data like below
if(getArguments().getExtras != null) {
String catid = getArguments.getStringExtra("id");
String catname = getArguments.getStringExtra("name");
yourEditText.setText(catname);
}
Hope you got my point
My app has a 3-tabbed ActionBar layout. The 3 tabs are Dashboard, Feed and Messages.
When you click any of the three, the application is supposed to create a WebView of www.flyalaskava.org/incog/mobile/ which - if you do not have an active session for - will display an image and a "log-in with facebook" button.
The problem is, when I load the first tab (Dashboard) and cliek Log-In with Facebook, it logs me in - but as soon as I click onto another tab, I lose my session and am re-prompted.
Please keep in mind that currently all of these are using the same php file and that the log-in system works perfectly outside of Android. Sorry if this is a newbie question - any help is appreciated.
package com.example.testing;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import com.handmark.pulltorefresh.library.PullToRefreshWebView;
public class Main extends FragmentActivity implements ActionBar.TabListener {
PullToRefreshWebView mPullRefreshWebView;
WebView mWebView;
/**
* The serialization (saved instance state) Bundle key representing the
* current tab position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPullRefreshWebView = (PullToRefreshWebView) findViewById(R.id.pull_refresh_webview);
mWebView = mPullRefreshWebView.getRefreshableView();
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new SampleWebViewClient());
mWebView.loadUrl("http://www.google.com");
// Set up the action bar to show tabs.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
actionBar.addTab(actionBar.newTab().setText(R.string.title_section1)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section2)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.title_section3)
.setTabListener(this));
}
private static class SampleWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current tab position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM)
);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current tab position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
displayAlert();
break;
case R.id.menu_exit:
displayExit();
break;
default:;
}
return(super.onOptionsItemSelected(item));
}
public void displayAlert() {
new AlertDialog.Builder(this)
.setMessage("This Application was created by Grant Adkins")
.setTitle("About")
.setCancelable(false)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
dialog.cancel();
}
}
)
.show();
}
public void displayExit() {
new AlertDialog.Builder(this).setMessage("Exit the application")
.setTitle("Are you sure?")
.setCancelable(false)
.setNeutralButton(android.R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
dialog.cancel();
}
}).setPositiveButton(android.R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
}
)
.show();
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
String summary = "<html><body>No Network Connection.</body></html>";
mWebView.loadData(summary, "text/html", null);
return false;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the
// container view
int page = tab.getPosition() + 1;
if(page == 1) {
/// eventually is going to load index.php?content=dashboard
mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/");
isOnline();
} else if (page == 2) {
/// eventually is going to load index.php?content=messages
mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/");
isOnline();
} else if (page == 3) {
/// eventually is going to load index.php?content=feed
mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/");
isOnline();
} else {
mWebView.loadUrl("http://www.google.com");
isOnline();
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(
Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER))
);
return textView;
}
}
}`
*\\\\\\\\UPDATE\\\\\\*
I found this article which seems to be a similar problem, maybe because im using mWebView.loadUrl("http://www.flyalaskava.org/incog/mobile/"); it is acting like a new browser, is there any way to change urls without using that method.
Here is a picture of the problem.
Add the following lines after having created your WebView :
CookieSyncManager.createInstance(mWebView.getContext()).sync();
CookieManager.getInstance().acceptCookie();
Consider using a Service instead of cookies. A Service will allow you to maintain a connection to your server in the background of your application. Services are easily referenced once created (read about Services and Intents). The Service would then act as your session to your server.