I am trying to build a simple chat application. With chat conversation screen I'm using ListView with ArrayAdapter to store and show the message but when I receive or send new message, all of recent message is change to.
This is my adapter code:
public class MessageAdapter extends ArrayAdapter<Message> {
private Context context;
private ArrayList<Message> messages;
private DatabaseHelper databaseHelper;
private Message message;
#Override
public void add(Message object) {
messages.add(object);
super.add(object);
}
public MessageAdapter(Context context, int textViewResouceId, ArrayList<Message> messages) {
super(context, textViewResouceId);
this.context = context;
this.messages = messages;
databaseHelper = DatabaseHelper.getInstance(context);
}
public int getCount() {
return messages.size();
}
public Message getItem(int index) {
return messages.get(index);
}
public long getItemId(int position) {
return position;
}
#Override
public int getPosition(Message item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MessageViewHolder messageViewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.chat_item, parent, false);
messageViewHolder = new MessageViewHolder();
messageViewHolder.tv_userName = (TextView) convertView.findViewById(R.id.tv_chatName);
messageViewHolder.tv_message = (TextView) convertView.findViewById(R.id.tv_messageContent);
convertView.setTag(messageViewHolder);
} else {
messageViewHolder = (MessageViewHolder) convertView.getTag();
}
message = messages.get(position);
String username = databaseHelper.getUserByUserId(message.getUserId()).getUserName();
if (message.getUserId() == AppConfig.USER_ID) {
messageViewHolder.tv_message.setTextColor(Color.parseColor("#0066ff"));
messageViewHolder.tv_userName.setTextColor(Color.parseColor("#0066ff"));
} else {
messageViewHolder.tv_message.setTextColor(Color.parseColor("#000000"));
messageViewHolder.tv_userName.setTextColor(Color.parseColor("#000000"));
}
messageViewHolder.tv_userName.setText(username);
messageViewHolder.tv_message.setText(message.getMessage());
return convertView;
}
static class MessageViewHolder {
TextView tv_message;
TextView tv_userName;
}
}
This is my ListView Layout code:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<ScrollView
android:id="#+id/scroll_chat"
android:layout_width="match_parent"
android:layout_height="380dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:background="#null"
android:divider="#null"
android:stackFromBottom="true"
android:drawSelectorOnTop="false"
android:transcriptMode="alwaysScroll" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.92" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
And this is error when I send two message (the same error happen when I receive a message)
I think the problem is the way set the data to View but I cannot solve it.
Could anyone help me solve this issue.
This is chat screen when I close and open the activity again: It showed correct message.
This is Chatactivity code:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_send;
private static EditText txt_chat;
private String registId;
private Bundle bundle;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private ListView lv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
lv_message = (ListView) findViewById(R.id.listMessage);
// lv_message.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getMessges(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId());
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = Message.getInstance();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = Message.getInstance();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
}
In your ChatActivity. In onClickEvent
Try to change
Message messageObj = Message.getInstance();
to
Message messageObj = new Message();
You can read more about Singleton Pattern in here
Related
did not start activity and give data binding error
useradapter
public class useradapter extends RecyclerView.Adapter<useradapter.CustomView> {
String nn = "m";
List<allusermodel> list1;
private Context context;
private LayoutInflater layoutInflater;
public useradapter(Context context, List<allusermodel> list1) {
Log.e("reached1", nn);
this.context = context;
this.list1 = list1;
}
#Override
public useradapter.CustomView onCreateViewHolder(final ViewGroup parent, final int viewType) {
Log.e("reached2", nn);
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
final Entrys newsBinding = Entrys.inflate(layoutInflater, parent, false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView(newsBinding);
}
#Override
public void onBindViewHolder(useradapter.CustomView holder,int position) {
Log.e("reached3", nn);
// News news = newsList.get(position);
// holder.desc.setText(news.getDesc());
allusermodel newsModel1 = list1.get(position);
// Log.e("list", String.valueOf(list1));
Log.e("nameeeee",newsModel1.getAll_user());
// Log.e("position", String.valueOf(position));
//Log.e("names",newsModel1.getAll_user());
holder.bind(newsModel1);
}
#Override
public int getItemCount() {
return list1.size();
}
public class CustomView extends RecyclerView.ViewHolder {
private Entrys newsBinding;
// public TextView title;
//TextView title, desc;
public CustomView(Entrys newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
Log.e("reached4", nn);
// title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
newsBinding.setRecyclerclick(new Presenters2() {
#Override
public void onclickListener() {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
allusermodel clickedDataItem = list1.get(pos);
Intent intent = new Intent(context, messagelist.class);
intent.putExtra("clickid", clickedDataItem.getId());
context.startActivity(intent);
}
}
});
}
public void bind(allusermodel newsModel1)
{
Log.e("reached5", String.valueOf(newsModel1));
//String j = newsModel1.getAll_user();
// Log.e("bind",nn);
this.newsBinding.setAlluserentry(newsModel1);
}
public Entrys getNewsBinding() {
Log.e("reached6", nn);
return newsBinding;
}
}
}
messagelist
public class messagelist extends AppCompatActivity {
private RecyclerView recyclerView;
private ActivityMainBinding activityMainBinding1;
private Postmessagemodel postmessagemodel;
private messageadapter customAdapter;
private messagelist_datamanager dataManger;
private postmessage_datamanager postmessage_datamanager;
private List<messagemodel> newsList;
String tokens;
String sendmsg;
private int toid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_messagelist);
toid=getIntent().getExtras().getInt("clickid");
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
tokens = pref.getString("sherdtoken", "");
Log.e("token", tokens);
activityMainBinding1 = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
postmessagemodel = new Postmessagemodel();
postmessage_datamanager = new postmessage_datamanager(this);
//activityMainBinding1.setPostmsg(postmessagemodel);
/* activityMainBinding1.setPostbtn(new Post() {
#Override
public void onclick() {
postmessage();
}
});*/
sendmsg = postmessagemodel.getMSG();
dataManger = new messagelist_datamanager(this);
recyclerView = (RecyclerView) findViewById(R.id.recycle1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsList = new ArrayList<>();
customAdapter = new messageadapter(this, newsList);
recyclerView.setAdapter(customAdapter);
getmessage();
postmessage();
}
public void getmessage()
{
dataManger.sendVolleyRequest2(tokens,toid,messagelist.this, new messagelist_datavalue() {
#Override
public void setJsonDataResponse(JSONArray response) {
messagemodel userModel = new messagemodel();
newsList = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
// Log.e("final", String.valueOf(i));
userModel.setFromUserId(jsonObject.getInt("fromUserId"));
userModel.setMessage(jsonObject.getString("message"));
userModel.setToUserId(jsonObject.getInt("toUserId"));
newsList.add(userModel);
}
} catch (JSONException jsonDataResponse) {
Log.e("error", String.valueOf(jsonDataResponse));
}
customAdapter.notifyDataSetChanged();
}
#Override
public void setVolleyError(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
}
});
}
private void postmessage() {
postmessage_datamanager.sendVolleyRequest3(sendmsg,toid,tokens,messagelist.this,new postmessage_datavalue() {
#Override
public void setJsonDataResponse(JSONObject response) {
try {
Log.e("success",sendmsg);
} catch (Exception e) {
Log.e("error", e.toString());
}
}
#Override
public void setVolleyError(VolleyError volleyError) {
}
});
}
}
messagelist.xml
<?xml version="1.0" encoding="utf-8"?>
<layout 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:id="#+id/layout">
<data>
<variable
name="postmsg"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.Postmessagemodel"/>
<variable
name="postbtn"
type="com.example.mayurpancholi.chat_mvvm.interfaces.Post"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mayurpancholi.chat_mvvm.messagelist">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycle1"
android:scrollbars="vertical"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="80dp">
</android.support.v7.widget.RecyclerView>
<EditText
android:id="#+id/post_text"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="13dp"
android:text="#={postmsg.MSG}"
android:layout_marginLeft="9dp"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="#+id/post_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/post_text"
android:layout_alignParentEnd="true"
android:layout_marginBottom="7dp"
android:layout_marginRight="5dp"
android:background="#color/colorPrimary"
android:onClick="#{()->postbtn.onclick()}"
android:text="post" />
</RelativeLayout>
</layout>
innerlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class ="MessageBinding">
<variable
name="message_list"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.messagemodel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/main_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:text="#{message_list.message}"
android:textSize="17dp" />
</LinearLayout>
</layout>
messagelistadapter
public class messageadapter extends RecyclerView.Adapter<messageadapter.CustomView1> {
List<messagemodel> list;
private Context context;
private LayoutInflater layoutInflater;
public messageadapter(Context context,List<messagemodel> list)
{
this.context =context;
this.list = list;
}
public messageadapter() {
}
#Override
public messageadapter.CustomView1 onCreateViewHolder(ViewGroup parent, int viewType) {
if(layoutInflater == null)
{
layoutInflater = LayoutInflater.from(parent.getContext());
}
final MessageBinding newsBinding = MessageBinding.inflate(layoutInflater,parent,false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView1(newsBinding);
}
#Override
public void onBindViewHolder(messageadapter.CustomView1 holder, int position) {
messagemodel newsModel = list.get(position);
holder.bind(newsModel);
}
#Override
public int getItemCount() {
return list.size();
}
public class CustomView1 extends RecyclerView.ViewHolder {
private MessageBinding newsBinding;
// TextView title, desc;
public CustomView1(MessageBinding newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
//title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
}
public void bind(messagemodel newsModel1)
{
// this.newsBinding.setMessage_list(newsModel1);
}
public MessageBinding getNewsBinding()
{
return newsBinding;
}
}
}
when i click the recyclerview text it open messagelist but messagelist won't open and give error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mayurpancholi.chat_mvvm, PID: 21181
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mayurpancholi.chat_mvvm/com.example.mayurpancholi.chat_mvvm.messagelist}: java.lang.ClassCastException: com.example.mayurpancholi.chat_mvvm.databinding.ActivityMessagelistBinding cannot be cast to com.example.mayurpancholi.chat_mvvm.databinding.ActivityMainBinding
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
I think the error is self explanatory. As per your flow I can see you want to bind the messagelist actity layout with the Data binding of of MainActity class for which you might have layout as "activity_main.xml". For, As your messagelist activity binding layout name is "activity_messagelist.xml" so the generated binding class name will be "ActivityMessagelistBinding". Therefore, as per the logic of databinding the layout will bind with ActivityMessagelistBinding instead of ActivityMainBinding. So as a conclusion, you change the statement
private ActivityMainBinding activityMainBinding1;
activityMainBinding1 = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
to
private ActivityMessagelistBinding activityMessagelistBinding;
activityMessagelistBinding = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
Hope it should work.
I have an Activity where I enter a phone number and a message and when I click on the send Button, I want to display the message and number I entered in the layout of another Activity which has a RecyclerView. I have tried to use an Intent but it displays "NUMBER" and "NUMBER" in both TextViews.
This is some of the code below.
public class NewMessageActivity extends AppCompatActivity {
private String message, number;
private EditText mComposeMessage, mPhoneNumber;
private Button mSendButton, mCancelButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_message_layout);
mPhoneNumber = (EditText) findViewById(R.id.phone_number_et);
mComposeMessage = (EditText) findViewById(R.id.compose_et);
mSendButton = (Button) findViewById(R.id.send_button);
mCancelButton = (Button) findViewById(R.id.cancel_button);
number = mPhoneNumber.getText().toString();
message = mComposeMessage.getText().toString();
mSendButton.setOnClickListener(mButtonClickListener);
mCancelButton.setOnClickListener(mButtonClickListener);
}
private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.send_button:
Intent intent = new Intent(v.getContext(), SentActivity.class);
intent.putExtra(getString(R.string.key_message), message);
intent.putExtra("NUMBER", number);
startActivity(intent);
break;
case R.id.cancel_button:
break;
}
}
};
}
This is my Adapter
public class SentMessageAdapter extends RecyclerView.Adapter<SentMessageAdapter.MessageHolder> {
private List<String> mMessages;
public static class MessageHolder extends RecyclerView.ViewHolder {
private TextView mSentMessageTv;
private TextView mRecipientNumberTv;
private TextView mRecipientTv;
public MessageHolder(View v){
super(v);
mSentMessageTv = (TextView) v.findViewById(R.id.sent_message_tv);
mRecipientNumberTv = (TextView) v.findViewById(R.id.recipient_number_tv);
mRecipientTv = (TextView) v.findViewById(R.id.recipient_tv);
}
}
public SentMessageAdapter(List<String> messages){
mMessages = messages;
}
#Override
public MessageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sent_list_item, parent, false);
MessageHolder vH = new MessageHolder(v);
return vH;
}
#Override
public void onBindViewHolder(MessageHolder holder, int position) {
holder.mSentMessageTv.setText(mMessages.get(position));
holder.mRecipientNumberTv.setText(mMessages.get(position));
holder.mRecipientTv.setText(R.string.to);
}
#Override
public int getItemCount() {
return mMessages.size();
}
}
Activity where the text should be displayed
public class SentActivity extends AppCompatActivity {
private static final String LOG_TAG = SentActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
final ArrayList<String> messages = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.message_recycler_list);
Bundle extras = getIntent().getExtras();
String message = null;
if (extras != null){
message = extras.getString(String.valueOf(R.string.key_message), String.valueOf("NUMBER"));
}
if (message == null){
message = "text";
}
Log.d(LOG_TAG, message);
messages.add(0, message);
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
mRecyclerView = (RecyclerView) findViewById(R.id.message_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new SentMessageAdapter(messages);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
}
}
Layout for the Activity
<?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="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/sent_message_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
tools:text="Hello world"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:orientation="horizontal">
<TextView
android:id="#+id/recipient_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="#string/to"/>
<TextView
android:id="#+id/recipient_number_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="4dp"
android:paddingStart="4dp"
android:paddingRight="4dp"
android:paddingEnd="4dp" />
</LinearLayout>
</LinearLayout>
You're accessing phone number edit text in onCreate;
number = mPhoneNumber.getText().toString();
And it will be set to whatever your text in XML (It's set to NUMBER I guess). You need to access this after user entered text, so put this line in on click listener.
Get message and number value in onClick method not onCreate
switch (id) {
case R.id.send_button:
number = mPhoneNumber.getText().toString();
message = mComposeMessage.getText().toString();
Intent intent = new Intent(v.getContext(), SentActivity.class);
intent.putExtra(getString(R.string.key_message), message);
intent.putExtra("NUMBER", number);
startActivity(intent);
break;
}
Hope this will help you.
You are Not getting value that you entered is because you are accessing edittext values in onCreate method where it has default value so you should use
number = mPhoneNumber.getText().toString();
message = mComposeMessage.getText().toString();
this in onClick Methods
private View.OnClickListener mButtonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.send_button:
number = mPhoneNumber.getText().toString();
message = mComposeMessage.getText().toString();
Intent intent = new Intent(v.getContext(), SentActivity.class);
intent.putExtra(getString(R.string.key_message), message);
intent.putExtra("NUMBER", number);
startActivity(intent);
break;
case R.id.cancel_button:
break;
}
}
};
My mistake. I have fixed it now. I created a POJO class
public class Message {
private String mMessage;
private String mNumber;
public Message(String number, String message){
mNumber = number;
mMessage = message;
}
public String getMessage() {
return mMessage;
}
public String getNumber() {
return mNumber;
}
}
Then I changed the onBindViewHolder() to
#Override
public void onBindViewHolder(MessageHolder holder, int position) {
holder.mSentMessageTv.setText(mMessages.get(position).getMessage());
holder.mRecipientNumberTv.setText(mMessages.get(position).getNumber());
holder.mRecipientTv.setText(R.string.to);
}
I also changed to
String message = null;
String number = null;
if (extras != null){
message = extras.getString(String.valueOf("MESSAGE"));
number = extras.getString(String.valueOf("NUMBER"));
}
messages.add(new Message(number, message));
Finally, I changed all generics to
<Message>
I have manage to create a custom adapter and read data from web API but the suggestions are not displayed in the dropdown. I followed the tutorial at
http://makovkastar.github.io/blog/2014/04/12/android-autocompletetextview-with-suggestions-from-a-web-service/
Here is my custom AutoCompleteTextView
public class AutoCompleteDelay extends AutoCompleteTextView {
private static final int MESSAGE_TEXT_CHANGED = 100;
private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750;
private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY;
private ProgressBar mLoadingIndicator;
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
AutoCompleteDelay.super.performFiltering((CharSequence) msg.obj, msg.arg1);
}
};
public AutoCompleteDelay(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLoadingIndicator(ProgressBar progressBar) {
mLoadingIndicator = progressBar;
}
public void setAutoCompleteDelay(int autoCompleteDelay) {
mAutoCompleteDelay = autoCompleteDelay;
}
#Override
protected void performFiltering(CharSequence text, int keyCode) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.VISIBLE);
}
mHandler.removeMessages(MESSAGE_TEXT_CHANGED);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay);
}
#Override
public void onFilterComplete(int count) {
if (mLoadingIndicator != null) {
mLoadingIndicator.setVisibility(View.GONE);
}
super.onFilterComplete(count);
}
}
This is my custom Adapter
public class SearchAdapter extends BaseAdapter implements Filterable {
private static final int MAX_RESULTS = 10;
private Context mContext;
private List<User> resultList = new ArrayList<User>();
public SearchAdapter(Context context) {
mContext = context;
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public User getItem(int index) {
return resultList.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.search_results, parent, false);
}
((TextView) convertView.findViewById(R.id.user_name)).setText(getItem(position).getName());
((TextView) convertView.findViewById(R.id.user_phone)).setText(getItem(position).getPhone());
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
List<User> users = findUsers(mContext, constraint.toString());
// Assign the data to the FilterResults
filterResults.values = users;
filterResults.count = users.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
resultList = (List<User>) results.values;
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}};
return filter;
}
/**
* Returns a search result for the given book title.
*/
private List<User> findUsers(Context context, String query) {
// GoogleBooksProtocol is a wrapper for the Google Books API
SearchUser request = new SearchUser(context);
return request.sendRequest(query);
}
}
This is xml file for Adapter View
<?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:padding="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/user_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="18dp"
android:textIsSelectable="false"
android:layout_marginBottom="4dp"
android:textColor="#color/abc_background_cache_hint_selector_material_dark" />
<TextView
android:id="#+id/user_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0000000000"
android:textSize="16dp"
android:textIsSelectable="false"
android:layout_marginBottom="4dp"
android:textColor="#color/switch_thumb_disabled_material_dark" />
</LinearLayout>
This is the xml file where I am using 'AutoCompleteTextView`
<?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="16dp">
<TextView
android:id="#+id/error_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="User already exists"
android:visibility="gone"
android:textStyle="bold"
android:textColor="#color/design_textinput_error_color_light"
android:singleLine="true"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.krazz.futsaladmin.classes.AutoCompleteDelay
android:id="#+id/query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:inputType="textAutoComplete"></com.example.krazz.futsaladmin.classes.AutoCompleteDelay>
</android.support.design.widget.TextInputLayout>
<ProgressBar
android:id="#+id/pb_loading_indicator"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
This is the method that returns ArrayList<User>
public ArrayList<User> sendRequest(final String query) {
RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue();
//mErrorText.setVisibility(View.GONE);
String url = String.format(AppConfig.URL_SEARCH_USERS, query, AppConfig.APP_KEY, 4);
debug.L(url);
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
debug.L(response.toString());
JSONObject jObj = new JSONObject(response);
JSONArray jsonArray = jObj.getJSONArray("results");
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
JSONObject currentUser = jsonArray.getJSONObject(i);
int id = currentUser.getInt("id");
String name = currentUser.getString("name");
String phone = currentUser.getString("phone");
User users = new User(id, name, phone);
searchArrayList.add(users);
}
}
else{
/*mErrorText.setText("Users not found.");
mErrorText.setVisibility(View.VISIBLE);*/
debug.L("users not found");
}
} catch (JSONException e) {
/*mErrorText.setText(e.getMessage());
mErrorText.setVisibility(View.VISIBLE);*/
debug.L(e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/*mErrorText.setText(R.string.error_try_again);
mErrorText.setVisibility(View.VISIBLE);*/
debug.L(error.toString());
}
});
requestQueue.add(strReq);
return searchArrayList;
}
And finally here is where I am using my AutoCompleteTextView
mQueryInputView = (AutoCompleteDelay) view.findViewById(R.id.query);
mErrorText = (TextView) view.findViewById(R.id.error_text);
mQueryInputView.setThreshold(THRESHOLD);
mQueryInputView.setAdapter(new SearchAdapter(mContext));
mQueryInputView.setLoadingIndicator((ProgressBar) view.findViewById(R.id.pb_loading_indicator));
mQueryInputView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
User book = (User) adapterView.getItemAtPosition(position);
mQueryInputView.setText(book.getPhone());
}
});
There is no error or anything but my dropdown suggestion list is not showing even though API returns the values. What am I doing wrong?
The problem is that you are returning an empty ArrayList !!!
When you add a request to the Volley Que, it wall fulfill your request in another thread and return you the data whenever the server respond. so it would take time.
But you return the array list exactly after adding the request to the Que
requestQueue.add(strReq);
return searchArrayList;
What you should do is:
if(jsonArray != null){
for(int i=0; i<jsonArray.length(); i++){
...
searchArrayList.add(users);
}
// RENEW YOUR ADAPTER HERE OR ASSIGN IT AGAIN TO THE EDITTEXT
mAdapter.notifydataSetChanged();
}
Also try changing the constructor of your SearchAdapter. Once i had a similar problem with a fragment adapter:
private List<User> resultList = new ArrayList<User>();
public SearchAdapter(Context context,List<User> data) {
mContext = context;
resultList = data;
}
I am building a order receiving app for waiter in which half page is activity layout which contains listview and half is viewpager which contains json arraylist in fragment. I want to add the menu data from fragment when clicked on + button with number of quantity to be add on root activity's listview
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/My_Container_1_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="140dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
app:layout_collapseMode="parallax"
android:background="#mipmap/bgactionbar">
<ImageView
android:id="#+id/logo"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginLeft="30dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:background="#mipmap/logoapp"
/>
<ImageView
android:id="#+id/triangle"
android:layout_width="280dp"
android:layout_height="100dp"
android:layout_toRightOf="#+id/logo"
android:background="#mipmap/caley"
/>
<RelativeLayout
android:id="#+id/searchLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/triangle"
android:background="#F3EEE8"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_menu_search"
android:layout_toRightOf="#+id/search_menu"
/>
<EditText
android:id="#+id/search_menu"
android:layout_width="350dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="Search Menu..."
android:textColorHint="#color/tab_text"
android:textColor="#color/tab_text"
android:background="#android:color/transparent"
android:layout_alignParentLeft="true"
android:inputType="textVisiblePassword"/>
</RelativeLayout>
<ImageView
android:id="#+id/coffee"
android:layout_width="110dp"
android:layout_height="140dp"
android:layout_toRightOf="#+id/searchLayout"
android:background="#mipmap/coffee"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
style="#style/MyCustomTabLayout"
android:background="#mipmap/background"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/content"
android:layout_width="360dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:background="#mipmap/background"
android:layout_below="#id/My_Container_1_ID">
<TextView
android:id="#+id/txtorder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Order"
android:textStyle="bold"
android:textColor="#color/tab_text"
android:textSize="20sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/orderlist"
android:layout_width="340dp"
android:layout_height="match_parent"
android:layout_above="#+id/submit_order"
android:layout_below="#+id/txtorder"
android:background="#mipmap/background"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<Button
android:id="#+id/submit_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/orderlist"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/orderlist"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:background="#EE6426"
android:textColor="#android:color/white"
android:text="Submit" />
</RelativeLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_below="#+id/My_Container_1_ID"
android:layout_toRightOf="#+id/content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</RelativeLayout>
public class Menu extends AppCompatActivity implements Coffee.OnMenuInteractionListener {
// private ArrayList<MenuDataModel> allOrders;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
ListView listView;
RecyclerView recyclerView;
RecyclerAdapter adapter;
// MenuTabAdapter adapter;
// ArrayList<MenuDataModel> allOrders;
private List<MenuDataModel> allOrders = new ArrayList<MenuDataModel>();
// private List<String> orderList = new ArrayList<>();
private String Quantity, Name;
EditText count, inputSearch;
TextView order;
String searchValue;
private ArrayList<String> stringArrayList;
CollapsingToolbarLayout collapsingToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
collapsingToolbar= (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
// collapsingToolbar.setTitle(getString(R.string.app_name));
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// listView = (ListView) findViewById(R.id.orderlist);
// adapter = new MenuTabAdapter(this, allOrders);
// listView.setAdapter(adapter);
TextView orddd = (TextView) findViewById(R.id.txtorder);
inputSearch = (EditText) findViewById(R.id.search_menu);
// inputSearch.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// collapsingToolbar.setVisibility(View.GONE);
//
// }
// });
// recyclerView = (RecyclerView) findViewById(R.id.orderlist);
// recyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// recyclerView.setLayoutManager(layoutManager);
//
// adapter = new RecyclerAdapter(this, allOrders);
// recyclerView.setAdapter(adapter);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Coffee(), "Coffee");
adapter.addFragment(new Coffee(), "BreakFast");
adapter.addFragment(new Coffee(), "Beverage");
viewPager.setAdapter(adapter);
}
#Override
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList) {
allOrders = menuList;
}
#Override
public void onMenuListItemClick(int position) {
//musicService.setSong(position);
MenuDataModel menuorder = allOrders.get(position);
// menuorder.setName(menuorder.getName());
// menuorder.setName(allOrders);
allOrders.add(menuorder);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
public class Coffee extends Fragment {
ListView listView;
MenusAdapter adapter;
// Movies json url
private static final String url = "url";
private ProgressDialog pDialog;
private List<MenuDataModel> menuList = new ArrayList<MenuDataModel>();
OnMenuInteractionListener menuItemClick;
private String searchData;
private EditText inputSearch;
// Activity activity;
//OnMenuInteractionListener mCallback;
public Coffee() {
// Required empty public constructor
}
public interface OnMenuInteractionListener {
public void onFragmentSetOrders(ArrayList<MenuDataModel> menuList);
public void onMenuListItemClick(int position);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
menuItemClick = (OnMenuInteractionListener) getActivity();
}
#Override
public void onDetach() {
super.onDetach();
menuItemClick = null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// searchData = getArguments().getString("search");
inputSearch = (EditText) getActivity().findViewById(R.id.search_menu);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// When user changed the Text
//adapter.getFilter().filter(cs.toString());
if (count < before) {
// We're deleting char so we need to reset the adapter data
adapter.resetData();
}
Coffee.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
View view = inflater.inflate(R.layout.fragment_coffee, container, false);
listView = (ListView) view.findViewById(R.id.list);
adapter = new MenusAdapter(getActivity(), menuList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
showpDialog();
// Creating volley request obj
JsonObjectRequest bookingReq = new JsonObjectRequest(Request.Method.GET, "" + url + "?", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("bsd", response.toString());
// Parsing json
try {
JSONArray menu = response.getJSONArray("menus");
int length = menu.length();
for (int i = 0; i < menu.length(); i++) {
JSONObject obj = menu.getJSONObject(i);
MenuDataModel dm = new MenuDataModel();
// Log.d("vdata", String.valueOf(menu.length()));
dm.setID(obj.getString("id"));
dm.setName(obj.getString("name"));
dm.setThumbnailUrl(obj.getString("photo"));
Log.d("image", String.valueOf(obj.getString("photo")));
dm.setDescription(obj.getString("description"));
dm.setRate(obj.getString("price"));
dm.setStatus(obj.getString("status"));
// adding movie to movies array
menuList.add(dm);
// Log.d("nth", String.valueOf(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#SuppressWarnings("deprecation")
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("b", "Error: " + error.getMessage());
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(bookingReq);
return view;
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.setMessage("Please wait...");
pDialog.show();
}
private void hidepDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
public class MenusAdapter extends BaseAdapter implements Filterable {
private static final String TAG = MenusAdapter.class.getSimpleName();
List<MenuDataModel> MenuItems;
List<MenuDataModel> mSearchValues;
private android.widget.Filter menufilter;
Coffee.OnMenuInteractionListener mCallback;
//private Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public MenusAdapter(Activity activity, List<MenuDataModel> MenuItems) {
//this.activity = activity;
this.MenuItems = MenuItems;
this.mSearchValues = MenuItems;
}
#Override
public int getCount() {
return MenuItems.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return MenuItems.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.menu_item, parent, false);
}
// if (imageLoader == null)
// imageLoader = AppController.getInstance().getImageLoader();
final ImageView increase = (ImageView) view.findViewById(R.id.icon_increase);
ImageView decrease = (ImageView) view.findViewById(R.id.icon_decrease);
final EditText count = (EditText) view.findViewById(R.id.count_menu);
NetworkImageView thumbnailUrl = (NetworkImageView) view.findViewById(R.id.menu_image);
TextView name = (TextView) view.findViewById(R.id.menu_items);
// TextView description = (TextView) view.findViewById(R.id.description);
// TextView rate = (TextView) view.findViewById(R.id.price);
final MenuDataModel data = MenuItems.get(index);
name.setText(String.valueOf(data.getName()));
thumbnailUrl.setImageUrl(data.getThumbnailUrl(), imageLoader);
thumbnailUrl.setDefaultImageResId(R.mipmap.logoapp);
thumbnailUrl.setErrorImageResId(R.mipmap.logoapp);
// description.setText(String.valueOf(data.getDescription()));
// title.setText(data.getTitle());
// rate.setText(String.valueOf(data.getRate()));
// final double dis = Double.valueOf(data.getRate());
final int[] quantity = {MenuItems.get(index).getAnInt()};
increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(parent.getContext(), "Button Clicked"+ dataModel.getName(),Toast.LENGTH_LONG).show();
//Intent yes= new Intent(parent.getContext(), yes(dataModel.getName().class));
quantity[0]++;
count.setText(quantity[0] + "");
count.setTag(quantity[0] + "");
// mCallback.onFragmentSetOrders(all);
mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
// Coffee.OnMenuInteractionListener listener = (Coffee.OnMenuInteractionListener) activit;
// mCallback.onFragmentSetOrders(menu);
// Bundle bundle = new Bundle();
// bundle.putString("quantity", quantity[0] + "");
// bundle.putString("name", String.valueOf(data.getName()));
// q.putExtra("bookingid", dataModel.getbkid());
// parent.getContext().startActivity(q);
}
});
decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count.getTag();
count.setTag(quantity[0] + "");
quantity[0]--;
count.setText(quantity[0] + "");
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
return view;
}
#Override
public Filter getFilter() {
if (menufilter == null)
menufilter = new MenuFilter();
return menufilter;
}
public void resetData() {
MenuItems = mSearchValues;
}
private class MenuFilter extends android.widget.Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = mSearchValues;
results.count = mSearchValues.size();
} else {
// We perform filtering operation
List<MenuDataModel> nDriverList = new ArrayList<MenuDataModel>();
for (MenuDataModel p : MenuItems) {
if (p.getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nDriverList.add(p);
}
results.values = nDriverList;
results.count = nDriverList.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Now we have to inform the adapter about the new list filtered
if (results.count == 0)
notifyDataSetInvalidated();
else {
MenuItems = (List<MenuDataModel>) results.values;
notifyDataSetChanged();
}
}
}
;
}
i am getting null pointer exception on mCallback.onMenuListItemClick(MenuItems.get(index).getAnInt());
Step 1: Create Interface
public interface ActivityCommunicator{
public void passDataToActivity(ArrayList<string> arrayList);
}
Step 2:Initialize interface object in fragment class
private ActivityCommunicator activityCommunicator;;
public void onAttach(Activity activity)
{
super.onAttach(activity);
context = getActivity();
activityCommunicator =(ActivityCommunicator)context;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
public void init() {
activityButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
activityCommunicator.passDataToActivity("Your Array List");
}
});
}
step 3: Access Your arraylist from fragment in your activity class.
public class MainActivity extends FragmentActivity implements ActivityCommunicator{
public static ArrayList<String> aList;
#Override
public void passDataToActivity(ArrayList<String> arrayList){
aList = arrayList;
}
}
I am currently using normal horizontal navigation in my code such that when you click on the button, it will navigate to a new fragment horizontally. I want to make it such that instead of calling a new fragment it just expands /collapses upon clicking/clicking again. The code I have so far is :
Here is the activity:
public class ManageNewsCategoriesActivity extends AbsBaseDoubleButtonActivity {
private List<AdapterRow> mBreakingViews;
public HashSet<CategoryCheckableRow> mCategoriesMap = new HashSet<CategoryCheckableRow>();
private int mTitleId = R.string.title_manage;
public static void newInstance(final Activity activity) {
final Intent intent = new Intent(activity.getApplicationContext(), ManageNewsCategoriesActivity.class);
activity.startActivity(intent);
}
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_news_categories);
overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.no_animation);
mActiveFragment = ManageNewsCategoriesFragment.newInstance(getSupportFragmentManager(), 0);
}
public void animateTitle(final int textViewId) {
animateTitle(textViewId, R.anim.slide_in_from_right);
}
public void animateTitle(final int textViewId, final int animationId) {
final TextView titleView = (TextView) findViewById(textViewId);
final Animation animation = AnimationUtils.loadAnimation(this, animationId);
titleView.startAnimation(animation);
}
public void setBreakingViews(final List<AdapterRow> categoryRows) {
mBreakingViews = categoryRows;
}
public List<CategoryCheckableRow> getBreakingViews() {
return removeHeaders(mBreakingViews);
}
public List<AdapterRow> getBreakingViewsCategoryRows() {
if (mBreakingViews == null) {
return null;
}
return AbsBaseManageNewsFragment.getAClone(mBreakingViews);
}
private List<CategoryCheckableRow> removeHeaders(final List<AdapterRow> mCategoryRows) {
final List<CategoryCheckableRow> items = new ArrayList<CategoryCheckableRow>();
if (mCategoryRows != null) {
for (final AdapterRow row : mCategoryRows) {
if (row instanceof CategoryCheckableRow) {
final CategoryCheckableRow item = (CategoryCheckableRow) row;
items.add(item);
}
}
}
return items;
}
public boolean isDoneButtonEnabled() {
return !mCategoriesMap.isEmpty();
}
public void updateCategoriesMap(final HashSet<CategoryCheckableRow> categoryRows) {
for (final CategoryCheckableRow row : categoryRows) {
if (!mCategoriesMap.add(row)) {
mCategoriesMap.remove(row);
}
}
}
#Override
protected int getTitleId() {
return mTitleId;
}
#Override
public void updateTitleId(final int titleId) {
mTitleId = titleId;
updateTitleId();
}
Here is the fragment:
public class ManageNewsCategoriesFragment extends Fragment implements OnClickListener,OnCheckedChangeListener {
public final static String TAG_MANAGE_NEWS_CATEGORIES_FRAGMENT = "ManageNewsCategoriesFragment";
public static final String TYPE = "Type";
public static final String BREAKINGVIEWS = "Breakingviews";
public static final String ANIMATION = "animation";
protected Button mPreferencesDoneButton;
public static ManageNewsCategoriesFragment newInstance(final FragmentManager manager, final int animation) {
final ManageNewsCategoriesFragment fragment = new ManageNewsCategoriesFragment();
final Bundle arguments = new Bundle();
arguments.putInt(ANIMATION, animation);
fragment.setArguments(arguments);
final FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, R.id.manage_news_categories_container);
fragmentInfo.setFragmentTag(TAG_MANAGE_NEWS_CATEGORIES_FRAGMENT);
FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
return fragment;
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_manage_news_categories, container, false);
final Bundle arguments = getArguments();
final int animation = arguments.getInt(ANIMATION, 0);
final ManageNewsCategoriesActivity activity = (ManageNewsCategoriesActivity) getActivity();
if (animation != 0) {
activity.animateTitle(R.id.actionbar_title, arguments.getInt(ANIMATION, 0));
}
return view;
}
protected void setupClickListeners() {
mPreferencesDoneButton = (Button) getActivity().findViewById(R.id.button_done);
Typeface face = Typeface.createFromAsset(mPreferencesDoneButton.getContext().getAssets(),
"fonts/proxima-nova-regular.ttf");
mPreferencesDoneButton.setTypeface(face);
mPreferencesDoneButton.setOnClickListener(this);
mPreferencesDoneButton.setEnabled(((ManageNewsCategoriesActivity) getActivity()).isDoneButtonEnabled());
}
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final TextView titleView = (TextView) getActivity().findViewById(R.id.actionbar_title);
titleView.setText(R.string.title_manage);
initManageNewsCategoriesFragment();
}
private void initManageNewsCategoriesFragment() {
setupClickListeners();
final Button breakingViewsButton = (Button) getView().findViewById(R.id.button_breakingviews);
breakingViewsButton.setOnClickListener(this);
}
#Override
public void onClick(final View view) {
final ManageNewsCategoriesActivity activity = (ManageNewsCategoriesActivity) getActivity();
switch (view.getId()) {
case R.id.button_breakingviews:
ManageBreakingViewsFragment.newInstance(getFragmentManager());
return;
case R.id.button_done:
syncNewsCategories(activity);
break;
default:
break;
}
activity.onBackPressed();
}
private void syncNewsCategories(final ManageNewsCategoriesActivity activity) {
final List<CategoryCheckableRow> breakingViews = activity.getBreakingViews();
if ( ArrayUtils.isNotEmpty(breakingViews)) {
RestService.start(activity, new UserCategoriesSyncOperation(NewsContentProvider.USER_CATEGORIES_URI, breakingViews));
}
}
}
Here is the corresponding xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/altercolor2"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button_breakingviews"
android:layout_width="match_parent"
android:layout_height="#dimen/manage_news_btn_ht"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:background="#drawable/manage_market_category_btnbg"
android:gravity="left|center_vertical"
android:paddingLeft="#dimen/frequent_padding_left"
android:text="#string/button_breakingviews"
android:textColor="#cccccc"
android:textSize="#dimen/title" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingRight="17.5dp"
android:paddingTop="0dp"
android:src="#drawable/arrow_chevron_selector" />
</RelativeLayout>
</LinearLayout>
</FrameLayout>
Any clue how to go about the same? Please explain programmatically and with respect to my code to avoid confusion.
Thanks!
I think what you want is a custom expandable list view. Here is a very good tutorial on it: ExpandableListView