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

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

Related

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.database.sqlite.SQLiteDatabase.getVersion()' on a null object reference

Heyhey :)
I looked at several Questions to the same topic, but I found no solution to my problem.
and my button of add to bag it does not work
anyone here know how to help me
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.database.sqlite.SQLiteDatabase.getVersion()' on a null object reference
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:178)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
at com.yanistk.tkfood.Database.Database.getCarts(Database.java:26)
at com.yanistk.tkfood.Cart.loadListFood(Cart.java:102)
at com.yanistk.tkfood.Cart.onCreate(Cart.java:63)
The Logcat:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.database.sqlite.SQLiteDatabase.getVersion()' on a null object reference
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:178)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
at com.yanistk.tkfood.Database.Database.getCarts(Database.java:26)
at com.yanistk.tkfood.Cart.loadListFood(Cart.java:102)
at com.yanistk.tkfood.Cart.onCreate(Cart.java:63)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
2020-06-15 17:16:35.213 1759-1908/system_process E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
2020-06-15 17:16:35.213 1759-1908/system_process E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
2020-06-15 17:16:35.587 2379-14186/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting service_kind=0 source=16 tag=Measurement.PackageMeasurementTaskService.UPLOAD_TASK_TAG target_package=com.google.android.gms requires_charging=0 source_version=200414000 required_network_type=0 flex_time=506000 target_class=com.google.android.gms.measurement.PackageMeasurementTaskService runtime=1592237795535 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} required_idleness_state=0 period=1014000 last_runtime=0 task_type=0 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1474)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at aozt.a(:com.google.android.gms#200414022#20.04.14 (040700-294335909):147)
at aozi.a(:com.google.android.gms#200414022#20.04.14 (040700-294335909):182)
at aozi.a(:com.google.android.gms#200414022#20.04.14 (040700-294335909):25)
at aozi.a(:com.google.android.gms#200414022#20.04.14 (040700-294335909):177)
at aovr.run(:com.google.android.gms#200414022#20.04.14 (040700-294335909):8)
at srw.b(:com.google.android.gms#200414022#20.04.14 (040700-294335909):14)
at srw.run(:com.google.android.gms#200414022#20.04.14 (040700-294335909):2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at sxw.run(:com.google.android.gms#200414022#20.04.14 (040700-294335909):0)
at java.lang.Thread.run(Thread.java:761)
2020-06-15 17:21:35.235 1759-2314/system_process E/ActivityManager: Found activity ActivityRecord{73a2e8e u0 com.yanistk.tkfood/.MainActivity t74 f} in proc activity list using null instead of expected ProcessRecord{d5573e 16555:com.yanistk.tkfood/u0a80}
database
package com.yanistk.tkfood.Database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import com.google.firestore.v1.StructuredQuery;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
import com.yanistk.tkfood.model.Order;
import java.util.ArrayList;
import java.util.List;
public class Database extends SQLiteAssetHelper {
private static final String DB_NAME="jsonDB.db";
private static final int DB_VER=1;
public Context context;
public Database(Context context) {
super(context, DB_NAME, null, DB_VER);
this.context=context;
}
public List<Order> getCarts(){
SQLiteDatabase db=this.getReadableDatabase();
SQLiteQueryBuilder qb=new SQLiteQueryBuilder();
String[]sqlSelect={"ProductName","ProductId","Quantity","Price","Discount"};
String sqlTable="OrderDetail";
qb.setTables(sqlTable);
Cursor c=qb.query(db,sqlSelect,null,null,null,null,null);
final List<Order>result=new ArrayList<>();
if (c.moveToFirst()){
do {
result.add(new Order(c.getString(c.getColumnIndex("ProductId")),
c.getString(c.getColumnIndex("ProductName")),
c.getString(c.getColumnIndex("Price")),
c.getString(c.getColumnIndex("Quantity")),
c.getString(c.getColumnIndex("Discount"))
));
}while (c.moveToNext());
}
return result;
}
public void addToCart(Order order){
SQLiteDatabase db=this.getReadableDatabase();
String query=String.format("INSERT OR REPLACE INTO OrderDetail(ProductId,ProductName,Quantity,Price,Discount) VALUES('%s','%s','%s','%s','%s');",
order.getProductId(),
order.getProductName(),
order.getPrice(),
order.getQuantity(),
order.getDiscount());
db.execSQL(query);
}
public void cleanCart(){
SQLiteDatabase db=this.getReadableDatabase();
String query=String.format("DELETE FROM OrderDetail");
db.execSQL(query);
}
}
cart.java
package com.yanistk.tkfood;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.yanistk.tkfood.Common.Common;
import com.yanistk.tkfood.Database.Database;
import com.yanistk.tkfood.model.Order;
import com.yanistk.tkfood.model.Request;
import com.yanistk.tkfood.viewHolder.CartAdapter;
import java.util.ArrayList;
import java.util.List;
public class Cart extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference requests;
TextView txtTotalPrice;
Button btnPlace;
List<Order> cart=new ArrayList<>();
CartAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
database=FirebaseDatabase.getInstance();
requests=database.getReference("Requests");
//Init
recyclerView=(RecyclerView)findViewById(R.id.listCart);
recyclerView.setHasFixedSize(true);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
txtTotalPrice=(TextView)findViewById(R.id.total);
btnPlace=(Button)findViewById(R.id.btnPlace);
btnPlace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAlertDialog();
}
});
loadListFood();
}
private void showAlertDialog() {
AlertDialog.Builder alertDialog=new AlertDialog.Builder(Cart.this);
alertDialog.setTitle("Un pas de plus");
alertDialog.setMessage("Entrer votre address(Le lieu de livraion): ");
final EditText edtAddress=new EditText(Cart.this);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
edtAddress.setLayoutParams(lp);
alertDialog.setView(edtAddress);
alertDialog.setPositiveButton("Envoyer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Request request=new Request(
Common.currentUser.getName(),
Common.currentUser.getPhone(),
edtAddress.getText().toString(),
txtTotalPrice.getText().toString(),
cart
);
//submit to firebase
requests.child(String.valueOf(System.currentTimeMillis()))
.setValue(request);
//delete cart
new Database(getBaseContext()).cleanCart();
Toast.makeText(Cart.this, "Merci de passer la commande", Toast.LENGTH_SHORT).show();
finish();
}
});
alertDialog.show();
}
private void loadListFood() {
cart=new Database(this).getCarts();
adapter=new CartAdapter(cart,this);
recyclerView.setAdapter(adapter);
//calculate total
int total=0;
for (Order order:cart){
total+=(Integer.parseInt(order.getPrice()))*(Integer.parseInt(order.getQuantity()));
txtTotalPrice.setText(total);
}
}
}

How can I redirect 2 buttons to different intents in android?

enter image description here
I put a listener on each button that takes me to different activities.
The login button works perfectly, but the register button stops the app when I click on it.
I've tried to put a Toast message in the _btnreg listener, and it worked...
I got this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.virtualshelter, PID: 24128
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.virtualshelter/com.example.android.virtualshelter.register}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.android.virtualshelter.register.onCreate(register.java:35)
at android.app.Activity.performCreate(Activity.java:6754)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6247) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity
{
Button _btnreg, _btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_btnlogin = findViewById(R.id.btnlogin);
_btnreg = findViewById(R.id.btnreg);
_btnreg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,register.class);
startActivity(intent);
}
});
_btnlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(MainActivity.this,login.class);
startActivity(intent);
}
});
}
}
My register.java code
package com.example.android.virtualshelter;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
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 register extends AppCompatActivity
{
SQLiteOpenHelper openHelper;
SQLiteDatabase db;
Button _btnReg;
EditText _txtfname, _txtlname, _txtpass, _txtemail, _txtphone;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
openHelper = new DatabaseHelper(register.this);
_txtfname = findViewById(R.id.txtfname);
_txtlname = findViewById(R.id.txtlname);
_txtpass = findViewById(R.id.txtpass);
_txtemail = findViewById(R.id.txtemail);
_txtphone = findViewById(R.id.txtphone);
_btnReg = findViewById(R.id.btnreg);
_btnReg.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
db = openHelper.getWritableDatabase();
String fname = _txtfname.getText().toString();
String lname = _txtlname.getText().toString();
String pass = _txtpass.getText().toString();
String email = _txtemail.getText().toString();
String phone = _txtphone.getText().toString();
insertdata(fname, lname, pass, email, phone);
Toast.makeText(getApplicationContext(), "register successfully", Toast.LENGTH_LONG).show();
}
});
}
public void insertdata(String fname, String lname, String pass, String email, String phone)
{
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_2, fname);
contentValues.put(DatabaseHelper.COL_3, lname);
contentValues.put(DatabaseHelper.COL_4, pass);
contentValues.put(DatabaseHelper.COL_5, email);
contentValues.put(DatabaseHelper.COL_6, phone);
long id = db.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
}
}
I expect to go to activity register.java, but the app is crashing
My hunch is, you are not able find the button, causing a NPE when setting the listner. Could be that you don't have the button defined in R.layout.activity_main, but in a different layout.

ClassCastException : Fragment cannot be cast to Fragment

I have that app when, in MainActivity(which here is LoginActivity) first is replaced with a fragment(LoginFragment), for the sake of good code.
If a user want to signup, is redirected to a new SignUpFragment directly from mainActivity supportFragment manager:
//setting the first fragment in onCreate
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
//Opening new registration fragment in LoginFragment.java
signUpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((LoginActivity)getActivity()).loadSignUpFragment();
}
});
//In LoginActvity.java
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
all good, is working at first opening. Trying to register a new user, is working
But, after applying some minor code changes(like showing a snackbar if login fails), i got that error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.minimalart.studentlife/com.minimalart.studentlife.activities.LoginActivity}: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519)
at android.app.ActivityThread.-wrap19(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassCastException: com.minimalart.studentlife.fragments.SignUpFragment cannot be cast to com.minimalart.studentlife.fragments.LoginFragment
at com.minimalart.studentlife.activities.LoginActivity$override.onCreate(LoginActivity.java:38)
at com.minimalart.studentlife.activities.LoginActivity$override.access$dispatch(LoginActivity.java)
at com.minimalart.studentlife.activities.LoginActivity.onCreate(LoginActivity.java:0)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4519) 
at android.app.ActivityThread.-wrap19(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
why i got that?
i'm switching and opening fragments only from my main activity
Thanks.
all LoginActivity.java:
package com.minimalart.studentlife.activities;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.minimalart.studentlife.R;
import com.minimalart.studentlife.fragments.LoginFragment;
import com.minimalart.studentlife.fragments.SignUpFragment;
public class LoginActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = FirebaseAuth.getInstance();
fragmentManager = getSupportFragmentManager();
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentById(R.id.activity_main_content);
if(fragment == null){
fragment = LoginFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.activity_main_content, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit();
}
}
public void loadSignUpFragment(){
SignUpFragment fragmentSignUp = SignUpFragment.newInstance();
fragmentManager.beginTransaction().replace(R.id.activity_main_content, fragmentSignUp).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).addToBackStack(null).commit();
}
public void signUpNewUser(String email, String pass, String firstName, String secName, String age){
firebaseAuth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
}
else{
Snackbar.make(findViewById(R.id.signUpLinearLayout), task.getException().getLocalizedMessage(), Snackbar.LENGTH_LONG).show();
}
// ...
}
});
}
public void logInUser(String email, String pass){
}
}
I solved this, i found that the problem is at declaring main fragment
replaced
LoginFragment fragment = (LoginFragment)fragmentManager.findFragmentById(R.id.activity_main_content);
with
Fragment fragment = fragmentManager.findFragmentById(R.id.activity_main_content);
thanks #Selvin for your hint :)

App crashes during Bluetooth discovery

What I'm trying to do
I'm trying to create an app that searches all the Bluetooth devices nearby and connects to the ones user wishes to connect to.
I'm trying to create a Connect button in one activity that starts the discovery function in another activity
How I'm trying to do it
So I have this MainActivity.java class / activity that has the Connect button. Upon clicking this button, it should do three things:
Check if the Bluetooth on my Smartphone is on & if it's not, turn it on.
Display a TOAST message to show whether BT has been successfully turned on or not
Start this new activity, called SearchBTDevice.java that looks for nearby BT devices & list them in a ListView
The first two are perfectly working since they're on MainActivity.java & that's where my button has been created.
Problem comes when it creates the new activity & tries to do the 3rd one. The app crashes.
This is what my MainActivity.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import static java.lang.Thread.sleep;
public class MainActivity extends AppCompatActivity {
public BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
private int REQ_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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 connect(View v)
{
if(BA == null)
Toast.makeText(MainActivity.this, "System Doesn't Support Bluetooth", Toast.LENGTH_SHORT).show();
else if(!BA.isEnabled())
{
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQ_CODE);
}
else {
Toast.makeText(MainActivity.this, "ALREADY ON!!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode!=RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "TURNED ON!", Toast.LENGTH_SHORT).show();
searchBTDevices();
}
else
Toast.makeText(MainActivity.this,"FAILED TO ENABLE BLUETOOTH", Toast.LENGTH_LONG).show();
}
public void searchBTDevices()
{
Thread searchThread = new Thread() {
#Override
public void run() {
Intent searchBT = new Intent(getApplicationContext(), SearchBTDevice.class);
startActivity(searchBT);
}
};
searchThread.start();
}
}
This is what my SearchBTDevice.java looks like
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter, BTArrayAdapter;
public IntentFilter filter = new IntentFilter();
public ListView devicesFound;
public Set<BluetoothDevice> pairedDevices;
private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(!BTArrayAdapter.isEmpty())
BTArrayAdapter.clear();
searchBTDevices();
}
public void searchBTDevices()
{
pairedDevices = BlueAdapter.getBondedDevices();
if(pairedDevices.size()>0)
for(BluetoothDevice device: pairedDevices)
PairedArrayAdapter.add(device.getName() + "\t\t" + device.getAddress() + "\n");
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
PairedArrayAdapter.add(btd.getName() + "\t\t" + btd.getAddress() + "\n");
}
}
};
BlueAdapter.startDiscovery();
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
}
}
This is what the logcat shows when my app crashes
03-17 11:51:40.120 19178-19178/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: main
Process: vertex2016.mvjce.edu.bluealert, PID: 19178
java.lang.RuntimeException: Unable to start activity ComponentInfo{vertex2016.mvjce.edu.bluealert/vertex2016.mvjce.edu.bluealert.SearchBTDevice}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.ArrayAdapter.isEmpty()' on a null object reference
at vertex2016.mvjce.edu.bluealert.SearchBTDevice.onCreate(SearchBTDevice.java:57)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
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:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
So these are my questions:
Where am I going wrong & what should I do?
Is there any way I can retrieve the BluetoothAdapter, which was created in my MainActivity.java, in my new activity called SearchBTDevice.java?
Is there anyway I can set the onClick operation of a button defined in one activity from another activity?
Thank you for your time!
Define your BTArrayAdapter object in SearchBTDevice class. It is null while you call BTArrayAdapter.isEmpty() in onCreate().

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