Display other data based on spinner selection - java

I have an xml file where I am displaying the text from the first tag, treasure name, in a spinner for the user to select. Once selected, I need to be able to access the other data associated to the treasure name selected that is stored in the xml document (in data file stored on device). I've parsed through the xml file and store each item in a separate array list. When a user clicks on a button (Get Clue), I need to be able to display the first clue associated to that treasure. This project is due today by midnight, and this is the last piece I just can't seem to get. Any help would be greatly appreciated. I added code to try and do this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
//import java.lang.reflect.Array;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.os.Bundle;
import android.app.Activity;
//import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class PlayGeoTreasureActivity extends Activity implements OnItemSelectedListener {
ArrayList<String> treasureList=new ArrayList<String>();
ArrayList<String>clue1List=new ArrayList<String>();
ArrayList<String> clue2List=new ArrayList<String>();
ArrayList<String> clue3List=new ArrayList<String>();
ArrayList<String> answerList=new ArrayList<String>();
ArrayList<String> locationList=new ArrayList<String>();
ArrayList<String> pointValueList=new ArrayList<String>();
XmlPullParserFactory parser;
XmlPullParser xpp;
TextView selected;
Spinner spinnerTreasures;
//Spinner spinnerTreasures = new Spinner(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_geo_treasure);
spinnerTreasures = (Spinner)findViewById(R.id.treasuresSpinner);
//get the xml file
File filename = new File(getFilesDir(), "treasure.xml");
//check to see if file exists. If it does, read it.
try {
if(filename.exists())
{
readXML(filename);
}
else
{
Toast.makeText(null, "File not Found", Toast.LENGTH_LONG).show();
}
}catch (FileNotFoundException e) {
//String errorMessage=(e.getMessage()==null)?"Message is Empty":e.getMessage();
//Log.e("GeoTreasureGameLog",errorMessage);
Log.e("GeoTreasureGameLog", (e.toString()));
e.printStackTrace();
} catch (XmlPullParserException e) {
//String errMessage=(e.getMessage()==null)?"Message is Empty":e.getMessage();
//Log.e("GeoTreasureGameLog",errMessage);
Log.e("GeoTreasureGameLog", (e.toString()));
e.printStackTrace();
}
}
private void readXML(File filename) throws XmlPullParserException, FileNotFoundException {
// pull parser to read xml file
parser = XmlPullParserFactory.newInstance();
xpp = parser.newPullParser();
// point the xml parser to file
xpp.setInput(new FileReader(filename));
// get start and end tags
int eventType = xpp.getEventType();
// set current tag
String currentTag="";
// current value of the tag's element
String currentElement="";
//int counter = 0;
try{
// parse the entire xml file until done
while (eventType != XmlPullParser.END_DOCUMENT)
{
// look for start tags
if(eventType == XmlPullParser.START_TAG)
{
// get the name of the start tag
currentTag = xpp.getName();
if (currentTag.equals("TreasureName"))
{
currentElement = xpp.nextText();
treasureList.add(currentElement);
}
else if (currentTag.equals("ClueOne"))
{
currentElement = xpp.nextText();
clue1List.add(currentElement);
}
else if (currentTag.equals("ClueTwo"))
{
currentElement = xpp.nextText();
clue2List.add(currentElement);
}
else if (currentTag.equals("ClueThree"))
{
currentElement = xpp.nextText();
clue3List.add(currentElement);
}
else if (currentTag.equals("Answer"))
{
currentElement = xpp.nextText();
answerList.add(currentElement);
}
else if (currentTag.equals("TreasureLocation"))
{
currentElement = xpp.nextText();
locationList.add(currentElement);
}
else if (currentTag.equals("PointValue"))
{
currentElement = xpp.nextText();
pointValueList.add(currentElement);
}
}
eventType = xpp.next();
}
} catch (Exception e)
{
//Log.e("GeoTreasureGameLog", e.getMessage());
Log.e("GeoTreasureGameLog", (e.toString()));
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,treasureList);
selected=(TextView) findViewById(R.id.itemSelected);
spinnerTreasures.setOnItemSelectedListener(PlayGeoTreasureActivity.this);
spinnerTreasures.setAdapter(spinnerArrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.play_geo_treasure, menu);
return true;
}
#Override
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
selected.setText(treasureList.get(position));
int i=treasureList.indexOf(selected);
clueOne=clue1List.get(i).toString();
clueTwo=clue2List.get(i).toString();
clueThree=clue3List.get(i).toString();
Button getClue = (Button)findViewById(R.id.getClueBtn);
getClue.setOnClickListener((OnClickListener) this);
}
public void OnClick(View v) throws IOException{
int buttonClicks = 3;
TextView clue1=(TextView)findViewById(R.id.clue1TxtView);
TextView clue2 = (TextView)findViewById(R.id.clue2TextView);
TextView clue3=(TextView)findViewById(R.id.clue3TextView);
if (buttonClicks == 3){
clue1.setText(clueOne);
buttonClicks=2;
}
else if (buttonClicks==2){
clue2.setText(clueTwo);
buttonClicks=1;
}
else if (buttonClicks==1){
clue3.setText(clueThree);
buttonClicks=0;
}
else if (buttonClicks==0)
Toast.makeText(getBaseContext(), "No more clues are available", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selected.setText("Please choose a treasure");
}
}
Thanks to any input I can get!!!
Ok, I tried doing it this way, and am getting the error:
09-15 16:33:47.439: E/AndroidRuntime(1440): FATAL EXCEPTION: main
09-15 16:33:47.439: E/AndroidRuntime(1440): java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
09-15 16:33:47.439: E/AndroidRuntime(1440): at java.util.ArrayList.get(ArrayList.java:310)
09-15 16:33:47.439: E/AndroidRuntime(1440): at com.rasmussen.geotreasuresgame.PlayGeoTreasureActivity.onItemSelected(PlayGeoTreasureActivity.java:182)
09-15 16:33:47.439: E/AndroidRuntime(1440): at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
09-15 16:33:47.439: E/AndroidRuntime(1440): at android.widget.AdapterView.access$200(AdapterView.java:49)
09-15 16:33:47.439: E/AndroidRuntime(1440): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
09-15 16:33:47.439: E/AndroidRuntime(1440): at android.os.Handler.handleCallback(Handler.java:730)
09-15 16:33:47.439: E/AndroidRuntime(1440): at android.os.Handler.dispatchMessage(Handler.java:92)
09-15 16:33:47.439: E/AndroidRuntime(1440): at android.os.Looper.loop(Looper.java:137)
09-15 16:33:47.439: E/AndroidRuntime(1440): at android.app.ActivityThread.main(ActivityThread.java:5103)
09-15 16:33:47.439: E/AndroidRuntime(1440): at java.lang.reflect.Method.invokeNative(Native Method)
09-15 16:33:47.439: E/AndroidRuntime(1440): at java.lang.reflect.Method.invoke(Method.java:525)
09-15 16:33:47.439: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-15 16:33:47.439: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-15 16:33:47.439: E/AndroidRuntime(1440): at dalvik.system.NativeStart.main(Native Method)

I ran into same Error (java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1) with spinners too. In my case, I was trying to setAdapter on spinner outside the ui thread. After wrapping the related code inside runOnUiThread, the issue is solved.

Related

Android display SD card files throws java.lang.NullPointerException

This is the MainActivity file. When I run it in the emulator and phone, logcat displays a crash due to a NullPointerException. I've read a lot about not letting the user or another activity pass "null" value to my method but could not get around this.
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I used a listview with id= "filelist" in layout
ListView lv;
ArrayList<String> FilesInFolder;
FilesInFolder = GetFiles(Environment.getExternalStorageDirectory().getPath()+ "/sdcard/");
lv = (ListView)findViewById(R.id.filelist);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, FilesInFolder);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Clicking on items
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
}
This is the logcat:
07-02 01:09:40.500 4407-4407/com.amenhotep.filelister W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
07-02 01:09:40.501 4407-4407/com.amenhotep.filelister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amenhotep.filelister, PID: 4407
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amenhotep.filelister/com.amenhotep.filelister.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.amenhotep.filelister.MainActivity.GetFiles(MainActivity.java:44)
at com.amenhotep.filelister.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
at android.app.ActivityThread.access$900(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5345)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
the problem is in your sdcard path, use this code to get path of sdcard
String DIR_SDCARD = Environment.getExternalStorageDirectory().getAbsolutePath();
and there is no need to add "/sdcard/" to it, also change your GetFiles method, and remove mkdirs() because sdcard exists before.
look at this example
File sdcard_files_and_folders[] = new File(DIR_SDCARD).listFiles();
for (File fileOrFolder: sdcard_files_and_folders) {
// do any thing that you want, add them to list or...
Log.i("FILE", fileOrFolder.toString());
}

GoogleMap error 2

I wrote this code in other to integrate google map v2 to my android app and i am getting errors. I need to know where i made a mistake. The code and the logcat error is listed below:
EkoMap.java:
package com.src.apps.myekoapp;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.wallet.Address;
#SuppressLint("NewApi")
public class EkoMap extends Activity {
private GoogleMap ekoMap;
LocationManager locMan;
Location lastLoc;
LatLng lastLatLng;
private Marker userMarker;
private int user_icon;
Geocoder mGeocoder;
double lat, lng;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_fragment);
user_icon = R.drawable.user_icon;
// Setting zoom controls
//ekoMap.getUiSettings().setZoomControlsEnabled(true);
try {
if (ekoMap == null) {
ekoMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.the_map)).getMap();
}
if (ekoMap != null) {
// ok - proceed
}
ekoMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
// Updating User Location
updatePlaces();
updateWithNewlocation(lastLoc);
}
#Override
public void onResume() {
super.onResume();
}
// showing current location
private void updatePlaces() {
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
lat = lastLoc.getLatitude();
lng = lastLoc.getLongitude();
lastLatLng = new LatLng(lat, lng);
if (userMarker != null)
userMarker.remove();
userMarker = ekoMap.addMarker(new MarkerOptions().position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(user_icon))
.snippet("Your last recorded location"));
ekoMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 300,
null);
}
// showing the new location as the user moves
public void updateWithNewlocation(Location l) {
mGeocoder = new Geocoder(this, Locale.getDefault());
String addressString = "No address found";
if (!Geocoder.isPresent())
addressString = "No geocoder available";
else {
try {
List<android.location.Address> address = mGeocoder
.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (address.size() > 0) {
android.location.Address addresses = address.get(0);
for (int i = 0; i < addresses.getMaxAddressLineIndex(); i++)
sb.append(addresses.getAddressLine(i)).append("\n");
sb.append(addresses.getLocality()).append("\n");
sb.append(addresses.getPostalCode()).append("\n");
sb.append(addresses.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {
Log.d("WHERE AM I", "IOException", e);
}
}
Toast.makeText(getApplicationContext(),
"Your current Location is " + addressString, Toast.LENGTH_SHORT)
.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Adding menus to change the look of the map
MenuInflater mMenuInflater = getMenuInflater();
mMenuInflater.inflate(R.menu.map_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem mMenuItem) {
// Handle presses on the action bar items
switch (mMenuItem.getItemId()) {
// Handle up/home navigation
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
// Handle hybrid view
case R.id.item_hybrid:
try {
ekoMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
} catch (Exception e) {
e.printStackTrace();
}
// Handle satellite view
case R.id.item_satellite:
try {
ekoMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
} catch (Exception e) {
e.printStackTrace();
}
// Handle terrain view
case R.id.item_terrain:
try {
ekoMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
} catch (Exception e) {
e.printStackTrace();
}
// Handel about app
case R.id.action_about:
return true;
// Handle call
case R.id.action_call:
startActivity(new Intent(getApplicationContext(), CallLASMA.class));
// Return menuItem
default:
return super.onOptionsItemSelected(mMenuItem);
}
}
}
LogCat error:
06-26 17:28:18.096: E/AndroidRuntime(415): FATAL EXCEPTION: main
06-26 17:28:18.096: E/AndroidRuntime(415): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.src.apps.myekoapp/com.src.apps.myekoapp.EkoMap}: java.lang.NullPointerException
06-26 17:28:18.096: E/AndroidRuntime(415): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.os.Handler.dispatchMessage(Handler.java:99)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.os.Looper.loop(Looper.java:126)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.app.ActivityThread.main(ActivityThread.java:3997)
06-26 17:28:18.096: E/AndroidRuntime(415): at java.lang.reflect.Method.invokeNative(Native Method)
06-26 17:28:18.096: E/AndroidRuntime(415): at java.lang.reflect.Method.invoke(Method.java:491)
06-26 17:28:18.096: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
06-26 17:28:18.096: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
06-26 17:28:18.096: E/AndroidRuntime(415): at dalvik.system.NativeStart.main(Native Method)
06-26 17:28:18.096: E/AndroidRuntime(415): Caused by: java.lang.NullPointerException
06-26 17:28:18.096: E/AndroidRuntime(415): at com.src.apps.myekoapp.EkoMap.updatePlaces(EkoMap.java:81)
06-26 17:28:18.096: E/AndroidRuntime(415): at com.src.apps.myekoapp.EkoMap.onCreate(EkoMap.java:67)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
06-26 17:28:18.096: E/AndroidRuntime(415): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)
06-26 17:28:18.096: E/AndroidRuntime(415): ... 11 more
locMan is null.
Did you add the following permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Can't display banners

I have this activity - including the needed code in order to load the admob banner ads.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.gs.britishjokes.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AllJokes extends Activity {
public static ArrayAdapter<String> adapter;
public static ListView listView;
private AdView adView;
/* Your ad unit id. Replace with your actual ad unit id. */
private static final String AD_UNIT_ID = "ca-app-pub-codehere/code";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_jokes);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
// .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
// .addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
.build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
final GlobalsHolder globals = (GlobalsHolder)getApplication();
// if(globals.isLoaded == false){ SETJOKESNAMELIST MAI SE POLZVA OT DRUGO ACTIVITY!!!! ZATOVA IZLIZA PRAZNO SLED PROVERKATA!
new loadJson().execute();
// }
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
adapter.clear();
adapter.addAll(globals.getMyStringArray());
listView = (ListView) findViewById(R.id.allJokesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
globals.setClickedJokeName((String) ((TextView) view).getText());
openJokeBody(view);
globals.setClickedPosition(position);
// When clicked, shows a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.all_jokes, menu);
return true;
}
public class loadJson extends AsyncTask<Void, Integer, String[]>{
private ProgressDialog Dialog = new ProgressDialog(AllJokes.this);
#Override
protected void onPreExecute()
{
Dialog.setMessage("Fetching the latest jokes!");
Dialog.show();
}
#Override
protected String[] doInBackground(Void... params) {
/*Getting the joke names JSON string response from the server*/
URL u;
StringBuffer buffer = new StringBuffer();
StringBuffer buffer2 = new StringBuffer();
try {
u = new URL("https://site.com/android/Jokes/showJokes.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
try {
u = new URL("https://site.com/android/Jokes/showJokesBody.php?JokeCat=allJokes");
URLConnection conn = u.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
buffer2.append(inputLine);
in.close();
}catch(Exception e){
e.printStackTrace();
}
// return buffer.toString(); ako se naloji da vurna - da pogledna tva return4e
return new String[]{buffer.toString(), buffer2.toString()};
}
#SuppressLint("NewApi")
protected void onPostExecute(String[] buffer) {
final GlobalsHolder globals = (GlobalsHolder)getApplication();
JSONArray jsonArray = new JSONArray();
JSONArray jsonArray1 = new JSONArray();
try {
jsonArray = new JSONArray(buffer[0]);
jsonArray1 = new JSONArray(buffer[1]);
} catch (JSONException e) {
e.printStackTrace();
}
/*Looping trough the results and adding them to a list*/
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> list1 = new ArrayList<String>();
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
try {
list.add(jsonArray.get(i).toString());
globals.setJokeNamesList(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if (jsonArray != null) {
int len = jsonArray1.length();
for (int i=0;i<len;i++){
try {
list1.add(jsonArray1.get(i).toString());
globals.setList(list1);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
/* Redrwawing the view */
adapter.clear();
adapter.addAll(list);
Dialog.dismiss();
globals.setLoaded(true);
}
}
/*This method opens the new activity - TopJokesBody when a joke name from the list is clicked*/
public void openJokeBody(View view) {
Intent intent = new Intent(this, AllJokesBody.class);
startActivity(intent);
}
}
It is my 1st try and I already stucked. Logcat is throwing tons of exceptions and to be honest I can't understand what I'm doing wrong.
Here the exceptions are:
03-29 13:55:37.713: E/AndroidRuntime(1750): FATAL EXCEPTION: main
03-29 13:55:37.713: E/AndroidRuntime(1750): Process: com.gs.britishjokes, PID: 1750
03-29 13:55:37.713: E/AndroidRuntime(1750): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gs.britishjokes/com.gelasoft.britishjokes.AllJokes}: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Handler.dispatchMessage(Handler.java:102)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.os.Looper.loop(Looper.java:136)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): at java.lang.reflect.Method.invoke(Method.java:515)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-29 13:55:37.713: E/AndroidRuntime(1750): at dalvik.system.NativeStart.main(Native Method)
03-29 13:55:37.713: E/AndroidRuntime(1750): Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.widget.AdapterView.addView(AdapterView.java:452)
03-29 13:55:37.713: E/AndroidRuntime(1750): at com.gelasoft.britishjokes.AllJokes.onCreate(AllJokes.java:55)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Activity.performCreate(Activity.java:5231)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-29 13:55:37.713: E/AndroidRuntime(1750): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
03-29 13:55:37.713: E/AndroidRuntime(1750): ... 11 more
I'm sure that I miss something inside of the xml layout file, but I'm not able to spot it as a total beginner.
Ps. here the layout is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".AllJokes" >
<ListView
android:id="#+id/allJokesList"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</RelativeLayout>
Should I declare something in it? Please, give me a clue!
Caused by: java.lang.UnsupportedOperationException: addView(View) is not supported in AdapterView
you cant add a view to adapterview
your issue is with
ListView layout = (ListView) findViewById(R.id.allJokesList);
layout.addView(adView);
You need to add the adView inside the adapter
http://googleadsdeveloper.blogspot.co.il/2012/03/embedding-admob-ads-within-listview-on.html
Don't try to add an AdView as an element in a ListView. It is a recipe for pain as it will be entirely different to your other items with different needs.
Add it as it's own element either above or below your ListView.
Instead create a LinearLayout either above or below your ListView
<LinearLayout android:id="#+id/adViewContainer
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
and then change this part of your onCreate to
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
final ViewGroup adViewContainer = (ViewGroup) findViewById(R.id.adViewContainer);
adViewContainer.addView(adView);

Writing to excel file with apache poi in android project

I have problem whit getting my project to work i will
paste the java files and error log hopefully someone can give me a hint.
The app crash when button R.id.bskickaTidSc3 in TidSc3.java is clicked.
error log
06-08 12:45:49.365: E/dalvikvm(1243): Could not find class 'org.apache.poi.hssf.usermodel.HSSFWorkbook', referenced from method com.example.spapp_beta.TidsedelExcel.SetExcelVecka
06-08 12:45:49.365: W/dalvikvm(1243): VFY: unable to resolve new-instance 67 (Lorg/apache/poi/hssf/usermodel/HSSFWorkbook;) in Lcom/example/spapp_beta/TidsedelExcel;
06-08 12:45:49.365: D/dalvikvm(1243): VFY: replacing opcode 0x22 at 0x0000
06-08 12:45:49.365: D/dalvikvm(1243): DexOpt: unable to opt direct call 0x0087 at 0x09 in Lcom/example/spapp_beta/TidsedelExcel;.SetExcelVecka
06-08 12:45:49.375: D/AndroidRuntime(1243): Shutting down VM
06-08 12:45:49.375: W/dalvikvm(1243): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-08 12:45:49.387: E/AndroidRuntime(1243): FATAL EXCEPTION: main
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidsedelExcel.SetExcelVecka(TidsedelExcel.java:17)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.example.spapp_beta.TidSc3.onClick(TidSc3.java:96)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View.performClick(View.java:4204)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.view.View$PerformClick.run(View.java:17355)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.handleCallback(Handler.java:725)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Handler.dispatchMessage(Handler.java:92)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.os.Looper.loop(Looper.java:137)
06-08 12:45:49.387: E/AndroidRuntime(1243): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 12:45:49.387: E/AndroidRuntime(1243): at java.lang.reflect.Method.invoke(Method.java:511)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-08 12:45:49.387: E/AndroidRuntime(1243): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-08 12:45:49.387: E/AndroidRuntime(1243): at dalvik.system.NativeStart.main(Native Method)
06-08 12:46:37.675: E/Trace(1261): error opening trace file: No such file or directory (2)
06-08 12:46:38.065: D/gralloc_goldfish(1261): Emulator without GPU emulation detected.
TidSc3.java
package com.example.spapp_beta;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TidSc3 extends Activity implements OnClickListener {
Button skicka, visa;
TextView namn, vecka, ar, arbplts, man,tis,ons,tors,fre,lor,son,oI,oII,restid,km,trakt;
EditText v,ovrigt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tid_sc3);
ovrigt = (EditText) findViewById(R.id.eTovrigt);
v = (EditText) findViewById(R.id.eTtidSc3vecka);
namn = (TextView) findViewById(R.id.tVsamNamn);
vecka = (TextView) findViewById(R.id.tVsamVecka);
ar = (TextView) findViewById(R.id.tVsamAr);
arbplts = (TextView) findViewById(R.id.tVsamArbplts);
man = (TextView) findViewById(R.id.tVsamMan);
tis = (TextView) findViewById(R.id.tVsamTis);
ons = (TextView) findViewById(R.id.tVsamOns);
tors = (TextView) findViewById(R.id.tVsamTors);
fre = (TextView) findViewById(R.id.tVsamFre);
lor = (TextView) findViewById(R.id.tVsamLor);
son = (TextView) findViewById(R.id.tVsamSon);
oI = (TextView) findViewById(R.id.tVsamOI);
oII = (TextView) findViewById(R.id.tVsamOII);
restid = (TextView) findViewById(R.id.tVsamRestid);
km = (TextView) findViewById(R.id.tVsamKm);
trakt = (TextView) findViewById(R.id.tVsamTrakt);
visa = (Button) findViewById(R.id.bvisa);
skicka = (Button) findViewById(R.id.bskickaTidSc3);
skicka.setOnClickListener(this);
visa.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bvisa:
String s = v.getText().toString();
long l = Long.parseLong(s);
String[] veckaA = new String[16];
DbTidsedel2013 get = new DbTidsedel2013(TidSc3.this);
get.open();
veckaA = get.VeckaArray(l);
get.close();
vecka.setText(veckaA[0]);
ar.setText(veckaA[1]);
namn.setText(veckaA[2]);
arbplts.setText(veckaA[3] + "\n");
man.setText(veckaA[4]);
tis.setText(veckaA[5]);
ons.setText(veckaA[6]);
tors.setText(veckaA[7]);
fre.setText(veckaA[8]);
lor.setText(veckaA[9]);
son.setText(veckaA[10]);
restid.setText(veckaA[11]);
km.setText(veckaA[12]);
oI.setText(veckaA[13]);
oII.setText(veckaA[14]);
trakt.setText(veckaA[15]);
break;
case R.id.bskickaTidSc3:
String s1 = v.getText().toString();
long l1 = Long.parseLong(s1);
String[] veckaA1 = new String[16];
DbTidsedel2013 get1 = new DbTidsedel2013(TidSc3.this);
get1.open();
veckaA1 = get1.VeckaArray(l1);
get1.close();
TidsedelExcel tidEx = new TidsedelExcel();
try {
tidEx.SetExcelVecka(veckaA1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String ov = ovrigt.getText().toString();
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Tid vecka " + veckaA1[0]);
intent.putExtra(Intent.EXTRA_TEXT, ov);
intent.setData(Uri.parse("mailto:"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tid_sc3, menu);
return true;
}
}
TidsedelExcel.java
package com.example.spapp_beta;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class TidsedelExcel {
public void SetExcelVecka (String[] vecka) throws FileNotFoundException, IOException{
Workbook workbook = new HSSFWorkbook(new FileInputStream("/assets/TsO.xls"));
Sheet sheet = workbook.getSheetAt(0);
Cell cellvecka1 = sheet.getRow(1).getCell(14);
cellvecka1.setCellValue(vecka[0]);
Cell cellvecka2 = sheet.getRow(7).getCell(0);
cellvecka2.setCellValue(vecka[0]);
Cell cellAr = sheet.getRow(1).getCell(10);
cellAr.setCellValue(vecka[1]);
Cell cellNamn = sheet.getRow(3).getCell(0);
cellNamn.setCellValue(vecka[2]);
Cell cellArbplts = sheet.getRow(3).getCell(10);
cellArbplts.setCellValue(vecka[3]);
Cell cellMan = sheet.getRow(7).getCell(3);
int man = Integer.parseInt(vecka[4]);
cellMan.setCellValue(man);
Cell cellTis = sheet.getRow(7).getCell(4);
int tis = Integer.parseInt(vecka[5]);
cellTis.setCellValue(tis);
Cell cellOns = sheet.getRow(7).getCell(5);
int ons = Integer.parseInt(vecka[6]);
cellOns.setCellValue(ons);
Cell cellTors = sheet.getRow(7).getCell(6);
int tors = Integer.parseInt(vecka[7]);
cellTors.setCellValue(tors);
Cell cellFre = sheet.getRow(7).getCell(7);
int fre = Integer.parseInt(vecka[8]);
cellFre.setCellValue(fre);
Cell cellLor = sheet.getRow(7).getCell(8);
int lor = Integer.parseInt(vecka[9]);
cellLor.setCellValue(lor);
Cell cellSon = sheet.getRow(7).getCell(9);
int son = Integer.parseInt(vecka[10]);
cellSon.setCellValue(son);
Cell cellRestid = sheet.getRow(7).getCell(10);
int restid = Integer.parseInt(vecka[11]);
cellRestid.setCellValue(restid);
Cell cellMil = sheet.getRow(7).getCell(16);
int mil = Integer.parseInt(vecka[12]);
cellMil.setCellValue(mil);
Cell cellOI = sheet.getRow(7).getCell(13);
int oI = Integer.parseInt(vecka[13]);
cellOI.setCellValue(oI);
Cell cellOII = sheet.getRow(7).getCell(14);
int oII = Integer.parseInt(vecka[14]);
cellOII.setCellValue(oII);
Cell cellTrakt = sheet.getRow(7).getCell(15);
int trakt = Integer.parseInt(vecka[15]);
cellTrakt.setCellValue(trakt);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("/assets/Tidsedel_V_" + vecka[0] + "_" + vecka[1] + ".xls");
workbook.write(fileOut);
fileOut.close();
}
}
Thanks to anyone that is kind to help out
The error says
06-08 12:45:49.387: E/AndroidRuntime(1243): java.lang.NoClassDefFoundError: org.apache.poi.hssf.usermodel.HSSFWorkbook
Go to Project properties > Java Build Path > Order and Export tab and select the library you have used in your project..

Change Value of spinners dynamically according to another spinner value

I have 3 spinners in my view. 1st spinner has fixed initial values. rest of it are empty initially.
when i select a value from first spinner , new values are added to spinner 2 and 3 according to the selection of 1st spinner.
Here i Did something for only two Spinners ! There isn't any code error but i got run time error it's listed below the code ! can any one help me? Thanks in advance !
Coding
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import com.gtustudents.R;
import com.gtustudents.common.BaseActivity;
import com.gtustudents.login.HomePage;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class demo extends BaseActivity {
public Spinner spinner1;
public Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.MY_LAYOUT);
spinner1= (Spinner)findViewById(R.id.degree);
spinner1.setOnItemSelectedListener(new spinnerListen());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
startActivity(new Intent(this,HomePage.class));
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
class spinnerListen extends BaseActivity implements OnItemSelectedListener{
public Spinner spinner2;
public void onItemSelected(AdapterView<?> parent, View v, int pos,long id) {
// TODO Auto-generated method stub
//use the selected station and departure time to calculate the required time
Toast toast = Toast.makeText(parent.getContext(),"You've chosen: " + parent.getItemAtPosition(pos), 2);
toast.show();
String str = (String) parent.getSelectedItem();
Log.d("Select Item", str);
if(str.equals("SOME_VALUE"))
{
Log.d("Enter","YES");
final String[] items2 = new String[] {"SOne", "STwo", "SThree"};
Log.d("Enter","ArrayAdapter");
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items2);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("BE Enter","ArrayAdapter -2 ");
spinner2.setAdapter(dataAdapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
RunTime Error
08-30 16:49:18.586: ERROR/AndroidRuntime(865): FATAL EXCEPTION: main
08-30 16:49:18.586: ERROR/AndroidRuntime(865): java.lang.IllegalStateException: System services not available to Activities before onCreate()
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.app.Activity.getSystemService(Activity.java:3526)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.ArrayAdapter.init(ArrayAdapter.java:271)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:125)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.AdapterView.fireOnSelected(AdapterView.java:864)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.AdapterView.access$200(AdapterView.java:42)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:830)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.os.Handler.handleCallback(Handler.java:587)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.os.Handler.dispatchMessage(Handler.java:92)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.os.Looper.loop(Looper.java:123)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at android.app.ActivityThread.main(ActivityThread.java:4627)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at java.lang.reflect.Method.invokeNative(Native Method)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at java.lang.reflect.Method.invoke(Method.java:521)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-30 16:49:18.586: ERROR/AndroidRuntime(865): at dalvik.system.NativeStart.main(Native Method)
In your 2nd Class {{ spinnerListen }} your have declared a flied called spinner2 which is never intiated, but your tying to set an adapter to it.
I havent tried it, but i guess thats why the framework assume that you havent passed onCreate yet.
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import com.gtustudents.R;
import com.gtustudents.common.BaseActivity;
import com.gtustudents.login.HomePage;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class demo extends BaseActivity implements OnItemSelectedListener{
public Spinner spinner1;
public Spinner spinner2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.MY_LAYOUT);
spinner1= (Spinner)findViewById(R.id.degree);
spinner1.setOnItemSelectedListener(this);
spinner2 = (Spinner)findViewById(R.id.degree2); // TODO reference Proper id
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
startActivity(new Intent(this,HomePage.class));
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
public void onItemSelected(AdapterView<?> parent, View v, int pos,long id) {
// TODO Auto-generated method stub
//use the selected station and departure time to calculate the required time
Toast toast = Toast.makeText(parent.getContext(),"You've chosen: " + parent.getItemAtPosition(pos), 2);
toast.show();
String str = (String) parent.getSelectedItem();
Log.d("Select Item", str);
if(str.equals("SOME_VALUE"))
{
Log.d("Enter","YES");
final String[] items2 = new String[] {"SOne", "STwo", "SThree"};
Log.d("Enter","ArrayAdapter");
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items2);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Log.d("BE Enter","ArrayAdapter -2 ");
spinner2.setAdapter(dataAdapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}

Categories

Resources