简体   繁体   English

每当我按下按钮以查看我的列表视图时,应用程序始终崩溃

[英]Whenever i press a button to view my listview the app always crash

I have 2 buttons: Calculate Calories and Set Alarm. 我有2个按钮:计算卡路里和设置警报。 I'm able to enter my calculate calories page and continue with the activity inside. 我可以进入我的卡路里计算页面,然后继续进行其中的活动。 But when i press set alarm button that suppose to bring me to a listview of alarm that i will set but the app will crash as i press the set alarm button. 但是,当我按下“设置警报”按钮时,该按钮将使我进入我将要设置的警报列表视图,但是当我按下“设置警报”按钮时,应用程序将崩溃。 Im able to set my alarm through my calculate calories activity with a menu button, but when i save the alarm (which i expect it will add into the listview) apparently the app crashes. 我可以使用菜单按钮通过计算卡路里活动来设置闹钟,但是当我保存闹钟(我希望它将添加到列表视图中)时,应用显然崩溃了。 So basically i cant view my list of alarm. 所以基本上我无法查看我的警报列表。

*Second activity that contain a listview with the alarm i set. *第二个活动包含一个带有我设置的警报的列表视图。

    private Button mAddReminderButton, backbutton;
    private Toolbar mToolbar;
    AlarmCursorAdapter mCursorAdapter;
    AlarmReminderDbHelper alarmReminderDbHelper = new 
AlarmReminderDbHelper(this);
    ListView reminderListView;
    ProgressDialog prgDialog;

    private static final int VEHICLE_LOADER = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        reminderListView = (ListView) findViewById(R.id.list);
        View emptyView = findViewById(R.id.empty_view);
        reminderListView.setEmptyView(emptyView);

        mCursorAdapter = new AlarmCursorAdapter(this, null);
        reminderListView.setAdapter(mCursorAdapter);

        reminderListView.setOnItemClickListener(new 
AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View 
view, int position, long id) {
                Intent intent = new Intent(MainActivity2.this, 
Reminder.class);
                Uri currentVehicleUri = 
ContentUris.withAppendedId
(AlarmReminderContract.AlarmReminderEntry.CONTENT_U 
 RI, id);
                // Set the URI on the data field of the intent
                intent.setData(currentVehicleUri);

                startActivity(intent);
            }
        });
        mAddReminderButton = (Button) findViewById(R.id.aa);

        mAddReminderButton.setOnClickListener(new View.OnClickListener() 
{
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(v.getContext(), 
Reminder.class);
                startActivity(intent);
            }
        });
        getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        String[] projection = {
                AlarmReminderContract.AlarmReminderEntry._ID,
                AlarmReminderContract.AlarmReminderEntry.KEY_TITLE,
                AlarmReminderContract.AlarmReminderEntry.KEY_DATE,
                AlarmReminderContract.AlarmReminderEntry.KEY_TIME,
                AlarmReminderContract.AlarmReminderEntry.KEY_NOTIFICATION
        };

        return new CursorLoader(this,   // Parent activity context
                AlarmReminderContract.AlarmReminderEntry.CONTENT_URI,   
// Provider content URI to query
                projection,             // Columns to include in the 
resulting Cursor
                null,                   // No selection clause
                null,                   // No selection arguments
                null);                  // Default sort order
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        mCursorAdapter.swapCursor(cursor);
    }
   @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mCursorAdapter.swapCursor(null);
    }
}

*Error message i received. *我收到的错误消息。

   java.lang.RuntimeException: An error occurred while executing 
doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:325)
        at 
java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
        at 
java.util.concurrent.FutureTask.setException(FutureTask.java:223)
        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
        at 
 java.util.concurrent.ThreadPoolExecutor.runWorker
   (ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
     Caused by: java.lang.SecurityException: Permission Denial: opening 
provider com.delaroystudios.alarmreminder.data.AlarmReminderProvider from 
ProcessRecord{478ae61 26054:com.example.asus.caloriecount/u0a101} 
(pid=26054, uid=10101) that is not exported from uid 10087
        at android.os.Parcel.readException(Parcel.java:1684)
        at android.os.Parcel.readException(Parcel.java:1637)
        at 
android.app.ActivityManagerProxy.getContentProvider
(ActivityManagerNative.java:4199)
        at 
   android.app.ActivityThread.acquireProvider(ActivityThread.java:5476)
        at 

       android.app.ContextImpl$ApplicationContentResolver
    .acquireUnstableProvider
        (ContextImpl.java:2239)
                at 
   android.content.ContentResolver.acquireUnstableProvider
        (ContentResolver.java:1517)
             at 
    android.content.ContentResolver.query(ContentResolver.java:516)
             at 
    android.content.CursorLoader.loadInBackground(CursorLoader.java:64)
             at 
      android.content.CursorLoader.loadInBackground(CursorLoader.java:56)
        at 
       android.content.AsyncTaskLoader.onLoadInBackground
       (AsyncTaskLoader.java:312)
                   at 
android.content.AsyncTaskLoader$LoadTask.doInBackground
       (AsyncTaskLoader.java:69)
              at android.content.AsyncTaskLoader$LoadTask.doInBackground
        (AsyncTaskLoader.java:66)
              at android.os.AsyncTask$2.call(AsyncTask.java:305)
              at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at java.util.concurrent.ThreadPoolExecutor.runWorker
       (ThreadPoolExecutor.java:1133) 
              at java.util.concurrent.ThreadPoolExecutor$Worker.run
        (ThreadPoolExecutor.java:607) 
                 at java.lang.Thread.run(Thread.java:761) 

*My Manifest *我的清单

 <application
       android:allowBackup="true"
       android:icon="@drawable/bij"
       android:label="@string/app_name"
        android:roundIcon="@drawable/bij"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity2">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category 
android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
       </activity>
       <activity android:name=".Reminder">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" 
/>
             </intent-filter>
        </activity>
        <activity android:name=".Home">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" 
/>
            </intent-filter>
        </activity>
       <activity
            android:name=".SplashScreen"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" 
/>
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity" />
        <activity android:name=".AddNewEntryActivity" />
        <activity android:name=".DisplayLogActivity" />
        <activity
            android:name=".Data_Classess"
            android:label="@string/title_activity_data__classess"
            android:theme="@style/AppTheme.NoActionBar" />

        <provider
             android:name=".data.AlarmReminderProvider"
        android:authorities="com.example.asus.caloriecount.alarmreminder"
           android:exported="false" />

        <service
           android:name=".reminder.ReminderAlarmService"
            android:exported="false" />

     </application>

*Reminder Code *提醒代码

  private static final int EXISTING_VEHICLE_LOADER = 0;


    private EditText mTitleText;
    private TextView mDateText,
    mTimeText;
    private FloatingActionButton mFAB1;
    private FloatingActionButton mFAB2;
    private Calendar mCalendar;
    private int mYear,
    mMonth,
    mHour,
    mMinute,
    mDay;
    private String mTitle;
    private String mTime;
    private String mDate;
    private String mNotification;
    private Button save,
    delete;

    private Uri mCurrentReminderUri;
    private boolean mVehicleHasChanged = false;


    private static final String KEY_TITLE = "title_key";
    private static final String KEY_TIME = "time_key";
    private static final String KEY_DATE = "date_key";
    private static final String KEY_NOTIFICATION = "notification_key";



    private static final long milMinute = 60000 L;
    private static final long milHour = 3600000 L;
    private static final long milDay = 86400000 L;
    private static final long milWeek = 604800000 L;
    private static final long milMonth = 2592000000 L;

    private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            mVehicleHasChanged = true;
            return false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reminder);

        Intent intent = getIntent();
        mCurrentReminderUri = intent.getData();

        if (mCurrentReminderUri == null) {

            setTitle(getString(R.string.editor_activity_title_new_reminder));


            invalidateOptionsMenu();
        } else {

            setTitle(getString(R.string.editor_activity_title_edit_reminder));


            getLoaderManager().initLoader(EXISTING_VEHICLE_LOADER, null, this);
        }


        mTitleText = (EditText) findViewById(R.id.reminder_title);
        mDateText = (TextView) findViewById(R.id.set_date);
        mTimeText = (TextView) findViewById(R.id.set_time);
        mFAB1 = (FloatingActionButton) findViewById(R.id.starred1);
        mFAB2 = (FloatingActionButton) findViewById(R.id.starred2);


        mNotification = "true";

        mCalendar = Calendar.getInstance();
        mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
        mMinute = mCalendar.get(Calendar.MINUTE);
        mYear = mCalendar.get(Calendar.YEAR);
        mMonth = mCalendar.get(Calendar.MONTH) + 1;
        mDay = mCalendar.get(Calendar.DATE);

        mDate = mDay + "/" + mMonth + "/" + mYear;
        mTime = mHour + ":" + mMinute;


        mTitleText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mTitle = s.toString().trim();
                mTitleText.setError(null);
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        // Setup TextViews using reminder values
        mDateText.setText(mDate);
        mTimeText.setText(mTime);


        // To save state on device rotation
        if (savedInstanceState != null) {
            String savedTitle = savedInstanceState.getString(KEY_TITLE);
            mTitleText.setText(savedTitle);
            mTitle = savedTitle;

            String savedTime = savedInstanceState.getString(KEY_TIME);
            mTimeText.setText(savedTime);
            mTime = savedTime;

            String savedDate = savedInstanceState.getString(KEY_DATE);
            mDateText.setText(savedDate);
            mDate = savedDate;


            mNotification = savedInstanceState.getString(KEY_NOTIFICATION);
        }

        // Setup up active buttons
        if (mNotification.equals("false")) {
            mFAB1.setVisibility(View.VISIBLE);
            mFAB2.setVisibility(View.GONE);

        } else if (mNotification.equals("true")) {
            mFAB1.setVisibility(View.GONE);
            mFAB2.setVisibility(View.VISIBLE);
        }

        getSupportActionBar().setTitle(R.string.title_activity_add_reminder);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putCharSequence(KEY_TITLE, mTitleText.getText());
        outState.putCharSequence(KEY_TIME, mTimeText.getText());
        outState.putCharSequence(KEY_DATE, mDateText.getText());
        outState.putCharSequence(KEY_NOTIFICATION, mNotification);
    }


    public void setTime(View v) {
        Calendar now = Calendar.getInstance();
        TimePickerDialog tpd = TimePickerDialog.newInstance(
            this,
            now.get(Calendar.HOUR_OF_DAY),
            now.get(Calendar.MINUTE),
            false
        );
        tpd.setThemeDark(false);
        tpd.show(getFragmentManager(), "Timepickerdialog");
    }


    public void setDate(View v) {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(
            this,
            now.get(Calendar.YEAR),
            now.get(Calendar.MONTH),
            now.get(Calendar.DAY_OF_MONTH)
        );
        dpd.show(getFragmentManager(), "Datepickerdialog");
    }


    @Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        mHour = hourOfDay;
        mMinute = minute;
        if (minute < 10) {
            mTime = hourOfDay + ":" + "0" + minute;
        } else {
            mTime = hourOfDay + ":" + minute;
        }
        mTimeText.setText(mTime);
    }


    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
        monthOfYear++;
        mDay = dayOfMonth;
        mMonth = monthOfYear;
        mYear = year;
        mDate = dayOfMonth + "/" + monthOfYear + "/" + year;
        mDateText.setText(mDate);
    }


    public void selectFab1(View v) {
        mFAB1 = (FloatingActionButton) findViewById(R.id.starred1);
        mFAB1.setVisibility(View.GONE);
        mFAB2 = (FloatingActionButton) findViewById(R.id.starred2);
        mFAB2.setVisibility(View.VISIBLE);
        mNotification = "true";
    }

    public void selectFab2(View v) {
        mFAB2 = (FloatingActionButton) findViewById(R.id.starred2);
        mFAB2.setVisibility(View.GONE);
        mFAB1 = (FloatingActionButton) findViewById(R.id.starred1);
        mFAB1.setVisibility(View.VISIBLE);
        mNotification = "false";
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.save, menu);
        return true;
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        if (mCurrentReminderUri == null) {
            MenuItem menuItem = menu.findItem(R.id.discard_reminder);
            menuItem.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // User clicked on a menu option in the app bar overflow menu
        switch (item.getItemId()) {

            case R.id.save_reminder:


                if (mTitleText.getText().toString().length() == 0) {
                    mTitleText.setError("Reminder Title cannot be blank!");
                } else {
                    saveReminder();
                    finish();
                }
                return true;

            case R.id.discard_reminder:

                showDeleteConfirmationDialog();
                return true;

            case android.R.id.home:

                if (!mVehicleHasChanged) {
                    NavUtils.navigateUpFromSameTask(Reminder.this);
                    return true;
                }

                DialogInterface.OnClickListener discardButtonClickListener =
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            NavUtils.navigateUpFromSameTask(Reminder.this);
                        }
                    };

                showUnsavedChangesDialog(discardButtonClickListener);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showUnsavedChangesDialog(
        DialogInterface.OnClickListener discardButtonClickListener) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.unsaved_changes_dialog_msg);
        builder.setPositiveButton(R.string.discard, discardButtonClickListener);
        builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });


        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    private void showDeleteConfirmationDialog() {


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.delete_dialog_msg);
        builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                deleteReminder();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {

                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });


        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    private void deleteReminder() {

        if (mCurrentReminderUri != null) {

            int rowsDeleted = getContentResolver().delete(mCurrentReminderUri, null, null);

            if (rowsDeleted == 0) {
                Toast.makeText(this, getString(R.string.editor_delete_reminder_failed),
                    Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, getString(R.string.editor_delete_reminder_successful),
                    Toast.LENGTH_SHORT).show();
            }
        }

        finish();
    }

    // On clicking the save button
    public void saveReminder() {

        /*   if (mCurrentReminderUri == null ) {
        // Since no fields were modified, we can return early without creating a new reminder.
        // No need to create ContentValues and no need to do any ContentProvider operations.
        return;
    }
*/
        ContentValues values = new ContentValues();

        values.put(AlarmReminderContract.AlarmReminderEntry.KEY_TITLE, mTitle);
        values.put(AlarmReminderContract.AlarmReminderEntry.KEY_DATE, mDate);
        values.put(AlarmReminderContract.AlarmReminderEntry.KEY_TIME, mTime);
        values.put(AlarmReminderContract.AlarmReminderEntry.KEY_NOTIFICATION, mNotification);

        mCalendar.set(Calendar.MONTH, --mMonth);
        mCalendar.set(Calendar.YEAR, mYear);
        mCalendar.set(Calendar.DAY_OF_MONTH, mDay);
        mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
        mCalendar.set(Calendar.MINUTE, mMinute);
        mCalendar.set(Calendar.SECOND, 0);

        long selectedTimestamp = mCalendar.getTimeInMillis();


        if (mCurrentReminderUri == null) 

            Uri newUri = getContentResolver().insert(AlarmReminderContract.AlarmReminderEntry.CONTENT_URI, values);
            if (newUri == null) {
                Toast.makeText(this, getString(R.string.editor_insert_reminder_failed),
                    Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, getString(R.string.editor_insert_reminder_successful),
                    Toast.LENGTH_SHORT).show();
            }
        } else {

            int rowsAffected = getContentResolver().update(mCurrentReminderUri, values, null, null);

            if (rowsAffected == 0) {
                Toast.makeText(this, getString(R.string.editor_update_reminder_failed),
                    Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, getString(R.string.editor_update_reminder_successful),
                    Toast.LENGTH_SHORT).show();
            }
        }

        if (mNotification.equals("true")) {
            if (mNotification.equals("true")) {
                new AlarmScheduler().setAlarm(getApplicationContext(), selectedTimestamp, mCurrentReminderUri);
            } else if (mNotification.equals("false")) {
                new AlarmScheduler().setAlarm(getApplicationContext(), selectedTimestamp, mCurrentReminderUri);
            }

            Toast.makeText(this, "Alarm time is " + selectedTimestamp,
                Toast.LENGTH_LONG).show();
        }

        Toast.makeText(getApplicationContext(), "Saved",
            Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
    @Override
    public Loader < Cursor > onCreateLoader(int i, Bundle bundle) {
        String[] projection = {
            AlarmReminderContract.AlarmReminderEntry._ID,
            AlarmReminderContract.AlarmReminderEntry.KEY_TITLE,
            AlarmReminderContract.AlarmReminderEntry.KEY_DATE,
            AlarmReminderContract.AlarmReminderEntry.KEY_TIME,
            AlarmReminderContract.AlarmReminderEntry.KEY_NOTIFICATION,
        };

        return new CursorLoader(this, 
            mCurrentReminderUri, 
            projection, // Columns to include in the resulting Cursor
            null, // No selection clause
            null, // No selection arguments
            null); // Default sort order
    }

    @Override
    public void onLoadFinished(Loader < Cursor > loader, Cursor cursor) {
        if (cursor == null || cursor.getCount() < 1) {
            return;
        }

        if (cursor.moveToFirst()) {
            int titleColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_TITLE);
            int dateColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_DATE);
            int timeColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_TIME);
            int activeColumnIndex = cursor.getColumnIndex(AlarmReminderContract.AlarmReminderEntry.KEY_NOTIFICATION);


            String title = cursor.getString(titleColumnIndex);
            String date = cursor.getString(dateColumnIndex);
            String time = cursor.getString(timeColumnIndex);
            String notification = cursor.getString(activeColumnIndex);
            mTitleText.setText(title);
            mDateText.setText(date);
            mTimeText.setText(time);
        }

    }
    @Override
    public void onLoaderReset(Loader < Cursor > loader) {

    }

}

-- Set exported option to true for your provider under Manifest -在清单上为您的提供者设置导出选项为true

-- Also use a befitting name for your authority -也请使用合适的名称作为您的权限

<provider
             android:name=".data.AlarmReminderProvider"
        android:authorities="com.company.contentprovider"
           android:exported="true" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM