There already is another method with the same signature - java

I'm newbee on the android programming then I have a problem to integrate a part of code.
public class HomeActivity extends SherlockFragmentActivity
implements ActionBar.OnNavigationListener, VideoListFragment.OnVideoSelectedListener{
// create object of ActionBar and VideoListFragment
ActionBar actionbar;
VideoListFragment videoListFrag;
int selectedItem;
private AdController ad;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// add channel list array to actionbar spinner
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.channel_name, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
// remove actionbar title and add spinner to actionbar
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
}
// create option menu
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.home, menu);
return true;
}
// listener for option menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuShare:
// share google play link of this app to other app such as email, facebook, etc
Intent iShare = new Intent(Intent.ACTION_SEND);
iShare.setType("text/plain");
iShare.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.subject));
iShare.putExtra(Intent.EXTRA_TEXT, getString(R.string.message)+" "+getString(R.string.gplay_web_url));
startActivity(Intent.createChooser(iShare, getString(R.string.share_via)));
return true;
case R.id.menuRate:
// open google play app to ask user to rate & review this app
Intent iRate = new Intent(Intent.ACTION_VIEW);
iRate.setData(Uri.parse(getString(R.string.gplay_url)));
startActivity(iRate);
return true;
case R.id.menuAbout:
// open About app page
Intent iAbout = new Intent(this, AboutActivity.class);
startActivity(iAbout);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
selectedItem = itemPosition;
// create object of VideoListFragment and send data position to that fragment
videoListFrag = new VideoListFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", itemPosition);
videoListFrag.setArguments(bundle);
// call video list fragment with new data
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, videoListFrag, "VIDEO_LIST_FRAGMENT")
.commit();
return true;
}
#Override
public void onVideoSelected(String ID) {
// TODO Auto-generated method stub
// call player page to play selected video
Intent i = new Intent(this, PlayerActivity.class);
i.putExtra("id", ID);
startActivity(i);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_home);
ad = new AdController(this, "MY_LB_SECTION_ID");
ad.loadStartAd("MY_LB_AUDIO_ID", "MY_LB_REENGAGEMENT_ID");
AppTracker.startSession(this, "APPFIREWORKS_API_KEY");
}
#Override
public void onPause() { super.onPause();
if(ad != null) { ad.destroyAd();
} if(!isFinishing()) { AppTracker.pause(getApplicationContext());
} }
#Override
public void onResume() { super.onResume();
AppTracker.resume(getApplicationContext());
}
#Override
public void onDestroy() { super.onDestroy();
if(ad != null) { ad.destroyAd();
} AppTracker.closeSession(getApplicationContext(),true);
}
}
The problem is on on create.
Sorry for my bad english.
Thanks for your response.
Regards

You have 2 onCreate functions in the same Activity. You can only have one. That's why its complaining that there is already a method with same signature. Delete one of them and move the stuff from one to other. As mentioned by #Ravn in comments, you can have multiple functions with same name but ofcourse with different arguments.

You cannot have method with same signature twice
#Override
public void onCreate(Bundle savedInstanceState)
#Override
public void onCreate(Bundle b)

Related

Make Mapbox markers clickable and return the ID of the marker

So I've made a MapActivity which shows a MapBox map.
Then I load in all my markers(pins, which are eventually Point objects with longitude and latitude) from the database into a List< Features > markerCoordinates. markerCoordinates is then given through GeoJsonSource().
Now all my markers are displayed on the map.
Now I can't figure out how to make a marker clickable, and when clicked I need to obtain the ID of the marker so I can later on redirect to another Activity and then load in all data based on that ID. This ID of the pin needs to be the same as the ID from the database.
Mapbox Documentation doesn't really helped me out with this problem.
Does any one know how to implement this?
MapActivity.java
public class MapActivity extends AppCompatActivity {
private MapView mapView;
DatabaseHelper myDb;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_moments:
Intent intent = new Intent(MapActivity.this, MapActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
break;
case R.id.navigation_addmoment:
Intent intent2 = new Intent(MapActivity.this, AddMomentActivity.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent2);
break;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(this);
Mapbox.getInstance(this, "pk.eyJ1IjoiaGlqYWNrbWFuaWFjIiwiYSI6ImNqdWlyb3E3NzE5bjc0Zm9lOHpta3AzajMifQ.ithKXW2RvhRzlPqXWBexyg");
setContentView(R.layout.activity_map);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
// Importing markers from database
List<Feature> markerCoordinates = new ArrayList<>();
loadPins(markerCoordinates);
// Adding markers on the map
style.addSource(new GeoJsonSource("source-id",
FeatureCollection.fromFeatures(markerCoordinates)));
// Some styling below
style.addImage("marker-icon-id",
BitmapFactory.decodeResource(
MapActivity.this.getResources(), R.drawable.mapbox_marker_icon_default));
SymbolLayer symbolLayer = new SymbolLayer("layer-id", "source-id");
symbolLayer.withProperties(
PropertyFactory.iconImage("marker-icon-id")
);
style.addLayer(symbolLayer);
}
});
}
});
}
// Switch from map to moments
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.header_items, menu);
final MenuItem listItem = menu.findItem(R.id.list_menu);
listItem.setVisible(true);
listItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(MapActivity.this, MomentsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
return true;
}
});
return true;
}
// Reading the Database, appending each row to allMarkers
public void loadPins(List<Feature> allMarkers) {
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
// Error message
return;
}
while(res.moveToNext()) {
double longitude = Double.parseDouble(res.getString(4));
double latitude = Double.parseDouble(res.getString(5));
if(longitude == 0 || latitude == 0) {
continue;
} else {
allMarkers.add(Feature.fromGeometry(
Point.fromLngLat(
longitude,
latitude
)
));
}
}
}
#Override
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
First, you should implement the onMapClick or onMapLongClick methods, so that you can handle all map clicks and retrieve the data you need.
The steps to get the marker Id on every click are roughly these:
Check whether the click was on a marker or elsewhere.
You can do this by querying the source layer (your GeoJsonSource) and checking whether there is a feature nearby the clicked spot.
If a feature was found, get the property you need.
You could use feature.getProperties() to get all the properties or feature.getStringProperty("name_of_the_property") to get a specific one. See more here.
Check this example to see how to implement all of this.

Same activity getting stacked

I have an activity that is suppose to finish itself and close the application. Now, in certain cases, which are varying on how the user is navigating to the activity, the activity is getting stacked. When the activity is stacking up, then calling finish() or android.os.Process.killProcess(android.os.Process.myPid()); or both together is only showing up the same activity again.
The Manifest:
<activity
android:name="newActivities.HomeActivity"
android:label="#string/title_activity_home"
android:screenOrientation="portrait">
</activity>
The activity:
public class HomeActivity extends Activity {
private EditText studentNameEdittext;
private Button startYourStoryButton, loginButton, navCollegesButton, settingsButton, search_friends_button, browseStoriesButton;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// saveInPreference("loginStatus", "");
// }
// Set up the action bar
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#009945")));
bar.setTitle("Study Story");
bar.setIcon(R.drawable.statusbar_icon);
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView) findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.white_colour));
yourTextView.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// studentNameEdittext = (EditText)
// findViewById(R.id.studentNameEdittext);
startYourStoryButton = (Button) findViewById(R.id.startYourStoryButton);
// loginButton = (Button) findViewById(R.id.loginButton);
navCollegesButton = (Button) findViewById(R.id.navCollegesButton);
// settingsButton = (Button) findViewById(R.id.settingsButton);
// search_friends_button = (Button)
// findViewById(R.id.search_friends_button);
browseStoriesButton = (Button) findViewById(R.id.browseStoriesButton);
// textView1 = (TextView) findViewById(R.id.textView1);
// Set up font type
// studentNameEdittext.setTypeface(TypeFaceController.generalTextFace(HomeActivity.this));
startYourStoryButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// loginButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
navCollegesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// settingsButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// search_friends_button.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
browseStoriesButton.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
// textView1.setTypeface(TypeFaceController.titleFace(HomeActivity.this));
startYourStoryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0){
Intent i = new Intent(HomeActivity.this, SignUp.class);
i.putExtra("signUpCaller", "Home");
startActivity(i);
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View arg0){
// Intent i = new Intent(HomeActivity.this, Login.class);
// startActivity(i);
// }
// });
// search_friends_button.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this,
// FindStudentBrowseStoryActivity.class);
// i.putExtra("Button", "search_friends_button");
// i.putExtra("searchString", studentNameEdittext.getText().toString());
// startActivity(i);
//
// }
// });
browseStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, FindStudentBrowseStoryActivity.class);
i.putExtra("Button", "browseStoriesButton");
startActivity(i);
}
});
navCollegesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Intent i = new Intent(HomeActivity.this, CollegeListActivity.class);
startActivity(i);
}
});
// settingsButton.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v){
// Intent i = new Intent(HomeActivity.this, HomeSettingsActivity.class);
// i.putExtra("FromActivity", "HomeSettingsActivity");
// startActivity(i);
// finish();
//
// }
// });
}
// #Override
// protected void onStart(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onStart();
// }
//
// #Override
// protected void onResume(){
// if (getFromPreference("loginStatus").equalsIgnoreCase("true")) {
// finish();
// }
// super.onResume();
// }
// =========Login button action bar
#Override
public boolean onCreateOptionsMenu(Menu menu){
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_menu, menu);
return true;
}
// =========Login button action bar
#Override
public boolean onOptionsItemSelected(MenuItem item){
// handle item selection
switch (item.getItemId()) {
case R.id.home_login_string:
Intent i = new Intent(HomeActivity.this, Login.class);
// finish();
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// logic to fix logout
#Override
public void onBackPressed(){
// Intent startMain = new Intent(Intent.ACTION_MAIN);
// startMain.addCategory(Intent.CATEGORY_HOME);
// startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);;
// startActivity(startMain);
//
// int pid = android.os.Process.myPid(); //
// android.os.Process.killProcess(pid); // return; }
android.os.Process.killProcess(android.os.Process.myPid());
finish();
}
// method to save variable in preference
public void saveInPreference(String name, String content){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(name, content);
editor.commit();
}
// getting content from preferences
public String getFromPreference(String variable_name){
String preference_return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preference_return = preferences.getString(variable_name, "");
return preference_return;
}
}
Please tell me where am I going wrong? Why is the activity stacking?
P.S: We cannot use single top etc as it causes some transition issues with the existing custom theme!
Take one application class which extends Application and take one arrayList and maintain the references of the activities in the arraylist.
When you click on back button in desired activity then finish the all the activities using arraylist.
Take one base activity. Which is super class of all the activities
public class BaseActviity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App application = (App) getApplication();
application.addActivity(this);
}
}
Take one application class
public class App extends Application {
public App() {
if (listActivty == null) {
listActivty = new ArrayList<BaseActviity>();
}
}
public ArrayList<BaseActviity> listActivty;
public void addActivity(BaseActviity actviity) {
if (!listActivty.contains(actviity)) {
listActivty.add(actviity);
}
}
}
take 4 samples activity classes like ......
1) public class FirstActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
2) public class SecondActivity extends BaseActviity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
}
public void send(View view) {
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
}
3).........................
4) ............................
in 4 th activity class placed the following code
In desire activity that means final activity,override the onBackPressed
public void onBackPressed() {
super.onBackPressed();
App application = (App) getApplication();
ArrayList<BaseActviity> listActivty = application.listActivty;
for (BaseActviity actviity : listActivty) {
actviity.finish();
}
}
Wherever you are opening the activity which is getting stacked up, use this:
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Check if the Activity, that would be last activity when user clicks on the back button,is visible or not and if visible use
System.exit(0);
At last, the problem is solved. I has to do a little trick:
ParseUser.getCurrentUser();
ParseUser.logOut();
Intent i = new Intent(getActivity(), NewHomeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
getActivity().startActivity(i);
getActivity().finish();
This did not cause any transition issues as well.

loadPreference() for preferenceActivity method throws exception first time app is installed

I am a newbie to android, so please be patient.
I am trying to learn preferences. I have an app that has a mainActivity, when the menu icon it's pressed a MyPreferenceActivity is shown. It allows the user setting some preferences related to a subject.
In my mainActivity I have a loadPrefernces method that works fine when the app is installed, but the first time it throws an error: unable to start activity component info[..] java.lang.NullPointerException
Here is my code:
MainActivity
public class MainActivity extends Activity {
public static final String PREFERENCE_FILENAME = "com.id11298775.exercise6_preferences";
SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPreferences(); // this cause the error
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, MyPreferenceActivity.class);
startActivity(i);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
loadPreferences();
}
private void loadPreferences() {
mSharedPreferences = getSharedPreferences(PREFERENCE_FILENAME,
MODE_PRIVATE);
// Setting the textView related to the subject
TextView subjectTv = (TextView) findViewById(R.id.activitymain_favouritesubjectresult_tv);
subjectTv.setText(mSharedPreferences.getString("list_subject_pref",
null));
// Setting the TextView related to the URL
TextView urlTv = (TextView) findViewById(R.id.activitymain_handbookurlresult_tv);
urlTv.setText(mSharedPreferences.getString("et_subject_pref", null));
// Setting the TextView related to the times selected
TextView labTimeTv = (TextView) findViewById(R.id.activitymain_labtimeresult_tv);
// #SuppressWarnings("unchecked")
Map<String, ?> map = mSharedPreferences.getAll();
Object cs = map.get("list_times_pref");
labTimeTv.setText(cs.toString());
}
#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, menu);
return true;
}
}
this is my MyPreferenceActivity
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("list_subject_pref")) {
ListPreference preference = (ListPreference) findPreference(key);
CharSequence currText = preference.getEntry();
preference.setSummary(currText);
} else if (key.equals("et_subject_pref")) {
EditTextPreference preference = (EditTextPreference) findPreference(key);
String newUrl = preference.getText().toString();
preference.setSummary(newUrl);
} else if (key.equals("list_times_pref")) {
Set<String> selections = sharedPreferences.getStringSet(
"list_times_pref", null);
String[] selected = selections.toArray(new String[] {});
String listSelection = "";
for (int i = 0; i < selected.length; i++) {
listSelection += selected[i] + " ";
}
MultiSelectListPreference multi = (MultiSelectListPreference) findPreference(key);
multi.setSummary(listSelection);
} else if (key.equals("ringtonePref")) {
RingtonePreference preference = (RingtonePreference) findPreference("ringtonePref");
String strRingtonePreference = ((SharedPreferences) preference).getString("ringtonePref", "none");
Uri ringtoneUri = Uri.parse(strRingtonePreference);
Ringtone ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
String name = ringtone.getTitle(this);
preference.setSummary("select " + name);
}
}
}
here is logcat:
I think that the first time the app is installed there are no preference set, therefore the error, but I can't figure out a good way to prevent the exception.
Anybody can please help me?

How to Extend Two Classes in Android?

I need to extend Two classes from a Single Class.My class Wants to extend Both ListActivity & MainActivity.
I found a question similar to this.
But i don't know how to Implement this https://stackoverflow.com/a/5836735/2781359
Thanks for your Help.
The Class which has to be Extended is ConnectionEditActivity.
public class ConnectionEditActivity extends ListActivity implements OnClickListener
{
public static Connection connectionParam;
private Connection connection;
private Button save;
private EditText name;
private EditText password;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.connection = connectionParam;
this.save = (Button) this.findViewById(R.id.save);
this.save.setOnClickListener(this);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD)
{
// Don't need the Save button on newer devices
android.widget.LinearLayout.LayoutParams a = (LayoutParams) this.save.getLayoutParams();
a.height = 0;
this.save.setLayoutParams(a);
this.save.forceLayout();
}
this.name = (EditText) this.findViewById(R.id.name);
this.password = (EditText) this.findViewById(R.id.password);
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
// Inflate the menu items for use in the action bar
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.connection_edit_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(android.view.MenuItem item)
{
// Handle presses on the action bar items
switch (item.getItemId())
{
case R.id.action_save:
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
protected void onResume()
{
super.onResume();
this.name.setText(this.connection.getName());
this.password.setText(this.connection.getPassword());
}
protected void onPause()
{
super.onPause();
this.connection.setName(this.name.getText().toString());
this.connection.setPassword(this.password.getText().toString());
finish();
}
public void onClick(View v)
{
if (v == this.save)
{
this.finish();
}
}
}
Mainactivity
public abstract class MainActivity extends ActionBarActivity
{
protected ListView mDrawerList;
protected DrawerLayout mDrawer;
private CustomActionBarDrawerToggle mDrawerToggle;
private String[] menuItems;
String LOG_TAG = "Remote It";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR);
// getSupportActionBar().hide();
setContentView(R.layout.activity_main_drawer);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
mDrawer.setDrawerListener(mDrawerToggle);
}
private void _initMenu()
{
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems)
{
int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res], "drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
// if (res==1) mItem.counter=12; //it is just an example...
// if (res==3) mItem.counter=3; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
// Second Block
mAdapter.addHeader(R.string.ns_menu_main_header2);
menuItems = getResources().getStringArray(R.array.ns_menu_itemss);
String[] menuItemsIcons = getResources().getStringArray(R.array.ns_menu_items_iconss);
int ress = 0;
for (String item : menuItems)
{
int id_title = getResources().getIdentifier(item, "string", this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcons[ress], "drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
// if (res==1) mItem.counter=12; //it is just an example...
// if (res==3) mItem.counter=3; //it is just an example...
mAdapter.addItem(mItem);
res++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle
{
public CustomActionBarDrawerToggle(Activity mActivity, DrawerLayout mDrawerLayout)
{
super(mActivity, mDrawerLayout, R.drawable.ic_drawer, R.string.ns_menu_open, R.string.ns_menu_close);
}
#Override
public void onDrawerClosed(View view)
{
getSupportActionBar().setTitle(getString(R.string.ns_menu_close));
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView)
{
getSupportActionBar().setTitle(getString(R.string.ns_menu_open));
supportInvalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
mDrawer.closeDrawer(mDrawerList);
switch (position)
{
case 1:
Intent a = new Intent(MainActivity.this, Home.class);
startActivity(a);
break;
case 2:
Intent ac = new Intent(MainActivity.this, ConnectionListActivity.class);
startActivity(ac);
break;
default:
}
}
EDIT
I need to Extend it.Because the MainActivity has the navigation drawer.Now ConnectionEditActivity
doesn't shows the navigationDrawer nor the ActionBar .But i need to show the ActionBar
Any Suggestions ??
In Java you can't extend multiple classes, and for a good reason. Take for example what you are trying to accomplish by extending MainActivity and ListActivity. In your new class, when you call:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
}
Which onCreate() are you overriding? The one from ListActivity, or the one from MainActivity?
What the link you posted is saying is that instead of inheriting from another object, you compose your new object of the one you are trying to use. For example:
public class NewClass extends OldClass1 {
private OldClass2 mOldClass2 = new OldClass2();
#Override
public methodFromOldClass1() {
}
public methodFromOldClass2() {
mOldClass2.methodFromOldClass2();
}
}
The problem with this approach is that the methods from MainActivity and ListActivity are still going to have the same name, which although you can work around, it will become a headache quickly.
So the problem is a result of how you designed your class hierarchy. You will need to think about what functions you need from MainActivity, and what functions from ListActivity and choose how to reimplement your objects.
My Suggestion, since ListActivity only makes it slightly easier to work with lists (not that much easier) you can just skip it and implement the code related to the list on your own, and that way you can just extend MainActivity
You need to start by identifying what parts of MainActivity you need to inherit from, and what do you need from ListActivity.
Then, you have various possibilities:
Trivially, not extending ListActivity. Extending ListActivity only provides you with utility methods to work with the ListView, but you can totally have a ListView in an Activity without it being a ListActivity.
Create a utility class that contains extracted methods you need from MainActivity and call these methods from both your new class and MainActivity.
Modify MainActivity so that it extends ListActivity. After all it does contain a ListView (you'd loose the ActionBar thing, though).

How to retrieve data without using database,it has to display in listview

I am creating one dynamic list view i don't need database to store the data,whatever i am adding the data,it has to display in my list view. Right now its not displaying in my list view.
Projectlistactivity.java
public class Prayers extends ListActivity{
private static final int ACTIVITY_CREATE=0;
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prayers_list);
fillData();
registerForContextMenu(getListView());
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
//btn.setOnClickListener(listener);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
private void fillData() {
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_insert:
createProject();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, PrayersEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#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_prayers_list, menu);
return true;
}
}
This is my projecteditactivity.java
public class PrayersEditActivity extends Activity{
private EditText mTitleText;
private Button mConfirmButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prayers_edit);
mTitleText = (EditText) findViewById(R.id.title);
mConfirmButton = (Button) findViewById(R.id.confirm);
registerButtonListenersAndSetDefaultText();
}
private void registerButtonListenersAndSetDefaultText() {
mConfirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//saveState();
String title = mTitleText.getText().toString();
mTitleText.setText("");
//adapter.notifyDataSetChanged();
setResult(RESULT_OK);
Toast.makeText(PrayersEditActivity.this, getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
finish();
}
});
}
/*private void saveState() {
//mTitleText = (EditText) findViewById(R.id.title);
String title = mTitleText.getText().toString();
mTitleText.setText("");
adapter.notifyDataSetChanged();
}*/
}
In my listview if i click the menu button it has to go to the edit page,in their i have to add project after clicking the save button,it has to display in my listview,Right now its not display in my listview.
startActivityForResult(i, 1); and override this method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
list.add(result);
adapter.notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
in your projecteditactivity.java change the onClick to following code
#Override
public void onClick(View view) {
String title = mTitleText.getText().toString();
mTitleText.setText("");
Intent returnIntent = new Intent();
returnIntent.putExtra("result",title);
setResult(RESULT_OK,returnIntent);
finish();
}
Why cant you store the data in a file, so that, you can retrive it when the application goes to background and after a few time, when come back, you can retrive it from file if memory lost happend.
I used to keep data in a Json formatted string, Dont know how and from where you get the list data.
you may use the life_cycle function. In addtion, you may transmit the data between Activities. So that you can use the edit data to display.
keep your data with ondestroy, onpause and onresume method.. and second option is to keep it with sharedprefence or sqlite.

Categories

Resources