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?
Related
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.
So I have the action bar back button which returns me from an activity to my main activity. The problem I have is that it calls loadData() (which loads data from an API) when you press the action bar back button.
If I press the back button on the device (the button beside the home button) then I will be brought back to the previous view (the mainactivity) and won't have to call the API again.
So I'm trying to find a way to mimic the physical back button as an action bar widget.
I don't want MainActivity's code to be called again as it will execute another API call (I can only have 5 per minute) and it is also slower. I just want it to go back to the view I was just at.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<ListItem> listItems;
private String defaultQuery = "ham";
private String builtURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadData(defaultQuery);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
listItems.clear();
loadData(query);
(menu.findItem(R.id.action_search)).collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setIconified(false);
return true;
}
public void loadData(String query) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading recipes...");
progressDialog.show();
Log.d("q", "loadData: " + query);
builtURL = buildURL(query);
StringRequest request = new StringRequest(Request.Method.GET,
builtURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject obj = new JSONObject(response);
JSONArray hits = obj.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject a = hits.getJSONObject(i);
JSONObject recipe = a.getJSONObject("recipe");
String ingredients = recipe.getString("ingredientLines");
ingredients = ingredients.replace("[", "");
ingredients = ingredients.replace("]", "");
ingredients = ingredients.replace("\"", "");
ingredients = ingredients.replace("\\", "");
ingredients = ingredients.replace(",", "\n");
ListItem item = new ListItem(
recipe.getString("label"),
recipe.getString("source"),
recipe.getString("image"),
ingredients,
recipe.getString("url")
);
listItems.add(item);
}
adapter = new Adapter(listItems, getApplicationContext(), builtURL);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(request);
}
private String buildURL(String query) {
Log.d("q", "buildURL: " + query);
Uri.Builder builder = new Uri.Builder();
//url built here but I removed it because it shows API key etc.
String urlToSend = builder.build().toString();
//debugging purposes to show the url created
Log.d("url", "doInBackground: " + urlToSend);
return urlToSend;
}
#Override
public boolean onNavigateUp(){
finish();
return true;
}
This is the activity that I'm coming from.
public class recipe_view extends AppCompatActivity {
ImageView ivRecipeImage;
TextView tvRecipeName;
TextView tvRecipeCreator;
TextView tvRecipeIngredients;
String url;
Integer pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_view);
Bundle data = getIntent().getExtras();
ArrayList<ListItem> list = data.getParcelableArrayList("list");
pos = data.getInt("pos");
for (int i = 0; i < list.size() ; i++) {
System.out.println(list.get(i));
System.out.println(pos);
}
ivRecipeImage = findViewById(R.id.recipeImage);
tvRecipeName = findViewById(R.id.recipeName);
tvRecipeCreator = findViewById(R.id.recipeCreator);
tvRecipeIngredients = findViewById(R.id.ingredients);
tvRecipeName.setText(list.get(pos).getTitle());
tvRecipeCreator.setText(list.get(pos).getAuthor());
Picasso.with(getApplicationContext())
.load(list.get(pos).getImageUrl())
.centerCrop()
.fit()
.into(ivRecipeImage);
tvRecipeIngredients.setText(list.get(pos).getListOfIngredients());
url = list.get(pos).getRecipeUrl();
final Button button = findViewById(R.id.bViewInstructions);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
}
});
}
}
In your manifest xml
set
<activity
android:name=".your_activity"
android:label="#string/title_activity_sign_up"
android:parentActivityName=".whateveractivity"
android:screenOrientation="portrait" >
</activity>
then in code
#Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
// Otherwise defer to system default behavior.
super.onBackPressed();
}
To elaborate what you are doing is overriding the onbackpressed hardware button.
Also make your parent activity's launchmode singleInstance.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
finish();
}
});
When using my app the users inputs data and the data is supposed to be saved. However at the moment the back button erases the data from the EditText. Here is my java file for the activity, this activity is activated by a button press from the Main Activity. I've already tried to override the back button with no success. Any suggestions?
public class NewLocation extends ActionBarActivity {
public String coName;
public String coAddress;
public String coContact;
public String sqFt;
public String taxed;
public String concerns;
public EditText editCoName;
public EditText editCoAddress;
public EditText editCoContact;
public EditText editSqFt;
public EditText editTaxed;
public EditText editConcerns;
public static final String DEFAULT = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_location);
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NewLocation.this, RoomList.class));
}
});
editCoName = (EditText) findViewById(R.id.CoName);
editCoAddress = (EditText) findViewById(R.id.CoAddress);
editCoContact = (EditText) findViewById(R.id.CoContact);
editSqFt = (EditText) findViewById(R.id.SqFt);
editTaxed = (EditText) findViewById(R.id.Taxed);
editConcerns = (EditText) findViewById(R.id.Concerns);
coName = editCoName.getText().toString();
coAddress = editCoAddress.getText().toString();
coContact = editCoContact.getText().toString();
sqFt = editSqFt.getText().toString();
taxed = editTaxed.getText().toString();
concerns = editConcerns.getText().toString();
LoadPreferences();
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("coName", coName);
outState.putString("coAddress", coAddress);
outState.putString("coContact", coContact);
outState.putString("sqFt", sqFt);
outState.putString("taxed", taxed);
outState.putString("concerns", concerns);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
coName = savedInstanceState.get("coName").toString();
coAddress = savedInstanceState.get("coAddress").toString();
coContact = savedInstanceState.get("coContact").toString();
sqFt = savedInstanceState.get("sqFt").toString();
taxed = savedInstanceState.get("taxed").toString();
concerns = savedInstanceState.get("concerns").toString();
}
private void SavePreferences()
{
SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("coName", coName);
editor.putString("coAddress", coAddress);
editor.putString("coContact", coContact);
editor.putString("sqFt", sqFt);
editor.putString("taxed", taxed);
editor.putString("concerns", concerns);
editor.apply();
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);
coName = sharedPreferences.getString("coName", DEFAULT);
coAddress = sharedPreferences.getString("coAddress", DEFAULT);
coContact = sharedPreferences.getString("coContact", DEFAULT);
sqFt = sharedPreferences.getString("sqFt", DEFAULT);
taxed = sharedPreferences.getString("taxed", DEFAULT);
concerns = sharedPreferences.getString("concerns", DEFAULT);
editCoName.setText(coName);
editCoAddress.setText(coAddress);
editCoContact.setText(coContact);
editSqFt.setText(sqFt);
editTaxed.setText(taxed);
editConcerns.setText(concerns);
}
#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_new_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch(item.getItemId())
{
case R.id.home:
SavePreferences();
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
}
You should save/restore the persistent state of the activity in onSaveInstanceState/onRestoreInstanceState methods. You already override those, so just call SavePreferences/LoadPreferences from them.
Overriding the back button is not a good idea and saving state in onDestroy is also not recommended. Either onSaveInstanceState or onPause is intended for that.
If the data needs to be saved whenever the user leaves that activity, you could approach the problem with a TextWatcher. Override the onTextChanged() method of the TextWatcher with something like this:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length > 0) coName = s;
}
And then override onPause() to save the state of your variables if necessary.
[Edited] You can try:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
SavePreferences();
finish(); //<-- You need finish your activity after saved
return true;
}
return super.onKeyDown(keyCode, event);
}
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)
A search api is returning me some meta data along with a URL "eventURL". I am placing the data in the listview, each row containing some data and a unique URL.I want when the user taps on the row in the listview,that unique URL should open in a webview.I have created a WebViewActivity for it,I am having issue with implementing the onClickListener.
MainActivity
public class MainActivity extends Activity {
//private EditText m_search_text;
private EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_search_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(MainActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null ||m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("\\<.*?\\>", ""));
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
t.setText ("When:" + "\t"+meta.getString("startDate")+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" +"More Info:"+"\t" +meta.getString("eventURL")+"\n");
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}}
WebViewActivity
public class WebViewActivity extends MainActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("url");
}}
Thanks.
You need to use OnItemClickListener:
MainActivity implements OnItemClickListener {
onCreate() {
m_search_results.setOnItemClickListener(this);
Make this method:
onItemClick(AdapterView<?> parent, View view, int position, long id) {
url = JSON.getHowever(position);
//get the intent, load the url, and launch the activity
}
You also need to handle the intent in your WebViewActivity, but that's beside the question