在TextView中显示SQLite中的项目

时间:2016-01-25 08:48:48

标签: java android sqlite textview

我试图在TextView中显示来自SQLite的数据app_type。 以下是我试过的代码。但是在TextView中显示数据的代码似乎有问题,因为如果我运行显示活动,应用程序就会停止。

Bathroom.java(主要活动)

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;

public class bathroom extends Activity implements OnClickListener {
Button buttonOne,buttonTwo;
static String status="a";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bathroom);
    buttonOne = (Button) findViewById(R.id.add_tv);
    buttonTwo = (Button) findViewById(R.id.add_fan);
    buttonOne.setOnClickListener(this);
    buttonTwo.setOnClickListener(this);
}
@Override
public void onClick(View v) {       

    switch (v.getId()) {
        case R.id.add_tv:
            status="Television";
            Log.d("Mr.bool", "Button1 was clicked " + status);
            break;
        case R.id.add_fan:
            status="Amplifier";
            Log.d("MR.bool", "Button2 was clicked " + status);
           break;
        default:
            break;
    }
    Intent myIntent = new Intent(this,RegisterActivity.class);
    myIntent. putExtra("appleMessage", status);
    startActivity(myIntent);

    }
public static String getStatus(){
    return status;
}

}

RegisterActivity(用于将数据注册到SQLite中)

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity{
    EditText USER_NAME, POWER, USAGE;
    TextView APP_TYPE;
    String app_type, user_name, power, usage;
    Button REG;
    Context ctx=this;
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_layout);

    DisplayMetrics dm=new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    int width=dm.widthPixels;
    int height=dm.heightPixels;


    getWindow().setLayout((int)(width*.8),(int)(height*.6));

    Bundle status=getIntent().getExtras();
    String appleMessage=status.getString("appleMessage");
    APP_TYPE =(TextView)findViewById(R.id.app_type);
    APP_TYPE.setText(appleMessage);

    USER_NAME =(EditText) findViewById(R.id.reg_user);
    POWER =(EditText) findViewById(R.id.reg_power);
    USAGE =(EditText) findViewById(R.id.usage);
    REG = (Button) findViewById(R.id.user_reg);
    REG.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            app_type=APP_TYPE.getText().toString();
            user_name=USER_NAME.getText().toString();

            power=POWER.getText().toString();
            usage=USAGE.getText().toString();

            double power_input=Integer.parseInt(power);
            double usage_input=Integer.parseInt(usage);
            double power_used=(power_input*usage_input);
            if(user_name.equals("")||power.equals("")||usage.equals("")){
                Toast.makeText(getBaseContext(),"Please complete the details", Toast.LENGTH_LONG).show();
            }
            else{
                DatabaseOperations DB=new DatabaseOperations(ctx);
                DB.putInformation(DB,app_type, user_name, power,usage,power_used);
                Toast.makeText(getBaseContext(),"Appliance successfully added", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    });
}

}

DatabaseOperations.java

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;

import com.example.shyan.database.TableData.TableInfo;

public class DatabaseOperations extends SQLiteOpenHelper {

public static final int database_version = 1;
public String CREATE_QUERY = "CREATE TABLE " + TableInfo.TABLE_NAME + "(" +
        TableInfo.APP_TYPE + " TEXT, " +
        TableInfo.USER_NAME + " TEXT, " +
        TableInfo.POWER + " TEXT, " +
        TableInfo.USAGE + " TEXT, " +
        TableInfo.POWER_USED + " TEXT " + ");";

public DatabaseOperations(Context context) {
    super(context, TableInfo.DATABASE_NAME, null, database_version);
    Log.d("Database operations", "Database created");
}

@Override
public void onCreate(SQLiteDatabase sdb) {
    sdb.execSQL(CREATE_QUERY);
    Log.d("Database operations", "Table created");
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {

}

public void putInformation(DatabaseOperations dop, String type, String name, String power, String usage, Double power_used) {
    SQLiteDatabase SQ = dop.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(TableInfo.APP_TYPE, type);
    cv.put(TableInfo.USER_NAME, name);
    cv.put(TableInfo.POWER, power);
    cv.put(TableInfo.USAGE, usage);
    cv.put(TableInfo.POWER_USED, power_used);
    long k = SQ.insert(TableInfo.TABLE_NAME, null, cv);
    Log.d("Database operations", "One row inserted");
    }

   public static String databaseToString() {
       String dbString = "";
       SQLiteDatabase db = this.getWritableDatabase();
       String query = "SELECT "+TableInfo.APP_TYPE +" FROM " + TableInfo.TABLE_NAME + " WHERE 1";
       //Cursor points to a location in your results
       Cursor c = db.rawQuery(query, null);
       //Move to the first row in your results
       c.moveToFirst();
       //Position after the last row means the end of the results
       while (!c.isAfterLast()) {
           if (c.getString(c.getColumnIndex( "app_type")) != null) {
               dbString += c.getString(c.getColumnIndex( "app_type"));
               dbString += "\n";
           }
           c.moveToNext();
       }
       db.close();
       return dbString;
   }

}

RegisterList.java(显示数据的地方)

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterList extends Activity {
TextView title, app_list;
Context CTX = this;

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

    title = (TextView) findViewById(R.id.title);
    printDatabase();
}

public void printDatabase(){
    String dbString;
    dbString = DatabaseOperations.databaseToString();
    app_list.setText(dbString);
    }
}

register_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="List of Appliances"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/app_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dp"
    android:textAppearance="?android:attr/textAppearanceMedium" />

错误

C:\Users\shyan\AndroidStudioProjects\Database\app\src\main\java\com\example\shyan\database\DatabaseOperations.java
Error:(51, 28) error: non-static variable this cannot be referenced from a static context
C:\Users\shyan\AndroidStudioProjects\Database\app\src\main\java\com\example\shyan\database\RegisterList.java
Error:(30, 38) error: cannot find symbol method databaseToString()
Note: C:\Users\shyan\AndroidStudioProjects\Database\app\src\main\java\com\example\shyan\database\MainActivity.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

1 个答案:

答案 0 :(得分:0)

添加全局变量DBHelper并使用如下

public class DatabaseOperations extends SQLiteOpenHelper {
      ...
      private static DatabaseHelper DBHelper;
      ...
      public DatabaseOperations(Context context) {
        super(context, TableInfo.DATABASE_NAME, null, database_version);
        Log.d("Database operations", "Database created");
        DBHelper = new DatabaseHelper(context);
      }
      ...
      public static String databaseToString() {
        ...
        SQLiteDatabase db = DBHelper.getWritableDatabase();
        ...
      }
 }