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>
Related
I'm finding difficulties while using the branch.io(react-native-branch) integration for android for deep-linking app is getting stop after applying changes in mainactivity.java.
react:v17.0.2
react-native:v0.66.4
react-native-branch:v^5.4.0
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eneff.branchandroid">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>
<application
android:allowBackup="true"
android:name="com.eneff.branchandroid.CustomApplicationClass"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:launchMode="singleTask"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Branch URI Scheme -->
<intent-filter>
<data android:scheme="branchandroid" android:host="open" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
<!-- Branch App Links -->
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="uobg.app.link" />
</intent-filter>
</activity>
<!-- Branch keys -->
<!-- (Omit if setting keys in branch.json) -->
<meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_gdzsepIaUf7wG3dEWb3aBkmcutm0PwJa"/>
<meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_edwDakKcMeWzJ3hC3aZs9kniyuaWGCTa"/>
</application>
</manifest>
MainActivity.java
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import io.branch.rnbranch.*;
import android.content.Intent;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
#Override
protected String getMainComponentName() {
return "G4Plus";
}
#Override
protected void onStart() {
super.onStart();
RNBranchModule.initSession(getIntent().getData(), this);
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null &&
intent.hasExtra("branch_force_new_session") &&
intent.getBooleanExtra("branch_force_new_session",false)) {
RNBranchModule.onNewIntent(intent);}
}
#Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
#Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
}
MainApplication.java
package com.g4plus;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.swmansion.reanimated.ReanimatedPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JSIModulePackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.swmansion.reanimated.ReanimatedJSIModulePackage;
import io.branch.rnbranch.RNBranchModule;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
#Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage(); // <- add
}
// overide for branch
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
RNBranchModule.getAutoInstance(this);
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* #param context
* #param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.g4plus.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
I have taken references from the branch.io(react-native-branch) developer guide
https://help.branch.io/developers-hub/docs/react-native
try to downgrade this to version 5.0.0 I was having the same issue on my setup
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.
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!
I took the sample code from How to create custom components in JavaFX 2.0 using FXML?. the code working fine in jdk7 but the checkbox and combo box values are not working in jdk8. I am not able to click the check box even and select the dropdown.
Please guide me for the same.
Please find the sample code below
Package structure
com.example.javafx.choice
ChoiceCell.java
ChoiceController.java
ChoiceModel.java
ChoiceView.fxml
com.example.javafx.mvc
FxmlMvcPatternDemo.java
MainController.java
MainView.fxml
MainView.properties
ChoiceCell.java
package com.example.javafx.choice;
import java.io.IOException;
import java.net.URL;
import javafx.fxml.FXMLLoader;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Node;
import javafx.scene.control.ListCell;
public class ChoiceCell extends ListCell<ChoiceModel>
{
#Override
protected void updateItem(ChoiceModel model, boolean bln)
{
super.updateItem(model, bln);
if(model != null)
{
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try
{
Node root = (Node)fxmlLoader.load(location.openStream());
ChoiceController controller = (ChoiceController)fxmlLoader.getController();
controller.setModel(model);
setGraphic(root);
}
catch(IOException ioe)
{
throw new IllegalStateException(ioe);
}
}
}
}
ChoiceController.java
package com.example.javafx.choice;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
public class ChoiceController
{
private final ChangeListener<String> LABEL_CHANGE_LISTENER = new ChangeListener<String>()
{
public void changed(ObservableValue<? extends String> property, String oldValue, String newValue)
{
updateLabelView(newValue);
}
};
private final ChangeListener<Boolean> IS_SELECTED_CHANGE_LISTENER = new ChangeListener<Boolean>()
{
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue)
{
updateIsSelectedView(newValue);
}
};
private final ChangeListener<Boolean> IS_VISIBILITY1_CHANGE_LISTENER = new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> property, Boolean oldValue, Boolean newValue) {
updateIsVisibleView1(newValue);
}};
#FXML
private Label labelView;
#FXML
private CheckBox isSelectedView;
#FXML
ComboBox isVisible1;
private ChoiceModel model;
public ChoiceModel getModel()
{
return model;
}
public void setModel(ChoiceModel model)
{
if(this.model != null)
removeModelListeners();
this.model = model;
setupModelListeners();
updateView();
}
private void removeModelListeners()
{
model.labelProperty().removeListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().removeListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().removeListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().unbindBidirectional(model.isSelectedProperty());
}
private void setupModelListeners()
{
model.labelProperty().addListener(LABEL_CHANGE_LISTENER);
model.isSelectedProperty().addListener(IS_SELECTED_CHANGE_LISTENER);
model.isVisibleProperty1().addListener(IS_VISIBILITY1_CHANGE_LISTENER);
isSelectedView.selectedProperty().bindBidirectional(model.isSelectedProperty());
}
private void updateView()
{
updateLabelView();
updateIsSelectedView();
updateIsVisibleView1();
}
private void updateLabelView(){ updateLabelView(model.getLabel()); }
private void updateLabelView(String newValue)
{
labelView.setText(newValue);
}
private void updateIsSelectedView(){ updateIsSelectedView(model.isSelected()); }
private void updateIsSelectedView(boolean newValue)
{
isSelectedView.setSelected(newValue);
}
private void updateIsVisibleView1() {
updateIsVisibleView1(model.isVisible1());
}
private void updateIsVisibleView1(boolean newValue) {
isVisible1.setVisible(newValue);
}
}
ChoiceModel.java
package com.example.javafx.choice;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class ChoiceModel
{
private final StringProperty label;
private final BooleanProperty isSelected;
private final BooleanProperty isVisible1;
public ChoiceModel(String label, boolean isSelected, boolean isVisible1)
{
this.label = new SimpleStringProperty(label);
this.isSelected = new SimpleBooleanProperty(isSelected);
this.isVisible1 = new SimpleBooleanProperty(isVisible1);
}
public String getLabel(){ return label.get(); }
public void setLabel(String label){ this.label.set(label); }
public StringProperty labelProperty(){ return label; }
public boolean isSelected(){ return isSelected.get(); }
public void setSelected(boolean isSelected){ this.isSelected.set(isSelected); }
public BooleanProperty isSelectedProperty(){ return isSelected; }
public boolean isVisible1()
{
return isVisible1.get();
}
public void setVisible1(boolean isVisible1)
{
this.isVisible1.set(isVisible1);
}
public BooleanProperty isVisibleProperty1()
{
return isVisible1;
}
}
ChoiceView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<HBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="com.example.javafx.choice.ChoiceController">
<children>
<CheckBox fx:id="isSelectedView" />
<Label fx:id="labelView" />
<ComboBox id="isVisible1" fx:id="isVisible1" value="last 7 digits" visible="false">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="last 10 digits" />
<String fx:value="last 9 digits" />
<String fx:value="last 8 digits" />
<String fx:value="last 7 digits" />
<String fx:value="last 6 digits" />
<String fx:value="last 5 digits" />
<String fx:value="last 4 digits" />
<String fx:value="last 3 digits" />
</FXCollections>
</items>
</ComboBox>
</children>
</HBox>
FxmlMvcPatternDemo.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceController;
import java.util.ResourceBundle;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FxmlMvcPatternDemo extends Application
{
public static void main(String[] args) throws ClassNotFoundException
{
Application.launch(FxmlMvcPatternDemo.class, args);
}
#Override
public void start(Stage stage) throws Exception
{
Parent root = FXMLLoader.load
(
FxmlMvcPatternDemo.class.getResource("MainView.fxml"),
ResourceBundle.getBundle(FxmlMvcPatternDemo.class.getPackage().getName()+".MainView")/*properties file*/
);
ChoiceController controller = new ChoiceController();
stage.setScene(new Scene(root));
stage.show();
}
}
MainController.java
package com.example.javafx.mvc;
import com.example.javafx.choice.ChoiceCell;
import com.example.javafx.choice.ChoiceModel;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
public class MainController implements Initializable
{
#FXML
private ListView<ChoiceModel> choicesView;
#Override
public void initialize(URL url, ResourceBundle rb)
{
choicesView.setCellFactory(new Callback<ListView<ChoiceModel>, ListCell<ChoiceModel>>()
{
public ListCell<ChoiceModel> call(ListView<ChoiceModel> p)
{
return new ChoiceCell();
}
});
choicesView.setItems(FXCollections.observableArrayList
(
new ChoiceModel("Tiger", true, false),
new ChoiceModel("Shark", false, true),
new ChoiceModel("Bear", false, true),
new ChoiceModel("Wolf", true, true)
));
}
#FXML
private void handleForceChange(ActionEvent event)
{
if(choicesView != null && choicesView.getItems().size() > 0)
{
boolean isSelected = choicesView.getItems().get(0).isSelected();
choicesView.getItems().get(0).setSelected(!isSelected);
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox
xmlns:fx="http://javafx.com/fxml"
fx:controller="com.example.javafx.mvc.MainController"
prefWidth="300"
prefHeight="400"
fillWidth="false"
>
<children>
<Label text="%title" />
<ListView fx:id="choicesView" />
<Button text="Force Change" onAction="#handleForceChange" />
</children>
</VBox>
MainView.proprties
title=JavaFX 2.0 FXML MVC demo
I didn't dig deeper but refactoring like as following should suffice. Double check for correct executions of attached and removed listeners.
public class ChoiceCell extends ListCell<ChoiceModel> {
private Node root;
private ChoiceController controller;
public ChoiceCell() {
URL location = ChoiceController.class.getResource("ChoiceView.fxml");
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(location);
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
try {
root = (Node) fxmlLoader.load(location.openStream());
controller = (ChoiceController) fxmlLoader.getController();
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
#Override
protected void updateItem(ChoiceModel model, boolean bln) {
super.updateItem(model, bln);
if (model != null) {
controller.setModel(model);
setGraphic(root);
} else {
setGraphic(null);
}
}
}
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);