sunshine app crashing on emulator - java

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"

Related

ExpandableListView won't inflate/initialise in fragment code

I keep getting a null pointer exception when ever I try to run a fragment that must use an expandable list view item. I'm guessing it has something to do with the fragment because the similar code runs on an activity.
Here is the error (Logcat) message:
11-02 14:11:27.136 12947-12947/com.example.vhuhwavho.ctistudentportal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vhuhwavho.ctistudentportal, PID: 12947
java.lang.NullPointerException
at com.example.vhuhwavho.ctistudentportal.ForYouFragment.onCreateView(ForYouFragment.java:117)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Here is the fragment code:
package com.example.vhuhwavho.ctistudentportal;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by Vhuhwavho on 2017/10/31.
*/
public class ForYouFragment extends Fragment {
// To keep track of the counter, we need to add a global variable to the project,
// along with a key for saving and restoring.
static final String KEY_STUDENT_NUMBER = "studentNumber";
String studentNumber = "";
private static final int CODE_GET_REQUEST = 1024;
private static final int CODE_POST_REQUEST = 1025;
private Button mSubmit;
private Context mContext;
private LayoutInflater mInflater;
private View view;
private List < String > listHeadings;
private List < String > image_urls;
private List < Bitmap > images;
private List < String > messages;
private LinkedHashMap < String, GroupInfo > gMessages = new LinkedHashMap < String, GroupInfo > ();
private ArrayList < GroupInfo > list = new ArrayList < GroupInfo > ();
private ExpandableListAdapter listAdapter;
private ExpandableListView simpleExpandableListView;
//Connectivity manage instance
private ConnectivityManager mConnMgr;
// Image view reference
private ImageView imageView;
int imageCounter = 0, imageCounterSize = 0;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.for_you_fragment, container, false);
String extraStr;
try {
extraStr = getArguments().getString("studentNumber");
Log.e("try studentNumber", "tried student number");
} catch (NullPointerException e) {
studentNumber = "PT2014-1282";
Log.e("catch studentNumber", "catched student number");
}
requestForYou();
//get reference of the ExpandableListView
simpleExpandableListView = (ExpandableListView) this.getActivity().findViewById(R.id.simpleExpandableListView);
if ( simpleExpandableListView == null )
Log.d("Null or Not", "simpleExpandableList == null");
// create the adapter by passing your ArrayList data
listAdapter = new ExpandableListAdapter (this.getActivity().getApplicationContext(), list);
// attach the adapter to the expandable list view
simpleExpandableListView.setAdapter(listAdapter);
//expand all the Groups
expandAll();
// setOnChildClickListener listener for child row click
simpleExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//get the group header
GroupInfo headerInfo = list.get(groupPosition);
//get the child info
ChildInfo detailInfo = headerInfo.getHeadingList().get(childPosition);
//display it or do something with it
Toast.makeText(getActivity(), " Clicked on :: " + headerInfo.getHeading()
+ "/" , Toast.LENGTH_LONG).show();
return false;
}
});
// setOnGroupClickListener listener for group heading click
simpleExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//get the group header
GroupInfo headerInfo = list.get(groupPosition);
//display it or do something with it
return false;
}
});
listHeadings = new ArrayList<>();
messages = new ArrayList<>();
image_urls = new ArrayList<>();
return view;
} // end of onCreateView method
// To receive notifications of application state change, 2 methods are needed
// the onSaveInstanceState() and onRestoreInstanceState() methods
#Override
public void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_STUDENT_NUMBER, studentNumber);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated (savedInstanceState);
if (savedInstanceState != null) {
studentNumber = savedInstanceState.getString(KEY_STUDENT_NUMBER);
}
}
// save the data before the activity closes
#Override
public void onPause () {
super.onPause();
SharedPreferences settings = this.getActivity().getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_STUDENT_NUMBER, studentNumber);
editor.commit();
}
//method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.expandGroup(i);
}
}
//method to collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.collapseGroup(i);
}
}
private void requestForYou () {
PerformNetworkRequest request = new PerformNetworkRequest(API.URL_REQUEST_FOR_YOU, CODE_GET_REQUEST);
request.execute();
}
private void refreshForYou( JSONArray forYou) throws JSONException {
for ( int i = 0; i < forYou.length(); i++ ) {
JSONObject whats_happening = forYou.getJSONObject(i);
String heading = whats_happening.getString( "heading" );
String image_url = whats_happening.getString( "url" );
String message = whats_happening.getString( "message" );
listHeadings.add ( heading ) ;
messages.add ( message );
image_urls.add ( image_url );
Log.d("ForYouFragment", "refreshForYou");
}
imageCounterSize = listHeadings.size();
if ( mConnMgr != null ) {
// Get active network info
NetworkInfo networkInfo = mConnMgr.getActiveNetworkInfo();
// If any active network is available and internet connection is available
if ( networkInfo != null && networkInfo.isConnected() ) {
for ( String url : image_urls ) {
// Start a new Image Download Async Task
new DownloadImageTask().execute( url );
}
} else {
// If network is off or internet is not available, inform the user
Toast.makeText(this.getActivity(), "Network not Available", Toast.LENGTH_SHORT).show();
}
}
Log.d("ForYouFragment", "Finished refreshForYou");
for ( int loadData = 0; loadData < imageCounterSize; loadData++ ) {
addMessage ( listHeadings.get( loadData ) , messages.get( loadData ) , images.get( loadData ));
}
}
//here we maintain our products in various departments
private int addMessage ( String heading, String message, Bitmap image ){
int groupPosition = 0;
//check the hash map if the group already exists
GroupInfo headerInfo = gMessages.get(heading);
//add the group if doesn't exists
if( headerInfo == null ) {
headerInfo = new GroupInfo();
headerInfo.setHeading(heading);
gMessages.put(heading, headerInfo);
list.add(headerInfo);
}
//get the children for the group
ArrayList<ChildInfo> productList = headerInfo.getHeadingList();
//size of the children list
int listSize = productList.size();
//add to the counter
listSize++;
//create a new child and add that to the group
ChildInfo detailInfo = new ChildInfo();
detailInfo.setSequence ( String.valueOf( listSize ) );
detailInfo.setMessage ( message );
productList.add ( detailInfo );
headerInfo.setHeadingList ( productList );
//find the group position inside the list
groupPosition = list.indexOf(headerInfo);
return groupPosition;
}
public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
String url;
HashMap < String, String > params; // Store the names of the subjects enrolled
int requestCode;
PerformNetworkRequest ( String URL, int code ) {
url = URL;
requestCode = code;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute( String s ) {
Log.d("fetchWhatsHappening", "onPostExecute Register Response: " + s.toString());
super.onPostExecute( s );
try {
JSONObject root_object = new JSONObject( s );
JSONArray array = root_object.getJSONArray("for_you");
Log.d("GET URL", "Checking URL... " + API.URL_REQUEST_FOR_YOU );
if (!root_object.getBoolean("error")) {
Toast.makeText( getActivity(), root_object.getString("message"), Toast.LENGTH_SHORT ).show();
refreshForYou ( array );
} else {
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
} // end of doInBackground method
} // end of PerformNetworkRequest class
/*--------------------------- Setting ListView and Downloading Images ------------------------*/
public class GroupInfo {
private String heading;
private Bitmap image;
private ArrayList < ChildInfo > list = new ArrayList < ChildInfo >();
public String getHeading() {
return heading;
}
public void setHeading ( String heading ) {
this.heading = heading;
}
public void setImage (Bitmap image) {
this.image = image;
}
public Bitmap getImage () {
return image;
}
public ArrayList < ChildInfo > getHeadingList() {
return list;
}
public void setHeadingList(ArrayList<ChildInfo> headingList) {
this.list = headingList;
}
}
public class ChildInfo {
private String sequence = "";
private String message = "";
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<GroupInfo> forYou;
public ExpandableListAdapter (Context applicationContext, ArrayList<GroupInfo> forYou ) {
this.context = context;
this.forYou = forYou;
inflater = ( LayoutInflater.from( applicationContext ) );
}
#Override
public Object getChild( int groupPosition, int childPosition ) {
ArrayList < ChildInfo > headingList = forYou.get(groupPosition).getHeadingList();
return headingList.get(childPosition);
}
#Override
public long getChildId( int groupPosition, int childPosition ) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View view, ViewGroup parent) {
view = inflater.inflate(R.layout.for_you_list_item, null);
ChildInfo detailInfo = (ChildInfo) getChild( groupPosition, childPosition );
TextView childItem = (TextView) view.findViewById( R.id.forYouMessage );
childItem.setText( detailInfo.getMessage().trim() );
return view;
}
#Override
public int getChildrenCount ( int groupPosition ) {
ArrayList < ChildInfo > headingList = forYou.get( groupPosition ).getHeadingList();
return headingList.size();
}
#Override
public Object getGroup(int groupPosition) {
return forYou.get(groupPosition);
}
#Override
public int getGroupCount() {
return forYou.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
view = inflater.inflate(R.layout.for_you_heading_list_view, null);
GroupInfo headerInfo = (GroupInfo) getGroup(groupPosition);
TextView heading = (TextView) view.findViewById(R.id.forYouHeading);
ImageView image = (ImageView) view.findViewById(R.id.forYouIcon);
heading.setText(headerInfo.getHeading().trim());
image.setImageBitmap(headerInfo.getImage());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
} // end of ExpandableListAdapter
private class DownloadImageTask extends AsyncTask < String, Void, Bitmap > {
#Override
protected Bitmap doInBackground(String... urls) {
return downloadImage ( urls[0] );
}
#Override
protected void onPostExecute (Bitmap bitmap) {
if ( imageCounter < imageCounterSize ) {
if (bitmap == null) {
Drawable vectorDrawable = ResourcesCompat.getDrawable(getActivity().getResources(), R.drawable.no_image, null);
Bitmap no_image = ((BitmapDrawable) vectorDrawable).getBitmap();
images.add(no_image);
}
else if (bitmap != null) { // Add the newly downloaded image to the list
images.add( bitmap );
}
imageCounter++;
}
} // end of onPostExecute
}
public Bitmap downloadImage (String path) {
final String TAG = "Download Task";
Bitmap bitmap = null;
InputStream inStream;
try {
// Create a URL Connection object and set its parameters
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// Set connection time out of 5 seconds
urlConn.setConnectTimeout(5000);
// Set connection time out of 2.5 seconds
urlConn.setReadTimeout(2500);
// Set HTTP request method
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
// Perform network request
inStream = urlConn.getInputStream();
// Convert the input stream to Bitmap object
bitmap = BitmapFactory.decodeStream(inStream);
} catch (MalformedURLException e) {
Log.e(TAG, "URL error : " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Download Failed : " + e.getMessage());}
return bitmap;
}
}
Here's the for_you_fragment.xml file with the ExpandableListView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ExpandableListView
android:id="#+id/simpleExpandableListView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:divider="#f00"
android:childDivider="#0f0"
android:dividerHeight="1dp" />
</RelativeLayout>
Here's the list_item.xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/forYouMessage"
android:textSize="16dip"
android:paddingLeft="10dp"
android:paddingStart="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Here is the list_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/forYouIcon"
android:layout_width="fill_parent"
android:layout_height="200dp" />
<TextView
android:id="#+id/forYouHeading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/forYouIcon"
android:text="..."
android:textStyle="bold" />
</RelativeLayout>
You are passing wrong context here:
//get reference of the ExpandableListView
simpleExpandableListView = (ExpandableListView) this.getActivity().findViewById(R.id.simpleExpandableListView);
You have to pass the view which you are inflating as follow:
simpleExpandableListView = (ExpandableListView) view.findViewById(R.id.simpleExpandableListView);

unable to start a service error in android

I have created a service in my application and called the function that starts the service using a button using onClick in xml but the app crashes.
some help will be appreciated.
package slide.apptech.com.nav;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.Nullable;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.design.widget.FloatingActionButton;
import java.util.ArrayList;
import java.util.Calendar;
import static java.util.Calendar.*;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static String TAG = MainActivity.class.getSimpleName();
private Intent myIntent;
Button Refresh;
TextView updated;
//related to main screen list view
ListView lv;
Context context;
ArrayList prgmName;
public static int [] prgmImages={R.drawable.temp,R.drawable.hum,R.drawable.press,R.drawable.amb,R.drawable.alt};
public static String [] prgmNameList={" Temperature: "," Humidity: "," Pressure: "," Ambient Light:"," Altitude: "};
//GetFromServer gs1=new GetFromServer();
public String [] prgmVal={"1","2","3","4","5"};
public static String [] prgmUnit={" °C"," %"," hPa"," lx"," m"};
//public String datentime=gs1.DateNTime[0];
String datentime;
//boolean variable to indicate if the arrays have been set or not
Boolean arraysset;
GetFromServer gs1;
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
//these lines overite all the warnings by android to restrict large tasks
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
lv = (ListView) findViewById(R.id.listView);
updated=(TextView)findViewById((R.id.datentime));
Refresh = (Button) findViewById(R.id.refresh);
//block related to main screen list view
//creating a object from getfromserver class to give a request to server
gs1=new GetFromServer();
new loadSomeStuff().execute();
updated.setText(datentime);
prgmVal[0]=Double.toString(gs1.Temperature[0]);
prgmVal[1]=Double.toString(gs1.Humidity[0]);
prgmVal[2]=Double.toString(gs1.Pressure[0]);
prgmVal[3]=Double.toString(gs1.Ambient[0]);
prgmVal[4]=Double.toString(gs1.Altitude[0]);
datentime="Updated on :"+gs1.DateNTime[0];
context = this;
//this adapter is defined in custom adapter
// see class for all the constructors
lv.setAdapter(new CustomAdapter(MainActivity.this, MainActivity.prgmNameList, MainActivity.prgmImages, prgmVal, MainActivity.prgmUnit));
//code related to refresh button the main screen find xml in content_main
Refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(new Intent(getBaseContext(),service.class));
//Toast.makeText(context, "Please wait!", Toast.LENGTH_LONG).show();
gs1 = new GetFromServer();
gs1.sendData();
gs1.setArray();
//codeline to start athe service
prgmVal[0] = Double.toString(gs1.Temperature[0]);
prgmVal[1] = Double.toString(gs1.Humidity[0]);
prgmVal[2] = Double.toString(gs1.Pressure[0]);
prgmVal[3] = Double.toString(gs1.Ambient[0]);
prgmVal[4] = Double.toString(gs1.Altitude[0]);
String datentime = "Updated on :" + gs1.DateNTime[0];
updated.setText(datentime);
context = MainActivity.this;
lv.setAdapter(new CustomAdapter(MainActivity.this, MainActivity.prgmNameList, MainActivity.prgmImages, prgmVal, MainActivity.prgmUnit));
//Toast.makeText(context, "Refreshed!!!", Toast.LENGTH_LONG).show();
}
});
//this code is for a floation button see xml
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this,Faq.class);
startActivity(myIntent);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
//this is code related to back button in action bar to close drawer if open else go back to previous activity
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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);
}
//app crash due to following code
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.liConnection) {
drawer.closeDrawer(GravityCompat.START);
Intent myIntent = new Intent(MainActivity.this, Connect.class);
startActivity(myIntent);
}
else if (id == R.id.liRanges){
drawer.closeDrawer(GravityCompat.START);
Intent myIntent = new Intent(MainActivity.this, Ranges.class);
startActivity(myIntent);
}
else if (id == R.id.liSupport) {
drawer.closeDrawer(GravityCompat.START);
Intent myIntent = new Intent(MainActivity.this, Support.class);
startActivity(myIntent);
}
else if (id == R.id.liAbout) {
drawer.closeDrawer(GravityCompat.START);
Intent myIntent = new Intent(MainActivity.this, AboutUs.class);
startActivity(myIntent);
}
else if (id == R.id.liRateus) {
drawer.closeDrawer(GravityCompat.START);
Intent myIntent = new Intent(MainActivity.this,Rateus.class);
startActivity(myIntent);
}
return true;
}
public void getPosition(int position) {
if (position == 0) {
//code specific to first list item
myIntent = new Intent(MainActivity.this, ChartTemperature.class); //replace connect classs with analysis
startActivity(myIntent);
}
else if (position == 1) {
//code specific to first list item
Intent myIntent = new Intent(MainActivity.this, ChartHumidity.class);
startActivity(myIntent);
}
else if (position == 2) {
//code specific to first list item
Intent myIntent = new Intent(MainActivity.this, ChartPressure.class);
startActivity(myIntent);
}
else if (position == 3) {
//code specific to first list item
Intent myIntent = new Intent(MainActivity.this, ChartAmbient.class);
startActivity(myIntent);
}
else if (position == 4) {
//code specific to first list item
Intent myIntent = new Intent(MainActivity.this, ChartAltitude.class);
startActivity(myIntent);
}
}
// Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), service.class));
}
//here we are creating a async task to reduce load on oncreate method
public class loadSomeStuff extends AsyncTask<String, Integer, Void> {
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try {
gs1.sendData();
gs1.setArray();
prgmVal[0]=Double.toString(gs1.Temperature[0]);
prgmVal[1]=Double.toString(gs1.Humidity[0]);
prgmVal[2]=Double.toString(gs1.Pressure[0]);
prgmVal[3]=Double.toString(gs1.Ambient[0]);
prgmVal[4]=Double.toString(gs1.Altitude[0]);
datentime="Updated on :"+gs1.DateNTime[0];
arraysset = true;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
service.java
package slide.apptech.com.nav;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
/**
* Created by MOHIT on 17-04-2016.
*/
public class service extends Service{
//creating a server class object
GetFromServer gs1;
//creating a database object
database record;
String value;
boolean tempflag,pressflag,humflag,lightflag;
double temperature,humidity,pressure,light,max,min;
NotificationManager manager;
Notification myNotication;
Context context;
MainActivity main;
public final String UPDATE_DATA = "update";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(context, "Service Started in onStartCommand", Toast.LENGTH_LONG).show();
if(intent.getAction().equals(UPDATE_DATA)){
Toast.makeText(context, "Service Started in onStartCommand", Toast.LENGTH_LONG).show();
//getandcheck();
}
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void getandcheck(){
//getting the values from server
gs1 = new GetFromServer();
gs1.sendData();
gs1.setArray();
//setting variables to latest sensor values
temperature = gs1.Temperature[0];
humidity = gs1.Humidity[0];
pressure = gs1.Pressure[0];
light = gs1.Ambient[0];
record.open();
//making function calls to setup flags
checktemp();
checkhum();
checkpress();
checklight();
//if any flag is true the it means that readings are out of range
if(tempflag == true){
String readings = ("Temperature : " + temperature +" °C");
final Notification.Builder builder = new Notification.Builder(service.this);
builder.setStyle(new Notification.BigTextStyle(builder)
.bigText(readings)
.setBigContentTitle("WSstation")
.setSummaryText("Alert!!!"))
.setContentTitle("WSstation")
.setContentText("Your Temperature Readings are out of range")
.setSmallIcon(R.drawable.auicon);
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, builder.build());
}
if(pressflag == true){
String readings = ("Pressure : " + pressure +" hpa");
final Notification.Builder builder = new Notification.Builder(service.this);
builder.setStyle(new Notification.BigTextStyle(builder)
.bigText(readings)
.setBigContentTitle("WSstation")
.setSummaryText("Alert!!!"))
.setContentTitle("WSstation")
.setContentText("Your Pressure Readings are out of range")
.setSmallIcon(R.drawable.auicon);
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, builder.build());
}
if(humflag == true){
String readings = ("Humidity : " + humidity +" %");
final Notification.Builder builder = new Notification.Builder(service.this);
builder.setStyle(new Notification.BigTextStyle(builder)
.bigText(readings)
.setBigContentTitle("WSstation")
.setSummaryText("Alert!!!"))
.setContentTitle("WSstation")
.setContentText("Your Humidity Readings are out of range")
.setSmallIcon(R.drawable.auicon);
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, builder.build());
}
if(lightflag == true){
String readings = ("Ambient Light : " + light +" lx");
final Notification.Builder builder = new Notification.Builder(service.this);
builder.setStyle(new Notification.BigTextStyle(builder)
.bigText(readings)
.setBigContentTitle("WSstation")
.setSummaryText("Alert!!!"))
.setContentTitle("WSstation")
.setContentText("Your Ambient Light Readings are out of range")
.setSmallIcon(R.drawable.auicon);
final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, builder.build());
}
}
public void checktemp(){
//for temperature checking
value = record.getMax(1);
max = Double.parseDouble(value);
value = record.getMin(1);
min = Double.parseDouble(value);
if((temperature < min ) || (temperature > max)){
tempflag = true;
}
else{
tempflag = false;
}
}
public void checkhum(){
//for humidity checking
value = record.getMax(3);
max = Double.parseDouble(value);
value = record.getMin(3);
min = Double.parseDouble(value);
if((humidity < min ) || (humidity > max)){
humflag = true;
}
else{
humflag = false;
}
}
public void checkpress(){
//for pressure checking
value = record.getMax(2);
max = Double.parseDouble(value);
value = record.getMin(2);
min = Double.parseDouble(value);
if((pressure < min ) || (pressure > max)){
pressflag = true;
}
else{
pressflag = false;
}
}
public void checklight(){
//for ambient light checking
value = record.getMax(4);
max = Double.parseDouble(value);
value = record.getMin(4);
min = Double.parseDouble(value);
if((light < min ) || (light > max)){
lightflag = true;
}
else{
lightflag = false;
}
}
/*#Override
public void onCreate() {
super.onCreate();
Toast.makeText(context, "Service Started in oncreate", Toast.LENGTH_LONG).show();
}*/
}
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="slide.apptech.com.nav.MainActivity"
tools:showIn="#layout/app_bar_main">
<RelativeLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#004D40">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#004D40"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Home"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<!--<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textStyle="bold"
android:text=" Computer Languages..." />
-->
<ListView
android:paddingTop="60dp"
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="376dp"
android:layout_above="#+id/datentime">
</ListView>
<TextView
android:paddingTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Updated:"
android:textColor="#FFEB3B"
android:id="#+id/datentime"
android:layout_gravity="center_horizontal" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Refresh"
android:id="#+id/refresh"
android:layout_gravity="center_horizontal"
android:onClick="startService"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
logcat
04-20 20:15:18.623 27500-27500/slide.apptech.com.nav E/MotionRecognitionManager: mSContextService = null
04-20 20:15:18.628 27500-27500/slide.apptech.com.nav E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#28c858d
04-20 20:15:24.578 27500-27500/slide.apptech.com.nav E/AndroidRuntime: FATAL EXCEPTION: main
Process: slide.apptech.com.nav, PID: 27500
java.lang.RuntimeException: Unable to start service slide.apptech.com.nav.service#1aa1fa82 with Intent { cmp=slide.apptech.com.nav/.service }: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3978)
at android.app.ActivityThread.access$2300(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1803)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6912)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at slide.apptech.com.nav.service.onStartCommand(service.java:33)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3961)
at android.app.ActivityThread.access$2300(ActivityThread.java:211) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1803) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:6912) 
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:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
The intent you are checking in service.onStartCommand does not have an action. Change this
if(intent.getAction().equals(UPDATE_DATA)){
Toast.makeText(context, "Service Started in onStartCommand", Toast.LENGTH_LONG).show();
//getandcheck();
}
into this
if(intent.getAction() != null && intent.getAction().equals(UPDATE_DATA)){
Toast.makeText(context, "Service Started in onStartCommand", Toast.LENGTH_LONG).show();
//getandcheck();
}
UPDATE
To still show the toast you could put an extra boolean in your intent and check for this in your service. Start your service like this
startService(new Intent(getBaseContext(),service.class).putExtra("show_toast", true));
And check for it in your service like this
if (intent.getBooleanExtra("show_toast", false)) {
Toast.makeText(context, "Service Started in onStartCommand", Toast.LENGTH_LONG).show();
//getandcheck();
}
Looks like you didn't specify an action for the intent and you are getting a null pointer because of that.
Also be sure that you check the String constant against the object value to avoid null pointer exceptions.
UPDATE_DATA.equals(intent.getAction())

Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to implement DropDownMenu https://github.com/JayFang1993/DropDownMenu
I've got a problem with this code :
MainActivity
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import com.jayfang.dropdownmenu.DropDownMenu;
import com.jayfang.dropdownmenu.OnMenuSelectedListener;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionMenu;
import com.oguzdev.circularfloatingactionmenu.library.SubActionButton;
import com.sai.eventee.rss.ServiceStarter;
import com.sai.eventee.util.ScrimInsetsFrameLayout;
import com.sai.eventee.web.WebviewFragment;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
NavDrawerCallback {
private Toolbar mToolbar;
private NavDrawerFragment mNavigationDrawerFragment;
public static String DATA = "transaction_data";
public static String EMBEDD_DATA = "embedd";
SharedPreferences prefs;
boolean openedByBackPress = false;
//=======================================================
private DropDownMenu mMenu;
private ListView mList;
private int city_index;
private int sex_index;
private int age_index;
private List<String> data;
final String[] arr1=new String[]{"全部城市","北京","上海","广州","深圳"};
final String[] arr2=new String[]{"性别","男","女"};
final String[] arr3=new String[]{"全部年龄","10","20","30","40","50","60","70"};
final String[] strings=new String[]{"选择城市","选择性别","选择年龄"};
private FloatingActionButton mFAB;
private FloatingActionMenu mFABMenu;
//=======================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupFAB();
boolean newDrawer = getResources().getBoolean(R.bool.newdrawer);
if (newDrawer == true) {
setContentView(R.layout.activity_main_alternate);
} else {
setContentView(R.layout.activity_main);
Helper.setStatusBarColor(MainActivity.this, getResources()
.getColor(R.color.myPrimaryDarkColor));
}
mMenu=(DropDownMenu)findViewById(R.id.menu);
mMenu.setmMenuCount(3);
mMenu.setmShowCount(6);
mMenu.setShowCheck(true);
mMenu.setmMenuTitleTextSize(16);
mMenu.setmMenuTitleTextColor(Color.parseColor("#777777"));
mMenu.setmMenuListTextSize(16);
mMenu.setmMenuListTextColor(Color.BLACK);
mMenu.setmMenuBackColor(Color.parseColor("#eeeeee"));
mMenu.setmMenuPressedBackColor(Color.WHITE);
mMenu.setmMenuPressedTitleTextColor(Color.BLACK);
mMenu.setmCheckIcon(R.drawable.ico_make);
mMenu.setmUpArrow(R.drawable.arrow_up);
mMenu.setmDownArrow(R.drawable.arrow_down);
mMenu.setDefaultMenuTitle(strings);
mMenu.setShowDivider(false);
mMenu.setmMenuListBackColor(getResources().getColor(R.color.white));
mMenu.setmMenuListSelectorRes(R.color.white);
mMenu.setmArrowMarginTitle(20);
mMenu.setMenuSelectedListener(new OnMenuSelectedListener() {
#Override
public void onSelected(View listview, int RowIndex, int ColumnIndex) {
Log.i("MainActivity", "select " + ColumnIndex + " column and " + RowIndex + " row");
if (ColumnIndex == 0) {
city_index = RowIndex;
} else if (ColumnIndex == 1) {
sex_index = RowIndex;
} else {
age_index = RowIndex;
}
//过滤筛选
setFilter();
}
});
List<String[]> items = new ArrayList<>();
items.add(arr1);
items.add(arr2);
items.add(arr3);
mMenu.setmMenuItems(items);
mMenu.setIsDebug(false);
mList=(ListView)findViewById(R.id.lv_list);
data=getData();
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, data));
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mNavigationDrawerFragment = (NavDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_drawer);
if (newDrawer == true) {
mNavigationDrawerFragment.setup(R.id.scrimInsetsFrameLayout,
(DrawerLayout) findViewById(R.id.drawer), mToolbar);
mNavigationDrawerFragment
.getDrawerLayout()
.setStatusBarBackgroundColor(
getResources().getColor(R.color.myPrimaryDarkColor));
((ScrimInsetsFrameLayout) findViewById(R.id.scrimInsetsFrameLayout)).getLayoutParams().width = getDrawerWidth();
} else {
mNavigationDrawerFragment.setup(R.id.fragment_drawer,
(DrawerLayout) findViewById(R.id.drawer), mToolbar);
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mNavigationDrawerFragment.getView().getLayoutParams();
params.width = getDrawerWidth();
mNavigationDrawerFragment.getView().setLayoutParams(params);
}
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
// setting push enabled
String push = getString(R.string.rss_push_url);
if (null != push && !push.equals("")) {
// Create object of SharedPreferences.
boolean firstStart = prefs.getBoolean("firstStart", true);
if (firstStart) {
final ServiceStarter alarm = new ServiceStarter();
SharedPreferences.Editor editor = prefs.edit();
alarm.setAlarm(this);
// now, just to be sure, where going to set a value to check if
// notifications is really enabled
editor.putBoolean("firstStart", false);
// commits your edits
editor.commit();
}
}
// Checking if the user would prefer to show the menu on start
boolean checkBox = prefs.getBoolean("menuOpenOnStart", false);
if (checkBox == true) {
mNavigationDrawerFragment.openDrawer();
}
// New imageloader
Helper.initializeImageLoader(this);
}
private void setFilter(){
List<String> temp=new ArrayList<String>();
for (int i=0;i<getData().size();i++){
boolean city=((city_index==0)?true:data.get(i).contains(arr1[city_index]));
boolean sex=((sex_index==0)?true:data.get(i).contains(arr2[sex_index]));
boolean age=((age_index==0)?true:data.get(i).contains(arr3[age_index]));
if(city && sex && age){
temp.add(data.get(i));
}
}
mList.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1,temp));
}
private List<String> getData(){
List<String> data = new ArrayList<String>();
data.add("上海-男-10");
data.add("上海-男-20");
data.add("上海-男-30");
data.add("上海-男-40");
data.add("上海-男-50");
data.add("上海-男-60");
data.add("上海-男-70");
data.add("广州-男-10");
data.add("广州-女-10");
data.add("北京-男-20");
data.add("北京-女-10");
data.add("广州-男-10");
data.add("北京-男-10");
data.add("广州-男-10");
data.add("上海-女-60");
data.add("上海-女-20");
return data;
}
private void setupFAB() {
//define the icon for the main floating action button
ImageView iconFAB = new ImageView(this);
iconFAB.setImageResource(R.drawable.ic_action_new);
//set the appropriate background for the main floating action button along with its icon
mFAB = new FloatingActionButton.Builder(this)
.setContentView(iconFAB)
.setBackgroundDrawable(R.drawable.selector_button_red)
.build();
//define the icons for the sub action buttons
ImageView iconSortName = new ImageView(this);
iconSortName.setImageResource(R.drawable.ic_action_alphabets);
ImageView iconSortDate = new ImageView(this);
iconSortDate.setImageResource(R.drawable.ic_action_calendar);
ImageView iconSortRatings = new ImageView(this);
iconSortRatings.setImageResource(R.drawable.ic_action_important);
//set the background for all the sub buttons
SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
itemBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_sub_button_gray));
//build the sub buttons
SubActionButton buttonSortName = itemBuilder.setContentView(iconSortName).build();
SubActionButton buttonSortDate = itemBuilder.setContentView(iconSortDate).build();
SubActionButton buttonSortRatings = itemBuilder.setContentView(iconSortRatings).build();
/*
//to determine which button was clicked, set Tags on each button
buttonSortName.setTag(TAG_SORT_NAME);
buttonSortDate.setTag(TAG_SORT_DATE);
buttonSortRatings.setTag(TAG_SORT_RATINGS);
buttonSortName.setOnClickListener(this);
buttonSortDate.setOnClickListener(this);
buttonSortRatings.setOnClickListener(this);
*/
//add the sub buttons to the main floating action button
mFABMenu = new FloatingActionMenu.Builder(this)
.addSubActionView(buttonSortName)
.addSubActionView(buttonSortDate)
.addSubActionView(buttonSortRatings)
.attachTo(mFAB)
.build();
}
//===============================================================================*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.rss_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onNavigationDrawerItemSelected(int position, NavItem item) {
Fragment fragment;
try {
fragment = item.getFragment().newInstance();
if (fragment != null) {
Bundle bundle = new Bundle();
String extra;
String license = getResources().getString(R.string.google_play_license);
// if item does not require purchase, or app has purchased, or license is null/empty (app has no in app purchases)
if (item.requiresPurchase() == true
&& !SettingsFragment.getIsPurchased(this)
&& null != license && !license.equals("")) {
fragment = new SettingsFragment();
extra = SettingsFragment.SHOW_DIALOG;
} else {
extra = item.getData();
}
bundle.putString(DATA, extra);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).commit();
setTitle(item.getText());
if (null != MainActivity.this.getSupportActionBar()
&& null != MainActivity.this.getSupportActionBar()
.getCustomView()) {
MainActivity.this.getSupportActionBar().setDisplayOptions(
ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_TITLE);
}
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
Fragment webview = getSupportFragmentManager().findFragmentById(
R.id.container);
if (mNavigationDrawerFragment.isDrawerOpen()) {
mNavigationDrawerFragment.closeDrawer();
} else if (webview instanceof WebviewFragment) {
boolean goback = ((WebviewFragment) webview).canGoBack();
if (!goback)
super.onBackPressed();
} else {
super.onBackPressed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment frag : fragments)
frag.onActivityResult(requestCode, resultCode, data);
}
}
private int getDrawerWidth(){
// Navigation Drawer layout width
int width = getResources().getDisplayMetrics().widthPixels;
TypedValue tv = new TypedValue();
int actionBarHeight;
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
} else {
actionBarHeight = 0;
}
int possibleMinDrawerWidth = width - actionBarHeight;
int maxDrawerWidth = getResources().getDimensionPixelSize(R.dimen.drawer_width);
return Math.min(possibleMinDrawerWidth, maxDrawerWidth);
}
}
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_actionbar">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.jayfang.dropdownmenu.DropDownMenu
android:orientation="horizontal"
android:layout_width="fill_parent"
android:id="#+id/menu"
android:background="#color/ripple_material_dark"
android:layout_height="60dp"/>
<ListView
android:layout_width="fill_parent"
android:layout_below="#id/menu"
android:id="#+id/lv_list"
android:background="#ffffff"
android:layout_height="wrap_content"></ListView>
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="#+id/fragment_drawer"
android:name="com.sai.eventee.NavDrawerFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/drawer_fragment"
tools:layout="#layout/drawer_fragment" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
And Logcat:
10-04 22:48:47.884 27075-27075/com.sai.eventee E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.sai.eventee, PID: 27075
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sai.eventee/com.sai.eventee.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
at android.app.ActivityThread.access$800(ActivityThread.java:176)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5576)
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:955)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jayfang.dropdownmenu.DropDownMenu.setmMenuCount(int)' on a null object reference
at com.sai.eventee.MainActivity.onCreate(MainActivity.java:90)
at android.app.Activity.performCreate(Activity.java:6005)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2446)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2555)
            at android.app.ActivityThread.access$800(ActivityThread.java:176)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1437)
            at android.os.Handler.dispatchMessage(Handler.java:111)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5576)
            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:955)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:750)
I have no idea why I get a null pointer exception.
It means that findViewById(R.id.activity_main_alternate) returns null for mMenu. Does your activity_main_alternate.xml have the R.id.menu view?

Android Studio "Unfortunately my project has stopped"

The project itself does not report any error, but when I run my project with the emulator, it popped up "Unfortunately project has stopped", can anyone look at my project and know what error is? I got following logcat error:
Process: edu.drexel.weatherundergroundapi, PID: 1800
java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.drexel.weatherundergroundapi/edu.drexel.weatherundergroundapi.MainActivity}: java.lang.NullPointerException: storage == null
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: storage == null
at java.util.Arrays$ArrayList.<init>(Arrays.java:38)
at java.util.Arrays.asList(Arrays.java:155)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
at edu.drexel.weatherundergroundapi.CustomListAdapter.<init>(CustomListAdapter.java:35)
at edu.drexel.weatherundergroundapi.MainActivity.onCreate(MainActivity.java:25)
at android.app.Activity.performCreate(Activity.java:5933)
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)
There are three java classes and three xml files: 1. MainActivity.java 2. CustomListAdapter.java 3. MyBgTask.java 4. listView.xml
5. activity_main.xml
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyBgTask asyncTask = new MyBgTask();
CustomListAdapter adapter = new CustomListAdapter(this, asyncTask.getTimeArray(), asyncTask.getConditionArray(),
asyncTask.getTempArray(), asyncTask.getHumidityArray(), asyncTask.getUrls());
ListView list = (ListView) findViewById(R.id.listView);
list.setAdapter(adapter);
asyncTask.execute();
}
/*public void onListItemClick(ListView lv, View view, int position, int imgid) {
String Slecteditem= (String)getListAdapter().getItem(position);
Toast.makeText(this, Slecteditem, Toast.LENGTH_SHORT).show();
}*/
#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);
}
}
CustomListAdapter.java:
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] time;
private final String[] condition;
private final String[] temp;
private final String[] humidity;
private final String[] url;
public CustomListAdapter(Activity context, String[] time, String[] condition, String[] temp, String[] humidity, String[] url)
{
super(context, R.layout.listview, time);
this.context = context;
this.time = time;
this.condition = condition;
this.temp = temp;
this.humidity = humidity;
this.url = url;
}
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Error getting bitmap", e.toString());
}
return bm;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.listview, null, true);
TextView timeView = (TextView) rowView.findViewById(R.id.dateTime);
TextView conditionView = (TextView) rowView.findViewById(R.id.condition);
TextView tempView = (TextView) rowView.findViewById(R.id.temp);
TextView humidityView = (TextView) rowView.findViewById(R.id.humidity);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
timeView.setText(time[position]);
conditionView.setText(condition[position]);
tempView.setText(temp[position]);
humidityView.setText(humidity[position]);
imageView.setImageBitmap(getImageBitmap(url[position]));
return rowView;
}
}
MyBgTask.java
public class MyBgTask extends AsyncTask<Void, Void, Void> {
String[] timeArray;
String[] conditionArray;
String[] tempArray;
String[] humidityArray;
String[] urls;
public String[] getTimeArray() {
return timeArray;
}
public String[] getConditionArray() {
return conditionArray;
}
public String[] getTempArray() {
return tempArray;
}
public String[] getHumidityArray() {
return humidityArray;
}
public String[] getUrls() {
return urls;
}
#Override
protected Void doInBackground(Void... params) {
try {
// Get User Current Location
String geoURL = "http://api.wunderground.com/api/56419d324b9bf190/geolookup/q/autoip.json";
URL url = new URL(geoURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
request.getContent();
JsonParser geo_jp = new JsonParser();
JsonElement geo_root = geo_jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject geo_rootobj = geo_root.getAsJsonObject();
String city = geo_rootobj.get("location").getAsJsonObject().get("city").getAsString();
String state = geo_rootobj.get("location").getAsJsonObject().get("state").getAsString();
String zip = geo_rootobj.get("location").getAsJsonObject().get("zip").getAsString();
// Invoke hourly weather forcast with user's current location
String forecastURL = "http://api.wunderground.com/api/56419d324b9bf190/conditions/hourly/forecast/q/" + zip + ".json";
URL furl = new URL(forecastURL);
HttpURLConnection forecastRequest = (HttpURLConnection) furl.openConnection();
forecastRequest.connect();
forecastRequest.getContent();
JsonParser forecast_jp = new JsonParser();
JsonElement forecast_root = forecast_jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray forecast_array = forecast_root.getAsJsonObject().get("hourly_forcast").getAsJsonArray();
for (int hour = 0; hour < forecast_array.size(); hour++) {
String month = forecast_array.get(hour).getAsJsonObject().
get("FCTTIME").getAsJsonObject().
get("mon_abbrev").getAsString();
String monthDay = forecast_array.get(hour).getAsJsonObject().
get("FCTTIME").getAsJsonObject().
get("mday_padded").getAsString();
String time = forecast_array.get(hour).getAsJsonObject().
get("FCTTIME").getAsJsonObject().
get("civil").getAsString();
String dateAndtime = month + " " + monthDay + " " + time;
String condition = forecast_array.get(hour).getAsJsonObject().
get("condition").getAsString();
String temp = forecast_array.get(hour).getAsJsonObject().
get("temp").getAsJsonObject().
get("english").getAsString();
String humidity = forecast_array.get(hour).getAsJsonObject().
get("humidity").getAsString();
String icon_url = forecast_array.get(hour).getAsJsonObject().
get("icon_url").getAsString();
timeArray[hour] = dateAndtime;
conditionArray[hour] = condition;
tempArray[hour] = temp;
humidityArray[hour] = humidity;
urls[hour] = icon_url;
}
} catch (IOException e) {
Log.e("ERROR", e.toString());
}
return null;
}
protected void onPostExecute(Void... params) {
}
}
listView.xml
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/dateTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#33CC33"
android:text="#string/dateTime" />
<TextView
android:id="#+id/condition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/condition"
android:layout_marginLeft="10dp"/>
<TextView
android:id="#+id/temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/temp"
android:layout_marginLeft="10dp" />
<TextView
android:id="#+id/humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/humidity"
android:layout_marginLeft="10dp" />
</LinearLayout>
activity_main.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="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".main">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:clickable="false"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" >
</ListView>
Based on what I can see, the program crashes because time is null at this line:
public CustomListAdapter(Activity context, String[] time, String[] condition, String[] temp, String[] humidity, String[] url){
super(context, R.layout.listview, time);
...
}
This is because, as #codeMagic said in the comments, you are using the AsyncTask class incorrectly. The following code in your onCreate method
MyBgTask asyncTask = new MyBgTask();
CustomListAdapter adapter = new CustomListAdapter(this, asyncTask.getTimeArray(), asyncTask.getConditionArray(),
asyncTask.getTempArray(), asyncTask.getHumidityArray(), asyncTask.getUrls());
Creates an AsyncTask, but doesn't execute() it. When you call getTimeArray(), it returns the value of timeArray, which is a default-initialised null value.
Broadly, you need to
Execute the AsyncTask
Update the ArrayListAdapter when the task is done

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