Im trying to make mp3 player in android studio, i have loaded all songs from my phone in arraylist called audioList but i cant make recyclerView, can anyone find mistake?
MainActivity.java
import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private MediaPlayerService player;
private boolean serviceBound = false;
private ArrayList<Audio> audioList;
private RWAdapter adapt;
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
RecyclerView rv = (RecyclerView) findViewById(R.id.myRecyclerView);
assert rv != null;
rv.setLayoutManager(new LinearLayoutManager(this));;
loadAudio();
RWAdapter rwa = new RWAdapter(audioList);
rv.setAdapter(rwa);
playAudio(audioList.get(22).getData());
}
//ulozi sa instancia
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("ServiceState", serviceBound);
super.onSaveInstanceState(outState);
}
//obnovi sa instancia tam kde bola naposledy ulozena
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
serviceBound = savedInstanceState.getBoolean("ServiceState");
}
//znici instanciu
#Override
protected void onDestroy() {
super.onDestroy();
if(serviceBound){
unbindService(serviceConnection);
player.stopSelf();
}
}
//viaze tuto triedu s prehravacom, nastavi hodnotu serviceBound na true ked sa vytvori spojenie
private ServiceConnection serviceConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
Toast.makeText(MainActivity.this, "Service bound", Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
//Metoda dava spravu,intnet druhej aktivite o spusteni hudby
private void playAudio(String media){
if(!serviceBound){
Intent playerIntent = new Intent(this,MediaPlayerService.class);
playerIntent.putExtra("media",media);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
}
}
//nacita pesnicky z mobilu
private void loadAudio() {
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);
if(cursor != null && cursor.getCount() > 0) {
audioList = new ArrayList<>();
while (cursor.moveToNext()){
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
audioList.add(new Audio(data, title, album, artist));
}
}
cursor.close();
}
}
RecyclerViewAdapter
package com.example.rsabo.mp3player;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by RSabo on 15-Apr-17.
*/
public class RWAdapter extends RecyclerView.Adapter<RWAdapter.MyViewHolder>{
private List<Audio> list;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView play_pause;
MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
play_pause = (ImageView) itemView.findViewById(R.id.play_pause);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Audio currentAudio = list.get(getAdapterPosition());
}
});
}
}
public RWAdapter(List<Audio> list) {
this.list = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Inflate the layout, initialize the View Holder
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_songov, parent, false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//Use the provided View Holder on the onCreateViewHolder method to populate the current row on the RecyclerView
holder.title.setText(list.get(position).getTitle());
}
#Override
public int getItemCount() {
//returns the number of elements the RecyclerView will display
return list.size();
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.rsabo.mp3player.MainActivity">
<include layout="#layout/list_songov" />
list_songov.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/myRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
Check following code in your adapter .
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Inflate the layout, initialize the View Holder
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_songov, parent, false);
return new MyViewHolder(v);
}
Now , inside list_songov.xml layout file , there is no TextView , ImageView for Title and play_pause .
Please check if you have set the correct layout inside onCreateViewHolder() .
You are not calling the function loadAudio() , you should call this function when instatiating your adapter class
Basically your loadAudio() method should be AsyncTask (Background process) you have to wait while it load, so use AsyncTask and set adapter in onPostExecute method see example AsyncTask Android example or this https://developer.android.com/reference/android/os/AsyncTask.html
//nacita pesnicky z mobilu
private void loadAudio() {
ContentResolver contentResolver = getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);
if(cursor != null && cursor.getCount() > 0) {
audioList = new ArrayList<>();
while (cursor.moveToNext()){
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
audioList.add(new Audio(data, title, album, artist));
}
}
cursor.close();
}
Related
fragment reminder image - current problem
This current class that I am using called Fragment Reminder is used to display a list of the medications that have been entered. However this class before was a Fragment and I decided to change it to an Activity and the method which displays the list called onCreateView is unused now. When I click on that button to run this class the screen goes dark for some reason. Now that this class is an Activity the onCreateView cannot be used since that is for a Fragment. What should I change that to so I can create the list.
FragmentReminder:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.view.View.GONE;
public class FragmentReminder extends Activity implements View.OnClickListener{
private ArrayList al;
private List list=new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al)
{
this.al=al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
// #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setTitle("Medicine Reminder");
View v=inflater.inflate(R.layout.fragment_reminder, container, false);
fab=(FloatingActionButton)v.findViewById(R.id.floatingActionButton);
lv=(ListView)v.findViewById(R.id.rem_lv);
tv=(TextView) v.findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db=new DatabaseHandler(this);
list=db.getAllReminders();
if(list.size()==0)
{
lv.setVisibility(GONE);
return v;
}
tv.setVisibility(GONE);
adapter = new CustomList(this,list,desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in=new Intent(FragmentReminder.this,MedRemInfo.class);
in.putExtra("id",list.get(i).toString());
startActivity(in);
}
});
//***************************************************************************
return v;
}
#Override
public void onClick(View v) {
Intent in=new Intent(this,AddReminder.class);
startActivity(in);
}
}
fragment_reminder.xml:
<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"
tools:context="com.example.junai.mrtest2.FragmentReminder">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:id="#+id/reminder_tv"
android:textSize="20dp"
android:text="No Reminders to show, Add a reminder.."
android:gravity="center"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:src="#drawable/ic_add_black_24dp"
android:tint="#ffffff"
android:layout_gravity="bottom|center"
android:id="#+id/floatingActionButton" />
<ListView
android:layout_width="match_parent"
android:id="#+id/rem_lv"
android:layout_height="match_parent"
/>
</LinearLayout>
MainActivity:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Created by junai on 20/03/2018.
*/
public class MainActivity extends Activity {
private Button btn_addReminder, btn_reminderinfo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_addReminder = (Button) findViewById(R.id.btn_addReminder);
btn_addReminder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AddReminder.class));
}
});
btn_reminderinfo = (Button) findViewById(R.id.btn_reminderinfo);
btn_reminderinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, FragmentReminder.class));
}
});
}
}
CustomList:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import java.util.Random;
public class CustomList extends ArrayAdapter<String> {
private List names;
private String[] desc;
private Activity context;
public CustomList(Activity context, List names, String[] desc) {
super(context, R.layout.list_medinfo, names);
this.context = context;
this.names = names;
this.desc = desc;
}
String color_hex[]={"#ff4000","#0000ff","#003EFF","#5C246E","#8B668B","#CD2990","#D41A1F","#FBDB0C","#FF6600"};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//********************************************************************
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_medinfo, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(getItem(position));
String firstLetter = null;
//get first letter of each String item
Log.d("String",getItem(position));
String str=getItem(position);
firstLetter=String.valueOf(str.charAt(0)).toUpperCase();
// firstLetter.toUpperCase();
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
//int color = generator.getColor(getItem(position));
int color = generator.getRandomColor();
int pos= new Random().nextInt(color_hex.length);
color = Color.parseColor(color_hex[pos]);
Log.d("Color",""+pos);
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
holder.imageView.setImageDrawable(drawable);
return convertView;
//***********************************************************************
/* LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_medinfo, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.medname);
TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
textViewName.setText(names.get(position).toString());
textViewDesc.setText(desc[position]);
image.setImageResource(imageid[position]);
return listViewItem;*/
}
private class ViewHolder {
private ImageView imageView;
private TextView textView;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.medimage);
textView = (TextView) v.findViewById(R.id.medname);
Typeface typeface=Typeface.createFromAsset(context.getAssets(), "fonts/georgia.ttf");
textView.setTypeface(typeface);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
}
}
}
I've refactored your code:
public class FragmentReminder extends Activity implements View.OnClickListener {
private ArrayList al;
private List list = new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al) {
this.al = al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_reminder);
fab = (FloatingActionButton) findViewById(R.id.floatingActionButton);
lv = (ListView) findViewById(R.id.rem_lv);
tv = (TextView) findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db = new DatabaseHandler(this);
list = db.getAllReminders();
if (list.size() == 0) {
lv.setVisibility(GONE);
}
tv.setVisibility(GONE);
adapter = new CustomList(this, list, desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in = new Intent(FragmentReminder.this, MedRemInfo.class);
in.putExtra("id", list.get(i).toString());
startActivity(in);
}
});
}
#Override
public void onClick(View v) {
Intent in = new Intent(this, AddReminder.class);
startActivity(in);
}
}
You need only to move the code to onCreate() instead of onCreateView() and also you don't need to access the recently inflated view V to do findViewByID, all you have to do is setContentView() beforehand.
My app has a registration screen for blood donors and the blood type field is a spinner. I save all the donor information in an SQLite database. Now I need to retrieve it and show it for a list showing all the registered blood donors with their blood types.
How can I do that?
I've attached all my code below. The main problems appear in RegisterActivity.java and DonorList.java.
RegisterActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
EditText edtname, edtnumber;
Spinner spblood;
Button btnregister, btnlist;
public static SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
init();
Spinner spinner = findViewById(R.id.blood_selector);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.blood_type, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
sqLiteHelper = new SQLiteHelper(this, "Donors.sqlite", null, 1);
sqLiteHelper.queryData("CREATE TABLE IF NOT EXISTS DONORS (Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, number VARCHAR, blood VARCHAR)");
btnregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
sqLiteHelper.insertData(
edtname.getText().toString().trim(),
edtnumber.getText().toString().trim(),
spblood
);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
btnlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, DonorList.class);
startActivity(intent);
}
});
}
private void init() {
edtname = findViewById(R.id.name_input);
edtnumber = findViewById(R.id.numberinput);
spblood = findViewById(R.id.blood_selector);
btnregister = findViewById(R.id.register_button);
btnlist = findViewById(R.id.list_button);
}
}
DonorList.java
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.Spinner;
import java.util.ArrayList;
public class DonorList extends AppCompatActivity {
ListView listView;
ArrayList<Donor> list;
DonorListAdapter adapter = null;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.contacts_list);
list = new ArrayList<>();
adapter = new DonorListAdapter(this, R.layout.activity_main, list);
listView.setAdapter(adapter);
Cursor cursor = RegisterActivity.sqLiteHelper.getData("SELECT * FROM DONORS");
list.clear();
while (cursor.moveToNext()) {
String name = cursor.getString(1);
String number = cursor.getString(2);
String blood = cursor.getString(3);
list.add(new Donor(name, number, blood));
}
adapter.notifyDataSetChanged();
}
}
Donor.java
import android.widget.Spinner;
public class Donor {
private String name;
private String number;
private Spinner blood;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public Spinner getBlood() {
return blood;
}
public void setBlood(Spinner blood) {
this.blood = blood;
}
public Donor(String name, String number, Spinner blood) {
this.name = name;
this.number = number;
this.blood = blood;
}
}
SQLiteHelper.java
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.widget.Spinner;
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void queryData(String sql) {
SQLiteDatabase database = getWritableDatabase();
database.execSQL(sql);
}
public void insertData(String name, String number, Spinner blood) {
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO DONORS (name, number, blood) values (?, ?, ?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, name);
statement.bindString(2, number);
statement.bindString(3, blood.getSelectedItem().toString());
statement.executeInsert();
}
public Cursor getData(String sql) {
SQLiteDatabase database = getReadableDatabase();
return database.rawQuery(sql, null);
}
}
DonorListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class DonorListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Donor> donorList;
public DonorListAdapter(Context context, int layout, ArrayList<Donor> donorList) {
this.context = context;
this.layout = layout;
this.donorList = donorList;
}
#Override
public int getCount() {
return donorList.size();
}
#Override
public Object getItem(int position) {
return donorList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView txtname, txtnumber, txtblood;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = new ViewHolder();
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (inflater != null) {
row = inflater.inflate(layout, null);
}
if (row != null) {
holder.txtname = row.findViewById(R.id.name_input);
}
if (row != null) {
holder.txtnumber = row.findViewById(R.id.numberinput);
}
if (row != null) {
holder.txtblood = (TextView) row.findViewById(R.id.blood_selector);
}
if (row != null) {
row.setTag(holder);
}
}
else {
holder = (ViewHolder) row.getTag();
}
Donor donor = donorList.get(position);
holder.txtname.setText(donor.getName());
holder.txtnumber.setText(donor.getNumber());
holder.txtblood.setText(donor.getBlood().toString());
return row;
}
}
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.lumen.dayem.blooddonor.MainActivity">
<ListView
android:id="#+id/contacts_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice">
</ListView>
</LinearLayout>
activity_register.xml
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/name_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/person_name"
android:ems="10"
android:inputType="textCapWords"
android:layout_marginBottom="5sp" />
<EditText
android:id="#+id/numberinput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint"
android:ems="10"
android:inputType="phone"
android:layout_marginBottom="5sp" />
<TextView
android:id="#+id/blood"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/blood_type"
android:layout_marginBottom="10sp"/>
<Spinner
android:id="#+id/blood_selector"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/blood_type"
android:prompt="#string/blood_select"
android:layout_marginBottom="5sp"/>
<Button
android:id="#+id/register_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/register" />
<Button
android:id="#+id/list_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_donors" />
</LinearLayout>
contact_item.xml
<?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">
<TextView
android:id="#+id/contact_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/contact_name"
android:textSize="22sp"/>
<TextView
android:id="#+id/contact_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:textAppearanceSmall"
android:text="#string/contact_number"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="29sp"
android:layout_marginStart="29sp"
android:layout_marginTop="31sp" />
<TextView
android:id="#+id/contact_blood"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="?android:textAppearanceMedium"
android:text="#string/blood_type"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="300sp"
android:layout_marginStart="300sp"
android:layout_marginTop="30sp"/>
</RelativeLayout>
Your class Donor seems to have a field blood of type Spinner. I changed the type to String because a data class should not contain any Views:
public class Donor
{
private String name;
private String number;
private String blood;
// Getters and Setters here...
public Donor(String name, String number, String blood) {
this.name = name;
this.number = number;
this.blood = blood;
}
}
The SQLiteHelper should have a static getInstance() method so you can avoid having it as a static field in RegisterActivity. Also, I think that the database setup should be encapsulated. The Activity does not need to know anything about the database implementation. So I moved the DDL to the SQLiteHelper's onCreate() and dropped queryData(). For the same reason, I changed getData(String sql) to getDonors(). Lastly, insertData() should take data as parameters not Views. So one should not pass the Spinner but the selected item's value.
My version of SQLiteHelper.java:
public class SQLiteHelper extends SQLiteOpenHelper{
private static SQLiteHelper sqliteHelper;
private static String dbName = "Donors.sqlite";
private static int version = 1;
private static final String CREATE_TABLE_DONORS = "CREATE TABLE IF NOT EXISTS DONORS (Id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, number VARCHAR, blood VARCHAR)";
/**
* We use the application Context under the hood because this helps to avoid Exceptions
* #param ctx
*/
private SQLiteHelper(Context ctx){
super(ctx.getApplicationContext(), dbName, null, version);
}
/**
* SQLiteHelper as a Singleton
* #param ctx any Context
* #return x
*/
public static SQLiteHelper getInstance(Context ctx)
{
if(sqliteHelper == null){
sqliteHelper = new SQLiteHelper(ctx);
}
return sqliteHelper;
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE_DONORS);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// necessary if you have a new database version
}
public void insertData(String name, String number, String blood) {
SQLiteDatabase database = getWritableDatabase();
String sql = "INSERT INTO DONORS (name, number, blood) values (?, ?, ?)";
SQLiteStatement statement = database.compileStatement(sql);
statement.clearBindings();
statement.bindString(1, name);
statement.bindString(2, number);
statement.bindString(3, blood);
statement.executeInsert();
}
public Cursor getDonors() {
String sql = "SELECT * FROM DONORS";
SQLiteDatabase database = getReadableDatabase();
return database.rawQuery(sql, null);
}
}
The updated RegisterActivity.java (note that I got rid of the local variable spinner and only used spblood):
public class RegisterActivity extends AppCompatActivity
{
private EditText edtname, edtnumber;
private Spinner spblood;
private Button btnregister, btnlist;
private SQLiteHelper sqLiteHelper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
init();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.blood_type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spblood.setAdapter(adapter);
sqLiteHelper = SQLiteHelper.getInstance(this);
btnregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
sqLiteHelper.insertData(
edtname.getText().toString().trim(),
edtnumber.getText().toString().trim(),
spblood.getSelectedItem().toString()
);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
btnlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, DonorList.class);
startActivity(intent);
}
});
}
private void init() {
edtname = findViewById(R.id.name_input);
edtnumber = findViewById(R.id.numberinput);
spblood = findViewById(R.id.blood_selector);
btnregister = findViewById(R.id.register_button);
btnlist = findViewById(R.id.list_button);
}
}
The changes to DonorList and the Adapter are due to the changes I made to SQLiteHelper and Donor. In addition to that, you need to pass the resource id of the list row to the Adapter's Constructor not the resource id of the Activity's layout. Similarly, the R.id.... values for the TextViews in the list row have to match those in contact_item.xml
DonorList.java
public class DonorList extends AppCompatActivity
{
private ListView listView;
private ArrayList<Donor> list;
private DonorListAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.contacts_list);
list = new ArrayList<>();
adapter = new DonorListAdapter(this, R.layout.contact_item, list);
listView.setAdapter(adapter);
Cursor cursor = SQLiteHelper.getInstance(this).getDonors();
list.clear();
while (cursor.moveToNext()) {
String name = cursor.getString(1);
String number = cursor.getString(2);
String blood = cursor.getString(3);
list.add(new Donor(name, number, blood));
}
adapter.notifyDataSetChanged();
}
}
And finally, the Adapter:
public class DonorListAdapter extends BaseAdapter
{
private Context context;
private int layout;
private ArrayList<Donor> donorList;
public DonorListAdapter(Context context, int layout, ArrayList<Donor> donorList) {
this.context = context;
this.layout = layout;
this.donorList = donorList;
}
#Override
public int getCount() {
return donorList.size();
}
#Override
public Object getItem(int position) {
return donorList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView txtname, txtnumber, txtblood;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
ViewHolder holder = new ViewHolder();
row = LayoutInflater.from(context).inflate(layout, null);
holder.txtname = (TextView)row.findViewById(R.id.contact_name);
holder.txtnumber = (TextView)row.findViewById(R.id.contact_number);
holder.txtblood = (TextView) row.findViewById(R.id.contact_blood);
row.setTag(holder);
}
ViewHolder viewHolder = (ViewHolder) row.getTag();
Donor donor = donorList.get(position);
viewHolder.txtname.setText(donor.getName());
viewHolder.txtnumber.setText(donor.getNumber());
viewHolder.txtblood.setText(donor.getBlood());
return row;
}
}
Enjoy!
I develop (NEWS Android app) with android studio and I have a problem, I Post a Short topic in the app and I need to let the user see the full topic when clicks on TextView (Click Here), but I need to change the site link on every topic. Anyone can help me, please ??
I Update the news through (Firebase Database and Online Database)
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class Home extends AppCompatActivity {
RequestQueue requestQueue;
String url = "https://mobarmejlebanon.000webhostapp.com/show.php";
TextView textView;
ListView listview;
ArrayList<listitme> listitmes = new ArrayList<listitme>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
textView = (TextView) findViewById(R.id.textView);
listview = (ListView) findViewById(R.id.listview);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("allstudents");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String info = respons.getString("info");
String img = respons.getString("img");
listitmes.add(new listitme(id, name, info, img));
listAllItme();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
listAdpter lA = new listAdpter(listitmes);
listview.setAdapter(lA);
}
class listAdpter extends BaseAdapter {
ArrayList<listitme> listA = new ArrayList<listitme>();
public listAdpter(ArrayList<listitme> listA) {
this.listA = listA;
}
#Override
public int getCount() {
return listA.size();
}
#Override
public Object getItem(int position) {
return listA.get(position).id;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item, null);
TextView id = (TextView) view.findViewById(R.id.textView_id);
TextView name = (TextView) view.findViewById(R.id.textView_name);
TextView info = (TextView) view.findViewById(R.id.textView_info);
ImageView img = (ImageView) view.findViewById(R.id.image);
id.setText(listA.get(position).id);
name.setText(listA.get(position).name);
info.setText(listA.get(position).info);
Picasso.with(Home.this).load("https://mobarmejlebanon.000webhostapp.com/images/" + listA.get(position).img).into(img);
return view;
}
}
}
Here is the Firebase database code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Topic2 extends AppCompatActivity {
TextView TopicTitle,Topic;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference mRootReference = firebaseDatabase.getReference();
DatabaseReference mKidRefernece = firebaseDatabase.getReference("topictwotitle");
DatabaseReference mChildReference = mRootReference.child("topictwomessage");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic2);
TopicTitle = (TextView) findViewById(R.id.twotitle);
Topic = (TextView) findViewById(R.id.twomsg);
TopicTitle.setText("Please Wait");
Topic.setText("Loading");
}
#Override
protected void onStart() {
super.onStart();
mChildReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.getValue(String.class);
Topic.setText(message);
mKidRefernece.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String topictitle = dataSnapshot.getValue(String.class);
TopicTitle.setText(topictitle);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I suggest you to use CardView and RecyclerView in order to achieve your purpose. You can get a better insight of it here:
Also you can catch a glimpse of it in action here and hither.
EDIT
According to the new query regarding this question; I think you must catch up this How to get a text after clicking on the CardView.
Happy Coding...
EDIT
Here is your sample:
I added dummy right now.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<TopicDTO> topics = new ArrayList<>();
for (int i = 0; i < 10; i++) {
topics.add(new TopicDTO("" + i, "Topic " + (i + 1), "Your Topic info goes here", "Your Topic Image goes here", "http://www.google.com"));
}
ListView listTopics = (ListView) findViewById(R.id.listTopics);
listTopics.setAdapter(new TopicsListAdapter(MainActivity.this, topics));
}
}
TopicsListAdapter.java
public class TopicsListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<TopicDTO> mData;
public TopicsListAdapter(Context context, ArrayList<TopicDTO> data) {
mInflater = LayoutInflater.from(context);
mData = data;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ChildViewHolder holder;
if (convertView == null) {
holder = new ChildViewHolder();
convertView = mInflater.inflate(R.layout.row_topics, parent,
false);
holder.textTopicTitle = (TextView) convertView
.findViewById(R.id.textTopicTitle);
holder.textTopicInfo = (TextView) convertView
.findViewById(R.id.textTopicInfo);
holder.textTopicLink = (TextView) convertView
.findViewById(R.id.textTopicLink);
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
}
final TopicDTO mItem = mData.get(position);
holder.textTopicTitle.setText(mItem.name);
holder.textTopicInfo.setText(mItem.info);
/*You need to have a more info link per topic*/
holder.textTopicLink.setClickable(true);
holder.textTopicLink.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='" + mItem.moreInfoLink + "'> Click here to see full topic </a>";
holder.textTopicLink.setText(Html.fromHtml(text));
return convertView;
}
class ChildViewHolder {
TextView textTopicTitle, textTopicInfo, textTopicLink;
}
}
row_topics.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textTopicTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textTopicInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" />
</LinearLayout>
</LinearLayout>
<!--You need to add extra TextView in your row file of listview.
It will work as a link per topic.-->
<TextView
android:id="#+id/textTopicLink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:text="Click here to see full topic" />
</LinearLayout>
Read each comment carefully and then implement it. That's it. Nothing can be better than this.
OLD
You need to have a textView for each topic you have.You have something like listview or recyclerview. Then when user clicks on that textView open link associated with that topic only that is from your dataset of listview.
Try this on your textview on which you want to open a link :
info.setClickable(true);
info.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
info.setText(Html.fromHtml(text));
Replace "http://www.google.com" with your topic's link.
I am Trying to Display the Contact From Phone to the ListView(Which is used in a Fragment)..... I have Tried Putting a SearchView to Filter Data from ListView.....
Search View Does Not Filter Data ....
Pls Help ...I Am badly Stuck...
ScreenShot of App having SearchView over List View Showing Contact Details....
https://drive.google.com/file/d/0B8sFN35Zdhnfa0RtVEJKc2V2WG8/view?usp=sharing
https://drive.google.com/file/d/0B8sFN35ZdhnfWTljaTRWaGY3c1E/view?usp=sharing
contactfragment.xml , GetContactAdapter.java , Contact_Fragment3.java
are three different files..
**contractfragment.xml**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/searchContactLIST"
android:queryHint="Search...."
android:clickable="true"
>
</SearchView>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lists"
android:scrollbarStyle="outsideOverlay"
/>
</LinearLayout>
**GetContactAdapter.java**
package com.example.cosmic.zumi_test;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class GetContactAdapter extends ArrayAdapter<String> implements Filterable {
String[] phone = {};
String[] names = {};
int[] img = {};
Context c;
LayoutInflater inflater;
public class Viewholder {
TextView names;
TextView address;
ImageView img;
}
public GetContactAdapter(Context context, String[] names, String[] add) {
super(context, R.layout.customcontactlist, names);
this.c = context;
this.names = names;
this.phone = add;
this.img = img;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customcontactlist, null);
}
Viewholder viewholder = new Viewholder();
viewholder.names = (TextView) convertView.findViewById(R.id.contact_name);
viewholder.address = (TextView) convertView.findViewById(R.id.contact_no);
viewholder.img = (ImageView) convertView.findViewById(R.id.image_contactlist);
//ASSIGN DATA
viewholder.img.setImageResource(R.drawable.com_facebook_button_icon_blue);
viewholder.names.setText(names[position]);
viewholder.address.setText(phone[position]);
return convertView;
}
}
**Contact_Fragment3.java**
package com.example.cosmic.zumi_test;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filterable;
import android.widget.ListView;
import android.widget.Toast;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cosmic on 31/12/16.
*/
public class Contact_FRAGMENT3 extends Fragment {
private Uri uriContact;
private String contactID;
private ListView lstNames;
private GetContactAdapter adapter;
// Request code for READ_CONTACTS. It can be any number > 0.
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
private android.widget.SearchView search;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contactfragment, container, false);
this.lstNames = (ListView) v.findViewById(R.id.lists);
this.search = (android.widget.SearchView) v.findViewById(R.id.searchContactLIST);
// Read and show the contacts
showContacts();
return v;
}
private void showContacts() {
// Check the SDK version and whether the permission is already granted or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
//After this point you wait for callback in onRequestPermissionsResult(int, String[], int[]) overriden method
} else {
// Android version is lesser than 6.0 or the permission is already granted.
List<String> contacts = getContactNames();
// String[] arr_contact=contacts.to
List<String> contacts_no = getContactNo();
String[] strarray = new String[contacts.size()];
contacts.toArray(strarray);
String[] strarray2 = new String[contacts_no.size()];
contacts_no.toArray(strarray2);
adapter = new GetContactAdapter(getContext(), strarray, strarray2);
lstNames.setAdapter(adapter);
search.setOnQueryTextListener(new android.widget.SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return true;
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(getContext(), "Until you grant the permission, we cannot display the names", Toast.LENGTH_SHORT).show();
}
}
}
private List<String> getContactNames() {
List<String> contacts = new ArrayList<>();
List<String> number = new ArrayList<>();
// Get the ContentResolver
ContentResolver cr = getActivity().getContentResolver();
// Get the Cursor of all the contacts
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Move the cursor to first. Also check whether the cursor is empty or not.
if (cursor.moveToFirst()) {
// Iterate through the cursor
do {
// Get the contacts name
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String numbers = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
number.add(numbers);
contacts.add(name);
} while (cursor.moveToNext());
}
// Close the curosor
cursor.close();
return contacts;
}
private List<String> getContactNo() {
List<String> number = new ArrayList<>();
// Get the ContentResolver
ContentResolver cr = getActivity().getContentResolver();
// Get the Cursor of all the contacts
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Move the cursor to first. Also check whether the cursor is empty or not.
if (cursor.moveToFirst()) {
// Iterate through the cursor
do {
// Get the contacts name
// String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String numbers = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
number.add(numbers);
// contacts.add(name);
} while (cursor.moveToNext());
}
// Close the curosor
cursor.close();
return number;
}
}
try this code if it might help you
public class SearchViewFilterMode extends Activity implements SearchView.OnQueryTextListener {
private SearchView mSearchView;
private ListView mListView;
private final String[] mStrings = Cheeses.sCheeseStrings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.searchview_filter);
mSearchView = (SearchView) findViewById(R.id.search_view);
mListView = (ListView) findViewById(R.id.list_view);
mListView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
mStrings));
mListView.setTextFilterEnabled(true);
setupSearchView();
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(true);
mSearchView.setQueryHint("Search Here");
}
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
mListView.clearTextFilter();
} else {
mListView.setFilterText(newText.toString());
}
return true;
}
public boolean onQueryTextSubmit(String query) {
return false;
}
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I am getting a NullPointerException at line 67 while trying to set a listView with a chat adapter. Here is the class:
I have placed ** around the line I am getting the NullPointerException on. I'm not really understading why its returning as null when I'm setting messageAdapter to a new object of an inner class called ChatAdapter(this).
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MessageListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>();
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
listView = (ListView)findViewById(R.id.chatListView);
final EditText editText = (EditText)findViewById(R.id.messageText);
sendButton = (Button)findViewById(R.id.sendButton);
messageAdapter = new ChatAdapter(this); // chatAdapter is a built in adapater
**listView.setAdapter(messageAdapter);**
Cdb = new ChatDatabaseHelper(this);
Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class
// cursor will move through the database to find the next text if there is any.
while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // on click listener for the send button
String chatText = editText.getText().toString(); // changing editText to String
arrayList.add(chatText); // adding the string from EditTest to arrayList
boolean isInserted = Cdb.insertData(chatText); // inserting the message text into the database
if(isInserted = true)
{ Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
else {
Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
editText.setText(" "); // set the text on the send button to blank.
} // end of onClick view
}); // end of onClickListener
if (findViewById(R.id.message_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.
public ChatAdapter(MessageListActivity ctx) {
super(ctx, 0);
} // default constructor
// method to return the number of rows that will be in your array
// will tell how many times to run a for loop
public int getCount(){ return arrayList.size(); } // will return the size of the array
public String getItem(int position){ return arrayList.get(position); } // will return the item at position
// getview method
#Override
public View getView(int position, final View convertView, ViewGroup parent) {// inner class
LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
View result = null;
if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming
} else {
result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing
}
TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
final String messageText = getItem(position) ;
message.setText(messageText);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );
context.startActivity(intent);
}
}
});
return result; // return the view which is the Inflater.
}
} // end of chat adapter class
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
xml:
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ChatWindow">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatListView"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:layout_above="#+id/sendButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sendButton"
android:id="#+id/sendButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/messageText"
android:layout_toStartOf="#id/sendButton"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:enabled="true"
/>
</RelativeLayout>
just try
messageAdapter = new ChatAdapter(MessageListActivity .this);