The constructor LocationClient(MainActivity, MainActivity, MainActivity) is undefined - java

So I'm following along with a Lynda.com Tutorial on using Google Maps V2 to build mobile Apps and I was going along with a part that has you creating a map app that is finding the location programatically rather than relying on the setMyLocationEnabled(true) method. So I've followed along with the code and each time I go to run the app it crashes and give me the following error in the logcat:
05-15 12:18:35.139: E/AndroidRuntime(22270): FATAL EXCEPTION: main
05-15 12:18:35.139: E/AndroidRuntime(22270): Process: com.example.gmapsapp, PID: 22270
05-15 12:18:35.139: E/AndroidRuntime(22270): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gmapsapp/com.example.gmapsapp.MainActivity}: java.lang.ClassCastException: com.example.gmapsapp.MainActivity cannot be cast to com.google.android.gms.common.GooglePlayServicesClient$ConnectionCallbacks
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.access$900(ActivityThread.java:161)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.os.Handler.dispatchMessage(Handler.java:102)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.os.Looper.loop(Looper.java:157)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.main(ActivityThread.java:5356)
05-15 12:18:35.139: E/AndroidRuntime(22270): at java.lang.reflect.Method.invokeNative(Native Method)
05-15 12:18:35.139: E/AndroidRuntime(22270): at java.lang.reflect.Method.invoke(Method.java:515)
05-15 12:18:35.139: E/AndroidRuntime(22270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
05-15 12:18:35.139: E/AndroidRuntime(22270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
05-15 12:18:35.139: E/AndroidRuntime(22270): at dalvik.system.NativeStart.main(Native Method)
05-15 12:18:35.139: E/AndroidRuntime(22270): Caused by: java.lang.ClassCastException: com.example.gmapsapp.MainActivity cannot be cast to com.google.android.gms.common.GooglePlayServicesClient$ConnectionCallbacks
05-15 12:18:35.139: E/AndroidRuntime(22270): at com.example.gmapsapp.MainActivity.onCreate(MainActivity.java:60)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.Activity.performCreate(Activity.java:5426)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
05-15 12:18:35.139: E/AndroidRuntime(22270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
05-15 12:18:35.139: E/AndroidRuntime(22270): ... 11 more
Here's the code in my MainActivity.java, let me know if you need any other files to see if you can help with the issue thanks:
package com.example.gmapsapp;
import java.io.IOException;
import java.util.List;
import android.app.Dialog;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
#SuppressWarnings("unused")
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9002;
GoogleMap mMap;
#SuppressWarnings("unused")
private static final double SEATTLE_LAT = 47.60621,
SEATTLE_LNG =-122.33207,
SYDNEY_LAT = -33.867487,
SYDNEY_LNG = 151.20699,
NEWYORK_LAT = 40.714353,
NEWYORK_LNG = -74.005973;
private static final float DEFAULTZOOM = 15;
#SuppressWarnings("unused")
private static final String LOGTAG = "Maps";
LocationClient mLocationClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_map);
if (initMap()) {
// mMap.setMyLocationEnabled(true);
mLocationClient = new LocationClient(this, (ConnectionCallbacks) this, this);
mLocationClient.connect();
}
else {
Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show();
}
}
else {
setContentView(R.layout.activity_main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Can't connect to Google Play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
#SuppressWarnings("unused")
private void gotoLocation(double lat, double lng) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mMap.moveCamera(update);
}
private void gotoLocation(double lat, double lng,
float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
public void geoLocate(View v) throws IOException {
hideSoftKeyboard(v);
EditText et = (EditText) findViewById(R.id.editText1);
String location = et.getText().toString();
Geocoder gc = new Geocoder(this);
List<Address> list = gc.getFromLocationName(location, 1);
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show();
double lat = add.getLatitude();
double lng = add.getLongitude();
gotoLocation(lat, lng, DEFAULTZOOM);
}
private void hideSoftKeyboard(View v) {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mapTypeNone:
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
break;
case R.id.mapTypeNormal:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case R.id.mapTypeSatellite:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case R.id.mapTypeTerrain:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
break;
case R.id.mapTypeHybrid:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
case R.id.gotoCurrentLocation:
gotoCurrentLocation();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStop() {
super.onStop();
MapStateManager mgr = new MapStateManager(this);
mgr.saveMapState(mMap);
}
#Override
protected void onResume() {
super.onResume();
MapStateManager mgr = new MapStateManager(this);
CameraPosition position = mgr.getSavedCameraPosition();
if (position != null) {
CameraUpdate update = CameraUpdateFactory.newCameraPosition(position);
mMap.moveCamera(update);
// This is part of the answer to the code challenge
mMap.setMapType(mgr.getSavedMapType());
}
}
protected void gotoCurrentLocation() {
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "Connected to location service", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}

The second and third parameters of constructor have a type of:
GooglePlayServicesClient.ConnectionCallbacks
GooglePlayServicesClient.OnConnectionFailedListener
So you should implement these interfaces in your Activity, if you are pointing to this. But you've picked up similar interfaces from another class - GoogleApiClient

Not familiar with android apis but looks like a bad import of ConnectionCallbacks (import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;). When you cast to ConnectionCallbacks its using that bad import instead of GoogleApiClient.ConnectionCallbacks.
Edited:
ok so its the other way around!

Related

sunshine app crashing on emulator

i m completely beginner in android developing and following the tutorial for sunshine app, while running the app it was supposed to display the detail on detailactivity but gives error. help me figure it out
mainactivity
package com.example.android.sunshine.app;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new ForecastFragment())
.commit();
}*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
}
forecastFragment
package com.example.android.sunshine.app;
import android.content.Intent;
import android.net.*;
import android.os.*;
import android.support.v4.app.*;
import android.text.format.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import org.json.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
/**
* Created by Nabahat on 7/8/2015.
*/
public class ForecastFragment extends Fragment {
List<String> mWeekForecast;
ArrayAdapter<String> mForecastAdapter = null;
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Weds - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
"Sun - Sunny - 80/68"
};
List<String> weekForecast = new ArrayList<String>(
Arrays.asList(forecastArray));
mForecastAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String forecast = mForecastAdapter.getItem(position);
Intent intent = new Intent(getActivity(), DetailActivity.class )
.putExtra(Intent.EXTRA_TEXT, forecast);
startActivity(intent);
}
});
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time) {
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
* <p/>
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for (int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay + i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("API_KEY", "c84aeef73dfe54e9ec696154cfb89a5a");
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
urlConnection.setRequestProperty("Accept", "*/*");
urlConnection.setDoOutput(false);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
if (result != null) {
mForecastAdapter.clear();
for (String dayForecastStr : result) {
mForecastAdapter.add(dayForecastStr);
}
}
}
}
}
detail activity
package com.example.android.sunshine.app;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment()).commit();
}
}
#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_detail, 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);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)){
String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView) rootView.findViewById(R.id.detail_text))
.setText(forecastStr);
}
return rootView;
}
}
}
activitydetail.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/fragment"
android:name="com.example.android.sunshine.app.DetailActivity$DetailFragment"
tools:layout="#layout/fragment_detail" android:layout_width="match_parent"
android:layout_height="match_parent" />
activitymain.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="com.example.android.sunshine.app.ForecastFragment"
tools:layout="#layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
fragmentdetail.xml
<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:paddingLeft="64dp"
android:paddingRight="64dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context="com.example.android.sunshine.app.DetailFragment">
<TextView
android:id="#+id/detail_text"
android:text="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
fragmentmain.xml
<FrameLayout
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:paddingLeft="64dp"
android:paddingRight="64dp"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.sunshine.app.MainActivityFragment$PlaceholderFragment"
android:id="#+id/container">
<ListView
android:id="#+id/listview_forecast"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
logcat
android.support.v7.internal.widget.ActionBarOverlayLayout{bd47b46 V.E..... ... 0,0-0,0 #7f0c003e app:id/decor_content_parent}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ContentFrameLayout{252c0107 V.E..... ... 0,0-0,0 #1020002 android:id/content}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.widget.RelativeLayout{39c34c6e V.E..... ... 0,0-0,0 #7f0c004f app:id/fragment}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.widget.AppCompatTextView{e76c234 V.ED.... ... 0,0-0,0 #7f0c0050 app:id/detail_text}
07-09 22:24:29.820 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContainer{3ff4b85d V.ED.... ... 0,0-0,0 #7f0c003f app:id/action_bar_container}
07-09 22:24:29.826 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.widget.Toolbar{4d05d2 V.E..... ... 0,0-0,0 #7f0c0040 app:id/action_bar}
07-09 22:24:29.828 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.widget.TextView{2afda6a3 V.ED.... ... 0,0-0,0}
07-09 22:24:29.828 12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContextView{1bd7cda0 G.E..... ... 0,0-0,0 #7f0c0041 app:id/action_context_bar}
07-09 22:24:29.829 12200-12200/com.example.android.sunshine.app D/AndroidRuntime﹕ Shutting down VM
07-09 22:24:29.830 12200-12200/com.example.android.sunshine.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.android.sunshine.app, PID: 12200
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.sunshine.app/com.example.android.sunshine.app.DetailActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0c0051 (com.example.android.sunshine.app:id/container) for fragment DetailFragment{2a0c5022 #1 id=0x7f0c0051}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0051 (com.example.android.sunshine.app:id/container) for fragment DetailFragment{2a0c5022 #1 id=0x7f0c0051}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6006)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            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:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
07-09 22:24:32.288 12200-12209/com.example.android.sunshine.app W/art﹕ Suspending all threads took: 70.244ms
07-09 22:24:40.045 12200-12209/com.example.android.sunshine.app W/art﹕ Suspending all threads took: 5.676ms
Your DetailActivity has the lines:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment()).commit();
}
But your activity_detail.xml as you've posted doesn't have any id named container - in fact, it already has a Fragment directly in the layout. You should remove the lines from your DetailActivity's onCreate().
In activitydetail.xml change android:id="#+id/fragment" to android:"#+id/container"

Stuck, need help Program crashes whenever it tries to access the SharedPreferences

Program runs until it tries to access the SharedPreferences in my updateUserSettings() method. I have spent the last 2 hours searching the internet with no explanations. Please help!
I have the line that messes everything up Commented at the bottom of my onCreate();
Here is FuelEconomyCalculatorActivity.java
package com.example.fuelcalculator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class FuelEconomyCalculatorActivity extends ActionBarActivity implements
OnClickListener {
private EditText fuelEditText;
private EditText distanceEditText;
private TextView mpgTextView;
private TextView litresTextView;
private Button calculateButton;
private Button clearButton;
private RadioButton gallonsRadio;
private RadioButton litresRadio;
private RadioButton milesRadio;
private RadioButton kmRadio;
private String mpg = " ";
private String kp100 = " ";
private boolean metricChecked;
private boolean imperialChecked;
private boolean usGallonChecked;
private boolean ukGallonChecked;
private static final int RESULT_SETTINGS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fuel_economy_calculator);
fuelEditText = (EditText) findViewById(R.id.fuelEditText);
distanceEditText = (EditText) findViewById(R.id.distanceEditText);
mpgTextView = (TextView) findViewById(R.id.mpgTextView);
litresTextView = (TextView) findViewById(R.id.litresTextView);
calculateButton = (Button) findViewById(R.id.calculateButton);
clearButton = (Button) findViewById(R.id.clearButton);
gallonsRadio = (RadioButton) findViewById(R.id.gallonsRadio);
litresRadio = (RadioButton) findViewById(R.id.litresRadio);
milesRadio = (RadioButton) findViewById(R.id.milesRadio);
kmRadio = (RadioButton) findViewById(R.id.kmRadio);
calculateButton.setOnClickListener(this);
clearButton.setOnClickListener(this);
if (savedInstanceState != null) {
mpg = savedInstanceState.getString("mpg");
kp100 = savedInstanceState.getString("kp100");
initializeViews();
}
// updateUserSettings();
}
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("mpg", (String) mpgTextView.getText());
savedInstanceState.putString("kp100", (String) litresTextView.getText());
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
private void initializeViews() {
mpgTextView.setText(mpg);
litresTextView.setText(kp100);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fuel_economy_calculator, 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.
switch (item.getItemId()) {
case R.id.action_settings: {
Intent intent = new Intent(FuelEconomyCalculatorActivity.this,
FuelEconomySettingsActivity.class);
startActivityForResult(intent, RESULT_SETTINGS);
return true;
}
case R.id.action_about: {
Intent intent = new Intent(getApplicationContext(), FuelEconomyAboutPageActivity.class);
startActivity(intent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
updateUserSettings();
break;
}
}
private void updateUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
{
metricChecked = true;
imperialChecked = false;
}
else if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("imperial"))
{
imperialChecked = true;
metricChecked = false;
}
if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("uk"))
{
ukGallonChecked = true;
usGallonChecked = false;
}
else if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("us"))
{
usGallonChecked = true;
ukGallonChecked = false;
}
if(metricChecked)
{
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
else if(imperialChecked)
{
milesRadio.setChecked(true);
gallonsRadio.setChecked(true);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.calculateButton) {
float mpg = 0;
float kmLitres = 0;
// it doesn't matter which you use here, as long
// as you use a fuel and a distance method
if (ukGallonChecked && !usGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallons();
kmLitres = getLitres() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
} else if (usGallonChecked && !ukGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallonsUS();
kmLitres = getLitresUS() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
}
} else if (v.getId() == R.id.clearButton) {
resetValues();
}
}
public float CheckValues(EditText input) {
float value = 0;
try {
value = Float.parseFloat(input.getText().toString());
if (value < 1) {
Toast toast = Toast.makeText(this,
"Please enter a number that is larger than 0",
Toast.LENGTH_SHORT);
toast.show();
}
} catch (Exception ex) {
Toast toast = Toast.makeText(this, "Please enter a number",
Toast.LENGTH_SHORT);
toast.show();
}
return value;
}
public void resetValues() {
mpg = " ";
kp100 = " ";
fuelEditText.setText("");
distanceEditText.setText("");
mpgTextView.setText("");
litresTextView.setText("");
}
public float getKM() {
float distance = CheckValues(distanceEditText);
if (milesRadio.isChecked()) {
distance = (float) (distance * 1.60934);
}
return distance;
}
public float getMiles() {
float distance = CheckValues(distanceEditText);
if (kmRadio.isChecked()) {
distance = (float) (distance * 0.62137);
}
return distance;
}
public float getLitres() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 4.54609);
}
return fuel;
}
public float getLitresUS() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 3.785411784);
}
return fuel;
}
public float getGallons() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.219969);
}
return fuel;
}
public float getGallonsUS() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.264172);
}
return fuel;
}
}
And here is my FuelEconomySettingsActivity.java
package com.example.fuelcalculator;
import android.app.Activity;
import android.os.Bundle;
public class FuelEconomySettingsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new FuelEconomySettingsFragment()).commit();
}
}
Here is my LogCat
07-18 14:35:37.014: E/AndroidRuntime(3084): FATAL EXCEPTION: main
07-18 14:35:37.014: E/AndroidRuntime(3084): Process: com.example.fuelcalculator, PID: 3084
07-18 14:35:37.014: E/AndroidRuntime(3084): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fuelcalculator/com.example.fuelcalculator.FuelEconomyCalculatorActivity}: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.access$900(ActivityThread.java:161)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Handler.dispatchMessage(Handler.java:102)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Looper.loop(Looper.java:157)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.main(ActivityThread.java:5356)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invoke(Method.java:515)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-18 14:35:37.014: E/AndroidRuntime(3084): at dalvik.system.NativeStart.main(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): Caused by: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.updateUserSettings(FuelEconomyCalculatorActivity.java:128)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.onCreate(FuelEconomyCalculatorActivity.java:63)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Activity.performCreate(Activity.java:5426)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
07-18 14:35:37.014: E/AndroidRuntime(3084): ... 11 more
I am new to Android so I am not very good at debugging so could someone please assist me with my predicament?
The activity is already included in my Manifest so I know that is not the issue.
Any help is much obliged.
You are getting a NullPointerException because you are getting null as the default value for SharedPreference.getString()
Since it is getString() get an empty string as the default value...
So try this..
if(sharedPrefs.getString("measuringUnits", "").equalsIgnoreCase("metric"))
instead of
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))

Search bar to ListView return blank values and getFilter error

I need to add a search bar in my app, but all the tutorials I tried is not working. Because I want this bar to return the values ​​of my ListView imported from Excel (I applied in a way that the Activity shows the names of people). My ListView is imported from Excel, not created in-app code.
That is, when I search for "A" all the names of the ListView with "A" appears when I search "Arn", appear the names containing "Arn" (E.g. Arnold Clinton).
This is the code of TabelaActivity.java:
package com.akzonobel.malote.tabela;
import com.akzonobel.malote.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
public class TabelaActivity extends Activity {
CSVAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabela);
ListView mList = (ListView)findViewById(R.id.mList);
mAdapter = new CSVAdapter(this, -1);
mList.setAdapter(mAdapter);
}
}
This is the code of CSVAdapter.java:
package com.akzonobel.malote.tabela;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CSVAdapter extends ArrayAdapter<State>{
Context ctx;
public CSVAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.ctx = context;
loadArrayFromFile();
}
#Override
public View getView(final int pos, View convertView, final ViewGroup parent){
TextView mView = (TextView)convertView;
if(null == mView){
mView = new TextView(parent.getContext());
mView.setTextSize(19);
mView.setTextColor(Color.WHITE);
}
mView.setText(getItem(pos).getName());
return mView;
}
private void loadArrayFromFile(){
try {
InputStream is = ctx.getAssets().open("states.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
State cur = new State();
cur.setName(line);
this.add(cur);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the code of State.java:
package com.akzonobel.malote.tabela;
public class State {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I tried to apply this search bar:
EditText inputSearch;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
TabelaActivity.this.mAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
The search bar works, can you enter. But when I type the value... it just does not return anything, goes blank. Any help? How to make it work? Or is there another easy way to make a search bar? Can the ActionBar.. the important thing is it works.
Then I tried to apply the getFilter in CSVAdapter, but then when I try to use the bar with this getFilter, it crashes and closes alone.
This is the code I applied getFilter:
private List<State> allModelItemsArray;
private List<State> filteredModelItemsArray;
private Filter filter;
#Override
public Filter getFilter() {
if (filter == null){
filter = new ModelFilter();
}
return filter;
}
private class ModelFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = allModelItemsArray.size(); i < l; i++)
{
State m = allModelItemsArray.get(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = allModelItemsArray;
result.count = allModelItemsArray.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredModelItemsArray = (ArrayList<State>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = filteredModelItemsArray.size(); i < l; i++)
add(filteredModelItemsArray.get(i));
notifyDataSetInvalidated();
}
}
And when this is active getFilter, besides closing, it gives the following error in LogCat:
07-13 08:32:52.925: W/Filter(30254): An exception occured during performFiltering()!
07-13 08:32:52.925: W/Filter(30254): java.lang.NullPointerException
07-13 08:32:52.925: W/Filter(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.performFiltering(CSVAdapter.java:129)
07-13 08:32:52.925: W/Filter(30254): at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
07-13 08:32:52.925: W/Filter(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:32:52.925: W/Filter(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:32:52.925: W/Filter(30254): at android.os.HandlerThread.run(HandlerThread.java:60)
07-13 08:33:14.856: D/AndroidRuntime(30254): Shutting down VM
07-13 08:33:14.856: W/dalvikvm(30254): threadid=1: thread exiting with uncaught exception (group=0x41101930)
07-13 08:33:14.876: E/AndroidRuntime(30254): FATAL EXCEPTION: main
07-13 08:33:14.876: E/AndroidRuntime(30254): java.lang.NullPointerException
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.publishResults(CSVAdapter.java:156)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.app.ActivityThread.main(ActivityThread.java:5283)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invokeNative(Native Method)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invoke(Method.java:511)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-13 08:33:14.876: E/AndroidRuntime(30254): at dalvik.system.NativeStart.main(Native Method)
Add a constructor to the State class:
public State(String name) {
this.name = name;
}
Don't use the global allModelItemsArray and filteredItemsArray, get rid of them.
Then change your performFiltering function like this:
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
ArrayList<State> allItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
allItems.add(m);
}
synchronized(this)
{
result.values = allItems;
result.count = allItems.size();
}
}
return result;
}
This will work much better and is proper way to fix this.

Unable to start Activity ComponentInfo{} java.lang.nullPointerException

I'm still in the process of learning java, so I'm sorry if this question is too obvious. I'm trying to launch my app and it throws this error. The problem seems to be in the OnCreate() method, but I can't figure out what's causing it.
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String NAME = "nick.miros.famous.problems.MESSAGE";
public final static String EMAIL = "nick.miros.famous.problems.MESSAGE1";
public final static String STUFFSEX = "nick.miros.famous.problems.MESSAGE2";
public final static String BIRTHDAY = "nick.miros.famous.problems.MESSAGE3";
private boolean agreed;
private String sex;
public static String bornDate;
public EditText emailEdit;
public EditText nameEdit;
public EditText passwordEdit;
// public EditText passwordRepeatEdit;
public RadioGroup radioSex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEdit = (EditText) findViewById(R.id.name);
emailEdit = (EditText) findViewById(R.id.email);
passwordEdit = (EditText) findViewById(R.id.password);
// passwordRepeatEdit = (EditText) findViewById(R.id.passwordRepeat);
emailEdit.addTextChangedListener(new GenericTextWatcher(emailEdit));
nameEdit.addTextChangedListener(new GenericTextWatcher(nameEdit));
passwordEdit
.addTextChangedListener(new GenericTextWatcher(passwordEdit));
// passwordRepeatEdit.addTextChangedListener(new
// GenericTextWatcher(passwordRepeatEdit));
Button Go = (Button) findViewById(R.id.sendButton);
Go.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendAndCheck();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private String getSex(int id) {
switch (id) {
case R.id.radioMale:
sex = "Male";
break;
case R.id.radioFemale:
sex = "Female";
break;
}
return sex;
}
public void showThanks() {
Toast.makeText(this.getApplicationContext(), R.string.thank_you,
Toast.LENGTH_LONG).show();
}
public void onCheckBoxClicked(View view) {
// Is the view now checked?
agreed = ((CheckBox) findViewById(R.id.agreementBox)).isChecked();
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target)
.matches();
}
}
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
bornDate = Integer.toString(year) + "/" + Integer.toString(month)
+ "/" + Integer.toString(day);
}
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
/** Called when the user clicks the Send button */
public void sendAndCheck() {
CharSequence emailToCheck = ((EditText) findViewById(R.id.email))
.getText().toString();
if (agreed) {
// Do something in response to button
if (isValidEmail(emailToCheck)) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
String sent_name = ((EditText) findViewById(R.id.name))
.getText().toString();
String sent_email = ((EditText) findViewById(R.id.email))
.getText().toString();
int id = ((RadioGroup) findViewById(R.id.radioSex))
.getCheckedRadioButtonId();
String sent_sex = getSex(id);
String sent_birthday = bornDate;
intent.putExtra(NAME, sent_name);
intent.putExtra(EMAIL, sent_email);
intent.putExtra(STUFFSEX, sent_sex);
intent.putExtra(BIRTHDAY, sent_birthday);
startActivity(intent);
showThanks();
} else {
((EditText) findViewById(R.id.email)).setError("wrong email!");
}
} else {
AlertDialog.Builder Alert = new AlertDialog.Builder(this);
Alert.setMessage("Please agree with the terms and conditions first");
Alert.setTitle("Notice");
Alert.setPositiveButton("OK", null);
Alert.setCancelable(true);
Alert.create().show();
}
}
}
Here is the GenericTextWatcher:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
public class GenericTextWatcher implements TextWatcher{
private View view;
private PasswordValidator passwordValidator = new PasswordValidator();
String password = ((EditText) view).getText().toString();
GenericTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
String text = editable.toString();
switch(view.getId()){
case R.id.name:
if (!(text.equals("")))
{
}
else
{
((EditText) view).setError("wrong name!");
}
break;
case R.id.email:
CharSequence emailToCheck = ((EditText) view).getText().toString();
if (isValidEmail(emailToCheck))
{
}
else
{
((EditText) view).setError("wrong email!");
}
break;
case R.id.password:
if (passwordValidator.isValidPassword(text))
{
}
else
{
((EditText) view).setError("must have 1 uppercase letter, 1 number and be 6 characters long");
}
break;
/* case R.id.passwordRepeat:
String password = (((EditText) view) findViewById(R.id.password).getText().toString();
if (text.equals(password))
{
}
else
{
((EditText) view).setError("passwords don't match");
}
break;*/
}
}
public final static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target)
.matches();
}
}
public class PasswordValidator{
private Pattern pattern;
private Matcher matcher;
private static final String PASSWORD_PATTERN =
"((?=.*\\d)(?=.*[A-Z]).{6,20})";
public PasswordValidator(){
pattern = Pattern.compile(PASSWORD_PATTERN);
}
/**
* Validate password with regular expression
* #param password password for validation
* #return true valid password, false invalid password
*/
public boolean isValidPassword(String password){
matcher = pattern.matcher(password);
return matcher.matches();
}
}
}
Here is the LogCat:
02-04 03:59:14.267: D/dalvikvm(2400): GC_FOR_ALLOC freed 37K, 7% free 2640K/2820K, paused 1ms, total 34ms
02-04 03:59:14.267: I/dalvikvm-heap(2400): Grow heap (frag case) to 3.319MB for 635808-byte allocation
02-04 03:59:14.277: D/dalvikvm(2400): GC_FOR_ALLOC freed 2K, 6% free 3258K/3444K, paused 10ms, total 10ms
02-04 03:59:14.377: D/AndroidRuntime(2400): Shutting down VM
02-04 03:59:14.377: W/dalvikvm(2400): threadid=1: thread exiting with uncaught exception (group=0xb2eb7648)
02-04 03:59:14.377: E/AndroidRuntime(2400): FATAL EXCEPTION: main
02-04 03:59:14.377: E/AndroidRuntime(2400): java.lang.RuntimeException: Unable to start activity ComponentInfo{nick.miros.famous.problems/nick.miros.famous.problems.MainActivity}: java.lang.NullPointerException
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.os.Handler.dispatchMessage(Handler.java:99)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.os.Looper.loop(Looper.java:137)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.main(ActivityThread.java:5103)
02-04 03:59:14.377: E/AndroidRuntime(2400): at java.lang.reflect.Method.invokeNative(Native Method)
02-04 03:59:14.377: E/AndroidRuntime(2400): at java.lang.reflect.Method.invoke(Method.java:525)
02-04 03:59:14.377: E/AndroidRuntime(2400): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-04 03:59:14.377: E/AndroidRuntime(2400): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-04 03:59:14.377: E/AndroidRuntime(2400): at dalvik.system.NativeStart.main(Native Method)
02-04 03:59:14.377: E/AndroidRuntime(2400): Caused by: java.lang.NullPointerException
02-04 03:59:14.377: E/AndroidRuntime(2400): at nick.miros.famous.problems.GenericTextWatcher.<init>(GenericTextWatcher.java:15)
02-04 03:59:14.377: E/AndroidRuntime(2400): at nick.miros.famous.problems.MainActivity.onCreate(MainActivity.java:46)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.Activity.performCreate(Activity.java:5133)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-04 03:59:14.377: E/AndroidRuntime(2400): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-04 03:59:14.377: E/AndroidRuntime(2400): ... 11 more
There's a NullPointerException in GenericTextWatcher initialization (<init>), on line 15.
In there you have a member variable:
String password = ((EditText) view).getText().toString();
view is null at this point, you only assign it in constructor later. Move this code to constructor or later.

Unable to start activity ComponentInfo{MainFrag}: java.lang.NullPointerException

Hello I'm working on an application that is going to be android launcher there are three different screens in this launcher the first screen is a bookshelf that is supposed to import and Show all books in the SD card place on the device the second is a calculator (works just fine!) Third is a Homework page where you can make google drive docs and flashcards (also works fine!!) I get no errors when I run my code the app automatically crashes when it launches on my device and on the emulator.
Heres my Logcat:
11-23 15:05:06.314: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.084: E/Trace(3807): error opening trace file: No such file or directory (2)
11-23 15:05:15.254: E/AndroidRuntime(3807): FATAL EXCEPTION: main
11-23 15:05:15.254: E/AndroidRuntime(3807): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.d4a.tobias/it.gmariotti.android.examples.googleaccount.MainFrag}: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Looper.loop(Looper.java:137)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invoke(Method.java:511)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-23 15:05:15.254: E/AndroidRuntime(3807): at dalvik.system.NativeStart.main(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): Caused by: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.sibext.android_shelf.adapter.ShelfAdapter.setToListView(ShelfAdapter.java:70)
11-23 15:05:15.254: E/AndroidRuntime(3807): at it.gmariotti.android.examples.googleaccount.MainFrag.onCreate(MainFrag.java:78)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Activity.performCreate(Activity.java:5104)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
11-23 15:05:15.254: E/AndroidRuntime(3807): ... 11 more
11-23 15:05:15.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.824: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:07:05.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
Heres MainFrag.java:
package it.gmariotti.android.examples.googleaccount;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.ImportBooks;
import com.sibext.android_shelf.adapter.ShelfAdapter;
public class MainFrag extends FragmentActivity{
private MyAdapter mAdapter;
private ViewPager mPager;
//Shelf
private static final String TARGET_DIRECTORY = "mnt/sdcard/shelf/";
private ListView list;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainfrag);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
// titleIndicator.setViewPager(mPager);
// pts=(PagerTitleStrip)findViewById(R.id.pager_title_strip);
//Shelf
File dir = new File(TARGET_DIRECTORY);
if(!dir.exists()){
dir.mkdirs();
//past here
addBooksFromAssetsToCard();
}else{
String files[] = dir.list();
if(files.length == 0){
//past here
addBooksFromAssetsToCard();
}
}
list = (ListView)findViewById(R.id.list);
ShelfAdapter adapter = new ShelfAdapter(this, TARGET_DIRECTORY);
adapter.setToListView(list);
}
public static class MyAdapter extends FragmentPagerAdapter {
String arr[]={"Calculator","Books","Homework"};
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return arr[position];
}
#Override
public int getCount() {
return arr.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Calculator();
case 1:
return new Book();
case 2:
return new Homework();
default:
return null;
}
}
}
//Shelf
public void addBooksFromAssetsToCard(){
List<String> books;
try {
books = getBooksFromAsset(getApplicationContext());
for(String book : books){
copyFromAssets(book);
}
} catch (Exception e) {
}
}
public List<String> getBooksFromAsset(Context ctx) throws Exception
{
AssetManager assetManager =ctx.getAssets();
String[] files = assetManager.list("books");
List<String> it=Arrays.asList(files);
return it;
}
public void copyFromAssets(String book)
{
AssetManager assetManager = getAssets();
String[] files = null;
InputStream in = null;
OutputStream out = null;
//String filename = "filename.ext";
try
{
in = assetManager.open("books/"+book);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+"/shelf/"+book);
Log.d("Copying...", ""+book);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
Log.e("tag", "Failed to copy asset file: " + book, e);
}
}
public void copyFile(InputStream in, OutputStream out) throws Exception
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
Log.d("Copy_State", "Done...");
}
public void onImportClicked(View v){
Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(), ImportBooks.class);
startActivity(in);
}
}
EDIT ADDED Shelf Adapter.java :
package com.sibext.android_shelf.adapter;
import java.io.File;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.MainActivity;
import com.sibext.android_shelf.shelf.ShelfItem;
public class ShelfAdapter extends BaseAdapter {
private static final int ROW_COUNT_DEFAULT = 2;
private static final int ROW_COUNT_LAND_DEFAULT = 4;
private static final int ROW_HEIGHT_DEFAULT = 150;
private Context context;
private int rowCount = ROW_COUNT_DEFAULT;
private int rowCountLand = ROW_COUNT_LAND_DEFAULT;
private int rowHeight = ROW_HEIGHT_DEFAULT;
private SparseArray<LoadPreviewTask> taskPool;
private ArrayList<ShelfItem> items;
String PATH;
ShelfItem item;
public ShelfAdapter(Context context, String targetDir) {
this.context = context;
items = new ArrayList<ShelfItem>();
taskPool = new SparseArray<ShelfAdapter.LoadPreviewTask>();
if (targetDir == null || context == null) {
throw new NullPointerException("ShelfAdapter: wrong paramenters - " +
(targetDir == null ? "Target directory " : "Context ") + "is null");
}
File dir = new File(targetDir);
if(dir.exists() && dir.isDirectory()){
for(File f : dir.listFiles()){
if(f != null && f.getName().endsWith(".pdf")){
items.add(new ShelfItem(f));
}
}
}
}
public void setToListView(ListView list){
list.setDividerHeight(0);
list.setAdapter(this);
}
public void setRowCount(int rowCount, int rowCountLand) {
this.rowCount = rowCount;
this.rowCountLand = rowCountLand;
}
public void setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
}
#Override
public int getCount() {
int sub = getSubItemsCount();
return (int)(sub/getRowCount()) + (sub%getRowCount() == 0 ? 0 : 1);
}
public int getSubItemsCount(){
return items.size();
}
#Override
public ShelfItem getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = View.inflate(context, R.layout.shelf_row, null);
AbsListView.LayoutParams itemParams = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, rowHeight);
convertView.setLayoutParams(itemParams);
LinearLayout.LayoutParams subItemParams = getSubViewParams();
for(int i = 0; i < getRowCount(); i++){
View sub = getSubView(getSubPosition(position, i), null);
sub.setLayoutParams(subItemParams);
((ViewGroup)convertView).addView(sub);
holder.subViews.add(sub);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
for(int i = 0; i < holder.subViews.size(); i++){
getSubView(getSubPosition(position, i), holder.subViews.get(i));
}
}
return convertView;
}
public View getSubView(final int position, View convertView){
final SubViewHolder holder;
if(convertView == null){
convertView = View.inflate(context, R.layout.shelf_item, null);
holder = new SubViewHolder();
holder.img = (ImageView)convertView.findViewById(R.id.shelf_item_image);
convertView.setTag(holder);
} else {
holder = (SubViewHolder)convertView.getTag();
}
if(position >= getSubItemsCount()){
holder.img.setImageBitmap(null);
return convertView;
}
item = getItem(position);
PATH = item.getFile().getAbsolutePath();
Bitmap preview = item.getPreviewFromSD();
if(preview != null){
holder.img.setImageBitmap(preview);
} else {
holder.img.setImageResource(R.drawable.ic_launcher);
LoadPreviewTask task = taskPool.get(holder.hashCode());
if (task != null) {
task.cancel(true);
taskPool.remove(holder.hashCode());
task = null;
}
task = new LoadPreviewTask(holder, rowHeight);
taskPool.put(holder.hashCode(), task);
task.execute(item);
}
holder.img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ShelfItem si = items.get(position);
/*Toast.makeText(context, "Item #" + position+"\n"+si.getFile().getAbsolutePath(), Toast.LENGTH_SHORT).show();
*/
final CharSequence[] items = {"View", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Please choose:");
builder.setItems(items, new DialogInterface.OnClickListener() {
//Toast.makeText(getApplicationContext(), ""+items[0], Toast.LENGTH_SHORT).show();
public void onClick(DialogInterface dialog, int index) {
if(index == 0){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(si.getFile()),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}else if(index == 1){
File file = new File(si.getFile().getAbsoluteFile().toString());
boolean deleteStatus = file.delete();
if(deleteStatus){
Toast.makeText(context, "Deleted Successfully...", Toast.LENGTH_SHORT).show();
Intent in = new Intent(context, MainActivity.class);
context.startActivity(in);
}else{
Toast.makeText(context, "Unable to delete...", Toast.LENGTH_SHORT).show();
}
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
private int getSubPosition(int listItemPosition, int offset){
return listItemPosition * getRowCount() + offset;
}
private LinearLayout.LayoutParams getSubViewParams(){
LinearLayout.LayoutParams p = new LayoutParams(0, LayoutParams.MATCH_PARENT);
p.weight = 1f;
return p;
}
private int getRowCount() {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
? rowCount : rowCountLand;
}
private static class ViewHolder{
public ArrayList<View> subViews;
public ViewHolder() {
this.subViews = new ArrayList<View>();
}
}
private static class SubViewHolder{
public ImageView img;
}
private class LoadPreviewTask extends AsyncTask<ShelfItem, Void, Bitmap>{
private SubViewHolder holder;
private int rowHeight;
public LoadPreviewTask(SubViewHolder holder, int rowHeight) {
super();
this.holder = holder;
this.rowHeight = rowHeight;
}
#Override
protected Bitmap doInBackground(ShelfItem... params) {
ShelfItem item = (ShelfItem)params[0];
Bitmap preview = item.getPreview(rowHeight);
item.savePreview(preview);
return preview;
}
#Override
protected void onPostExecute(final Bitmap result) {
if(isCancelled()){
holder = null;
return;
}
holder.img.setImageBitmap(result);
taskPool.remove(holder.hashCode());
}
}
}
I'm still fairly new to Android so please don’t judge and any help will be greatly appreciated
Thanks in advance
list = (ListView)findViewById(R.id.list); returns null because your list is not created yet. Override the onViewCreated() and put your code in there.
Your problem is here: adapter.setToListView(list); should be something like: list.setAdapter(...) but you have another errors on ShelfAdapter.java, can you copy what you have written from line 65 to line 70?

Categories