我正在创建一个有3个屏幕的应用程序,第一个我插入联系人信息,如姓名,地址,电子邮件,手机......第二个屏幕我把社交网络链接, 然后我在RecyclerView中显示所有联系人信息,但是当我点击按钮转到第三个屏幕时,我会遇到这个错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.person.bernardo.myperson, PID: 14891
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.person.bernardo.myperson/com.person.bernardo.myperson.RecyclerViewActivity}: java.lang.ClassCastException: com.person.bernardo.myperson.RecyclerViewActivity cannot be cast to com.person.bernardo.myperson.PessoaAdapter$ItemClickListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2785)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1532)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6342)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
Caused by: java.lang.ClassCastException: com.person.bernardo.myperson.RecyclerViewActivity cannot be cast to com.person.bernardo.myperson.PessoaAdapter$ItemClickListener
at com.person.bernardo.myperson.RecyclerViewActivity.onCreate(RecyclerViewActivity.java:47)
at android.app.Activity.performCreate(Activity.java:6847)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2677)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2785)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1532)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6342)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
我的代码:
/**
* ---------------------------------------------- Documentacao preliminar
* Pontificia Universidade Catolica de Minas Gerais
* Curso de Ciencia da Computacao
* LDDM
* <p>
* Autor: Bernardo Morais Alfredo Matricula: 565524
* Versao: 0.06 Data: 18/03/2018
* <p>
* Dados:
* - Ler dados de uma pessoa e criar evento no calendario.
* <p>
* Para funcionar:
* <p>
* Insira (nas dependencies de build.gradle (Module:App) :
* compile fileTree(dir: 'libs', include: ['*.jar'])
* compile 'com.android.support:design:22.2.0'
* compile 'com.android.support:appcompat-v7:22.2.0'
* <p>
* Resultados:
* <p>
* -Funciona
* <p>
* Feito com ajuda de:
* Luiz Braganca
*/
package com.person.bernardo.myperson;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Vibrator;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.support.design.widget.TextInputLayout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
static Pessoa contato = new Pessoa();
EditText nome, nasc, tel, email, endereco;
// Variavel para utilizar o vibrador
private Vibrator vib;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setBotoes();
}
/**
* Metodo para converter EditText em String.
* @param txt
* @return
*/
public String converteTexto(EditText txt) {
// definir dados
String resp = txt.getText().toString();
return (resp);
}// end converteTexto( )
/**
* Metodo para verificar cada botao.
*/
private void setBotoes() {
// definindo botoes
Button addContato = findViewById(R.id.addContato),
salvaAniv = findViewById(R.id.anivesario),
envWhatsapp = findViewById(R.id.whatsapp),
save = findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nome = findViewById(R.id.nome);
nasc = findViewById(R.id.nascimento);
tel = findViewById(R.id.phone);
email = findViewById(R.id.email);
endereco = findViewById(R.id.endereco);
}// end onClick( )
});
// definindo os editText
nome = findViewById(R.id.nome);
nasc = findViewById(R.id.nascimento);
tel = findViewById(R.id.phone);
email = findViewById(R.id.email);
endereco = findViewById(R.id.endereco);
final TextInputLayout nomeInput = findViewById(R.id.input_layout_nome),
nascInput = findViewById(R.id.input_layout_data),
telInput = findViewById(R.id.input_layout_telefone),
emailInput = findViewById(R.id.input_layout_email),
endInput = findViewById(R.id.input_layout_endereco);
//Inicializando a variavel vibrator
vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// botao de adicionar contato
addContato.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean emptyNome = TextUtils.isEmpty(converteTexto(nome)),
emptyEmail = TextUtils.isEmpty(converteTexto(email)),
emptytel = TextUtils.isEmpty(converteTexto(tel)),
emptyAddress = TextUtils.isEmpty(converteTexto(endereco));
//Mostrar Erro se Nome Vazio
if (emptyNome) {
vib.vibrate(120);
nomeInput.setErrorEnabled(true);
nomeInput.setError(getResources().getString(R.string.erro_EditText_Nome));
}// end if
//Mostrar Erro se Email Vazio
if (emptyEmail) {
vib.vibrate(120);
emailInput.setErrorEnabled(true);
emailInput.setError(getResources().getString(R.string.erro_EditText_Email));
}// end if
//Mostrar Erro se Telefone Vazio
if (emptytel) {
vib.vibrate(120);
telInput.setErrorEnabled(true);
telInput.setError(getResources().getString(R.string.erro_EditText_Tel));
}// end if
//Mostrar Erro se Address Vazio
if (emptyAddress) {
vib.vibrate(120);
endInput.setErrorEnabled(true);
endInput.setError(getResources().getString(R.string.erro_EditText_Endereco));
}// end if
//Se os campos nao estiverem vazios:
if (!emptyNome && !emptyEmail && !emptytel && !emptyAddress) {
nomeInput.setErrorEnabled(false);
emailInput.setErrorEnabled(false);
telInput.setErrorEnabled(false);
endInput.setErrorEnabled(false);
contato.setNome(converteTexto(nome));
contato.setEmail((converteTexto(email)));
contato.setTelefone((converteTexto(tel)));
contato.setEndereco((converteTexto(endereco)));
addContact(converteTexto(nome), converteTexto(email), converteTexto(tel), converteTexto(endereco));
}// end if
}// end onClick( )
});
// botao de salvar aniversario
salvaAniv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean emptyNome = TextUtils.isEmpty(converteTexto(nome)),
emptyData = TextUtils.isEmpty(converteTexto(nasc));
//Mostrar erro se nome vazio.
if (emptyNome) {
vib.vibrate(120);
nomeInput.setErrorEnabled(true);
nomeInput.setError(getResources().getString(R.string.erro_EditText_Nome));
}// end if
//Mostrar erro se data de nascimento vazia.
if (emptyData) {
vib.vibrate(120);
nascInput.setErrorEnabled(true);
nascInput.setError(getResources().getString(R.string.erro_EditText_Nasc));
}// end if
if (!emptyNome && !emptyData) {
nomeInput.setErrorEnabled(false);
nascInput.setErrorEnabled(false);
aniversario(converteTexto(nome), converteTexto(nasc));
}// end if
}// end onClick
});
// botao de enviar whatsapp
envWhatsapp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean emptyTel = TextUtils.isEmpty(converteTexto(tel));
//Mostrar erro se telefone vazio.
if (emptyTel) {
vib.vibrate(120);
telInput.setErrorEnabled(true);
telInput.setError(getResources().getString(R.string.erro_EditText_Tel));
}// end if
//Mostrar erro.
if (!emptyTel) {
telInput.setErrorEnabled(false);
whatsapp(converteTexto(tel));
}// end if
}// end onClick
});
}// end setBotoes( )
/**
* Metodo addContact( ) - adicionar um contato.
*
* @Param: -Nome = nome contato
* -Email = email contato
* -Tel = Telefone contato
* -End = endereco contato
*/
public void addContact(String nome, String email, String tel, String end) {
//define o contato
// set intent
Intent intent = new Intent(ContactsContract.Intents.Insert.ACTION);
intent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
// set nome
intent.putExtra(ContactsContract.Intents.Insert.NAME, nome);
// set email
intent.putExtra(ContactsContract.Intents.Insert.EMAIL, email);
intent.putExtra(ContactsContract.Intents.Insert.EMAIL_TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME);
// set telefone
intent.putExtra(ContactsContract.Intents.Insert.PHONE, tel);
intent.putExtra(ContactsContract.Intents.Insert.PHONE_TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
// set endereco
intent.putExtra(ContactsContract.Intents.Insert.POSTAL, end);
intent.putExtra(ContactsContract.Intents.Insert.POSTAL_TYPE, ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME);
// set intent
startActivity(intent);
}// end addContact( )
/**
* Metodo para adicionar data de aniversário na agenda.
*/
public void aniversario(String nome, String nasc) {
// set data
int dia, mes, year;
Intent intent = new Intent(Intent.ACTION_INSERT);
contato.setAniversario(nasc);
// get day
dia = Pessoa.getDia(nasc);
contato.setDia(dia);
// get month
mes = Pessoa.getMes(nasc);
contato.setMes(mes);
// get year
year = Pessoa.getYear(nasc);
contato.setAno(year);
// set date
intent.setData(CalendarContract.Events.CONTENT_URI);
// set event title
intent.putExtra(CalendarContract.Events.TITLE, "Aniversário de " + nome);
// set event time
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
// set start day
Calendar startTime = Calendar.getInstance();
startTime.set(2018, mes, dia, 0, 0);
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime.getTimeInMillis());
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, startTime.getTimeInMillis());
intent.putExtra("rrule", "FREQ=YEARLY");
// iniciando a activity
startActivity(intent);
}// end aniversario( )
/**
* Metodo que manda mensagem pelo whatsapp.
*
* @Param: -Numero Telefone
*/
public void whatsapp(String number) {
contato.setTelefone(number);
// send contact number
Uri uri = Uri.parse("smsto:" + number);
// start intent
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, uri);
// text type
sendIntent.setPackage("text/plain");
// add whatsapp package
sendIntent.setPackage("com.whatsapp");
// start activity
startActivity(Intent.createChooser(sendIntent, ""));
}// end whatsapp( )
/**
* Metodo que vai para a segunda tela.
* @param view
*/
public void segundaTela(View view) {
// criando a intent para a segunda tela
Intent secondScreen = new Intent(this, MainSocial.class);
Pessoa proxPessoa = new Pessoa();
proxPessoa.setNome(nome.getText().toString());
proxPessoa.setTelefone(tel.getText().toString());
proxPessoa.setEmail(email.getText().toString());
proxPessoa.setEndereco(endereco.getText().toString());
proxPessoa.setAniversario(nasc.getText().toString());
secondScreen.putExtra("proxPessoa", proxPessoa);
// iniciando
startActivity(secondScreen);
}// end segundaTela( )
}// end class
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainSocial extends AppCompatActivity {
Pessoa receivePessoa;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_social);
Intent intent = getIntent();
receivePessoa = (Pessoa) intent.getSerializableExtra("proxPessoa");
pegarDados();
}
/**
* Metodo para converter EditText em String.
*
* @param txt
* @return
*/
public String editTextToString(EditText txt) {
// definir dados
String resp = "";
if (txt != null) {
resp = txt.getText().toString();
} else {
resp = "";
}
return (resp);
}// end converteTexto( )
/**
* Metodo para salvar os dados de cada rede no contato, se null = "".
*
* @param
* @return
*/
public void pegarDados() {
Button save = findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText facebook = findViewById(R.id.facebook);
String face = editTextToString(facebook);
receivePessoa.setFacebook(face);
EditText instagram = findViewById(R.id.instagram);
String insta = editTextToString(instagram);
receivePessoa.setInstagram(insta);
EditText linkedin = findViewById(R.id.linkedin);
String link = editTextToString(linkedin);
receivePessoa.setLinkedIn(link);
EditText spotify = findViewById(R.id.spotify);
String spot = editTextToString(spotify);
receivePessoa.setSpotify(spot);
EditText twitter = findViewById(R.id.twitter);
String twit = editTextToString(twitter);
receivePessoa.setTwitter(twit);
EditText youtube = findViewById(R.id.youtube);
String yout = editTextToString(youtube);
receivePessoa.setYoutube(yout);
}// end onClick( )
});
}
/**
* Metodo que vai para a segunda tela.
*
* @param view
*/
public void terceiraTela(View view) {
// criando a intent para a terceira tela com RecycleView
Intent terceiraTela = new Intent(this, RecyclerViewActivity.class);
terceiraTela.putExtra("pessoa2", receivePessoa);
System.out.println(receivePessoa.getNome());
System.out.println(receivePessoa.getTelefone());
System.out.println(receivePessoa.getEmail());
System.out.println(receivePessoa.getEndereco());
System.out.println(receivePessoa.getFacebook());
System.out.println(receivePessoa.getInstagram());
System.out.println(receivePessoa.getLinkedIn());
System.out.println(receivePessoa.getTwitter());
System.out.println(receivePessoa.getSpotify());
System.out.println(receivePessoa.getYoutube());
// iniciando
startActivity(terceiraTela);
}// end terceiraTela( )
}
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.TextView;
import java.util.List;
public class PessoaAdapter extends RecyclerView.Adapter<PessoaAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
PessoaAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
@Override
public int getItemCount() {
return mData.size();
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.show_nome);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
public class RecyclerViewActivity extends AppCompatActivity {
PessoaAdapter adapter;
Pessoa contato;
private List<Pessoa> movieList = new ArrayList<>();
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view_activity);
Intent intent = getIntent();
contato = (Pessoa) intent.getSerializableExtra("pessoa2");
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add(contato.getNome());
animalNames.add(contato.getTelefone());
animalNames.add(contato.getEmail());
animalNames.add(contato.getEndereco());
animalNames.add(contato.getFacebook());
animalNames.add(contato.getLinkedIn());
animalNames.add(contato.getInstagram());
animalNames.add(contato.getYoutube());
animalNames.add(contato.getSpotify());
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.listView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new PessoaAdapter(this, animalNames);
adapter.setClickListener((PessoaAdapter.ItemClickListener) this);
recyclerView.setAdapter(adapter);
}
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
}
我尝试使用此示例here.
答案 0 :(得分:0)
此行中的错误
adapter.setClickListener((PessoaAdapter.ItemClickListener) this);
你应该这样做
RecyclerViewActivity
实现接口PessoaAdapter.ItemClickListener
public class RecyclerViewActivity extends AppCompatActivity implements PessoaAdapter.ItemClickListener{
将方法添加到课程RecyclerViewActivity
void onItemClick(View view, int position){ your code }
您不再需要施放
adapter.setClickListener(this);
阅读此https://docs.oracle.com/javase/tutorial/java/IandI/usinginterface.html
答案 1 :(得分:0)
您需要从interface
课程中移出PessoaAdapter
。
创建一个新的类ItemClickListener.java
,如下所示。
package com.person.bernardo.myperson;
import android.view.View;
public interface ItemClickListener {
void onItemClick(View view, int position);
}
现在,在您的RecyclerViewActivity
中实现ItemClickListener
,如下所示,在将适配器设置为RecyclerView
时,您可以将侦听器与适配器一起设置。
package com.person.bernardo.myperson;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewActivity extends AppCompatActivity implements ItemClickListener {
PessoaAdapter adapter;
Pessoa contato;
private List<Pessoa> movieList = new ArrayList<>();
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler_view_activity);
Intent intent = getIntent();
contato = (Pessoa) intent.getSerializableExtra("pessoa2");
ArrayList<String> animalNames = new ArrayList<>();
animalNames.add(contato.getNome());
animalNames.add(contato.getTelefone());
animalNames.add(contato.getEmail());
animalNames.add(contato.getEndereco());
animalNames.add(contato.getFacebook());
animalNames.add(contato.getLinkedIn());
animalNames.add(contato.getInstagram());
animalNames.add(contato.getYoutube());
animalNames.add(contato.getSpotify());
// set up the RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.listView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Error in the following line
adapter = new PessoaAdapter(this, animalNames);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(View view, int position) {
// Do something based on the item click in the RecyclerView
}
}
修改后的适配器将如下所示。
package com.person.bernardo.myperson;
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.TextView;
import java.util.List;
public class PessoaAdapter extends RecyclerView.Adapter<PessoaAdapter.ViewHolder> {
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
PessoaAdapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the row layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String animal = mData.get(position);
holder.myTextView.setText(animal);
}
// total number of rows
@Override
public int getItemCount() {
return mData.size();
}
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.show_nome);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null)
mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
我已经从github下载了你的代码并修改了我在本地创建的分支中的代码。请检查github repository中修复分支中的提取请求。
希望有所帮助!