Putting images (emoticons) on ListView - android

I want to add new functionality to my chat. I have a code that allows me to insert chat bubbles and it's working pretty fine (1,2). I tried to make message and adapter (for images) classes analogically to previous adapter and message (for text) classes. I want it to work less like Messenger. When the message box is empty, sending button is emoticon button and it should put an emoticon on ListView (I skip increasing emoticon size within the length of pressing). When message box has text, emoticon button will change to sending button and this button should put the content of the box on the ListView. I tried but everything I tried, failed (when I put setAdapter to TextChangedListener the button do nothing and when I set setAdapter strictly to emojiAdapter Android Studio will throw me Null Pointer Exception). Below is my code:
Error log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bk.cryptit, PID: 2720
java.lang.NullPointerException
at com.bk.cryptit.Chats.sendEmojiMessage(Chats.java:115)
at com.bk.cryptit.Chats$2.onClick(Chats.java:77)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Application terminated.
ChatMessage.java
package com.bk.cryptit;
import java.util.Random;
public class ChatMessage {
public String body, sender, receiver, senderName;
public String Date, Time;
public String msgid;
public boolean isMine;
public ChatMessage(String Sender, String Receiver, String messageString,
String ID, boolean isMINE) {
body = messageString;
isMine = isMINE;
sender = Sender;
msgid = ID;
receiver = Receiver;
senderName = sender;
}
public void setMsgID() {
msgid += "-" + String.format("%02d", new Random().nextInt(100));
;
}
}
ChatAdapter.java
package com.bk.cryptit;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.InputFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import static android.R.id.list;
public class ChatAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
ArrayList<ChatMessage> chatMessageList;
public ChatAdapter(Activity activity, ArrayList<ChatMessage> list) {
chatMessageList = list;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return chatMessageList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage message = (ChatMessage) chatMessageList.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chatbubble, null);
TextView msg = (TextView) vi.findViewById(R.id.message_text);
msg.setText(message.body);
msg.setTextSize(16);
msg.setSingleLine(false);
LinearLayout layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout);
LinearLayout parent_layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout_parent);
layout.setPadding(15,11,15,15);
// if message is mine then align to right
if (message.isMine) {
layout.setBackgroundResource(R.drawable.chat_bubble_right);
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
layout.setBackgroundResource(R.drawable.chat_bubble_left);
parent_layout.setGravity(Gravity.LEFT);
}
if (message.isMine) {
msg.setTextColor(Color.WHITE);
}
else {
msg.setTextColor(Color.BLACK);
}
return vi;
}
public void add(ChatMessage object) {
chatMessageList.add(object);
}
}
EmojiMessage.java
package com.bk.cryptit;
import android.widget.ImageView;
import java.util.Random;
public class EmojiMessage {
public String sender, receiver, senderName;
public ImageView body;
public String Date, Time;
public String msgid;
public boolean isMine;// Did I send the message.
public EmojiMessage(String Sender, String Receiver, ImageView emoji,
String ID, boolean isMINE) {
body = emoji;
isMine = isMINE;
sender = Sender;
msgid = ID;
receiver = Receiver;
senderName = sender;
}
public void setMsgID() {
msgid += "-" + String.format("%02d", new Random().nextInt(100));
;
}
}
EmojiAdapter.java
package com.bk.cryptit;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class EmojiAdapter extends BaseAdapter{
private static LayoutInflater inflater = null;
ArrayList<EmojiMessage> chatMessageListEmoji;
public EmojiAdapter(Activity activity, ArrayList<EmojiMessage> list) {
chatMessageListEmoji = list;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return chatMessageListEmoji.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
EmojiMessage message = (EmojiMessage) chatMessageListEmoji.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.imagechatbubble, null);
ImageView msgEmoji = (ImageView) vi.findViewById(R.id.message_image);
LinearLayout layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout);
LinearLayout parent_layout = (LinearLayout) vi
.findViewById(R.id.bubble_layout_parent);
// if message is mine then align to right
if (message.isMine) {
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
parent_layout.setGravity(Gravity.LEFT);
}
return vi;
}
public void add(EmojiMessage object) {
chatMessageListEmoji.add(object);
}
}
Chats.java
package com.bk.cryptit;
import java.util.ArrayList;
import java.util.Random;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import com.bk.cryptit.ChatAdapter;
import com.bk.cryptit.ChatMessage;
import com.bk.cryptit.CommonMethods;
import com.bk.cryptit.EmojiMessage;
import com.bk.cryptit.EmojiAdapter;
import com.bk.cryptit.R;
public class Chats extends Fragment {
private EditText msg_edittext;
private String user1 = "khushi", user2 = "khushi1";
private Random random;
public static ArrayList<ChatMessage> chatlist;
public static ArrayList<EmojiMessage> emojilist;
public static EmojiAdapter emojiAdapter;
public static ChatAdapter chatAdapter;
ListView msgListView;
String editText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_welcome, container, false);
random = new Random();
msg_edittext = (EditText) view.findViewById(R.id.editText);
msgListView = (ListView) view.findViewById(R.id.messegesListView);
editText = msg_edittext.getText().toString();
final ImageButton sendButton = (ImageButton) view
.findViewById(R.id.button10);
sendButton.setImageResource(R.drawable.like);
// ----Set autoscroll of listview when a new message arrives----//
msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
msgListView.setStackFromBottom(true);
chatlist = new ArrayList<ChatMessage>();
chatAdapter = new ChatAdapter(getActivity(), chatlist);
emojilist = new ArrayList<EmojiMessage>();
emojiAdapter = new EmojiAdapter(getActivity(), emojilist);
msg_edittext.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (msg_edittext.getText().length()>0) {
sendButton.setImageResource(R.drawable.sending_black);
msgListView.setAdapter(chatAdapter);
} else sendButton.setImageResource(R.drawable.like); msgListView.setAdapter(emojiAdapter);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (msg_edittext.getText().length()>0) {
sendButton.setImageResource(R.drawable.sending_black);
msgListView.setAdapter(chatAdapter);
} else sendButton.setImageResource(R.drawable.like); msgListView.setAdapter(emojiAdapter);
}
#Override
public void afterTextChanged(Editable s) {
if (msg_edittext.getText().length()>0) {
sendButton.setImageResource(R.drawable.sending_black);
msgListView.setAdapter(chatAdapter);
} else sendButton.setImageResource(R.drawable.like); msgListView.setAdapter(emojiAdapter);
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendTextMessage(v);
}
});
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
}
public void sendTextMessage(View v) {
String message = msg_edittext.getEditableText().toString();
if (!message.equalsIgnoreCase("")) {
final ChatMessage chatMessage = new ChatMessage(user1, user2,
message, "" + random.nextInt(1000), true);
chatMessage.setMsgID();
chatMessage.body = message;
chatMessage.Date = CommonMethods.getCurrentDate();
chatMessage.Time = CommonMethods.getCurrentTime();
msg_edittext.setText("");
chatAdapter.add(chatMessage);
chatAdapter.notifyDataSetChanged();
}
}
public void sendEmojiMessage(View v) {
String message = msg_edittext.getEditableText().toString();
android.support.v7.widget.AppCompatImageView emoji = (android.support.v7.widget.AppCompatImageView) getView().findViewById(R.id.message_image);
emoji.setImageResource(R.drawable.like);
if (message.equalsIgnoreCase("")) {
final EmojiMessage emojiMessage = new EmojiMessage(user1, user2, emoji, "" + random.nextInt(1000), true);
emojiMessage.body = emoji;
emojiMessage.Date = CommonMethods.getCurrentDate();
emojiMessage.Time = CommonMethods.getCurrentTime();
msg_edittext.setText("");
emojiAdapter.add(emojiMessage);
emojiAdapter.notifyDataSetChanged();
}
}
}
chatbubble.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imagebubble_layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/imagebubble_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="24dp"
android:layout_marginLeft="56dp"
android:background="#android:color/transparent">
<android.support.v7.widget.AppCompatImageButton
android:id="#+id/message_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/transparent"
app:srcCompat="#drawable/like"/>
</LinearLayout>
imagechatbubble.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/imagebubble_layout_parent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/imagebubble_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="24dp"
android:layout_marginLeft="56dp"
android:background="#android:color/transparent">
<android.support.v7.widget.AppCompatImageButton
android:id="#+id/message_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/transparent"
app:srcCompat="#drawable/like"/>
</LinearLayout>

First, we need to test emoji is easily send to listView which has text above it.
You may add interface in activity which calls from the adapter.
The interface will call the TextChangedListener which eventually display send button or emoji.

Related

How to get EditText value from Recyclerview to ArrayList?

I have Activity and want to add edittext value to ArrayList useranswer. How I can do it? I reading some information from json file and add it in recyclerview.I also add Edittext in RecyclerView. It working, but i dont known how i can get infomation from edittext.Sorry about my english^^
TestText.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Objects;
public class TestText extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList< String > id = new ArrayList<>();
ArrayList< String > question = new ArrayList<>();
ArrayList< String > possible_answer1 = new ArrayList<>();
ArrayList< String > possible_answer2 = new ArrayList<>();
ArrayList< String > possible_answer3 = new ArrayList<>();
ArrayList< String > answer = new ArrayList<>();
ArrayList<Integer> useranswer = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_text);
recyclerView = findViewById(R.id.recyclerviewtest);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);
Intent intent = getIntent();
Context context=this;
String fName = intent.getStringExtra("name");
setTitle(fName);
try {
JSONObject jsonObject = new JSONObject(JsonDataFromAsset("tests.json"));
JSONArray jsonArray = jsonObject.getJSONArray(fName);
for (int i=0;i<= jsonArray.length();i++){
JSONObject userData=jsonArray.getJSONObject(i);
id.add(userData.getString("id"));
question.add(userData.getString("question"));
possible_answer1.add(userData.getString("possible_answer1"));
possible_answer2.add(userData.getString("possible_answer2"));
possible_answer3.add(userData.getString("possible_answer3"));
answer.add(userData.getString("answer"));
}
} catch (JSONException e) {
e.printStackTrace();
}
HelperAdapterForTest helperAdapter = new HelperAdapterForTest(id,question,possible_answer1,possible_answer2,possible_answer3,answer,TestText.this);
recyclerView.setAdapter(helperAdapter);
Button but=findViewById(R.id.verify_button);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Get edittext value in this place
}
});
}
public void GetThissheet(View view){
}
private String JsonDataFromAsset(String fileName) {
String json = null;
try {
InputStream inputStream = getAssets().open(fileName);
int sizeOfFile = inputStream.available();
byte[] bufferData = new byte[sizeOfFile];
inputStream.read(bufferData);
inputStream.close();
json = new String(bufferData, "UTF-8");
}catch (IOException e){
e.printStackTrace();
return null;
}
return json;
}
}
HelperAdapterForTest.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class HelperAdapterForTest extends RecyclerView.Adapter<HelperAdapterForTest.MyViewClass>
{
ArrayList< String > id;
ArrayList< String > question;
ArrayList< String > possible_answer1;
ArrayList< String > possible_answer2;
ArrayList< String > possible_answer3;
ArrayList< String > answer;
Context context;
public HelperAdapterForTest(ArrayList< String > id,ArrayList< String > question, ArrayList< String > possible_answer1,ArrayList< String > possible_answer2,ArrayList< String > possible_answer3,ArrayList< String > answer,Context context) {
this.id = id;
this.question = question;
this.possible_answer1 = possible_answer1;
this.possible_answer2 = possible_answer2;
this.possible_answer3 = possible_answer3;
this.answer=answer;
this.context = context;
}
#NonNull
#Override
public HelperAdapterForTest.MyViewClass onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.test,parent,false);
HelperAdapterForTest.MyViewClass myViewClass=new HelperAdapterForTest.MyViewClass(view);
return myViewClass;
}
#Override
public void onBindViewHolder(#NonNull HelperAdapterForTest.MyViewClass holder, #SuppressLint("RecyclerView") int position) {
holder.id.setText(id.get(position));
holder.question.setText(question.get(position));
holder.possible_answer1.setText(possible_answer1.get(position));
holder.possible_answer2.setText(possible_answer2.get(position));
holder.possible_answer3.setText(possible_answer3.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent intent = new Intent(context, TestText.class);
//intent.putExtra("name",question.get(position).toString());
//v.getContext().startActivity(intent);
//Toast.makeText(context,"Клик",Toast.LENGTH_LONG).show();
}
});
}
#Override
public int getItemCount() {
return id.size();
}
public class MyViewClass extends RecyclerView.ViewHolder{
TextView id;
TextView question;
TextView possible_answer1;
TextView possible_answer2;
TextView possible_answer3;
EditText answer;
public MyViewClass(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.questionid);
question=itemView.findViewById(R.id.question);
answer=itemView.findViewById(R.id.answer);
possible_answer1=itemView.findViewById(R.id.posibleanswer1);
possible_answer2=itemView.findViewById(R.id.posibleanswer2);
possible_answer3=itemView.findViewById(R.id.posibleanswer3);
}
}
}
activity_test_text.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TestText"
android:orientation="vertical"
>
<ScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:layout_weight="1">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerviewtest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
<Button
android:id="#+id/verify_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal">
</Button>
</LinearLayout>
you need to add abutton to confirm action in viewholder
public class MyViewClass extends RecyclerView.ViewHolder{
TextView id;
.
.
EditText answer;
Button getAnswer;
public MyViewClass(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.questionid);
.
.
getAnswer=itemView.findViewById(R.id.getAnswer);
}
}
and in the onBindViewHolder add this
holder.getAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answer.add(answer.getText().toString());
}
});
now the answere list will have a list of answers that get from edit text
use addTextChangedListener to your editText so that you can observe changes and add to your arrayList,
If you want to pass same value to Activity then you can create interface class and write a method which you can implement in Activity or you can use eventBus to pass value.
I find solution.I create setonclicklistener for this button and get data from edittext:)
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0;i<recyclerView.getAdapter().getItemCount();i++){
v=recyclerView.getChildAt(i);
EditText tutu=(EditText) v.findViewById(R.id.answer);
useranswer.add(i,tutu.getText().toString());
}
for (int i=0;i<useranswer.size();i++){
//Toast.makeText(TestText.this, useranswer.get(i)+","+answer.get(i), Toast.LENGTH_SHORT).show();
if (useranswer.get(i).equals(answer.get(i))){
v=recyclerView.getChildAt(i);
CardView card=v.findViewById(R.id.cardtest);
card.setCardBackgroundColor(Color.GREEN);
}else{
v=recyclerView.getChildAt(i);
CardView card=v.findViewById(R.id.cardtest);
card.setCardBackgroundColor(Color.RED);
}
}
}
});```

UploadingItemAdapter gives LogCat null value and listItem's text views are also remains blank in fragment of listview

I don't know in which part i made mistake. In UploadItemAdapter.class,uploadingDetails.getTitle() and uploadingDetails.getDiscription() both gives me null in my log cat. In android listView screen textView of item is also remains blank Screenshot .My Computer Screen.
My code is mentioned below.
UploadItemAdapter.java
package com.example.shiva.gconnection.extendedVersion;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.shiva.gconnection.R;
import com.example.shiva.gconnection.UploadingDetails;
import java.util.List;
/**
* Created by shiva on 3/3/18.
*/
public class UploadItemAdapter extends ArrayAdapter<UploadingDetails>{
public UploadItemAdapter( Context context, int resource, List<UploadingDetails> objects) {
super(context, resource, objects);
}
#Override
public View getView(int position ,View convertView,ViewGroup parent) {
if (convertView == null) {
convertView = ((FragmentActivity) getContext()).getLayoutInflater().inflate(R.layout.uploaded_material_child, parent, false);
}
TextView titalTV = (TextView) convertView.findViewById(R.id.title_item_upload_material);
TextView discriptionTV= (TextView) convertView.findViewById(R.id.discription_item_upload_material);
UploadingDetails uploadingDetails = getItem(position);
titalTV.setText(uploadingDetails.getTitle());
discriptionTV.setText(uploadingDetails.getDiscription());
Log.v("abcd",uploadingDetails.getTitle() +" "+uploadingDetails.getDiscription());
return convertView;
}
}
uploaded_material.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:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<ListView
android:id="#+id/lv_upload_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:transcriptMode="alwaysScroll"
tools:listitem="#layout/uploaded_material_child" />
</LinearLayout>
Uploaded_material_child.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
android:id="#+id/title_item_upload_material"
android:textSize="20dp"
android:textColor="#android:color/black"
android:layout_margin="5dp"/>
<TextView
android:layout_margin="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Discription"
android:textColor="#android:color/black"
android:id="#+id/discription_item_upload_material"
android:textSize="16dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="UploadedBy"
android:id="#+id/uploaded_by"
android:textSize="16dp"
android:textColor="#android:color/black"
android:layout_margin="5dp"/>
</LinearLayout>
FragmentLastView.java
package com.example.shiva.gconnection.extendedVersion;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.shiva.gconnection.R;
import com.example.shiva.gconnection.UploadingDetails;
import com.google.firebase.database.ChildEventListener;
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 java.util.ArrayList;
public class FragmentLastView extends Fragment {
private FirebaseDatabase mdatabase;
private DatabaseReference mdbRef;
private ListView mItemLV;
private ChildEventListener childEventListener;
private ArrayAdapter mUploadItemAdapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.uploaded_material,container,false);
mdatabase = FirebaseDatabase.getInstance();
mdbRef = mdatabase.getReference("College");
return view;
}
#Override
public void onViewCreated(View view,Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final String subjectName = getArguments().getString("SubjectName");
final String branchname = getArguments().getString("BranchName");
final String class1Name = getArguments().getString("Class1Name");
final String className = getArguments().getString("ClassName");
final ArrayList<UploadingDetails> uploadingDetails = new ArrayList<>();
mItemLV= (ListView)view.findViewById(R.id.lv_upload_item);
mUploadItemAdapter = new UploadItemAdapter(view.getContext(),R.layout.uploaded_material_child,uploadingDetails);
mItemLV.setAdapter(mUploadItemAdapter);
childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UploadingDetails updetails = dataSnapshot.getValue(UploadingDetails.class);
uploadingDetails.add(updetails);
mUploadItemAdapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdbRef.child(branchname).child(subjectName).child(className).child(class1Name).addChildEventListener(childEventListener);
}
}
UploadingDetails.java
package com.example.shiva.gconnection;
public class UploadingDetails {
private String mTitle;
private String mDiscription;
private String mArrayUri;
public UploadingDetails(){
}
public UploadingDetails(String title, String discription,String arrayUri){
this.mTitle= title;
this.mDiscription=discription;
this.mArrayUri=arrayUri;
}
public String getTitle(){
return this.mTitle;
}
public String getDiscription(){
return this.mDiscription;
}
public String getArrayUri(){return this.mArrayUri;}
}
The name of the fields in your model class must much to the name of the data on witch your want retrieve in firebase data reference node
I don't understand how it worked but when i changed following code problem was solved
UploadindDetils.java
package com.example.shiva.gconnection;
public class UploadingDetails {
private String mTitle;
private String mDiscription;
private String mArrayUri;
public UploadingDetails() {
}
public UploadingDetails(String title, String discription, String arrayUri) {
this.mTitle = title;
this.mDiscription = discription;
this.mArrayUri = arrayUri;
}
public String getTitle() {
return this.mTitle;
}
public void setTitle(String title) {
this. mTitle = title;
}
public void setDiscription(String discription) {
this.mDiscription = discription;
}
public void setArrayUri(String arrayUri) {
this.mArrayUri = arrayUri;
}
public String getDiscription() {
return this.mDiscription;
}
public String getArrayUri() {
return this.mArrayUri;
}
}

spinner onitemselected is not working as expected?

I did not add spinner on my layout
I did not use addView function
code
Spinner spinner = new Spinner(MainActivity.this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, myArray);
spinner.setAdapter(spinnerArrayAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
//this place is never called
}
public void onNothingSelected(AdapterView<?> parent)
{
}
});
I called spinner like this:
spinner.performClick();
After this I click one of my item which in my array and then I expect to fire onItemSelected but it never fires.
the problem is
onitemselected is never called.
thanks in advance
Try this,
1.Create a custom adapter.
2.set click Listener to textview in adapter.(so you can get position in adapter)
3.according to positon do whatever u feel like.
CustomModel.
public class CustomModel {
private String id;
private String description;
public char[] name;
public CustomModel() {
}
public CustomModel(String id, String description) {
this.id = id;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return description;
}
public void setName(String description) {
this.description = description;
}
}
Activity.
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import adapter.CustomAdapter;
import models.CustomModel;
import utils.SessionManager;
import static android.R.attr.id;
import static android.R.id.text1;
public class spinner extends AppCompatActivity {
private SessionManager sessionManager;
private List<CustomModel> myArray=new ArrayList<CustomModel>();
CustomModel customModel;
LinearLayout container;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinnre);
container = (LinearLayout) findViewById(R.id.container);
customModel=new CustomModel();
customModel.setName("Select a number");
myArray.add(customModel);
for(int i=0;i<10;i++)
{
customModel=new CustomModel();
customModel.setName(String.valueOf(i));
myArray.add(customModel);
}
LinearLayout.LayoutParams spinnerParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams textParamas = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
spinnerParamas.setMargins(0,50,0,0);
Spinner spinner = new Spinner(spinner.this);
spinner.setLayoutParams(spinnerParamas);
spinner.setId(0);
CustomAdapter customAdapter=new CustomAdapter(spinner.this,myArray,spinner);
spinner.setAdapter(customAdapter);
container.addView(spinner);
}
}
Adapter
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.ciomp.global.R;
import models.CustomModel;
/**
* Created by ciomp on 11/23/2016.
*/
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List<CustomModel> mList=new ArrayList<CustomModel>();
private LayoutInflater mLayoutInflater;
private String mType=null;
private Spinner mSpinner;
int one=0;
public CustomAdapter(Context mContext, List<CustomModel> list, Spinner spin) {
this.mContext=mContext;
this.mList=list;
mSpinner=spin;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
CustomAdapter.ViewHolder holder=null;
LayoutInflater layoutInflater=(LayoutInflater)mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView==null){
convertView = layoutInflater.inflate(R.layout.customlayout, null);
holder = new CustomAdapter.ViewHolder();
holder.textView2=(TextView)convertView.findViewById(R.id.txt_text1);
convertView.setTag(holder);
}
else {
holder = (CustomAdapter.ViewHolder) convertView.getTag();
}
CustomModel classModel=mList.get(position);
holder.textView2.setText(classModel.getName());
holder.textView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(one==0)
{
mSpinner.performClick();
one=1;
}
else if(one==1)
{
Toast.makeText(mContext, mList.get(position).getName(), Toast.LENGTH_SHORT).show();
try {
Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
method.invoke(mSpinner);
} catch (Exception e) {
e.printStackTrace();
}
one=0;
}
}
});
return convertView;
}
static class ViewHolder{
TextView textView2;
}
}
spinnre.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">
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_marginRight="5dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="5dp"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
customlayout.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">
<TextView
android:id="#+id/txt_text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_marginBottom="13dp"
android:gravity="center"
android:layout_marginTop="13dp"
android:layout_marginLeft="5dp"
android:paddingLeft="5dp"
android:textColor="#000"
/>
/>
</LinearLayout>
hope it may help you.
In order to programatically select item from spinner. you need to call
spinner.setSelection(1);
Whereas 1 in the index, you want to select

Android runtime eror: the app suddenly stops

My app is to perform ListView. When it was running, the error message notified that "Unfortunately, App has stopped". Here is my code.
package com.example.admin.customadapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Nation>nationifo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.ListViewNation);
nationifo = new ArrayList<>();
nationifo.add(new Nation("VietNam",1945));
nationifo.add(new Nation("Malaysia",1975));
nationifo.add(new Nation("Laos",1943));
NationAdapter adp = new NationAdapter(
MainActivity.this,
R.layout.nation_list,
nationifo
);
listView.setAdapter(adp);
}
}
Nation.java
package com.example.admin.customadapter;
public class Nation {
public String name;
public Integer year;
public Nation(String Name, Integer Year){
Name = name;
Year = year;
}
}
NationAdapter.java
package com.example.admin.customadapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class NationAdapter extends BaseAdapter {
Context mycontext;
int mylayout;
List<Nation>arrayNation;
public NationAdapter (Context context, int layout, List<Nation>nationList){
mycontext = context;
mylayout = layout;
arrayNation = nationList;
}
public int getCount() {
return arrayNation.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(mylayout,null);
TextView txtv1 = (TextView) convertView.findViewById(R.id.textView);
txtv1.setText(arrayNation.get(position).name);
TextView txtv2 =(TextView) convertView.findViewById(R.id.textView2);
txtv2.setText(String.valueOf(arrayNation.get(position).year));
return convertView;
}
}
nation_list.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:background = "#ffffff">
<TextView
android:textColor="#ff0400"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/textView" />
<TextView
android:textColor="#0022ff"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2" />
</LinearLayout>
My Android Studio is 2.2. But I don't think that this version is diferrent to another.
try to use the following
convertView = inflater.inflate(mylayout,parent,false);
instead of
convertView = inflater.inflate(mylayout,null);

Android autocompletetextview won't populate contacts with custom adapter

I've created a custom adapter and custom list item. I was originally using a simple list item and just populated either the name or the number. However, now I'd like to show both the name and phone number in each list item. When I type something now into the autocomplete text it won't populate any anything. I did some error testing and it seems that it isn't even calling the overridden getView() method. I can't seem to figure out why this isn't working.
Also, yes I've added the READ_CONTACTS permission in the manifest.
MainActivity.java
package com.sncrmck.autocompletetest;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.widget.AutoCompleteTextView;
import com.sncrmck.adapter.ContactAdapter;
import com.sncrmck.obj.SimpleContact.SimpleContact;
public class MainActivity extends Activity {
AutoCompleteTextView acTextField;
private ContactAdapter adapter;
public ArrayList<SimpleContact> contactList = new ArrayList<SimpleContact>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver resolver = getContentResolver();
acTextField = (AutoCompleteTextView) findViewById(R.id.autoComplete);
Uri contacts = Uri.parse("content://icc/adn");
Cursor cursor = resolver.query(contacts, null, null, null, null);
if (cursor.moveToFirst()) {
String contactName;
String phoneNumber;
int nameColumn = cursor.getColumnIndex("name");
int phoneColumn = cursor.getColumnIndex("number");
do {
contactName = cursor.getString(nameColumn);
phoneNumber = cursor.getString(phoneColumn);
if((contactName != " " || contactName != null) && (phoneNumber!= " " ||phoneNumber!= null))
{
SimpleContact sc = new SimpleContact(contactName, phoneNumber);
contactList.add(sc);
}
} while (cursor.moveToNext());
}
adapter = new ContactAdapter(this, R.layout.grid_item, contactList);
acTextField.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
CustomAdapter.java
package com.sncrmck.adapter;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.sncrmck.autocompletetest.R;
import com.sncrmck.obj.SimpleContact.SimpleContact;
public class ContactAdapter extends ArrayAdapter<SimpleContact> {
private ArrayList<SimpleContact> entries;
private Activity activity;
public ContactAdapter(Activity a, int textViewResourceId, ArrayList<SimpleContact> entries){
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
Toast.makeText(getContext(), "Constructor", Toast.LENGTH_SHORT).show();
}
public static class ViewHolder{
public TextView item1;
public TextView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Toast.makeText(getContext(), "Get View", Toast.LENGTH_SHORT).show();
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.grid_item, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.big);
holder.item2 = (TextView) v.findViewById(R.id.small);;
}
else
holder=(ViewHolder)v.getTag();
final SimpleContact contactInfo = entries.get(position);
if (contactInfo != null) {
holder.item1.setText(contactInfo.getContactName());
holder.item2.setText(contactInfo.getContactNumber());
}
return v;
}
}
This is the SimpleContact object I'm passing to the ContactAdapter
package com.sncrmck.obj.SimpleContact;
public class SimpleContact {
private String contactName;
private String contactNumber;
public SimpleContact(String string, String string2) {
this.contactName = string;
this.contactNumber = string2;
}
public String getContactName() { return contactName; }
public void set(String contactName) { this.contactName= contactName; }
public String getContactNumber() { return contactNumber; }
public void setcustomSmall(String contactNumber) { this.contactNumber = contactNumber; }
}
Lastly, this is my custom list item - grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:textSize="24dp"
android:id="#+id/big"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:textSize="24dip"
android:id="#+id/small"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
You need to override the getFilter() Method of your custom adapter
Also implement a custom filter and override the methods in that.
See this similar question.
I don't have my code available at work so but if I get a chance tonight I'll edit the answer.

Categories

Resources