我想在本地sqlite数据库中保存用户配置文件和用户信息

时间:2018-04-12 20:53:46

标签: java android database sqlite

  

我已经完成了登录和注册的firebase身份验证,现在我想要   在本地sqlite数据库中保存用户配置文件。我已经抓住了用户   来自firebase的信息并将它们存储在字符串变量中   将这些变量传递给Adduser函数以保存此数据   本地数据库。但是没有存储数据并显示"错误   保存用户"那就是rowid是" -1"总是。我是android的新手。   请帮我解决这个问题。提前谢谢

java文件

 package com.example.mansi.busezon;

import android.app.Application;
import android.content.ContentValues;
mport android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mansi.busezon.data.dbContract;
import com.example.mansi.busezon.data.dbHelper;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
i
public class SELL_BUY extends AppCompatActivity {
   // private  dbHelper mDbHelper;
    String name;
    String email ;
    String address ;
    String phoneno ;
    String password ;
    //String userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                // Set the content of the activity to use the activity_main.xml layout file
                setContentView(R.layout.activity_sell__buy);

            check();


        TextView BUY= (TextView) findViewById(R.id.buy);
                BUY.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //create intent to open the activity
                       Intent BUYintent= new Intent(SELL_BUY.this,HomeActivity.class);
                        //start the new activity
                        startActivity(BUYintent);
                    }
                });

                TextView SELL= (TextView) findViewById(R.id.sell);
                SELL.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //create intent to open the activity
                        Intent SELLintent= new Intent(SELL_BUY.this,SellHomepage.class);
                        //start the new activity
                        startActivity(SELLintent);
                    }
                });
            }
    public void sendMessage(View view)
    {
        Intent intent = new Intent(SELL_BUY.this, profile_page.class);
        startActivity(intent);
    }



    private void check()
    {
        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        //database reference pointing to demo node
//        DatabaseReference demoRef = rootRef.child("CI8hvEW0sfZ0oU1GziTpGYPJv2z2");
//        String value = "User22";
//        //push creates a unique id in database
//        demoRef.push().setValue(value);
        rootRef.addListenerForSingleValueEvent(new ValueEventListener()
        {
            String userId=getIntent().getStringExtra("Id");
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                    for(DataSnapshot ds : dataSnapshot.getChildren())
                    {
                        if(ds.getKey().equals(userId))
                        {
                            //name1="aakritijohar";

                            name = ds.child("name").getValue(String.class);
                            email = ds.child("email").getValue(String.class);
                            address = ds.child("addres").getValue(String.class);
                            phoneno = ds.child("phoneno").getValue(String.class);
                            TextView textView = (TextView) findViewById(R.id.test);
                            textView.setText(phoneno);
                            password = ds.child("password").getValue(String.class);
                            Toast.makeText(SELL_BUY.this, email + " " + ds.getKey(), Toast.LENGTH_SHORT).show();
                            insertUser(name,email,address,phoneno,password);
                        }
                    }
                Bundle extras=getIntent().getExtras();
                if(extras!=null) {
                    String name = extras.getString("name");
                }

                }

            @Override
        public void onCancelled(DatabaseError databaseError) {}

        });
    }

    private void insertUser(String nameString,String EMAILString,String addressString,String numbertString,String pass) {
        // Create database helper
        dbHelper mDbHelper = new dbHelper(this);

        // Gets the database in write mode
        SQLiteDatabase db = mDbHelper.getWritableDatabase();




        ContentValues values = new ContentValues();

        values.put(dbContract.userEntry.COLUMN_USER_NAME, nameString);
        values.put(dbContract.userEntry.COLUMN_EMAIL, EMAILString);
        values.put(dbContract.userEntry.COLUMN_number, numbertString);
        values.put(dbContract.userEntry.COLUMN_address, addressString);
        values.put(dbContract.userEntry.COLUMN_password, pass);

        // Insert a new row for user in the database, returning the ID of that new row.
        long newRowId = db.insert(dbContract.userEntry.TABLE_NAME, null, values);

        // Show a toast message depending on whether or not the insertion was successful
        if (newRowId == -1) {
            // If the row ID is -1, then there was an error with insertion.
            Toast.makeText(this, "Error with saving user", Toast.LENGTH_SHORT).show();
        } else {
            // Otherwise, the insertion was successful and we can display a toast with the row ID.
            Toast.makeText(this, "user saved " + newRowId, Toast.LENGTH_SHORT).show();
        }
    }

        }

数据库助手类

   package com.example.mansi.busezon.data;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;




/**
 * Database helper for Pets app. Manages database creation and version management.
 */
public class dbHelper extends SQLiteOpenHelper {

    public static final String LOG_TAG = dbHelper.class.getSimpleName();

    /** Name of the database file */
    private static final String DATABASE_NAME = "user.db";

    /**
     * Database version. If you change the database schema, you must increment the database version.
     */
    private static final int DATABASE_VERSION = 1;

    /**
     * Constructs a new instance of {@link dbHelper}.
     *
     * @param context of the app
     */
    public dbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    /**
     * This is called when the database is created for the first time.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Create a String that contains the SQL statement to create the pets table
        String SQL_CREATE_USER_TABLE =  "CREATE TABLE " + dbContract.userEntry.TABLE_NAME + " ("
                + dbContract.userEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + dbContract.userEntry.COLUMN_USER_NAME + " TEXT NOT NULL, "
                + dbContract.userEntry.COLUMN_address + " VARCHAR, "
                + dbContract.userEntry.COLUMN_number + " VARCHAR NOT NULL, "
                + dbContract.userEntry.COLUMN_EMAIL + " VARCHAR NOT NULL, "
                + dbContract.userEntry.COLUMN_password + " VARCHAR NOT NULL );";

        // Execute the SQL statement
        db.execSQL(SQL_CREATE_USER_TABLE);
    }

    /**
     * This is called when the database needs to be upgraded.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // The database is still at version 1, so there's nothing to do be done here.
    }
}

1 个答案:

答案 0 :(得分:0)

代码似乎没有任何问题。

因此我怀疑您的问题可能是您在运行应用程序后更改了表结构。

  • e.g。通过添加新列然后相应地更改代码

但是,您没有考虑到 img_id = 0; $.each($(this)[0].files, function(i, file){ if (input.files && input.files[0]) { ++img_id; var reader = new FileReader(); reader.onload = function (e) { $('#display_image').prepend("<img id='"+img_id+"' src='"+e.target.result+"' />"); }; reader.readAsDataURL(input.files[count]); } count++; }); 方法仅在创建数据库时自动调用。

这就是每次启动应用程序时都不会运行'onCreate'方法。

我建议删除应用程序的数据或卸载应用程序,然后重新运行应用程序将解决问题。

如果这不能解决问题,那么请检查日志,因为它应包含堆栈跟踪,以便onCreate遇到问题,即使应用程序本身没有崩溃(您可以使用<{1}}方法代替insert,然后会导致异常/崩溃。

如果您仍有问题,请更新问题以包含堆栈跟踪。