Android Studio crashes when trying to google search words from TextEdit - java

I am writing code where I need to google search item from textedit from previous screen. But when I press the button to search, android studio crashes, what do I do wrong?
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
TextView name;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
name = findViewById(R.id.textView3);
button = findViewById(R.id.Button2);
String Name = getIntent().getStringExtra("text");
name.setText(name.getText().toString()+ "" + Name);
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//https://www.google.com/#q=
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/#q=" + name.getText())));
}
});
}
}
My crash stacktraces:
D/AndroidRuntime: Shutting down VM E/AndroidRuntime: FATAL EXCEPTION:
main Process: com.example.myapplication, PID: 17740
java.lang.IllegalStateException: Could not find method onClick(View)
in a parent or ancestor Context for android:onClick attribute defined
on view class androidx.appcompat.widget.AppCompatButton with id
'Button2' at
androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:436)
at
androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:393)
at android.view.View.performClick(View.java:7125) at
android.view.View.performClickInternal(View.java:7102) at
android.view.View.access$3500(View.java:801) at
android.view.View$PerformClick.run(View.java:27336) at
android.os.Handler.handleCallback(Handler.java:883) at
android.os.Handler.dispatchMessage(Handler.java:100) at
android.os.Looper.loop(Looper.java:214) at
android.app.ActivityThread.main(ActivityThread.java:7356) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I/Process: Sending signal. PID: 17740 SIG: 9 Disconnected from the
target VM, address: 'localhost:8621', transport: 'socket'

You do not define an onClickListerner for your button.
I think name.setOnClickListener must be button.setOnClickListener
BTW: Do not use the same variable name in two different cases:
TextView name; and
String Name =.
By convention variable names should start with lower case character

Related

Problem with Android Networking (Using Google Book API and LoadManager/ AsyncTaskLoader)

Having problems debugging an android networking application. I think I might have some problems with the import but I don't know which. If you can see the problem, please do let me know. Thank you.
MainActivity.java
package com.example.networkingfinals;
import androidx.appcompat.app.AppCompatActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<BookInfo>> {
private String url;
private String input;
private BookAdapter bookAdapter;
private int LOADER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.input);
input = String.valueOf(editText.getText());
url = "https://www.googleapis.com/books/v1/volumes?q="+input+"&maxResults=3";
}
});
LoaderManager loaderManager = getLoaderManager();
getLoaderManager().initLoader(LOADER_ID, null, this);//Set loader manager to call asyncloader in onCreateLoader
//TODO: Implement AsyncTaskLoader and LoadManager fetching network data on parallel thread
}
#Override
public Loader<List<BookInfo>> onCreateLoader(int id, Bundle args) {
Loader<List<BookInfo>> books = new BookAsync(this, url);
return books;
//Call oncreate Loader , fetching List of Book Info
}
#Override
public void onLoadFinished(Loader<List<BookInfo>> loader, List<BookInfo> data) {
Log.v("onLoadFinished", "Return " + data);
bookAdapter.addAll(data);
}
#Override
public void onLoaderReset(Loader loader) {
bookAdapter.clear();
}
Logcat
2021-01-10 18:44:55.950 13590-13590/com.example.networkingfinals V/onCreateLoader: Return BookAsync{814c192 id=0}
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals V/onLoadFinished: Return null
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals D/AndroidRuntime: Shutting down VM
2021-01-10 18:44:56.055 13590-13590/com.example.networkingfinals E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.networkingfinals, PID: 13590
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:61)
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:17)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:497)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:465)
at android.content.Loader.deliverResult(Loader.java:157)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:274)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:97)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
2021-01-10 18:44:56.138 13590-13590/com.example.networkingfinals I/Process: Sending signal. PID: 13590 SIG:
I think I don't understand how onCreateLoader() and onLoadFinished() works. I tried and find that onCreateLoader return non-null data but in onLoadFinished() the data passed into it was null.
This error is because your adapter is not initialized yet you need to initialize it in onCreate
this.bookAdapter = new BookAdapter();
the error message says
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
that means is your adapter is null and you call addAll from the null object reference

TextWatcher shuts down my application after starting up

My app keeps crashing since I started using a TextWatcher...
As you can see below i made a TextWatcher to 3 EditText fields...
And i made a button which listens to the 3 EditText..
If they are empty the button become disabled.
When the fields are filled the button should become enabled..
package com.example.magazijnapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.MenuPopupWindow;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Array;
public class MainActivity extends AppCompatActivity {
Spinner spinnermagazijn;
Button knop;
private EditText EditTextregisternummerbalk;
private EditText EditTextticketnummerbalk;
private EditText EditTextartikelnummerbalk;
private Button knopconfirm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextregisternummerbalk = findViewById(R.id.registernummerbalk);
EditTextticketnummerbalk = findViewById(R.id.ticketnummerbalk);
EditTextartikelnummerbalk = findViewById(R.id.artikelnummerbalk);
knopconfirm = findViewById(R.id.knop);
EditTextregisternummerbalk.addTextChangedListener(invulTextWatcher);
EditTextticketnummerbalk.addTextChangedListener(invulTextWatcher);
EditTextartikelnummerbalk.addTextChangedListener(invulTextWatcher);
}
private TextWatcher invulTextWatcher = 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) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
knopconfirm.setEnabled(!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
{
spinnermagazijn = findViewById(R.id.spinnermagazijn);
knop = findViewById(R.id.knop);
populatespinnermagazijn();
// Dit is het stukje voor de Knop afboeken waarmee je een melding genereerd, String aanpassen voor ander resultaat.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
}
// Dit gedeelte is voor de spinner.
private void populatespinnermagazijn() {
ArrayAdapter<String> magazijnenAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.steunpunten));
magazijnenAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnermagazijn.setAdapter(magazijnenAdapter);
}
}
And this is my logcat...
03-19 21:04:06.293 21151-21151/? E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
03-19 21:04:06.293 21151-21151/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-19 21:04:06.293 21151-21151/? I/art: Not late-enabling -Xcheck:jni (already on)
03-19 21:04:06.313 21151-21161/? I/art: Debugger is no longer active
03-19 21:04:06.351 21151-21151/? D/AndroidRuntime: Shutting down VM
03-19 21:04:06.354 21151-21151/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.magazijnapp, PID: 21151
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.magazijnapp/com.example.magazijnapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
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:5254)
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.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.magazijnapp.MainActivity.<init>(MainActivity.java:73)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
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:5254) 
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) 
03-19 21:04:07.996 21151-21151/? I/Process: Sending signal. PID: 21151 SIG: 9
There are two findViewById(R.id.knop);
remove this line:
knop = findViewById(R.id.knop);
and change :
knopconfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
You are saying your app is crashing since you started using TextWatcher. So why don't you stop using it?
you can achieve the same thing without using TextWatcher by doing this.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
if((!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty())) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
}
});
you will not need any TextWathcer just modify the listner

New To Android Development: App Runs On My MacBook Pro But Fails With Kotlin Typecast Exception on iMac

This is the weirdest thing.. A few weeks ago I ran into this issue and found the solution to be to update the Gradle Runtime, which I did on both computers. I decided I wanted to sit at my desk with my iMac and work last night, but could not get the app to run do to a Kotlin Typecast Exception. I switched to the remote branch I have pulled on my MacBook, but got this error:
09-23 12:28:29.112 4141-4141/com.example.pmarl.peedeehealthadvisor E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pmarl.peedeehealthadvisor, PID: 4141
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pmarl.peedeehealthadvisor/com.example.pmarl.peedeehealthadvisor.MainActivity}: kotlin.TypeCastException: null cannot be cast to non-null type android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
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:5254)
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: kotlin.TypeCastException: null cannot be cast to non-null type android.widget.Button
at com.example.pmarl.peedeehealthadvisor.MainActivity.onCreate(MainActivity.kt:31)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
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:5254) 
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) 
I panic'd and tested the MacBook again, but it worked fine.
`
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private Button MyHealthData;
private Button MyHealthResources;
private boolean firstStart;
#Override
protected void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
/*First time open code*/
SharedPreferences app_preferences = getApplicationContext()
.getSharedPreferences("MyPref",0);
SharedPreferences.Editor editor = app_preferences.edit();
firstStart = app_preferences.getBoolean("first_time_start",true);
/*If statement to see if the app has been open before or not*/
if(firstStart)
{
/*If the app hasn't been opened before, it runs the following code
* and sets firstStart to false*/
editor.putBoolean("first_time_start",false);
editor.commit();
//do your one time code here
launchFirstTimeLogIn();
//Toast.makeText(this,"This is first app run!", Toast.LENGTH_LONG).show();
}
else
{
//app open directly
Toast.makeText(this, "Welcome!!!", Toast.LENGTH_LONG).show();
}
this.MyHealthData = (Button) findViewById(R.id.MyHealthData);
this.MyHealthData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchMyHealthData();
}
});
this.MyHealthResources = (Button) findViewById(R.id.HealthResources);
this.MyHealthResources.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
launchSearchServiceActivity();
}
});
}
private void launchMyHealthData()
{
Intent intent = new Intent (this, MyHealthDataActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
private void launchSearchServiceActivity()
{
Intent intent = new Intent (this, SearchServiceActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
private void launchFirstTimeLogIn()
{
Intent intent = new Intent(this, FirstTimeLogin.class);
intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK | intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
`
Both are the same Gradle versions, and the same version of Android Studio. I"m not sure what this would be caused by? My logic says that if it is the Button causing the issue, like the posts I found say, it wouldn't work on my MacBook.
Thank you for the help everyone!
null cannot be cast to non-null type android.widget.Button
I'm assuming that you declared a Button like this: (for example)
mineBtn = findViewById(R.id.yourbtnid) as Button
Add "?" after the as:
mineBtn = findViewById(R.id.yourbtnid) as? Button
Then error should be gone.
Edit: Remove this. before declaring widgets. And declare a widget like this:
MyHealthData = (Button) findViewById(R.id.MyHealthData);
Note that it's better to change R.id.MyHealthData from xml layout to be make sure it won't cause other issues in future.

E/SQLiteLog: (1) near "ENTER": syntax error

I'm getting this weird error while trying to create a database. I'm building an expense manager app and want to store the data from textview into SQLite database but I'm getting these errors when I press the save button. IS This because I'm trying to create database in another activity rather than the MainActivity??
07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 E/SQLiteLog: (1) near "ENTER": syntax error
07-20 01:49:31.032 28795-28795/com.example.alkesh.expensemanager101 D/AndroidRuntime: Shutting down VM
--------- beginning of crash
07-20 01:49:31.042 28795-28795/com.example.alkesh.expensemanager101 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alkesh.expensemanager101, PID: 28795
Theme: themes:{default=overlay:com.baranovgroup.nstyle, iconPack:com.baranovgroup.nstyle, fontPkg:com.baranovgroup.nstyle, com.android.systemui=overlay:com.baranovgroup.nstyle, com.android.systemui.navbar=overlay:com.baranovgroup.nstyle}
android.database.sqlite.SQLiteException: near "ENTER": syntax error (code 1): , while compiling: ENTER INTO money (name) VALUES ('25');
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.alkesh.expensemanager101.AddMoney.insertIntoDatabase(AddMoney.java:95)
at com.example.alkesh.expensemanager101.AddMoney.onClick(AddMoney.java:63)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
Here's my code for the AddMoney Activity
package com.example.alkesh.expensemanager101;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddMoney extends AppCompatActivity implements View.OnClickListener{
Button Save,Cancel;
EditText expText;
int[] expense=new int[100];
int temp=900;
int c=0;
int sum=0;
String DBOnce;
private SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_money);
expText=(EditText)findViewById(R.id.expense);
Cancel=(Button)findViewById(R.id.cancelbutton);
Cancel.setOnClickListener(this);
Save = (Button)findViewById(R.id.savebutton);
Save.setOnClickListener(this);
CreateDatabase();
}
#Override
public void onClick(View view) {
if(view== Save){
insertIntoDatabase();
}
if(view==Cancel){
Intent intent =new Intent(AddMoney.this,MainActivity.class);
startActivity(intent);
finish();
}
}
protected void CreateDatabase(){
db=openOrCreateDatabase("MoneyDB", Context.MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS money(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR);");
}
protected void insertIntoDatabase(){
String amount = expText.getText().toString().trim();
if(amount.equals("")){
Toast.makeText(this,"Please enter your expense or press Cancel to go back",Toast.LENGTH_LONG).show();
return;
}
String query="ENTER INTO money (name) VALUES ('"+amount+"');";
db.execSQL(query);
Toast.makeText(this,"Expense Saved",Toast.LENGTH_LONG).show();
}
}
Here's my code for MainActivity.
package com.example.alkesh.expensemanager101;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button Add;
TextView expense;
int c=0;
String DBonce="0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add = (Button) findViewById(R.id.addbutton);
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddMoney.class);
intent.putExtra("counter", DBonce);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menuhome,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.feedback:{}
break;
case R.id.exit: finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
In AddMoney Activity function insertIntoDatabase() change your query Enter to INSERT

Error while opening Android app

i am new to android development and i am writing an app for my college project .The app transmits a string of data stored in shared preferences .The data is stored by one time setup screen which is never shown again.The issue is after first time,when app is started again it shows that "app has unfortunately stopped working "and when i click ok the app starts.Can anybody tell me why this is happening?
Code:
package com.example.homeautomation.zigbeehomeauto;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainScreen extends ActionBarActivity {
NdefMessage msg;
NfcAdapter nfcadapter;
public static final String PREFS_NAME = "MyPrefsFile";
public String pass2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
String Pass = check.getString("Str", "Nothing");
pass2 = Pass;
nfcadapter = NfcAdapter.getDefaultAdapter(this);
if (nfcadapter == null) {
Toast.makeText(this, "NFC is not available User", Toast.LENGTH_LONG)
.show();
finish();
}
}
public void ExApp(View v) {
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void Nsend(View v)
{
byte[] stringBytes = pass2.getBytes();
nfcadapter.setNdefPushMessage(msg = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", stringBytes)
}),this);
}
}
Logcat Ouput:
04-07 12:04:38.478 10836-10836/com.example.homeautomation.zigbeehomeauto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.homeautomation.zigbeehomeauto, PID: 10836
android.util.SuperNotCalledException: Activity {com.example.homeautomation.zigbeehomeauto/com.example.homeautomation.zigbeehomeauto.SetupScreen} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2603)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5752)
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:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Check in your SetupScreen.java do you have super.onCreate(savedInstanceState);
after onCreate() Method is starts .
post your SetupScreen.java code also ..
Your onCreate() method of class SetupScreen do not call the super.onCreate(). Add the statement and the error should go away.

Categories

Resources