How can I implement tabs in an Android Browser? - android

I am trying to implement tab functionality in an Android browser. I tried to save the webpage in a cache, but I can't figure out how to save multiple of them and load them when the user switches tabs. How could I implement this?
I would like to save the current webpage in a cache when the user wants to add a new tab and open Main_activity, and then next time when the user switches tabs, the current webpage should get saved in a cache, and the intended webpage of the intended tab gets loaded in the webview. Now the issue is, I don't know how to handle multiple webpages in a cache, and select which one to load when.
My code consists of two activities, main_activity with some icons and webView_activity with a simple webview. I am using a custom dialog box with a ListView in it, so I will need to add new rows for new tabs and edit them when tabs are switched.
Here is my main_activity
public class MainActivity extends AppCompatActivity {
ImageView yt,google,gm,twitter;
SearchView g_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g_search = (SearchView) findViewById(R.id.g_search);
g_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
yt = (ImageView) findViewById(R.id.yt);
google = (ImageView) findViewById(R.id.google);
gm = (ImageView) findViewById(R.id.gm);
twitter = (ImageView) findViewById(R.id.twitter);
yt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.youtube.com");
startActivity(i);
}
});
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.google.com");
startActivity(i);
}
});
gm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.gmail.com");
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.twitter.com");
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m1, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_new_tab){
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(MainActivity.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Here is my web_view activity
public class webview1 extends AppCompatActivity {
CustomWebView web1;
String search_q,shortcut;
FloatingActionButton fab;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview1);
web1 = (CustomWebView) findViewById(R.id.web1);
web1.setGestureDetector(new GestureDetector(new CustomGestureDetector()));
web1.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(final WebView view, int errorCode, String description,
final String failingUrl) {
fragmentManager.beginTransaction()
.replace(R.id.container, new blankState())
.commit();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
registerForContextMenu(web1);
// web1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setBuiltInZoomControls(true);
web1.getSettings().setDisplayZoomControls(false);
web1.getSettings().setLoadWithOverviewMode(true);
web1.getSettings().setUseWideViewPort(true);
search_q=getIntent().getStringExtra("query");
shortcut=getIntent().getStringExtra("shortcut");
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_toolbar);
ImageView action_back = (ImageView) findViewById(R.id.action_back);
action_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setVisibility(GONE);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code for launching new tab here
}
});
web1.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress ){
frame_layout.setVisibility(View.VISIBLE);
progress_bar.setProgress(progress);
if(progress==100){
frame_layout.setVisibility(GONE);
srl.setRefreshing(false);
}
super.onProgressChanged(view, progress);
}
});
progress_bar.setProgress(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_url){
ShowUrlDialog();
return true;
}
if(item.getItemId()==R.id.action_home){
Intent i = new Intent(webview1.this,MainActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_new_tab){
// code to launch new tab here
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(webview1.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(webview1.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m2, menu);
// Associate searchable configuration with the SearchView
return true;
}
#Override
public void onBackPressed() {
if (web1.canGoBack()) {
web1.goBack();
} else {
super.onBackPressed();
}
}
}

Related

Filter working text is not highlighting in recyclerview in android [duplicate]

Hi in the MainActivity I was Implemented a Different Fragments.Now toolbar contains a searchview functionality I was added in my Activity.
Now I search for text all the fragement are also searching for same text.But I want to clear the text which one i typed for last fragement.
MainActivity:
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setSearchtollbar();
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close_black_24dp);
// closeButton.setImageResource(ContextCompat.getDrawable(getApplication(), R.drawable.ic_close_black_24dp));
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
Log.i("query", "" + query);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
Fragment:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
return true;
case R.id.refresh:
fetchJSON();
return true;
}
return true;
}
Menu:
<item android:id="#+id/search"
android:orderInCategory="0"
android:title="search"
android:icon="#drawable/ic_search"
app:showAsAction="always"/>

Android - display progress bar when click on any sound from listview

this is what i want but dont know how to do it.Below is the code of my main activity. I have a listview of sound clips and i want to show a progressbar and button when we click on any sound, that progress bar should indicate the progress of the respective sound clip and button shoud be change to stop icon. i am using adapterview with arraylist.i have attached an image of that
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,NavigationView.OnNavigationItemSelectedListener {
private ArrayList<String> songList;
private ListView songView;
SearchView searchView;
private MediaPlayer mp;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songList = new ArrayList<>();
mp = new MediaPlayer();
songView = findViewById(R.id.song_list);
progressBar=findViewById(R.id.progressBar);
try {
getSongList();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ArrayAdapter<String> listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, songList);
songView.setAdapter(listAdapter);
songView.setOnItemClickListener(this);
registerForContextMenu(songView);
Intent serviceIntent =
new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// code for scroll to top button
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
songView.setSelection(0);
}
});
DrawerLayout drawer = 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 = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
public void getSongList() throws IllegalAccessException {
Field[] fields = R.raw.class.getFields();
// loop for every file in raw folder
for (Field field : fields) {
int rid = field.getInt(field);
// Use that if you just need the file name
String filename = field.getName();
songList.add(filename);
songList
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void onDestroy() {
super.onDestroy();
if (mService != null) {
unbindService(mServiceConn);
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
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
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_remove_ads) {
} else if (id == R.id.nav_share) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "SoundBoard");
String sAux = "\nGet this app on Google Play\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.facebook.orca \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch (Exception e) {
//e.toString();
}
} else if (id == R.id.nav_rate) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.facebook.orca"));
startActivity(intent);
} else if (id == R.id.about_us) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// selected item
TextView txtView = (TextView) view;
String fname = txtView.getText().toString().toLowerCase();
int resID = getResources().getIdentifier(fname, "raw", getPackageName());
Toast.makeText(getApplicationContext(), "Hello Javatpoint"+getResources().getResourceName(resID), Toast.LENGTH_SHORT).show();
MediaPlayer mediaPlayer = MediaPlayer.create(this, resID);
mediaPlayer.start();
if (mp.isPlaying()) {
mp.reset();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.song_list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
View view = info.targetView;
TextView txtView = (TextView) view;
String fname = txtView.getText().toString().toLowerCase();
int resID = getResources().getIdentifier(fname, "raw", getPackageName());
switch (item.getItemId()) {
case R.id.share:
// add stuff here
//String sharepath=
//Uri uri = Uri.parse(view.getResources().getResourceName(resID));
//String sharePath = Environment.getExternalStorageDirectory().getPath()
// + "/Soundboard/Ringtones/custom_ringtone.ogg";
//Uri uri = Uri.parse(sharePath);
// Use this to load the file
Uri uri=Uri.parse("file://" +getResources().getResourceEntryName(resID)+".mp3");
String str=("content://"+uri);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/mp3");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
return true;
case R.id.notification:
// edit stuff here
uri=Uri.parse("file://" +getResources().getResourceEntryName(resID)+".mp3");
str=("content://"+uri);
Toast.makeText(getApplicationContext(), ""+uri, Toast.LENGTH_SHORT).show();
return true;
case R.id.ringtone:
// remove stuff here
return true;
default:
return super.onContextItemSelected(item);
}
}
}

Converting Activity to a fragment gives onCreateOptionsMenu error

I was converting my UserListing Activity to a fragment when i received this error in myOnCreateOptionsMenu.
This is my Fragment Activity.
public class UserListingActivity extends Fragment implements LogoutContract.View {
private Toolbar mToolbar;
private TabLayout mTabLayoutUserListing;
private ViewPager mViewPagerUserListing;
private LogoutPresenter mLogoutPresenter;
public static void startActivity(Context context) {
Intent intent = new Intent(context, UserListingActivity.class);
context.startActivity(intent);
}
public static void startActivity(Context context, int flags) {
Intent intent = new Intent(context, UserListingActivity.class);
intent.setFlags(flags);
context.startActivity(intent);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
bindViews();
init();
setHasOptionsMenu(true);
return super.onCreateView(inflater, container, savedInstanceState);
}
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_user_listing);
// bindViews();
// init();
// }
private void bindViews() {
mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
mTabLayoutUserListing = (TabLayout) getActivity().findViewById(R.id.tab_layout_user_listing);
mViewPagerUserListing = (ViewPager) getActivity().findViewById(R.id.view_pager_user_listing);
}
private void init() {
// set the toolbar
setSupportActionBar(mToolbar);
// set the view pager adapter
UserListingPagerAdapter userListingPagerAdapter = new UserListingPagerAdapter(getFragmentManager());
mViewPagerUserListing.setAdapter(userListingPagerAdapter);
// attach tab layout with view pager
mTabLayoutUserListing.setupWithViewPager(mViewPagerUserListing);
mLogoutPresenter = new LogoutPresenter(this);
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getActivity().getMenuInflater().inflate(R.menu.menu_user_listing, menu);
// return super.onCreateOptionsMenu(menu);
// }
#Override
public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.menu_user_listing, menu);
return super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
logout();
break;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
new AlertDialog.Builder(this)
.setTitle(R.string.logout)
.setMessage(R.string.are_you_sure)
.setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mLogoutPresenter.logout();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
#Override
public void onLogoutSuccess(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
LoginActivity.startIntent(this,
Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
}
#Override
public void onLogoutFailure(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(this, MainActivity.class));
}
}
What has to be changed to solve this and what more has to be changed to covert it into a Fragment. I am beginner so detailed help would be appreciated.
Thanks
Method signature in fragment should be as below
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
The problem is with the return type of the method, make it void and error will be gone as the super-type returns void.

saving the edittext value to another activity on click of save actionbutton in android

how to save the text given to edit text, after clicking the save action button in action bar that should save to another activity.
my first activity Add.java
public class Add extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_add_action, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:save();
return true;
case R.id.cancel:cancelnavi();
return true;
}
return super.onOptionsItemSelected(item);
}
private void save() {
EditText titlename;
titlename=(EditText)findViewById(R.id.edittitle);
String title=titlename.getText().toString();
if (title.equalsIgnoreCase("")){
Toast.makeText(Add.this, "Script title should not be empty", Toast.LENGTH_LONG).show();
} else {
Intent i;
i=new Intent(getApplicationContext(), Scripts.class);
i.putExtra("n", titlename.getText().toString());
startActivityForResult(i, 0);
titlename.setText("");
}
}
}
It should be saved to scripts.java
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:editscript();
break;
}
return true;
}
private void editscript() {
Intent editinIntent;
editinIntent=new Intent(Scripts.this, Edit.class);
startActivity(editinIntent);
}
}
Maybe this can help you.
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
//Extract the data
String yourTitle = getIntent().getStringExtra("n");
}
}

OptionMenu doesn't show anything in Sherlock Fragment

I am working in Sherlock Fragment and needed to add some options in the optionMenu. But unable to do this. Here is my code below. i have already added setHasOptionMenu(true) in onCreateView :So please have a look at this code,,, and tell me where i am wrong
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
progress = menu.add("Progress");// first option
progress.setIcon(android.R.id.progress);
progress.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
MenuItem add = menu.add("Refresh");// second option
add.setIcon(R.drawable.ic_menu_refresh);
add.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
MenuItem get = menu.add("Logout");// third option
get.setIcon(R.drawable.power);
get.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
get.setOnMenuItemClickListener(new OnMenuItemClickListener()
{
#Override
public boolean onMenuItemClick(MenuItem item)
{
userfunctions = new UserFunctions();
//AsyncTask
class AsyncLogout extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
json = userfunctions.logoutUser(userid);
try {
if (json.getString(KEY_SUCCESS) != "1") {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
p_error_msg = "successful";
}
} else {
p_error_msg = "error";
}
} catch (Exception e) {
e.printStackTrace();
}
return p_error_msg;
}
protected void onPostExecute(String result) {
try {
if (result.equals("successful")) {
Intent ii = new Intent(getActivity(),
HomeActivity.class);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("login", "0");
editor.remove("PREF_ACCESS_TOKEN_TWITTER");
editor.remove("PREF_ACCESS_TOKEN_SECRET_TWITTER");
editor.remove("PREF_ACCESS_TOKEN_FB");
editor.remove("PREF_ACCESS_TOKEN_SECRET_FB");
editor.commit();
startActivity(ii);
getActivity().finish();
} else {
}
} catch (Exception e) {
}
}
protected void onPreExecute() {
super.onPreExecute();
}
}
AsyncLogout as=new AsyncLogout();
as.execute();
return false;
}
});
add.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item)
{
Intent i = new Intent(getActivity(), MainActivity.class);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("login", "1");
editor.putInt("defaultSelector", 2);
editor.commit();
startActivity(i);
getActivity().finish();
return false;
}
});
}
Here is the proper way how to handle MenuItems from Fragment :
public class MyFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_inner_cards, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.action_sort:
// DO STUFF
break;
case R.id.action_anytag:
// DO STUFF
break;
}
return true;
}
}
My suggestion is, instead of creating the items in Java code, use a custom menu.xml only for your Fragment, inflate it and use onOptionsItemSelected() for handling click event on menu items.

Categories

Resources