Application on Device Close on open

613 Views Asked by At

Every time I open my App on my phone to check it, it close on the second it opens and says: ""Name of app" stopped"

its just autoclose without even go to main layout

p.s tnx for help guys!

Debug says:

Target device: 54d1969c Installing APK: C:\Users\Erel\AndroidStudioProjects\AccountSaver\app\build\outputs\apk\app-debug.apk Uploading file to: /data/local/tmp/com.erelbiran.accountsaver com.android.ddmlib.AdbCommandRejectedException: device unauthorized. This adb server's $ADB_VENDOR_KEYS is not set Try 'adb kill-server' if that seems wrong. Otherwise check for a confirmation dialog on your device.

MainActivity

package com.erelbiran.accountsaver;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


    DB myDB;
    Button btnAdd;
    EditText User = (EditText)findViewById(R.id.EnterUser), Pass = (EditText)findViewById(R.id.EnterPass), Acc = (EditText)findViewById(R.id.EnterAcc);

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        openDB();
        btnAdd.setOnClickListener(
                new View.OnClickListener()
                {
                public void onClick(View view) {
                    myDB.insertRow(User.getText().toString(), Pass.getText().toString(), Acc.getText().toString());
                    Toast.makeText(MainActivity.this, "Account Added!", Toast.LENGTH_SHORT).show();
                }}
                 );




    }
    private void openDB(){
        myDB = new DB(this);
        myDB.open();
    }
    private void closeDB(){
        myDB.close();
    }

}

Menifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.erelbiran.accountsaver">

    <application
        android:debuggable="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Database Code:

// ------------------------------------ DBADapter.java ---------------------------------------------

package com.erelbiran.accountsaver;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DB {

    /////////////////////////////////////////////////////////////////////
    //  Constants & Data
    /////////////////////////////////////////////////////////////////////
    // For logging:
    private static final String TAG = "DBAdapter";

    // DB Fields
    public static final String KEY_ROWID = "_id";
    public static final int KEY_ACCID = 0;
    public static final String KEY_USER = "username";
    public static final String KEY_PASS = "password";
    public static final String KEY_ACC = "accounts";

    //
    // Setup fields
    public static final int COL_USER = 1;
    public static final int COL_PASS = 2;
    public static final int COL_ACC = 3;


    public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_USER, KEY_PASS, KEY_ACC};

    // DB info: it's name, and the table we are using (just one).
    public static final String DATABASE_NAME = "MyDb";
    public static final String DATABASE_TABLE = "mainTable";
    public static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE_SQL =
            "create table " + DATABASE_TABLE
                    + " (" + KEY_ACCID + " integer primary key autoincrement, "
                    + KEY_USER + " string not null, "
                    + KEY_PASS + " string not null, "
                    + KEY_ACC + " string not null"

                    // Rest  of creation:
                    + ");";

    // Context of application who uses us.
    private final Context context;

    private DatabaseHelper myDBHelper;
    private SQLiteDatabase db;

    /////////////////////////////////////////////////////////////////////
    //  Public methods:
    /////////////////////////////////////////////////////////////////////

    public DB(Context ctx) {
        this.context = ctx;
        myDBHelper = new DatabaseHelper(context);
    }

    // Open the database connection.
    public DB open() {
        db = myDBHelper.getWritableDatabase();
        return this;
    }

    // Close the database connection.
    public void close() {
        myDBHelper.close();
    }

    // Add a new set of values to the database.
    public long insertRow(String username   , String password  , String account) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_USER, username);
        initialValues.put(KEY_PASS, password);
        initialValues.put(KEY_ACC, account);


        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    // Delete a row from the database, by rowId (primary key)
    public boolean deleteAcc(long accId) {
        String where = KEY_ACCID + "=" + accId;
        return db.delete(DATABASE_TABLE, where, null) != 0;
    }

    public void deleteAll() {
        Cursor c = getAllRows();
        long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
        if (c.moveToFirst()) {
            do {
                deleteAcc(c.getLong((int) rowId));
            } while (c.moveToNext());
        }
        c.close();
    }



    // Return all data in the database.
    public Cursor getAllRows() {
        String where = null;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
                where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = KEY_ROWID + "=" + rowId;
        Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
                where, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        return c;
    }




    /////////////////////////////////////////////////////////////////////
    //  Private Helper Classes:
    /////////////////////////////////////////////////////////////////////

    /**
     * Private class which handles database creation and upgrading.
     * Used to handle low-level database access.
     */
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DATABASE_CREATE_SQL);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading application's database from version " + oldVersion
                    + " to " + newVersion + ", which will destroy all old data!");

            // Destroy old database:
            _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

            // Recreate new database:
            onCreate(_db);
        }
    }
}
4

There are 4 best solutions below

1
On

You have some erros with your code.

Error1:

EditText User = (EditText)findViewById(R.id.EnterUser), Pass = (EditText)findViewById(R.id.EnterPass), Acc = (EditText)findViewById(R.id.EnterAcc);

You have to move it to onCreate. You can not call findViewById outside a method.

You should change it to:

public class MainActivity extends Activity {

    DB myDB;
    Button btnAdd;
    EditText User,Pass, Acc;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        User = (EditText)findViewById(R.id.EnterUser);
        Pass = (EditText)findViewById(R.id.EnterPass);
        Acc = (EditText)findViewById(R.id.EnterAcc);
    }
}

NOTE that findViewById is called after setContentView()

Error2:

You are setting a clickListener in a null object:

btnAdd is created but not instantiated. You have to find the View that btnAdd should point to. Use findViewByID before setOnClickListener:

public class MainActivity extends Activity {
    Button btnAdd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        btnAdd = (Button)findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(......
    }
}

Error3

String used to create database is wrong. Column names should be inside quotes.

Change it to something like:

From

public class DB {
    private static final String DATABASE_CREATE_SQL =
        "create table " + DATABASE_TABLE
        + " (" + KEY_ACCID + " integer primary key autoincrement, "
        + KEY_USER + " string not null, "
        + KEY_PASS + " string not null, "
        + KEY_ACC + " string not null"
        + ");";
}

To

public class DB {
    private static final String DATABASE_CREATE_SQL =
        "create table " + DATABASE_TABLE
        + " (\"" + KEY_ACCID + "\" integer primary key autoincrement, \""
        + KEY_USER + "\" string not null, \""
        + KEY_PASS + "\" string not null, \""
        + KEY_ACC + "\" string not null"
        + ")";
}
0
On

onCreate(Bundle) is where you initialize your activity.
Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically. Try to get your ui in onCreate(Bundle ) Just try

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    User = (EditText)findViewById(R.id.EnterUser);
    Pass = (EditText)findViewById(R.id.EnterPass);
    Acc = (EditText)findViewById(R.id.EnterAcc);
0
On

your Error is this line:

  EditText User = (EditText)findViewById(R.id.EnterUser), 
Pass = (EditText)findViewById(R.id.EnterPass),
 Acc = (EditText)findViewById(R.id.EnterAcc);

move it to OnCreate() of your activity

0
On

Follow these stepes to fix your problem if you still have errors:

  1. Install USB driver(can easily download from vendor site)
  2. Check for USB Debugging(in mobile) and Tools->Enable Integration(in Android SDK)
  3. Connect your device,first Uncheck and then Check USB Debugging(in mobile) a dialog will be shown to confirm authorisation(Works for me)