GoogleMap error 2 - java

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" />

Related

at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)

I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:492) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:397) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:353) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5019) 
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:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful

Android Studio can't find Resuorces

This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#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_main, 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;
}
return super.onOptionsItemSelected(item);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.
A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception

How to fix application has stopped in android app when clicking another button inside main activity?

I have an app that when logged in by user the user redirects to main activity which had his personal details displayed and had two buttons to click: dashboard button redirected to his dashboard manager settings and a button log out. When logged in all is working fine showing his personal details and when I clicked dashboard button for his dashboard settings the app is unfortunately stopped. It said errors in my log cat which I can't fix with my own. I am new to Android. I searched and tried threads here in SO that has same problems with me but still can not be solved. Anybody with a great heart can help me to solve this? It's been quiet a week I'm stuck on this.
note* my dashboard button is calling another layout that contains two buttons
This is my main activity java :
package com.myapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import library.JSONParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ProfileView extends Activity implements OnClickListener{
private Button bLogout, backdashboard;
private TextView tvusername, tvfullname;
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();
// Profile json object
JSONArray user;
JSONObject display;
//String name for my sharedpref extras
String ngalan;
// Profile JSON url
private static final String PROFILE_URL = "http://10.0.2.2/webservice/profile.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
//setup textview
tvusername=(TextView)(findViewById(R.id.tvusernamedisplay));
tvfullname=(TextView)(findViewById(R.id.tvfullname));
//settup buttons
backdashboard=(Button)(findViewById(R.id.backdashboard));
bLogout=(Button)(findViewById(R.id.blogout));
//button listener
backdashboard.setOnClickListener(this);
bLogout.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras.containsKey("username")) {
ngalan = extras.getString("username");
// Loading Profile in Background Thread
new LoadProfile().execute();
}
}
#Override
public void onClick(View args) {
// TODO Auto-generated method stub
switch (args.getId()) {
case R.id.backdashboard:
Intent r = new Intent(this, Dashboard.class);
startActivity(r);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(ProfileView.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
class LoadProfile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileView.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", ngalan));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("Profile JSON: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try
{
display = new JSONObject(json);
JSONArray user = display.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String idnum = jb.getString("username");
String fulname = jb.getString("lastname");
// displaying all data in textview
tvusername.setText(idnum );
tvfullname.setText(fulname);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
This is my Dashboard activity java another activity calls when dashboard button is clicked...
package com.myapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Dashboard extends Activity implements OnClickListener{
private Button view, manage, logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
initialise();
}
private void initialise() {
// TODO Auto-generated method stub
//settup buttons
manage=(Button)(findViewById(R.id.bManage));
view=(Button)(findViewById(R.id.bView));
logout=(Button)(findViewById(R.id.blogout));
//button listener
manage.setOnClickListener(this);
view.setOnClickListener(this);
logout.setOnClickListener(this);
}
#Override
public void onClick(View item) {
// TODO Auto-generated method stub
switch (item.getId()) {
case R.id.bManage:
Intent r = new Intent(this, Manage.class);
startActivity(r);
finish();
break;
case R.id.bView:
Intent l = new Intent(this, View.class);
startActivity(l);
finish();
break;
case R.id.blogout:
new AlertDialog.Builder(this)
.setTitle("Logout")
.setMessage("Would you like to logout?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// logout
Intent myIntent = new Intent(Dashboard.this, LoginActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// user doesn't want to logout
}
})
.show();
default:
break;
}
}
}
This is my log cat error message"
08-23 18:59:36.949: E/AndroidRuntime(900): FATAL EXCEPTION: main
08-23 18:59:36.949: E/AndroidRuntime(900): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
Please help me guys :(
This is the full logcat message:
Unable to start activity ComponentInfo{com.myapp/com.myapp.Dashboard}: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Handler.dispatchMessage(Handler.java:99)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.os.Looper.loop(Looper.java:137)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.main(ActivityThread.java:5039)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invokeNative(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): at java.lang.reflect.Method.invoke(Method.java:511)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-23 18:59:36.949: E/AndroidRuntime(900): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-23 18:59:36.949: E/AndroidRuntime(900): at dalvik.system.NativeStart.main(Native Method)
08-23 18:59:36.949: E/AndroidRuntime(900): Caused by: java.lang.NullPointerException
08-23 18:59:36.949: E/AndroidRuntime(900): at com.myapp.Dashboard.onCreate(Dashboard.java:27)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Activity.performCreate(Activity.java:5104)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-23 18:59:36.949: E/AndroidRuntime(900): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-23 18:59:36.949: E/AndroidRuntime(900): ... 11 more
I guess that NPE occurs in this line: grade.setOnClickListener(this);
You don't initialize this variable anywhere.

Display other data based on spinner selection

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.

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