Help with ListView Database - database

I am having issues # run with this code: App Force Closing..
Sprinter.Java
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
public class Sprinter extends ListActivity {
/** Called when the activity is first created. */
final static String MY_DB_NAME = "Sprinter";
final static String MY_DB_TABLE = "Stations";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase myDB = null;
try {
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + "_id integer primary key autoincrement, name varchar(100);");
myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Oceanside Transit Center');");
myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Coast Highway');");
Cursor mCursor = myDB.rawQuery("SELECT name" + " FROM " + MY_DB_TABLE, null);
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, mCursor, new String[] { "name" }, new int[] { R.id.Name });
this.setListAdapter(adapter);
this.getListView().setTextFilterEnabled(true);
} finally {
if (myDB != null) {
myDB.close();
}
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="#id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Data"
/>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="#+id/LinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>

For the SimpleCursorAdapter you need to also select a primary ID called _id. You only need this in your cursor, you don't have to use it for anything.
Cursor mCursor = myDB.rawQuery("SELECT _id, name" + " FROM " + MY_DB_TABLE, null);

Related

I'm having trouble creating a Kotlin database adapter

I'm trying to build a room database app with Kotlin. Database part is ok. I need to create adapter to show database data in Recyclerview. But I can't use the holder command. I think it might be related to "Kotlinx.Synthetic has been deprecated". I want to introduce textviews id's to adapter. When i try "holder.itemView.id_txt.text = currentItem.id.toString()" it does not recognize "id_txt.text". Can you help with introduce the custom row's textview ids to adapter. Thank you.
User.kt
import androidx.room.Entity
import androidx.room.PrimaryKey
#Entity(tableName = "user_table")
data class User(
#PrimaryKey(autoGenerate = true)
val id: Int,
val firstName: String,
val lastName: String,
val age: String
)
UserDao.kt
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
#Dao
interface UserDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun addUser(user: User)
#Query("SELECT * FROM user_table ORDER BY id ASC")
fun readAllData(): LiveData<List<User>>
}
UserDatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
#Database(entities = [User::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
#Volatile
private var INSTANCE: UserDatabase? = null
fun getDatabase(context: Context): UserDatabase{
val tempInstance = INSTANCE
if(tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
UserDatabase::class.java,
"user_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
UserRepository.kt
import androidx.lifecycle.LiveData
class UserRepository(private val userDao: UserDao) {
val readAllData: LiveData<List<User>> = userDao.readAllData()
suspend fun addUser(user: User){
userDao.addUser(user)
}
}
UserViewModel.kt
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class UserViewModel(application: Application): AndroidViewModel(application) {
private val readAllData: LiveData<List<User>>
private val repository: UserRepository
init {
val userDao = UserDatabase.getDatabase(application).userDao()
repository = UserRepository(userDao)
readAllData = repository.readAllData
}
fun addUser(user: User){
viewModelScope.launch(Dispatchers.IO) {
repository.addUser(user)
}
}
}
AddFragment.kt
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.basehw.R
import com.example.basehw.data.UserViewModel
import com.example.basehw.databinding.FragmentAddBinding
import android.text.TextUtils
import android.widget.Toast
import com.example.basehw.data.User
class AddFragment : Fragment() {
private lateinit var mUserViewModel: UserViewModel
private var _binding: FragmentAddBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentAddBinding.inflate(inflater, container, false)
mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java)
binding.addBtn.setOnClickListener{
insertDataToDatabase()
}
return binding.root
}
private fun insertDataToDatabase() {
val firstName = binding.addFirstNameEt.text.toString()
val lastName = binding.addFirstNameEt.text.toString()
val age = binding.addAgeEt.text.toString()
if(inputCheck(firstName, lastName, age)){
// Create User Object
val user = User(
0,
firstName,
lastName,
age
)
// Add Data to Database
mUserViewModel.addUser(user)
Toast.makeText(requireContext(), "Successfully added!", Toast.LENGTH_LONG).show()
// Navigate Back
findNavController().navigate(R.id.action_addFragment_to_listFragment)
}else{
Toast.makeText(requireContext(), "Please fill out all fields.", Toast.LENGTH_LONG).show()
}
}
override fun onDestroy() {
super.onDestroy()
}
private fun inputCheck(firstName: String, lastName: String, age: String): Boolean{
return !(TextUtils.isEmpty(firstName) && TextUtils.isEmpty(lastName) && age.isEmpty())
}
}
ListFragment.kt
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.basehw.R
import com.example.basehw.databinding.FragmentListBinding
class ListFragment : Fragment() {
private var _binding: FragmentListBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
_binding = FragmentListBinding.inflate(inflater, container, false)
binding.floatingActionButton.setOnClickListener{
findNavController().navigate(R.id.action_listFragment_to_addFragment)
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
}
}
ListAdapter.kt
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.adapter.FragmentViewHolder
import com.example.basehw.R
import com.example.basehw.data.User
import com.example.basehw.databinding.ActivityMainBinding
import com.example.basehw.databinding.FragmentListBinding
class ListAdapter: RecyclerView.Adapter<ListAdapter.MyViewHolder>() {
private var binding: ActivityMainBinding? = null
private var userList = emptyList<User>()
class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.custom_row, parent, false))
}
override fun getItemCount(): Int {
return userList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = userList[position]
holder.itemView.id_txt.text = currentItem.id.toString()
holder.itemView.firstName_txt.text = currentItem.firstName
holder.itemView.lastName_txt.text = currentItem.lastName
holder.itemView.age_txt.text = currentItem.age.toString()
}
fun setData(user: List<User>){
this.userList = user
notifyDataSetChanged()
}
}
custom_row.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/custom_row"
android:padding="24sp">
<TextView
android:id="#+id/id_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/_1"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/firstName_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="80dp"
android:text="#string/john"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/id_txt"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/lastName_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:text="#string/dao"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/firstName_txt"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/age_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:textSize="24sp"
android:text="#string/_25"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/lastName_txt"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_list.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.list.ListFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
android:clickable="true"
android:focusable="true"
android:tint="#color/white"
android:src="#drawable/ic_add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="SpeakableTextPresentCheck" />
</androidx.constraintlayout.widget.ConstraintLayout>
As Kotlinx.Synthetics has been deprecated, you should use view binding which you are already using in your fragment and activity, you should also use it in your RecyclerView adapter.
Make a few changes in your recycler view adapter to work with view bindings.
class ListAdapter: RecyclerView.Adapter<ListAdapter.MyViewHolder>() {
private var userList = emptyList<User>()
class MyViewHolder(private val customRowBinding: CustomRowBinding): RecyclerView.ViewHolder(customRowBinding.root) {
fun bind(user: User) {
customRowBinding.idTxt.text = user.id.toString()
customRowBinding.firstNameTxt.text = user.firstName
customRowBinding.lastNameTxt.text = user.lastName
customRowBinding.ageTxt.text = user.age.toString()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
return MyViewHolder(CustomRowBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
override fun getItemCount(): Int {
return userList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = userList[position]
holder.bind(currentItem)
}
fun setData(user: List<User>){
this.userList = user
notifyDataSetChanged()
}
}
Instead of binding data inside onBindViewHolder, create a bind() method inside the view holder and bind there.

Fetch SQL data into table layout in Android Studio

I just started programming using android. Currently, I want to set table layout in activity_main.xml like the picture below and retrieve/display data from SQL server database into it.
I have tried the following things.
I created some subclasses that interprets table in real database like ScanAdapter.java, ScanResultModel.java and I created also new layout scanresult.xml to provide identity of TextView in table row.
Set and design activity_main.xml
The problem is I don't know how to created the code to retrieve data from SQL database server. I did not find the solution.
Here is the activity_main.xml code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/txtlabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:hint="Scan Label No"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.089" />
<EditText
android:id="#+id/txtqty"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:hint="Enter Qty"
android:inputType="number"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.168" />
<EditText
android:id="#+id/txtrmrks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:hint="Enter Remarks"
android:inputType="textAutoCorrect"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.244" />
<TextView
android:id="#+id/txtconnect"
android:layout_width="255dp"
android:layout_height="19dp"
android:text="con"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.41"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.99" />
<TextView
android:id="#+id/txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan Barcode Label"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.464"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.009" />
<Button
android:id="#+id/btn_scan"
android:layout_width="89dp"
android:layout_height="48dp"
android:text="Scan"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.027"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.948" />
<Button
android:id="#+id/btn_save"
android:layout_width="89dp"
android:layout_height="48dp"
android:text="Save"
app:backgroundTint="#8CD635"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.326"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.948" />
<Button
android:id="#+id/btn_load"
android:layout_width="89dp"
android:layout_height="48dp"
android:onClick="Loaddgv"
android:text="Load"
app:backgroundTint="#8CD635"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.627"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.948" />
<Button
android:id="#+id/btn_clear"
android:layout_width="89dp"
android:layout_height="48dp"
android:onClick="clearScan"
android:text="Clear"
app:backgroundTint="#8CD635"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.93"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.948" />
<TableLayout
android:layout_width="395dp"
android:layout_height="358dp"
android:layout_margin="8dp"
android:stretchColumns="1,2,3,4"
tools:context=".MainActivity"
tools:layout_editor_absoluteX="9dp"
tools:layout_editor_absoluteY="255dp"
android:background="#E8EEF3">
<TableRow
android:layout_height="1px"
android:background="#BDBDBD">
<TextView
android:layout_column="1"
android:gravity="center"
android:padding="10dp"
android:text="LabelNo"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:layout_column="1"
android:gravity="center"
android:padding="10dp"
android:text="Qty"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:layout_column="1"
android:gravity="center"
android:padding="10dp"
android:text="Remarks"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:layout_column="1"
android:gravity="center"
android:padding="10dp"
android:text="ScanDate"
android:textSize="16dp"
android:textStyle="bold" />
</TableRow>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout >
MainActivity.java
package com.nid.shikakarikensa;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
Connection connect;
String ConnectionResult;
private Button btnScan, btnSave, btnLoad, btnClear;
private TextView tstatus,tconnect, tusrid,msg;
private EditText trmrks, tqty, tlblno;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScan = findViewById(R.id.btn_scan);
btnSave = findViewById(R.id.btn_save);
btnLoad = findViewById(R.id.btn_load);
btnClear = findViewById(R.id.btn_clear);
tstatus = findViewById(R.id.txtstatus);
tqty = findViewById(R.id.txtqty);
trmrks = findViewById(R.id.txtrmrks);
tusrid = findViewById(R.id.txtuserid);
tlblno = findViewById(R.id.txtlabel);
tconnect = findViewById(R.id.txtconnect);
tlblno.requestFocus();
tlblno.setEnabled(false);
btnScan.setOnClickListener(s ->
{
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CAMERA)) {
startScan();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{Manifest.permission.CAMERA}, 0);
}
} else {
startScan();
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String lblno = tlblno.getText().toString();
String qty = tqty.getText().toString();
if (lblno.isEmpty() || qty.isEmpty()){
Toast.makeText(MainActivity.this, "Please check your details data!", Toast.LENGTH_SHORT).show();
return;
}
SaveDataToDB(v);
tlblno.getText().clear();
tqty.getText().clear();
trmrks.getText().clear();
}
});
}
public void clearScan(View v)
{
tlblno.getText().clear();
tqty.getText().clear();
trmrks.getText().clear();
MessageBox("Data Cleared");
}
public void MessageBox(String message)
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void startScan()
{
Intent intent = new Intent(getApplicationContext(), ScannerActivity.class);
startActivityForResult(intent, 20);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 20) {
if (resultCode == RESULT_OK && data!=null) {
String code = data.getStringExtra("result");
tlblno.setText(code);
}
}
}
#Override
public void onRequestPermissionsResult (int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startScan();
} else {
Toast.makeText(this,"Failed to open camera!", Toast.LENGTH_LONG).show();
}
}
}
#SuppressLint("SetTextI18n")
public void SaveDataToDB(View v)
{
String lblno = tlblno.getText().toString();
String rmrks = trmrks.getText().toString();
String usrid = tusrid.getText().toString();
String value = tqty.getText().toString();
int qty=Integer.parseInt(value);
try {
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connectionclass();
if (connect!=null) {
String query = "exec dbo.i_shikakarikensa '"+lblno+"', '"+qty+"', '"+rmrks+"','"+usrid+"' ";
Statement statement = connect.createStatement();
ResultSet result = statement.executeQuery(query);
Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
} else {
ConnectionResult = "Database connection error";
}
}
catch (Exception ex)
{
Log.e("Set Error", ex.getMessage());
}
}
}
ScanAdapter.java
package com.nid.shikakarikensa;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class ScanAdapter extends RecyclerView.Adapter<ScanAdapter.ViewHolder> {
Context context;
List<ScanResultModel> scanresult_list;
public ScanAdapter(Context context, List<ScanResultModel> scanresult_list) {
this.context = context;
this.scanresult_list = scanresult_list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.dgvscanrslt, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (scanresult_list != null && scanresult_list.size() > 0 ){
ScanResultModel model = scanresult_list.get(position);
holder.gvlabel.setText(model.getLabelNo());
holder.gvqty.setText(model.getQty());
holder.gvrmrks.setText(model.getRmrks());
holder.gvscandt.setText(model.getInsTs());
} else {
return;
}
}
#Override
public int getItemCount() {
return scanresult_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView gvlabel,gvqty,gvrmrks,gvscandt;
public ViewHolder(#NonNull View itemView) {
super(itemView);
gvlabel = itemView.findViewById(R.id.gvlabel);
gvqty = itemView.findViewById(R.id.gvqty);
gvrmrks = itemView.findViewById(R.id.gvrmrks);
gvscandt = itemView.findViewById(R.id.gvscandt);
}
}
}
ScanResultModel.java
package com.nid.shikakarikensa;
public class ScanResultModel {
String LabelNo, Qty, Rmrks, InsTs;
public ScanResultModel(String labelNo, String qty, String rmrks, String insTs) {
LabelNo = labelNo;
Qty = qty;
Rmrks = rmrks;
InsTs = insTs;
}
public String getLabelNo() {
return LabelNo;
}
public String getQty() {
return Qty;
}
public String getRmrks() {
return Rmrks;
}
public String getInsTs() {
return InsTs;
}
}
scanresult.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="1"
android:orientation="vertical"
android:padding="5dp">
<TableRow>
<TextView
android:id="#+id/gvlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7F00FF"
android:textSize="17sp" />
<TextView
android:id="#+id/gvqty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7F00FF"
android:textSize="17sp" />
<TextView
android:id="#+id/gvrmrks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7F00FF"
android:textSize="17sp" />
<TextView
android:id="#+id/gvscandt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7F00FF"
android:textSize="17sp" />
</TableRow>
</TableLayout>

How to create a mobile app using xamarin connecting to a database with a form

I am new to microsoft visual studio xamarin
I wanted to create a form with data source,username,database and password input test fields with a connect button to connect to a microsoft sql server database
I have created the interfaces to connect to the sqlserver database but encountered some issues.
strings.xml
<?xml version = "1.0" encoding = "utf-8"?>
<resources>
<string name = "HelloXamarin">Server</string>
<string name = "ApplicationName">connect</string>
<string name = "app_name">connect</string>
<string name = "ButtonClick">Connect</string>
<string name = "username">Username</string>
<string name = "database">Database</string>
<string name = "password">Password</string>
</resources>
activity_main.axml
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:background = "#d3d3d3"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent">
<TextView
android:text = "#string/HelloXamarin"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "#+id/textView2"
android:textColor = "#android:color/black" />
<EditText
android:id="#+id/plain_text_input"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:inputType="text"/>
<TextView
android:text = "#string/database"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "#+id/database"
android:textColor = "#android:color/black" />
<EditText
android:id="#+id/database_text_input"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:inputType="text"/>
<TextView
android:text = "#string/username"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "#+id/username"
android:textColor = "#android:color/black" />
<EditText
android:id="#+id/username_text_input"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:inputType="text"/>
<TextView
android:text = "#string/password"
android:textAppearance = "?android:attr/textAppearanceLarge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:id = "#+id/password"
android:textColor = "#android:color/black" />
<EditText
android:id="#+id/password_text_input"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:inputType="text"/>
<Button
android:id = "#+id/MyButton"
android:layout_width = "fill_parent"
android:layout_height = "wrap_content"
android:text = "#string/ButtonClick" />
</LinearLayout>
Mainactivity.Cs
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Data.SqlClient;
//using System.Data.Sql;
namespace first
{
[Activity(Label = "#string/app_name", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate {
// button.Text = "Hello world I am your first App";
string connectionString = #"Server='test';Database='connect';User Id='test';Password='test';Trusted_Connection=true";
string databaseTable = "Connect";
//string referenceAccountNumber = "0001134919";
string selectQuery = String.Format("SELECT * FROM {0} ", databaseTable);
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
//open connection
connection.Open();
button.Text = "Connection Successful";
SqlCommand command = new SqlCommand(selectQuery, connection);
command.Connection = connection;
command.CommandText = selectQuery;
var result = command.ExecuteReader();
//check if account exists
var exists = result.HasRows;
}
}
catch (Exception exception)
{
#region connection error
AlertDialog.Builder connectionException = new AlertDialog.Builder(this);
connectionException.SetTitle("Connection Error");
connectionException.SetMessage(exception.ToString());
connectionException.SetNegativeButton("Return", delegate { });
connectionException.Create();
connectionException.Show();
#endregion
}
};
}
}
}
However the program gives an error that the type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference)
But i already have defined the assembly
using System.Data.SqlClient;
Anyone has any idea what is wrong?
Resolved.Add reference of system.data.sqlclient using the system.data.dll from the following location:C:\Windows\Microsoft.NET\Framework\v2.0.50727
References->Add reference->Browse
To ensure apps can connect to sqlserver,use the following connection string:
string connectionString = #"Server=servername;Database=databasename;User Id=username;Password=password";

List Adapter receives the objects but it does not display them in the List View

So, here is the case, in the onPostExecute method I have used a ListView and I have adapted a list adapter in it in order to display the objects (events) in a list view. The problem is that the adapter recognizes the objects but it does not display them in the ListView. I have looked of how to populate an Array of Hashmaps with a List adapter and I am prettu sure that I have done it correctly in my code. I think that the problem might be in the xml file. Any ideas that can guide me to the right direction?
This is my xml file:
<?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">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textSize="16sp"/>
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip" />
<TextView
android:id="#+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start"/>
<TextView
android:id="#+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start" />
<TextView
android:id="#+id/time_end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start" />
</LinearLayout>
And the .java file:
public class EventsJSONActivity extends ListActivity {
private static String url = "http://mob.students.acg.edu/json3.php";
public static final String TAG_EVENT_INFO = "eventsinfo";
public static final String TAG_ID = "id";
public static final String TAG_TITLE = "title";
public static final String TAG_DATE = "date";
public static final String TAG_TIME = "time";
public static final String TAG_TIME_END = "time_end";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_json);
new GetEvents().execute();
}
class GetEvents extends AsyncTask<Void,Void,Void> {
ArrayList<HashMap<String,String>> eventList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
proDialog = new ProgressDialog(EventsJSONActivity.this);
Log.d("prodialog: ","Setting Message.");
proDialog.setMessage("Please wait...");
Log.d("prodialog: ","Setting cancellable.");
proDialog.setCancelable(false);
Log.d("prodialog: ","Showing...");
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
WebRequest webreq = new WebRequest();
String url = "http://mob.students.acg.edu/json3.php";
String jsonStr = webreq.makeWebServiceCall(url,WebRequest.POSTRequest);
Log.d("Response: ", "> " + jsonStr);
eventList = ParseJSON(jsonStr);
Log.d("eventList info: " , eventList.toString());
return null;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
if (proDialog.isShowing()) {
proDialog.dismiss();
Log.d("prodialog: ","dismissing dialog.");
}
Log.d("Listadapter: ", "eventList: " + eventList.toString());
ListAdapter adapter = new SimpleAdapter(
EventsJSONActivity.this,eventList,
android.R.layout.simple_list_item_1,
new String[] {TAG_ID, TAG_TITLE, TAG_DATE, TAG_TIME, TAG_TIME_END},
new int[] {R.id.id,R.id.title,R.id.date,R.id.time,R.id.time_end});
Log.d("Listadapter: ","data fed");
ListView lv = (ListView)findViewById(android.R.id.list);
lv.setAdapter(adapter);
Log.d("Listadapter: ",adapter.getCount() + " items set");
}//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
private ArrayList<HashMap<String,String>> ParseJSON(String json) {
if (json != null) {
try {
ArrayList<HashMap<String,String>> eventList = new ArrayList<>();
JSONObject jsonObj = new JSONObject(json);
JSONArray events = jsonObj.getJSONArray(TAG_EVENT_INFO);
for (int i = 0; i < events.length(); i++) {
JSONObject j = events.getJSONObject(i);
String id = j.getString(TAG_ID);
String title = j.getString(TAG_TITLE);
String date = j.getString(TAG_DATE);
String time = j.getString(TAG_TIME);
String time_end = j.getString(TAG_TIME_END);
HashMap<String,String> event = new HashMap<String,String>();
event.put(TAG_ID,id);
event.put(TAG_TITLE,title);
event.put(TAG_DATE,date);
event.put(TAG_TIME,time);
event.put(TAG_TIME_END,time_end);
/*event.put(TAG_ID,"id");
event.put(TAG_TITLE,"title");
event.put(TAG_DATE,"date");
event.put(TAG_TIME,"time");
event.put(TAG_TIME_END,"time_end");*/
eventList.add(event);
}
Log.d("EventList > ", eventList.toString());
return eventList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
}
Try checking the solution that was posted here ... updating ListView from AsyncTask. The runOnUiThread runnable may be what you are missing since the code you have here looks correct. If that doesn't work, you can try creating class levels variables for the listview and/or adapter and modify them in the onPostExecute of AsyncTask.
Hope this helps!

SQLite Database: Unable to get specific entry data

I'm following a tutorial about setting up SQLite database with Android Java. I've created a database and a simple table to contain data about food and its calories. I've setup a few buttons with functions to enter data, view, get information about a specific entry, modify and delete it.
All works well except the button to get a specific entry. When I click on the 'Get Information' button, it's supposed to return with the food name and its calories value, according to the row ID I put.
Can anyone help to look at my code here, to check what's wrong or missing?
Here is the code for the classes. I've excluded some parts which are not related.
Creating the database:
public class FormDatabase
{
public static final String KEY_ROWID = "_id";
public static final String KEY_FOOD = "food_name";
public static final String KEY_CALORIE = "food_calories";
private static final String DATABASE_NAME = "Calories";
private static final String DATABASE_TABLE = "FoodTable";
private static final int DATABASE_VERSION = 2;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper
{
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
KEY_FOOD + " TEXT NOT NULL , " +
KEY_CALORIE + " TEXT NOT NULL);"
);
}
public String getFood(long l) throws SQLException{
// get data of food name
String[] columns = new String[]{ KEY_ROWID, KEY_FOOD, KEY_CALORIE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String food = c.getString(1);
return food;
}
return null;
}
public String getCalorie(long l) throws SQLException{
// get data of food calorie
String[] columns = new String[]{ KEY_ROWID, KEY_FOOD, KEY_CALORIE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" +
l, null, null, null, null);
if (c != null){
c.moveToFirst();
String calorie = c.getString(2);
return calorie;
}
return null;
}
Another class for setting the main page:
public class DatabaseMain extends Activity implements OnClickListener{
Button sqlUpdate, sqlView, sqlModify, sqlGetInfo, sqlDelete;
EditText sqlFood, sqlCalorie, sqlRow;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.database_main);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlFood = (EditText) findViewById(R.id.etSQLFood);
sqlCalorie = (EditText) findViewById(R.id.etSQLCalorie);
sqlView = (Button) findViewById (R.id.bSQLopenView);
sqlView.setOnClickListener(this);
sqlUpdate.setOnClickListener(this);
sqlRow = (EditText) findViewById(R.id.etSQLrowInfo);
sqlModify = (Button) findViewById(R.id.bSQLmodify);
sqlGetInfo = (Button) findViewById(R.id.bgetInfo);
sqlDelete = (Button) findViewById(R.id.bSQLdelete);
sqlDelete.setOnClickListener(this);
sqlModify.setOnClickListener(this);
sqlDelete.setOnClickListener(this);
}
public void onClick(View arg0)
{
// When click on buttons, data entry into database, view, modify and
delete row
switch (arg0.getId())
{
case R.id.bgetInfo:
try {
String s = sqlRow.getText().toString();
long l = Long.parseLong(s);
FormDatabase foodcal = new FormDatabase(this);
foodcal.open();
String returnedFood = foodcal.getFood(l);
String returnedCalories = foodcal.getCalorie(l);
foodcal.close();
sqlFood.setText(returnedFood);
sqlCalorie.setText(returnedCalories);
}catch (Exception e)
{
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("This is an error!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
}
}
The database_main layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width ="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:text="Food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<EditText
android:id="#+id/etSQLFood"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" >
</EditText>
<TextView
android:id="#+id/textView3"
android:text="Food Calorie"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/etSQLCalorie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
<Button
android:text="Update SQLite Database"
android:id="#+id/bSQLUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="View"
android:id="#+id/bSQLopenView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<TextView
android:id="#+id/textView2"
android:text="Enter Row ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/etSQLrowInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" >
<requestFocus></requestFocus>
</EditText>
<Button
android:text="Get Information"
android:id="#+id/bgetInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Edit Entry"
android:id="#+id/bSQLmodify"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Delete Entry"
android:id="#+id/bSQLdelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
to add a check to your switch statement, add a default case:
switch (arg0.getId())
{
case R.id.bgetInfo:
... do something...
break;
default:
//this will handle everything else
// write out the argument for debugging, eg:
Console.WriteLine(arg0.getId().ToString());
break;
}
this will tell you what is coming through. if arg0.getId() is not R.id.bgetInfo, the event won't fire...
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" +
l, null, null, null, null);
instead using above statement use this one
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=?",
new String[] { String.valueOf(l) }, null, null, null, null);

Resources