gpt4 book ai didi

android - 如何在表布局中动态添加行或如何在单表布局中显示完整的数据库记录

转载 作者:行者123 更新时间:2023-11-29 17:16:31 26 4
gpt4 key购买 nike

你好 Techie :) 我是 android 的新手。我正在开发一个应用程序,用户在其中注册所有个人详细信息和移动设备详细信息,并且在用户登录后所有事情都正常工作并遇到结果但是当我移动到管理部分时我有问题,我对此一无所知。

我卡住的部分管理部分:-1) 管理员登录后,所有表格记录应显示在一个表格布局中,您可以说我想在表格布局中填充所有表格记录。

我尝试使用特定的用户名并将其显示在表格布局中,但这不是我的要求,我必须在表格布局中显示所有用户。

我在这里分享我的代码,你们会建议我下一步做什么以及我怎样才能达到我的要求。感谢您的宝贵时间:)

//MainActivity.java

package com.example.yadapras.mobiltyemp;
import android.content.Context;
import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.VectorEnabledTintResources; import android.telephony.TelephonyManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;

/** * Created by yadapras on 6/26/2016. */ public class MainActivity extends AppCompatActivity {


EditText a,b;
String usr,pass;
DatabaseHelper helper = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

public void onButtonClick(View v)
{
if (v.getId() == R.id.BLogin)
{
a = (EditText)findViewById(R.id.userName);
usr = a.getText().toString();
b = (EditText)findViewById(R.id.userPassword);
pass = b.getText().toString();



String password = null;

if( a.getText().toString().length() == 0 || usr == "" || usr == null)
a.setError( " User name is required!" );
if( b.getText().toString().length() == 0 || pass =="" || pass == null)
b.setError( "Password is required!" );
else{
password = helper.searchPass(usr);
}

if (a.getText().toString().equals("admin") && b.getText().toString().equals("admin"))
{
Intent intent = new Intent(getApplicationContext(), AdminDisplay.class);
startActivity(intent);
}else{
if (pass.equals(password) && password != null) {
Intent intent = new Intent(getApplicationContext(), EmpDetail.class);
intent.putExtra("usr", usr);

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String uid = telephonyManager.getDeviceId();
String manufacturer = Build.MANUFACTURER; // Not used in current scenario
String model = Build.MODEL;
int version = Build.VERSION.SDK_INT;
String versionRelease = Build.VERSION.RELEASE; // not used in current scenario
String msg = "IMEI No: " + uid + "\n" + "Manufacturer is :" + manufacturer + "\n" + "Model is :" + model + "\n" + "Os Version is :" + version + "\n" + "VersionRelease is :" + versionRelease;
Toast toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG);
toast.show();

Register r = new Register();
r.setImei_no(uid);
r.setDev_model(model);
r.setOs_version(version);
r.setUname(usr);

helper.updateTable(r); /*For updating table with new Coloumn*/

startActivity(intent);
}
else
{
Toast err_pass = Toast.makeText(MainActivity.this,"UserName and Password don't Match",Toast.LENGTH_SHORT);
err_pass.show();
}
}


}
if (v.getId() == R.id.BSignup)
{
Intent intent = new Intent(getApplicationContext(), Registration.class);
startActivity(intent);
}
}

}

//DatabaseHelper.java

    package com.example.yadapras.mobiltyemp;

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

import org.json.JSONException;
import org.json.JSONObject;

/**
* Created by yadapras on 7/8/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {


private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "registrationDB.db";
public static final String TABLE_NAME = "registrations";

public static final String COLUMN_ID = "id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_PASSWORD= "password";
public static final String COLUMN_RE_PASSWORD= "re_password";
public static final String COLUMN_NAME= "name";
public static final String COLUMN_EMAIL= "email";
public static final String COLUMN_PHONE_NO= "phone_no";

/*Adding three coloumn IMEI_NO,OS_Version,Model_Device Respectively*/

public static final String COLUMN_IMEI_NO = "imei_no";
public static final String COLUMN_DEV_MODEL = "dev_model";
public static final String COLUMN_OS_VERSION = "os_version";


SQLiteDatabase sqLiteDatabase;
private static final String TABLE_CREATE = "create table registrations(id integer primary key not null, " +
"username text not null, password text not null, re_password text not null, name text not null, email text not null," +
"phone_no number not null,imei_no text, dev_model text, os_version text);";


public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);
this.sqLiteDatabase=sqLiteDatabase;
Log.d("#####Table Value",TABLE_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS " +TABLE_NAME ;
sqLiteDatabase.execSQL(query);
this.onCreate(sqLiteDatabase);
}

public void registerUser(Register r) {
/*Inserting anything in to the dataBase make sure it should be writable*/
sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();

String query = "select * from registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);

int count = cursor.getCount();

Log.d("##count",""+count);
values.put(COLUMN_ID,count);
Log.d("##id",r.getUname());
values.put(COLUMN_USERNAME,r.getUname());
values.put(COLUMN_PASSWORD,r.getPassword());
values.put(COLUMN_RE_PASSWORD,r.getRe_password());
values.put(COLUMN_NAME,r.getName());
values.put(COLUMN_EMAIL, r.getEmail());
values.put(COLUMN_PHONE_NO, r.getPhone_no());

sqLiteDatabase.insert(TABLE_NAME, null,values); /*this will insert Register object in to the Database*/

sqLiteDatabase.close();
}

public String searchPass(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query = "select username,password from "+TABLE_NAME;
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
String a,b ; // a and b will be userName and Password respectively
b = "Not Found";
if (cursor.moveToFirst())
{
do {
a = cursor.getString(0);
Log.d("##username from db",a);
if (a.equals(usr))
{
b = cursor.getString(1);
break;
}
}while (cursor.moveToNext());
}
return b;
}

public JSONObject showDetail(String usr) {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations where username='"+usr+"'" ;//"select * from registrations where username = p";
// String query = "SELECT * FROM registrations";
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
JSONObject data = new JSONObject();
if (cursor.moveToFirst()){
do {

int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));
for (int idx=0; idx<columnsQty; ++idx) {
try {
data.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}

}
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}

public void updateTable(Register r) {
SQLiteDatabase db = getWritableDatabase();

ContentValues cv = new ContentValues();

cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
db.update(TABLE_NAME,cv,"username = ?",new String[]{r.getUname()});; /*Working for all fields*/

/*SQLiteDatabase db = getWritableDatabase();

ContentValues cv = new ContentValues();

cv.put(COLUMN_IMEI_NO,r.getImei_no());
Log.d("###Column_IMEI_NO",r.getImei_no());
cv.put(COLUMN_DEV_MODEL,r.getDev_model());
cv.put(COLUMN_OS_VERSION,r.getOs_version());
String updateQuery = "Update registrations set " + COLUMN_IMEI_NO + " = '"+ r.getImei_no() +"' where " + COLUMN_USERNAME + "="+"'"+ r.getUname() +"'";
db.execSQL(updateQuery);
db.close();*/
}

}

//AdminDisplay.java

    package com.example.yadapras.mobiltyemp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class AdminDisplay extends AppCompatActivity {


DatabaseHelper helper = new DatabaseHelper(this);
TextView id,name,email,mobileno,imei_no,dev_model ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_display);
TableLayout table = (TableLayout)findViewById(R.id.tableLayout1) ;
id = (TextView)findViewById(R.id.admin_usr_id);
name = (TextView)findViewById(R.id.admin_Uname);
email = (TextView)findViewById(R.id.admin_usr_email);
mobileno = (TextView)findViewById(R.id.admin_usr_phone);
imei_no = (TextView)findViewById(R.id.admin_usr_imeiNo);
dev_model = (TextView)findViewById(R.id.admin_usr_dev_model);

JSONObject details = helper.showDetail("pcu9044"); // ***Here i'm trying registered user so i'm getting only this user field in TableLayout .***

for (int i=0; i<details.length();i++){
TableRow row = (TableRow)findViewById(R.id.tableRow1);

try {
table.removeView(row);
((TextView)row.findViewById(R.id.admin_usr_id)).setText(details.getString("id"));
((TextView)row.findViewById(R.id.admin_usr_email)).setText(details.getString("email"));
((TextView)row.findViewById(R.id.admin_Uname)).setText(details.getString("name"));
((TextView)row.findViewById(R.id.admin_usr_phone)).setText(details.getString("phone_no"));
((TextView)row.findViewById(R.id.admin_usr_imeiNo)).setText(details.getString("imei_no"));
((TextView)row.findViewById(R.id.admin_usr_dev_model)).setText(details.getString("dev_model"));
table.addView(row);
} catch (JSONException e) {
e.printStackTrace();
}

}
}
}

我附上了我的输出的屏幕截图,如果有人有任何疑问,请随时询问。提前谢谢你。

Result output with my code

最佳答案

我在这里看到的问题是当你说:

"i try with specific user name and its showing in the table layout but it's not my requirement , i have to show all users in Table layout".

通过从数据库中搜索单个用户,您只会在数据库中检索与您要搜索的用户名相关联的单个记录。您的方法 helper.showDetail() 返回一个 JSONObject - 此对象对应于数据库中用户名 = pcu9044 的记录。

如果我对您的情况的理解正确,您需要调用一个方法来从数据库中选择所有记录,以便在屏幕上显示您想要的内容。您的 helper.showDetail() 将是一个好的开始,但您可以稍微修改代码以实现您想要的效果。

我建议使用 JSONObject 列表或数组,而不是单个 JSONObject。在输入 if (cursor.moveToFirst()) 条件(就像你现在拥有的)之前初始化你的数据结构,但在循环的每次迭代中,你创建一个新对象,用什么填充它游标返回该行,然后将其添加到结构中。代码看起来像这样:

public JSONArray showDetail() {
sqLiteDatabase = this.getReadableDatabase();
String query ="SELECT * FROM registrations";// * THIS WILL RETURN ALL RECORDS IN REGISTRATIONS
Cursor cursor = sqLiteDatabase.rawQuery(query,null);
//JSONObject data = new JSONObject(); *change this to an array
JSONArray data = new JSONArray();
if (cursor.moveToFirst()){
do {

int columnsQty = cursor.getColumnCount();
Log.d("###count-->", String.valueOf(columnsQty));

// Must create a new object each time you iterate to a new row to add to the array
JSONObject record = new JSONObject();

for (int idx=0; idx<columnsQty; ++idx) {
try {
// Fill the object
record.put(cursor.getColumnName(idx),cursor.getString(idx));
} catch (JSONException e) {
e.printStackTrace();
}

}

// Add the object to the array and repeat
data.put(record);
}while (cursor.moveToNext());
}
cursor.close();
Log.d("###Data Value",data.toString());
return data;
}

如果您这样做,您的 helper.showDetail() 将返回一个数组,其中填充了对象,每个对象代表一行。然后,您的 AdminDisplay.java 应该循环遍历数组,抓取每个对象,并用您需要的信息填充一个新行。

希望这对您有所帮助!

关于android - 如何在表布局中动态添加行或如何在单表布局中显示完整的数据库记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38609507/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com