Android runtime eror: the app suddenly stops - android

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);

Related

Putting images (emoticons) on ListView

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.

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: ListView not working properly after scroll

Hi I'm trying to show text, image alternatively in list view. To load the content into my list view i had three scenarios.
1. Some times i'm getting only the text from json. So, in this case i have to hide the ImageView
2. Some cases i'm getting only the image url from json. So, in this case i have to hide the TextView
3. In other case i'm getting both image url and text from json, so, in this case i don't have to hide anything
By following these scenarios i'm loading all the content correctly at first time but when i'm scrolling top to bottom and bottom to up. All the image views are filled with images (But there is no image url for that particular position)
My adapter code is
package com.app.listviewitemid.adapter;
import java.util.ArrayList;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends ArrayAdapter<Items>{
ArrayList<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
ViewHolder holder;
Button btnCheck;
Items globPosition;
public ItemsAdapter(Context context, int resource, ArrayList<Items> objects){
super(context, resource, objects);
this.context = context;
this.Resource = resource;
this.itemsArrayList = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
v = inflater.inflate(Resource, null);
holder = new ViewHolder();
holder.tvPostID = (TextView) v.findViewById(R.id.tv_post_id);
holder.tvPostText = (TextView) v.findViewById(R.id.tv_post_text);
holder.ivPostImage = (ImageView) v.findViewById(R.id.iv_post_img);
btnCheck = (Button) v.findViewById(R.id.btn_check);
v.setTag(holder);
}else{
holder = (ViewHolder) v.getTag();
}
globPosition = itemsArrayList.get(position);
holder.tvPostID.setText(itemsArrayList.get(position).getPostID());
if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
}else {
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
}else {
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", globPosition.getPostID());
}
});
return v;
}
static class ViewHolder{
TextView tvPostID;
TextView tvPostText;
ImageView ivPostImage;
}
}
adapter layout
<?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/tv_post_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/post_id"
android:textColor="#000000"
android:textSize="12sp" />
<TextView
android:id="#+id/tv_post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="12sp" />
<ImageView
android:id="#+id/iv_post_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/empty" />
<Button
android:id="#+id/btn_check"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#000000"
android:text="#string/check"
android:textColor="#FFFFFF" />
</LinearLayout>
How to get rid of this?
if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
holder.tvPostText.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
holder.ivPostImage.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}
I got the idea from ankit aggarwal answer (his code is not working properly but he gave me the basic idea). And one more thing, previously i didn't get the correct position, so i changed the adapter code little bit
Code
package com.app.listviewitemid.adapter;
import java.util.List;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends BaseAdapter{
List<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
Button btnCheck;
public ItemsAdapter(Context context, List<Items> items) {
this.context = context;
this.itemsArrayList = items;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int location) {
return itemsArrayList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams") #Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.adapter_layout, null);
TextView tvPostID = (TextView) convertView.findViewById(R.id.tv_post_id);
TextView tvPostText = (TextView) convertView.findViewById(R.id.tv_post_text);
ImageView ivPostImage = (ImageView) convertView.findViewById(R.id.iv_post_img);
btnCheck = (Button) convertView.findViewById(R.id.btn_check);
final Items items = itemsArrayList.get(position);
tvPostID.setText(items.getPostID());
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
//ivPostImage.setVisibility(View.GONE);
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
tvPostText.setVisibility(View.GONE);
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
//tvPostText.setVisibility(View.GONE);
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", items.getPostID());
}
});
return convertView;
}
}
Thanks to ankit aggarwal

How to add Listeners of Dynamic Check Boxes in Simple Adapter

I have dynamic CheckBoxes and now I want to check which CheckBox clicked or not
AdditionalInformation.Java File Here Simple Adapter is defined :
package com.example.ahmad.cvbuilder21;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AdditionalInformation extends ActionBarActivity {
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_additional_infromation);
cb=(CheckBox)findViewById(R.id.additionalchk);
ABC s = ABC.getSingletonObject();
String[][] str = s.getString();
ListView lv=((ListView)findViewById(R.id.additionallist));
String[] additionalOptions={"Add your Picture","Add Experince / Project","Add Reference","Add Skills / Languages"};
String[] txtViewNames={"options"};
List<HashMap<String,String>>list=new ArrayList<HashMap<String, String>>();
for (int i = 0; i < additionalOptions.length; i++) {
HashMap<String, String> map= new HashMap<String, String>();
map.put("options", additionalOptions[i]);
list.add(map);
}
SimpleAdapter simpleAdpt = new SimpleAdapter(this, list, R.layout.mylayout2,txtViewNames , new int[] {R.id.additionaltxt1});
lv.setAdapter(simpleAdpt);
}
public void additionalData(View view1)
{
if(cb.isChecked())
{
cb.findViewById(R.id.additionalchk).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast toast = Toast.makeText(getApplicationContext(), "Checked",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
toast.show();
}
}
);
}
else{}
}
}
AdditionalInformation.xml file: where additionalData function is called to
check which CheckBox clicked.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Additional Options:"
android:id="#+id/additionalBtn"
/>
<ListView
android:layout_below="#id/additionalBtn"
android:layout_centerHorizontal="true"
android:id="#+id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
<Button
android:layout_below="#id/additionallist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to CV"
android:onClick="additionalData"
/>
</RelativeLayout>
mylayout2.xml file where I define the controls for simple adapter:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_alignParentLeft="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/additionaltxt1"
/>
<CheckBox
android:layout_alignParentRight="true"
android:layout_alignRight="#id/additionaltxt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"
android:id="#+id/additionalchk"
/>
</RelativeLayout>
What you actually need to do is create a custom adapter. In that custom you could listen for checkbox event at the right position.
Here is an example:
public class ListEmployeesAdapter extends BaseAdapter {
public List<Employees> items;
Context c;
public ListEmployeesAdapter(Context c, List<Employees> items) {
this.c = c;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
c.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.employee_item, null);
}
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(items.get(position).name);
name.setOnCLickListener(new OnClickListener(){
#Override
public void onClick(){
//listen to the click
}
});
return convertView;
}
}
Just replace the the layout with you layout and call checkbox instead of TextView and you are good to go.

need tutorials on Android Custom-List

last days I was browsing one of the apps in Android
and I found out an amazing list.
I Found that Custom ListView Interesting.
When we click on the Text it shows me some Activity and when we click on the Arrow on Right it shows me a dialog.
I want to learn this. Can anybody go through some Tutorials where this Custom List is explained. Please Friends. guide me.. Thanks alot
Hi Below Is Custom ListView Example
First Create test.Java File below is code
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class test extends Activity {
/** Called when the activity is first created. */
ArrayList<String> arrayString = new ArrayList<String>();
test_adapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrayString.add("TextView1");
arrayString.add("TextView2");
arrayString.add("TextView3");
arrayString.add("TextView4");
arrayString.add("TextView5");
ListView list = (ListView) findViewById(R.id.LIST);
adapter = new test_adapter(this, arrayString);
list.setAdapter(adapter);
}
}
Also Used below Class file test_adapter.java
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class test_adapter extends BaseAdapter {
private Activity activity;
ArrayList<String> data = new ArrayList<String>();
private static LayoutInflater inflater = null;
public test_adapter(Activity a, ArrayList<String> d) {
activity = a;
data = d;
inflater = LayoutInflater.from(activity);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView txt1;
public Button btn1;
public RelativeLayout rel1;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.txt1 = (TextView) vi.findViewById(R.id.txt1);
holder.btn1 = (Button) vi.findViewById(R.id.btn1);
holder.rel1 = (RelativeLayout) vi.findViewById(R.id.rel1);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.txt1.setText(data.get(position));
holder.rel1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast
.makeText(activity, "Click On TextView",
Toast.LENGTH_LONG).show();
}
});
holder.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "Click On Button", Toast.LENGTH_LONG)
.show();
}
});
return vi;
}
}
Used below layout files main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ListView android:layout_width="fill_parent" android:id="#+id/LIST"
android:layout_height="fill_parent" />
</LinearLayout>
Used listview.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout android:id="#+id/rel1" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/txt1"
android:text="Test Description"></TextView>
</RelativeLayout>
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/btn1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="ClickHere"
android:layout_alignParentRight="true"></Button>
</RelativeLayout>
</LinearLayout>
Used Above Code and you will get display toast message and you can changed as per you requirement.

Categories

Resources