how to exclude service numbers from an android contacts search - android

I have a Galexy S10+ cell phone. In the contacts app, there are preloaded AT&T service numbers. On the internet, I was able to find instructions on how to disable these numbers from loading, but the instructions are for an old cell phone model. So first anyone know how to keep these from loading?
Here is the old http instructions:
https://www.google.com/search?q=samsung+cell+phone+delete+att+contacts+2020&rlz=1C1CHBF_enUS977US977&oq=&aqs=chrome.0.69i59i450l8.27328431j0j15&sourceid=chrome&ie=UTF-8#kpvalbx=_Dbo4Y9nqDf-j5NoPuZGegA8_21
Alternatively, I would like to do this programmatically, but excluding a string such as "AT&T" from the search in my app. So based upon my code, see below, either on the search line on the cell phone or embedded in the code, I need to alter what is contained in the search string "%$p0%" in the code. Any suggestions. Thanks.
...
package com.example.myapplication
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ListView
import androidx.appcompat.widget.SearchView
import android.widget.SimpleCursorAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import java.io.IOException
class ConnectActivity : AppCompatActivity() {
private lateinit var searchView: SearchView
private lateinit var listView: ListView
var cols = listOf<String> (
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone._ID
).toTypedArray()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_connect)
try {
//Toast.makeText(getApplicationContext(), "got here", Toast.LENGTH_SHORT).show();
searchView = findViewById(R.id.searchView)
listView = findViewById(R.id.listView)
if (ActivityCompat.checkSelfPermission( this#ConnectActivity, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this#ConnectActivity, Array(1){Manifest.permission.READ_CONTACTS}, 111)
}
else {
readContact()
}
} catch (e: Exception) {
Toast.makeText(getApplicationContext(), e.message, Toast.LENGTH_LONG).show()
}
}
override fun onRequestPermissionsResult(requestCode: Int,permissions: Array<out String>,grantResults: IntArray){
super.onRequestPermissionsResult(requestCode,permissions,grantResults)
Toast.makeText(getApplicationContext(), "then here", Toast.LENGTH_SHORT).show()
if (requestCode==111 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
readContact()
}
private fun readContact() {
var from = listOf<String>(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER).toTypedArray()
var to = intArrayOf(android.R.id.text1,android.R.id.text2)
var rs = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
cols,null,null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
var adapter = SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,
rs,from,to,0)
listView.adapter =adapter
searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(p0: String?):Boolean {
return false
}
override fun onQueryTextChange(p0:String?):Boolean{
rs = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
cols,"${ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME} LIKE ?",
Array(1){"%$p0%"},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
adapter.changeCursor(rs)
return false
}
})
}
...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<androidx.appcompat.widget.SearchView
android:id="#+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="20dp"
android:queryHint="hi"
/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="20dp"
android:layout_below="#+id/searchView"
/>
</RelativeLayout>
...

Related

How is defined MediaRecorder( )?

i make program for record audio for android but i find MediaRecorder() Deprecated
kotlin code
package noteapp.notesnotesnotescairo.mynoteapp
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.icu.text.SimpleDateFormat
import android.media.MediaRecorder
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.os.Looper.prepare
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.NonCancellable.start
import java.io.IOException
import java.util.*
const val REQUEST_CODE=200
private var permission = arrayOf(Manifest.permission.RECORD_AUDIO)
private var permissionGranted=false
private lateinit var recorder : MediaRecorder
private var dirPath=""
private var filename=""
private var isRecording=false
private var isPaused=false
class MainActivity : AppCompatActivity(){
#RequiresApi(Build.VERSION_CODES.S)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
permissionGranted=ActivityCompat.checkSelfPermission(this, permission[0])==PackageManager.PERMISSION_GRANTED
if(!permissionGranted)
ActivityCompat.requestPermissions(this, permission, REQUEST_CODE)
btnRecord.setOnClickListener{
when{
isPaused->resumeRecorder()
isRecording->pauseRecorder()
else->startRecording()
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode== REQUEST_CODE)
permissionGranted=grantResults[0]==PackageManager.PERMISSION_GRANTED
}
private fun pauseRecorder(){
recorder.pause()
isPaused=true
btnRecord.setImageResource(R.drawable.ic_record)
}
private fun resumeRecorder(){
recorder.resume()
isPaused=false
btnRecord.setImageResource(R.drawable.ic_pause)
}
#RequiresApi(Build.VERSION_CODES.S)
private fun startRecording(){
if(!permissionGranted){
ActivityCompat.requestPermissions(this, permission, REQUEST_CODE)
return
}
recorder = MediaRecorder( this)
dirPath="${externalCacheDir?.absolutePath}/"
var simpleDateFormat= SimpleDateFormat("yyyy.mm.dd.hh.mm.ss")
var date :String=simpleDateFormat.format(Date())
filename="audio_record_$date"
recorder.apply {
setAudioSource(MediaRecorder.AudioSource.MIC)
setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
setOutputFile("$dirPath$filename.mp3")
try{
prepare()
}catch (e:IOException){}
start()
}
btnRecord.setImageResource(R.drawable.ic_pause)
isRecording=true
isPaused=false
}
}
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">
<TextView
android:id="#+id/tvTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textSize="56sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toBottomOf="parent"
>
<ImageButton
android:id="#+id/btnDelete"
android:layout_width="#dimen/btn_size"
android:src="#drawable/ic_delete_disable"
android:layout_height="#dimen/btn_size"
android:background="#drawable/ic_ripple"/>
<ImageButton
android:id="#+id/btnRecord"
android:layout_width="66dp"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:layout_height="66dp"
android:background="#drawable/ic_record"/>
<ImageButton
android:id="#+id/btnList"
android:layout_width="#dimen/btn_size"
android:src="#drawable/ic_list"
android:layout_height="#dimen/btn_size"
android:background="#drawable/ic_ripple"/>
<ImageButton
android:id="#+id/btnDone"
android:layout_width="#dimen/btn_size"
android:src="#drawable/ic_done"
android:visibility="gone"
android:layout_height="#dimen/btn_size"
android:background="#drawable/ic_ripple"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
what is new defind for MediaRecorder() not Deprecated ?
give me error
java.lang.NoSuchMethodError: No direct method (Landroid/content/Context;)V in class Landroid/media/MediaRecorder; or its super classes (declaration of 'android.media.MediaRecorder' appears in /system/framework/framework.jar!classes2.dex)
Use an if/else to set the property using the supported constructor:
recorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) MediaRecorder(this) else MediaRecorder()
Down the road it is possible Jetpack will add a helper function that would do this for you, something like MediaRecorderCompat.newInstance(this). However, it has been so long I think we can assume they will probably not be adding it.
I used the following script in an app published on the Playstore
fun prepare_audio_and_directories(v : View) {
var tempDir : File
// current_filename = (v.findViewById(R.id.audio_filename_xml) as TextView).text.toString()
current_dir = main?.dir!!
tempDir = current_dir
main?.filenameCompletePath = tempDir?.toPath().toString() + "/" +current_filename + "."+ main?.ext
main?.filename_text = current_filename
Log.d("$TAG:prepare_audio_and_directories:main?.filenameCompletePath=", main?.filenameCompletePath!!
)
Log.d("$TAG:prepare_audio_and_directories:main?.filename_text=", main?.filename_text!!)
Log.d("NoiseSuppressor.isAvailable()=", NoiseSuppressor.isAvailable().toString() )
mediaRecorder = MediaRecorder()
mediaRecorder?.setAudioSource(MediaRecorder.AudioSource.MIC)
mediaRecorder?.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
mediaRecorder?.setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
mediaRecorder?.setAudioEncodingBitRate(128000)
mediaRecorder?.setAudioSamplingRate(96000);
mediaRecorder?.setOutputFile(main?.filenameCompletePath)
}
The versions I tested it with are API 28,29,30 and 31.

Bitmap decodefile() by filepath displays empty

I'm new to Android development using Kotlin. I'm trying to practice uploading image from a mobile phone to my app using some methods as codes in the code below. everything works just fine with some processes such as I can select on the imageview then screen popup that can let me select image in my phone. unfortunately, after selecting the image, It shows empty/blank, shows nothing in the app. I've tried to search for help but It didn't work out. Hopefully, I can get a hand here. thanks in advance!
Activity code
package student
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.example.amazontutoringcenter.databinding.ActivityMainBinding
import com.example.amazontutoringcenter.databinding.ActivityStudentClassroomBinding
import com.squareup.picasso.Picasso
class StudentClassroomActivity: AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.imageView.setOnClickListener {
checkPermission()
}
}
val READ_IMAGE:Int=338
private fun checkPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.READ_EXTERNAL_STORAGE)!=
PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf( android.Manifest.permission.READ_EXTERNAL_STORAGE),READ_IMAGE)
return
}
}
loadImage()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when(requestCode) {
READ_IMAGE->{
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
loadImage()
}else{
Toast.makeText(applicationContext,"Cannot access your images",Toast.LENGTH_LONG).show()
}
}
else-> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
val PICK_IMAGE_CODE=123
private fun loadImage(){
var intent=Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent,PICK_IMAGE_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if(requestCode==PICK_IMAGE_CODE && data!=null && resultCode == RESULT_OK){
val selectedImage=data.data
val filePathColum= arrayOf(MediaStore.Images.Media.DATA)
val cursor= contentResolver.query(selectedImage!!,filePathColum,null,null,null)
cursor!!.moveToFirst()
val columnIndex=cursor!!.getColumnIndex(filePathColum[0])
val picturePath=cursor!!.getString(columnIndex)
cursor!!.close()
//.load(picturePath).into(binding.imageStudentProfile)
//Picasso.get().load(picturePath).fit().into(binding.imageStudentProfile)
binding.imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath))
}
}
}
XML File
<?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">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test Layout"
android:layout_marginTop="50dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
android:src="#drawable/ic_attendant"/>
</androidx.constraintlayout.widget.ConstraintLayout>
ImageView has a member to load an image from an uri.
And you have an uri data.data.
So use it.

Recyclerview No adapter attached; skipping layout (Kotlin)

i'd like to know what i'm doing wrong over here. I'm building a CRUD app in Kotlin, and i'm using the recyclerview to make the readData page. The problem is, when i'm on the readData page doesn't show me anything, just the text views, so i debugged and when i join in the page, show this message: "Recyclerview No adapter attached; skipping layout".
Here's my code:
(i'm brazilian, so, some words are in portuguese, but you'll get it.)
verDados.kt
package com.nicolas.csrd
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_ver_database.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class verDados : AppCompatActivity() {
private lateinit var database: FirebaseDatabase
private lateinit var reference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ver_database)
database = FirebaseDatabase.getInstance()
reference = database.getReference("usuarios")
verDados()
btn_voltar.setOnClickListener() {
startActivity(Intent(this#verDados, Dashboard::class.java))
finish()
}
}
private fun verDados() {
reference.addValueEventListener(object: ValueEventListener{
override fun onCancelled(p0: DatabaseError) {
Log.e("cancelar", p0.toString())
}
override fun onDataChange(p0: DataSnapshot) {
//Colocando os usuarios numa lista
var list = ArrayList<DatabaseModelo>()
for (data in p0.children) {
val model = data.getValue(DatabaseModelo::class.java)
list.add(model as DatabaseModelo)
}
if (list.size > 0) {
val ususariosModelo = usuariosModelo(list)
recyclerview.adapter = ususariosModelo
}
}
})
}
}
DatabaseModel
package com.nicolas.csrd
class DatabaseModelo() {
lateinit var email: String
lateinit var senha: String
constructor(email: String, senha: String) : this() {
this.email = email
this.senha = senha
}
}
usuariosModelo.kt (recyclerview adapter)
package com.nicolas.csrd
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.appcompat.view.menu.MenuView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.usuarios_modelo.view.*
class usuariosModelo(val list: ArrayList<DatabaseModelo>): RecyclerView.Adapter<usuariosModelo.ViewHolder>() {
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val email = itemView.campo_email
val senha = itemView.campo_senha
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.usuarios_modelo, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.email.text = list[position].email
holder.senha.text = list[position].senha
}
override fun getItemCount(): Int {
return list.size
}
}
----- XML FILES -----
activity_ver_database.xml (read data page)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dark"
tools:context=".Login">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal" >
<ImageView
android:id="#+id/btn_voltar"
android:layout_width="50dp"
android:layout_height="30dp"
android:layout_gravity="start"
android:layout_marginStart="5dp"
android:layout_marginTop="23dp"
android:src="#drawable/back_arrow" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DADOS"
android:textColor="#7ec1d1"
android:textSize="30sp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:letterSpacing="0.15"
android:fontFamily="#font/montserrat_medium"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Todos os usuários cadastrados"
android:textColor="#7ec1d1"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="0dp"
android:fontFamily="#font/montserrat_thin"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerview"
android:layout_margin="10sp"/>
<TextView
android:id="#+id/btn_cadastrar"
android:layout_width="350dp"
android:layout_height="50dp"
android:layout_marginTop="30dp"
android:backgroundTint="#7ec1d1"
android:gravity="center_horizontal"
android:fontFamily="#font/montserrat_regular"
android:text="Deseja cadastrar alguém? Clique aqui."
android:textColor="#color/white2"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
You are getting this error because you have no defined an adaptor for the RecyclerView that you are using. Somewhere inn your onCreate method, create the adaptor and set it to the RecyclerView. Something like:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_ver_database)
recyclerView = findViewById(R.id.recyclerview)
recyclerView.apply {
adapter = usuariosModelo(listOfItems)
}
database = FirebaseDatabase.getInstance()
reference = database.getReference("usuarios")
verDados()
btn_voltar.setOnClickListener() {
startActivity(Intent(this#verDados, Dashboard::class.java))
finish()
}
}
i solve the problem just adding the tag below inside the recyclerview tag in the .xml file:
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
I hope that help y'all!

When launching the application, no content is displayed

I followed a tutorial to create an application that displays data from a mysql table, if i run the app everything works without error, the application opens with the header but without content, blank page instead of the content list.
activity_main.xml :
package com.example.bingmada
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
class MainActivity : AppCompatActivity() {
var adapter:ArticleAdapter ?=null
var articles:ArrayList<Article> ?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
articles= ArrayList()
getArticlesFromServer()
adapter = ArticleAdapter(articles!!)
var recyclerView = findViewById<RecyclerView>(R.id.recyclevirtuel)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter=adapter
}
fun getArticlesFromServer(){
var url="https://www.exemplesite.com/android/bingmada.php"
var stringRequest=StringRequest(Request.Method.GET,url,Response.Listener { response -> parseData(response) }, Response.ErrorListener { error ->
Toast.makeText(this,"Erreur de connexion ", Toast.LENGTH_SHORT).show()
})
var req=Volley.newRequestQueue(this)
req.add(stringRequest)
}
fun parseData(response:String){
var arrayJson = JSONArray(response)
for(i in 0..arrayJson.length()-1){
var currentObject=arrayJson.getJSONObject(i)
var article = Article(currentObject.getInt("id"),
currentObject.getString("nom"),
currentObject.getString("lienimg"),
currentObject.getString("ifram"))
articles?.add(article)
}
}
}
the page https://www.exemplesite.com/android/bingmada.php show :
[{"id":"1","nom":"tesmon","lienimg":"bingo1","ifram":"car1"},{"id":"2","nom":"testeds","lienimg":"bingo","ifram":"car2"},{"id":"3","nom":"test1","lienimg":"bingo3","ifram":"car3"},{"id":"4","nom":"testr","lienimg":"bingo4","ifram":"car4"},{"id":"5","nom":"test2","lienimg":"bingo5","ifram":"car5"},{"id":"6","nom":"letest","lienimg":"bingo6","ifram":"car6"},{"id":"7","nom":"test3","lienimg":"bingo7","ifram":"car7"},{"id":"8","nom":"testo","lienimg":"bingo8","ifram":"car8"},{"id":"9","nom":"test4","lienimg":"bingo9","ifram":"car9"},{"id":"10","nom":"testad","lienimg":"bingo10","ifram":"car10"},{"id":"11","nom":"test5","lienimg":"bingo11","ifram":"car11"},{"id":"12","nom":"testd","lienimg":"bingo12","ifram":"car12"},{"id":"13","nom":"test6","lienimg":"bingo13","ifram":"car13"},{"id":"14","nom":"testiu","lienimg":"bingo14","ifram":"car14"},{"id":"15","nom":"teste","lienimg":"bingo15","ifram":"car15"}]
in my page listevirtuelles.kt :
package com.example.bingmada
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class Article(var id:Int,var nom:String,var lienimg:String, var ifram:String){
}
class ArticleAdapter (var articles:ArrayList<Article>) : RecyclerView.Adapter<ArticleAdapter.MyViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var vue=LayoutInflater.from(parent.context).inflate(R.layout.activity_listevirtuelles, parent, false)
return MyViewHolder(vue)
}
override fun getItemCount(): Int {
return articles.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
var article = articles.get(position)
holder.idvirtuelleli.setText(article.id)
holder.nomvisite.setText(article.nom)
holder.lieimgvisite.setText(article.lienimg)
holder.ifram.setText(article.ifram)
}
class MyViewHolder(var vue:View):RecyclerView.ViewHolder(vue){
var idvirtuelleli=vue.findViewById<TextView>(R.id.idvirtuelleli)
var nomvisite=vue.findViewById<TextView>(R.id.nom_virtuelleli)
var lieimgvisite=vue.findViewById<TextView>(R.id.lienimg)
var ifram=vue.findViewById<TextView>(R.id.ifram)
}
}
activity_main.xml page :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclevirtuel"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
a page activity_listevirtuelles.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="#+id/idvirtuelleli"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="id"
android:textSize="25dp"
/>
<TextView
android:id="#+id/nom_virtuelleli"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Lenom"
android:textSize="25dp"
/>
<TextView
android:id="#+id/lienimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="lien dimage"
android:textSize="25dp"
/>
<TextView
android:id="#+id/ifram"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="codeifram"
android:textSize="25dp"
/>
</LinearLayout>
can you help me find the problem please?
If you can see the relevant data in the activity. Since it is an asynchronous process, can you apply the structure I added to connect the data with recyclerview?
class MainActivity : AppCompatActivity() {
var adapter:ArticleAdapter ?=null
var articles:ArrayList<Article> ?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
articles= ArrayList()
adapter = ArticleAdapter(articles!!) // 1 line up to changed
getArticlesFromServer()
var recyclerView = findViewById<RecyclerView>(R.id.recyclevirtuel)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter=adapter
}
fun getArticlesFromServer(){
var url="https://www.exemplesite.com/android/bingmada.php"
var stringRequest=StringRequest(Request.Method.GET,url,Response.Listener { response -> parseData(response) }, Response.ErrorListener { error ->
Toast.makeText(this,"Erreur de connexion ", Toast.LENGTH_SHORT).show()
})
var req=Volley.newRequestQueue(this)
req.add(stringRequest)
}
fun parseData(response:String){
var arrayJson = JSONArray(response)
for(i in 0..arrayJson.length()-1){
var currentObject=arrayJson.getJSONObject(i)
var article = Article(currentObject.getInt("id"),
currentObject.getString("nom"),
currentObject.getString("lienimg"),
currentObject.getString("ifram"))
articles?.add(article)
}
adapter.notifydatasetchanged() // added
}
}

Recycler View displaying blank

I trying to display a page feed or users post feed inside an app but I am not getting the desired output. Instead of post messages I get a blank activity and suspect the error is inside adapter class .
recylerView = findViewById<RecyclerView>(R.id.recyclerView)
var inBundle: Bundle = getIntent().getExtras()
var araayList: ArrayList<Data> = inBundle.getParcelableArrayList<Data>("data")
if (araayList == null) {
Toast.makeText(this, "it's empty", Toast.LENGTH_SHORT).show()
} else {
this.displayingPostAdapters = DisplayingPostAdapters(araayList, this)
this.displayingPostAdapters!!.notifyDataSetChanged()
var mlayoutManager = LinearLayoutManager(this)
this.recylerView?.layoutManager = mlayoutManager
this.recylerView?.itemAnimator = DefaultItemAnimator()
this.recylerView?.adapter = displayingPostAdapters
this.recylerView?.setHasFixedSize(true)
code inside Adapter class
package com.internshala.test1
import android.content.Context
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import org.json.JSONArray
class DisplayingPostAdapters(mAraay:ArrayList<Data>, context: Context) : RecyclerView.Adapter<DisplayingPostAdapters.myViewHolder>() {
var _mArray:ArrayList<Data>? = null
var mContext:Context? = null
init {
this._mArray = mAraay
this.mContext = context
}
#RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1) override fun onBindViewHolder(holder:myViewHolder?, position: Int) {
Toast.makeText(mContext, "NO DATA", Toast.LENGTH_SHORT).show()
var mDisplayingContent = _mArray?.get(position)
holder?.mDisplay?.text = mDisplayingContent?.message
holder?.mId?.text = mDisplayingContent?.created_time
holder?.mCreatedTime?.text = mDisplayingContent?.id
}
override fun getItemCount(): Int {
if (_mArray == null) {
return 0
} else {
return (_mArray as ArrayList<Data>).size
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int):myViewHolder {
var itemView = LayoutInflater.from(parent?.context)
.inflate(R.layout.row_custome_data, parent, false)
return myViewHolder(itemView)
}
class myViewHolder(view:View):RecyclerView.ViewHolder(view) {
var mDisplay:TextView? = null
var mId:TextView? = null
var mCreatedTime:TextView? = null
init {
this.mDisplay = view.findViewById(R.id.display)
this.mId = view.findViewById(R.id.mId)
this.mCreatedTime = view.findViewById(R.id.mCreatedDate)
}
}
}
When I try to run this app and click on post Button, my logcat issues this warning (Warning issued in logcat no crash):
https://i.stack.imgur.com/ZI1F8.png
My xml files look like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerView">
</android.support.v7.widget.RecyclerView>>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>

Categories

Resources