Here, this is detailActivity.java which gathers data from openWeatherAPI and populates the data into a listView. When I click on the item on listView there is NPE in OnCreateOptionsMenu.
package com.example.sunshine2;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.sunshine2.data.WeatherContract.WeatherEntry;
public class DetailActivity extends ActionBarActivity {
#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.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();
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class DetailFragment extends Fragment implements
LoaderCallbacks<Cursor> {
private static final String LOG_TAG = DetailFragment.class
.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private ShareActionProvider mShareActionProvider;
private String mForecast;
private static final int DETAIL_LOADER = 0;
private static final String[] FORECAST_COLUMNS = {
WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
WeatherEntry.COLUMN_DATE, WeatherEntry.COLUMN_SHORT_DESC,
WeatherEntry.COLUMN_MAX_TEMP, WeatherEntry.COLUMN_MIN_TEMP, };
// these constants correspond to the projection defined above, and must
// change if the
// projection changes
private static final int COL_WEATHER_ID = 0;
private static final int COL_WEATHER_DATE = 1;
private static final int COL_WEATHER_DESC = 2;
private static final int COL_WEATHER_MAX_TEMP = 3;
private static final int COL_WEATHER_MIN_TEMP = 4;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is
// present.
inflater.inflate(R.menu.detail_fragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat
.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set
// the share intent now.
if (mForecast != null) {
mShareActionProvider
.setShareIntent(createShareForecastIntent());
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast
+ FORECAST_SHARE_HASHTAG);
return shareIntent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.v(LOG_TAG, "In onCreateLoader");
Intent intent = getActivity().getIntent();
if (intent == null) {
return null;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(getActivity(), intent.getData(),
FORECAST_COLUMNS, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.v(LOG_TAG, "In onLoadFinished");
if (!data.moveToFirst()) {
return;
}
String dateString = Utility.formatDate(data
.getLong(COL_WEATHER_DATE));
String weatherDescription = data.getString(COL_WEATHER_DESC);
boolean isMetric = Utility.isMetric(getActivity());
String high = Utility.formatTemperature(
data.getDouble(COL_WEATHER_MAX_TEMP), isMetric);
String low = Utility.formatTemperature(
data.getDouble(COL_WEATHER_MIN_TEMP), isMetric);
mForecast = String.format("%s - %s - %s/%s", dateString,
weatherDescription, high, low);
TextView detailTextView = (TextView) getView().findViewById(
R.id.detail_text);
detailTextView.setText(mForecast);
// If onCreateOptionsMenu has already happened, we need to update
// the share intent now.
if (mShareActionProvider != null) {
mShareActionProvider
.setShareIntent(createShareForecastIntent());
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
}
And Here is the LogCat
04-13 01:22:51.916: E/AndroidRuntime(20197): FATAL EXCEPTION: main
04-13 01:22:51.916: E/AndroidRuntime(20197): Process: com.example.sunshine2, PID: 20197
04-13 01:22:51.916: E/AndroidRuntime(20197): java.lang.NullPointerException
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.example.sunshine2.DetailActivity$DetailFragment.onCreateOptionsMenu(DetailAc tivity.java:117)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1582)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1967)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivityDelegateICS.onCreatePanelMenu(ActionBarActivityDelegateICS.java:146)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivity.onCreatePanelMenu(ActionBarActivity.java:199)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onCreatePanelMenu(ActionBarActivityDelegateICS.java:293)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:803)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Handler.handleCallback(Handler.java:733)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Handler.dispatchMessage(Handler.java:95)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Looper.loop(Looper.java:149)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.app.ActivityThread.main(ActivityThread.java:5077)
04-13 01:22:51.916: E/AndroidRuntime(20197): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 01:22:51.916: E/AndroidRuntime(20197): at java.lang.reflect.Method.invoke(Method.java:515)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
04-13 01:22:51.916: E/AndroidRuntime(20197): at dalvik.system.NativeStart.main(Native Method)
I've tried debugging the code, but the
- mShareActionProvider gives me null, which I can't figure out how
I think the problem is you have a onClick function declared in your XML menu layout file but no corresponding function in your code.
Related
I'm making an app that by now should save and then get the value of a numeric Edit Text. When i put to load data from string.xml it went fine, but when i switched to SharedPreferences it didn't even start. Any help finding the problem would be appreciated. BTW .java is below and i'm sure layout .xml is fine.
package programmingandroidapps.brightnesscustomizationapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
final EditText mEditText1=(EditText)findViewById(R.id.editText1), mEditText2=(EditText)findViewById(R.id.editText2), mEditText3=(EditText)findViewById(R.id.editText3), mEditText4=(EditText)findViewById(R.id.editText4), mEditText5=(EditText)findViewById(R.id.editText5);
Button mButton1=(Button)findViewById(R.id.button1), mButton2=(Button)findViewById(R.id.button2), mButton3=(Button)findViewById(R.id.button3), mButton4=(Button)findViewById(R.id.button4), mButton5=(Button)findViewById(R.id.button5);
SharedPreferences storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE), storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE), storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE), storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE), storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#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);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
I believe this is the applications crash log. I'm new to Android so if it is not just say it, no need to get angry :P
05-01 13:24:53.061 1624-1624/programmingandroidapps.brightnesscustomizationapp D/dalvikvm: Not late-enabling CheckJNI (already on)
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp D/AndroidRuntime: Shutting down VM
05-01 13:24:56.451 1624-1624/programmingandroidapps.brightnesscustomizationapp W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb3d11b20)
05-01 13:24:56.471 1624-1624/programmingandroidapps.brightnesscustomizationapp E/AndroidRuntime:
FATAL EXCEPTION: main
Process: programmingandroidapps.brightnesscustomizationapp, PID: 1624
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{programmingandroidapps.brightnesscustomizationapp/programmingandroidapps.brightnesscustomizationapp.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at programmingandroidapps.brightnesscustomizationapp.MainActivity.<init>(MainActivity.java:21)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
The problem is that you are calling findViewById and getSharedPreferences before layout has been applied and the activity (this) was initialized. You should put those method calls in onCreate after setContentView(R.layout.activity_main);.
Dejan is right about moving part of the code into the onCreate lifecycle method, specifically, your code should change to something like this:
package programmingandroidapps.brightnesscustomizationapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends AppCompatActivity {
//Declarations
String brightnessValue;
int choice, brightnessValueInt;
private EditText mEditText1, mEditText2, mEditText3, mEditText4, mEditText5;
private Button mButton1,mButton2, mButton3, mButton4, mButton5;
private SharedPreferences storedBrightness1, storedBrightness2, storedBrightness3,storedBrightness4,storedBrightness5;
private SharedPreferences.Editor mEditor;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton1 =(Button)findViewById(R.id.button1);
mButton2=(Button)findViewById(R.id.button2);
mButton3=(Button)findViewById(R.id.button3);
mButton4=(Button)findViewById(R.id.button4);
mButton5=(Button)findViewById(R.id.button5);
mEditText1 =(EditText)findViewById(R.id.editText1);
mEditText2=(EditText)findViewById(R.id.editText2);
mEditText3=(EditText)findViewById(R.id.editText3);
mEditText4=(EditText)findViewById(R.id.editText4);
mEditText5=(EditText)findViewById(R.id.editText5);
//instead of doing this, I'd rather use "named" SharedPreferences - call it "brightness" and will carry the five values
//something like SharedPreferences brightnessPreferences = this.getSharedPreferences("brightness", Context.MODE_PRIVATE);
//I ma just adding this here because that's the way you have it
storedBrightness1 = this.getSharedPreferences("brightv1", Context.MODE_PRIVATE),
storedBrightness2 = this.getSharedPreferences("brightv2", Context.MODE_PRIVATE),
storedBrightness3 = this.getSharedPreferences("brightv3", Context.MODE_PRIVATE),
storedBrightness4 = this.getSharedPreferences("brightv4", Context.MODE_PRIVATE),
storedBrightness5 = this.getSharedPreferences("brightv5", Context.MODE_PRIVATE);
//Get saved brightness values from string.xml and set them to ediText1-5
brightnessValueInt = storedBrightness1.getInt("brightv1", 0);
brightnessIntToString();
printToEditText(1);
brightnessValueInt = storedBrightness2.getInt("brightv2", 0);
brightnessIntToString();
printToEditText(2);
brightnessValueInt = storedBrightness3.getInt("brightv3", 0);
brightnessIntToString();
printToEditText(3);
brightnessValueInt = storedBrightness4.getInt("brightv4", 0);
brightnessIntToString();
printToEditText(4);
brightnessValueInt = storedBrightness5.getInt("brightv5", 0);
brightnessIntToString();
printToEditText(5);
//
// On Click Button Listeners
mButton1.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Validate >=0 and <=100, paint #222222 if is valid, paint red if not
Log.v(brightnessValue, mEditText1.getText().toString());
mEditor = storedBrightness1.edit();
mEditor.putInt("brightv1", brightnessValueInt);
}
});
//
}
#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);
}
public void printToEditText(int choice)
{
if(choice==1)
{
mEditText1.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==2)
{
mEditText2.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==3)
{
mEditText3.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else if(choice==4)
{
mEditText4.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
else
{
mEditText5.setText(brightnessValue, TextView.BufferType.EDITABLE);
}
}
public void brightnessIntToString()
{
brightnessValue=brightnessValueInt+"";
}
}
I have a list of Claim objects, each claim object is initialized with a name and an expense list.
i made an adapter for the listview for the claims. what I am trying to do now is create an adaptor for the expenses. Since each claim has its own expense list, i cannot just make a general adapter. i need to make an adapter for a specific Claim, or am thinking of this wrong? here is what I did..
JUST TO BE CLEAR< MY QUESTION IS: How do I make an adaptor for the list initializd with the expenses, and open that list-view to see the expenses of a specific claim when I click on it?
package app.zioueche_travelexpense;
import java.util.ArrayList;
import java.util.Collection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
//figure out how to add claim in different page. so we can add date range.
public class AddClaim extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_claim);
//adapter for claim view this one works. it is the expenses one that i do not know how to implement
ListView listView = (ListView) findViewById(R.id.claimListView);
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
final ArrayList<Claim> list = new ArrayList<Claim>(claims);
final ArrayAdapter<Claim> claimAdapter = new ArrayAdapter<Claim>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(claimAdapter);
//Added observer pattern
ClaimListController.getClaimList().addListener(new Listener(){
#Override
public void update(){
list.clear();
Collection<Claim> claims = ClaimListController.getClaimList().getClaim();
list.addAll(claims);
claimAdapter.notifyDataSetChanged();
}
});
//SINGLE TAP FUNCTION
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//adapter expenses I DO NOT KNOW HOW TO IMPLEMENT THIS
ListView expView = (ListView) findViewById(R.id.ExpenseListView);
Collection<Expense> expenses = list.get(position).getExpenses();
final ArrayList<Expense> expense = new ArrayList<Expense>(expenses);
final ArrayAdapter<Expense> expAdap = new ArrayAdapter<Expense>(AddClaim.this, android.R.layout.simple_list_item_1, expense);
expView.setAdapter(expAdap); //THIS IS MY LINE 64
}
});
//LONG CLICK FUNCTIONS
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view);
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true;
}
});
popup.show();
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_claim, menu);
return true;
}
protected void onDeleteClick(final int position, final ArrayList<Claim> list){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(position).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(position);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addClaimView(MenuItem item){
Toast.makeText(this, "going to claim creation page", Toast.LENGTH_SHORT).show();
setContentView(R.layout.claim_add_page);
}
public void addClaims(View v){
ClaimListController ct = new ClaimListController();
EditText textView = (EditText) findViewById(R.id.add_claim_field);
String added = textView.getText().toString();
if (!TextUtils.isEmpty(added)){
final String t = format("added",added);
ct.addClaim(new Claim(added));
Toast.makeText(this, t, Toast.LENGTH_SHORT).show();
textView.setText("");
setContentView(R.layout.claim_list);
//Intent intent = new Intent(MainActivity.this, AddClaim.class);
//startActivity(intent);
}else{
Toast.makeText(AddClaim.this,"Please type something before adding", Toast.LENGTH_SHORT).show();
}
}
private String format(String string, String added) {
String formats = string +" "+ added;
return formats;
}
}
As you can see, i made my listview adapter for the expenses inside the onclick method, since i need the position to get the expense list out of the specific claim.
How can I do this/ when I run this code I get null pointer exceptions on line 64.
here is the log cat.
01-24 02:01:15.434: E/AndroidRuntime(1099): FATAL EXCEPTION: main
01-24 02:01:15.434: E/AndroidRuntime(1099): java.lang.NullPointerException
01-24 02:01:15.434: E/AndroidRuntime(1099): at app.zioueche_travelexpense.AddClaim$2.onItemClick(AddClaim.java:64)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.widget.AbsListView$1.run(AbsListView.java:3423)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.handleCallback(Handler.java:725)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Handler.dispatchMessage(Handler.java:92)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.os.Looper.loop(Looper.java:137)
01-24 02:01:15.434: E/AndroidRuntime(1099): at android.app.ActivityThread.main(ActivityThread.java:5041)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invokeNative(Native Method)
01-24 02:01:15.434: E/AndroidRuntime(1099): at java.lang.reflect.Method.invoke(Method.java:511)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-24 02:01:15.434: E/AndroidRuntime(1099): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-24 02:01:15.434: E/AndroidRuntime(1099): at dalvik.system.NativeStart.main(Native Method)
01-24 02:01:17.814: E/Trace(1117): error opening trace file: No such file or directory (2)
Having serious problems with a lab and I am not the only one. I have my emulator running fine with all Facebook example apps. FacebookSDK and HelloFacebookSample project all work fine. It is something in the code that is incorrect. All xml, and manifest coding is correct. I am sure it is something in the Java code. It compiles, it prompts a Log-In then it asks about permissions, then it crashes.
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.model.GraphObject;
import com.facebook.SessionState;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
final TextView newsFeedTextView = (TextView) rootView
.findViewById(R.id.newsFeed);
StatusCallback mCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
/* make the API call */
new Request(session, "/GmitClubsandsocieties/feed", null,
HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
/* check logcat for responce */
System.out.println(response);
newsFeedTextView
.setText(parseDataFromFQLResponse(response));
}
}).executeAsync();
}
}
};
Session.OpenRequest request = new Session.OpenRequest(getActivity());
// request.setPermissions(Arrays.asList("read_stream"));
request.setCallback(mCallback);
// get active session
Session mFacebookSession = Session.getActiveSession();
if (mFacebookSession == null || mFacebookSession.isClosed()) {
mFacebookSession = new Session(getActivity());
}
// mFacebookSession.openForRead(request);
mFacebookSession.openForRead(request);
return rootView;
}
}
private static String parseDataFromFQLResponse(Response response) {
StringBuilder responseText = new StringBuilder(" ");
try {
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
for (int i = 0; i < (arr.length()); i++) {
JSONObject json_obj = arr.getJSONObject(i);
responseText.append(String.format("Message: %s\n\n",
json_obj.getString("message")));
}
} catch (Throwable t) {
t.printStackTrace();
}
return responseText.toString();
}
}
This is the logFile:
04-24 09:57:28.453: D/AndroidRuntime(2574): Shutting down VM
04-24 09:57:28.453: W/dalvikvm(2574): threadid=1: thread exiting with uncaught exception (group=0xb2ae0ba8)
04-24 09:57:28.513: E/AndroidRuntime(2574): FATAL EXCEPTION: main
04-24 09:57:28.513: E/AndroidRuntime(2574): Process: ie.gmit.facebooknewsfeed, PID: 2574
04-24 09:57:28.513: E/AndroidRuntime(2574): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {ie.gmit.facebooknewsfeed/ie.gmit.facebooknewsfeed.MainActivity}: java.lang.NullPointerException
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.deliverResults(ActivityThread.java:3365)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3408)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.access$1300(ActivityThread.java:135)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.os.Handler.dispatchMessage(Handler.java:102)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.os.Looper.loop(Looper.java:136)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-24 09:57:28.513: E/AndroidRuntime(2574): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 09:57:28.513: E/AndroidRuntime(2574): at java.lang.reflect.Method.invoke(Method.java:515)
04-24 09:57:28.513: E/AndroidRuntime(2574): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-24 09:57:28.513: E/AndroidRuntime(2574): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-24 09:57:28.513: E/AndroidRuntime(2574): at dalvik.system.NativeStart.main(Native Method)
04-24 09:57:28.513: E/AndroidRuntime(2574): Caused by: java.lang.NullPointerException
04-24 09:57:28.513: E/AndroidRuntime(2574): at ie.gmit.facebooknewsfeed.MainActivity.onActivityResult(MainActivity.java:40)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.Activity.dispatchActivityResult(Activity.java:5423)
04-24 09:57:28.513: E/AndroidRuntime(2574): at android.app.ActivityThread.deliverResults(ActivityThread.java:3361)
04-24 09:57:28.513: E/AndroidRuntime(2574): ... 11 more
04-24 09:57:32.283: I/Process(2574): Sending signal. PID: 2574 SIG: 9
Your data parameter may not be properly populated. In onActivityResult
add the line Bundle bundle = data.getExtras();
I have tried to learn to write an application which is basically a bluetooth messenger. Things had been fine unless I tried to install and run it. It gets installed successfully but crashes down at start up itself. Can you please tell me what is wrong ?
This is the code for the main activity. There are three more activities apart from this.
import java.io.IOException;
import java.util.ArrayList;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public final static String UUID = "3606f360-e4df-11e0-9572-0800200c9a66";
BluetoothAdapter bluetoothAdapter;
BroadcastReceiver discoverDevicesReceiver;
BroadcastReceiver discoveryFinishedReceiver;
//---store all the discovered devices---
ArrayList<BluetoothDevice> discoveredDevices;
ArrayList<String> discoveredDevicesNames;
//---store all the paired devices---
ArrayList<BluetoothDevice> pairedDevices;
static TextView txtData;
EditText txtMessage;
//---thread for running the server socket---
ServerThread serverThread;
//---thread for connecting to the client socket---
ConnectToServerThread connectToServerThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---init the ArrayList objects and bluetooth adapter---
discoveredDevices = new ArrayList<BluetoothDevice>();
discoveredDevicesNames = new ArrayList<String>();
pairedDevices = new ArrayList<BluetoothDevice>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//---for displaying the messages received---
txtData = (TextView) findViewById(R.id.txtData);
txtMessage = (EditText) findViewById(R.id.txtMessage);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//---make yourself discoverable---
public void MakeDiscoverable(View view)
{
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(i);
}
/*
//---find all the previously paired devices---
private void QueryPairedDevices(){
Set<BluetoothDevice> allPairedDevices =
bluetoothAdapter.getBondedDevices();
//---if there are paired devices---
if (allPairedDevices.size() > 0) {
//---loop through paired devices---
for (BluetoothDevice device : allPairedDevices) {
//---add the name and address to an array adapter
// to show in a ListView---
Log.d("UsingBluetooth", device.getName() + "\n" +
device.getAddress());
pairedDevices.add(device);
}
}
}
*/
//---used to discover other bluetooth devices---
private void DiscoveringDevices() {
if (discoverDevicesReceiver == null) {
discoverDevicesReceiver = new BroadcastReceiver() {
//---fired when a new device is discovered---
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//---a device is discovered---
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//---get the BluetoothDevice object from
// the Intent---
BluetoothDevice device =
intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE);
//---add the name and address to an array
// adapter to show in a ListView---
//---only add if the device is not already
// in the list---
if (!discoveredDevices.contains(device)) {
//---add the device---
discoveredDevices.add(device);
//---add the name of the device; used for
// ListView---
discoveredDevicesNames.add(device.getName());
//---display the items in the ListView---
setListAdapter(new
ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_list_item_1,
discoveredDevicesNames));
}
}
}
};
}
if (discoveryFinishedReceiver==null) {
discoveryFinishedReceiver = new BroadcastReceiver() {
//---fired when the discovery is done---
#Override
public void onReceive(Context context, Intent intent) {
//---enable the listview when discovery is over; about 12 seconds---
getListView().setEnabled(true);
Toast.makeText(getBaseContext(),
"Discovery completed. Select a device to start chatting.",
Toast.LENGTH_LONG).show();
unregisterReceiver(discoveryFinishedReceiver);
}
};
}
//---register the broadcast receivers---
IntentFilter filter1 = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
IntentFilter filter2 = new
IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoverDevicesReceiver, filter1);
registerReceiver(discoveryFinishedReceiver, filter2);
//---disable the listview when discover is in progress---
getListView().setEnabled(false);
Toast.makeText(getBaseContext(),
"Discovery in progress...please wait...",
Toast.LENGTH_LONG).show();
bluetoothAdapter.startDiscovery();
}
//---discover other bluetooth devices---
public void DiscoverDevices(View view)
{
//---query for all paired devices---
//QueryPairedDevices();
//---discover other devices---
DiscoveringDevices();
}
#Override
public void onPause() {
super.onPause();
//---cancel discovery of other bluetooth devices
bluetoothAdapter.cancelDiscovery();
//---unregister the broadcast receiver for
// discovering devices---
if (discoverDevicesReceiver != null) {
try {
unregisterReceiver(discoverDevicesReceiver);
} catch(Exception e) {
}
}
//---if you are currently connected to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---stop the thread running---
if (serverThread!=null) serverThread.cancel();
}
//---used for updating the UI on the main activity---
static Handler UIupdater = new Handler() {
#Override
public void handleMessage(Message msg) {
int numOfBytesReceived = msg.arg1;
byte[] buffer = (byte[]) msg.obj;
//---convert the entire byte array to string---
String strReceived = new String(buffer);
//---extract only the actual string received---
strReceived = strReceived.substring(
0, numOfBytesReceived);
//---display the text received on the TextView---
txtData.setText(txtData.getText().toString() +
strReceived);
}
};
#Override
public void onResume() {
super.onResume();
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
//---when a client is tapped in the ListView---
public void onListItemClick(ListView parent, View v,
int position, long id) {
//---if you are already talking to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection first---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---connect to the selected Bluetooth device---
BluetoothDevice deviceSelected =
discoveredDevices.get(position);
connectToServerThread = new
ConnectToServerThread(deviceSelected, bluetoothAdapter);
connectToServerThread.start();
//---tell the user that he is connected to who---
Toast.makeText(this, "You have connected to " +
discoveredDevices.get(position).getName(),
Toast.LENGTH_SHORT).show();
}
private class WriteTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... args) {
try {
connectToServerThread.commsThread.write(args[0]);
} catch (Exception e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
return null;
}
}
//---send a message to the connected socket client---
public void SendMessage(View view)
{
if (connectToServerThread!=null) {
///=========
//connectToServerThread.commsThread.write(
// txtMessage.getText().toString());
new WriteTask().execute(txtMessage.getText().toString());
///=========
} else {
Toast.makeText(this, "Select a client first",
Toast.LENGTH_SHORT).show();
}
}
}
ServerThread class :
import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ServerThread extends Thread {
//---the server socket---
private final BluetoothServerSocket bluetoothServerSocket;
public ServerThread(BluetoothAdapter bluetoothAdapter) {
BluetoothServerSocket tmp = null;
try {
//---UUID must be the same for both the client and
// the server---
tmp =
bluetoothAdapter.listenUsingRfcommWithServiceRecord(
"BluetoothApp", UUID.fromString(MainActivity.UUID));
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
bluetoothServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
//---keep listening until exception occurs
// or a socket is returned---
while (true) {
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
break;
}
//---if a connection was accepted---
if (socket != null) {
//---create a separate thread to listen for
// incoming data---
CommsThread commsThread = new CommsThread(socket);
commsThread.run();
}
}
}
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
}
}
LogCat
04-13 18:25:06.684: D/AndroidRuntime(397): Shutting down VM
04-13 18:25:06.684: W/dalvikvm(397): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:06.704: E/AndroidRuntime(397): FATAL EXCEPTION: main
04-13 18:25:06.704: E/AndroidRuntime(397): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:06.704: E/AndroidRuntime(397): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): Caused by: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:06.704: E/AndroidRuntime(397): ... 12 more
04-13 18:25:08.764: I/Process(397): Sending signal. PID: 397 SIG: 9
04-13 18:25:10.354: D/AndroidRuntime(415): Shutting down VM
04-13 18:25:10.354: W/dalvikvm(415): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:10.364: E/AndroidRuntime(415): FATAL EXCEPTION: main
04-13 18:25:10.364: E/AndroidRuntime(415): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:10.364: E/AndroidRuntime(415): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): Caused by: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:10.364: E/AndroidRuntime(415): ... 12 more
04-13 18:25:13.304: I/Process(415): Sending signal. PID: 415 SIG: 9
Possible changes you can try which might help you.
In ServerThread.java
public void run() {
....
while(!Thread.currentThread().isInterrupted()){
//do something
}
}
If this works fine, otherwise try:
In MainActivity.java
#Override
public void onCreate() {
....
//Start your thread here
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
#Override
public void onResume() {
super.onResume();
//handle your thread here - the following maynot be helpful, but logiaclly speaking, //you must handle your threads here
if(serverThread.isAlive())
serverThread.resume();
else
serverThread.interrupt();
}
I have been working on a game for Android and I want to put highscores in. I think that this code should be working and cannot see why it isn't. I have got it set so that when the menu button is pressed a dialog box opens for the user to enter their name. This works but then when you press ok, the app crashes. The line it crashes on is ArrayList<Player> players= fs.getScores();
Here is the code for the activity class which is where it crashes:
package com.example.game;
import java.util.Collections;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.widget.EditText;
import android.view.LayoutInflater;
public class MyGame extends Activity {
GameView gv;
private final int DIALOG_TEXT_ENTRY = 1;
Filestore fs;
private String GAME_KEY= "game_key";
private Bundle sis;
TextView hscores;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
gv = new GameView(this);
setContentView(gv);
gv.setStarted(true);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent msg) {
if (keyCode==KeyEvent.KEYCODE_DPAD_RIGHT)
gv.setSpriteState(2);
if (keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
gv.setSpriteState(1);
if (keyCode == KeyEvent.KEYCODE_MENU)
showDialog(DIALOG_TEXT_ENTRY);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
gv = new GameView(this);
gv.setStarted(true);
setContentView(gv);
return true;
case R.id.save:
showDialog(DIALOG_TEXT_ENTRY);
return true;
case R.id.quit:
finish();
return true;
case R.id.highscores:
setContentView(R.layout.highscores);
hscores = (TextView) findViewById(R.id.myhighscores);
ArrayList<Player> players= fs.getScores();
if(!(players==null))
{
Collections.sort(players);
String s=String.format("%15s%15s","NAME","SCORE\n");
for(Player p:players)
{
s+=String.format("%15s%15s",p.getName(),
p.getScore()+"\n");
}
hscores.setText(s);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_TEXT_ENTRY:
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.save, null);
final EditText t = (EditText) textEntryView.findViewById(R.id.save_edit);
name = t.toString();
return new AlertDialog.Builder(MyGame.this)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.alert_dialog_save_title)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
Player p= new Player(t.getText().toString(),gv.getTime());
ArrayList<Player> players= fs.getScores();
if(players==null)
players= new ArrayList<Player>();
players.add(p);
fs.saveScores(players);
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).create();
}
return null;
}
public void onClick(DialogInterface dialog,
int whichButton) {
Player p= new Player(name,gv.getTime());
ArrayList<Player> players= fs.getScores();
if(players==null)
players= new ArrayList<Player>();
players.add(p);
fs.saveScores(players);
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putBundle(GAME_KEY, gv.saveState());
sis=outState;
}
}
And here is the logcat:
07-08 20:56:24.799: E/AndroidRuntime(1649): FATAL EXCEPTION: main
07-08 20:56:24.799: E/AndroidRuntime(1649): java.lang.NullPointerException
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.example.game.MyGame$1.onClick(MyGame.java:117)
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
07-08 20:56:24.799: E/AndroidRuntime(1649): at android.os.Handler.dispatchMessage(Handler.java:99)
07-08 20:56:24.799: E/AndroidRuntime(1649): at android.os.Looper.loop(Looper.java:123)
07-08 20:56:24.799: E/AndroidRuntime(1649): at android.app.ActivityThread.main(ActivityThread.java:3687)
07-08 20:56:24.799: E/AndroidRuntime(1649): at java.lang.reflect.Method.invokeNative(Native Method)
07-08 20:56:24.799: E/AndroidRuntime(1649): at java.lang.reflect.Method.invoke(Method.java:507)
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
07-08 20:56:24.799: E/AndroidRuntime(1649): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
07-08 20:56:24.799: E/AndroidRuntime(1649): at dalvik.system.NativeStart.main(Native Method)
I have tried to include everything I could think of but I am new to this. Any help would be really appreciated.
ArrayList<Player> players= fs.getScores();
It seems fs is pointing to null and resulting in NullPointerException.
In your code you are no where pointing fs to valid instance/object.
The field fs (the file store) is not initialized. You need to create (or get) an instance first, maybe like you initialize the GameView in your onCreate method.