How to change my chat layout output as like whatsapp chat layout? - java

I am developing an android application, In that i have a chat window layout at present my chat window ouput is looking below (when i am send the message to others)
but i am expected my output as,
My layout code is below,
<?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="horizontal"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingLeft="10dp">
<TextView
android:id="#+id/txtInfo"
android:layout_width="wrap_content"
android:layout_height="30sp"
android:layout_gravity="right"
android:layout_marginRight="50dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:textSize="12sp"
android:textColor="#color/lightred"
android:textStyle="italic"
/>
<TextView
android:id="#+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:layout_marginRight="200dp"
android:background="#color/grey"
android:textColor="#color/white"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textStyle="italic|bold"
/>
</LinearLayout>
My programming code is below,
public class MessagesListAdapter extends BaseAdapter {
private Context context;
private List<ChatMessageObjects> messagesItems;
public MessagesListAdapter(Context context, List<ChatMessageObjects> navDrawerItems) {
this.context = context;
this.messagesItems = navDrawerItems;
}
#Override
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessageObjects m = messagesItems.get(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (messagesItems.get(position).getMessage_type() == Constants.IS_TYPE_CHAT_IMAGE) {
convertView = mInflater.inflate(R.layout.chat_image,
null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imgView);
TextView imageLabel = (TextView) convertView.findViewById(R.id.lblImage);
if (messagesItems.get(position).isSelf() == 0) {
Log.i(Constants.TAG, " the value is from others");
try {
URL url = new URL(messagesItems.get(position).getMessage());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
imageView.setImageBitmap(BitmapFactory.decodeStream(input));
} catch (IOException e) {
Log.i(Constants.TAG, e.toString());
}
} else if (messagesItems.get(position).isSelf() == 1) {
Log.i(Constants.TAG, " the value is itself");
imageView.setImageURI(Uri.fromFile(imgFile));
imageLabel.setText(messagesItems.get(position).getFromName());
}
} else if (messagesItems.get(position).getMessage_type() == Constants.MESSAGE_TYPE_MSG) {
// message belongs to you, so load the right aligned layout
if (messagesItems.get(position).isSelf() == 1) {
convertView = mInflater.inflate(R.layout.chat_message_right,
null);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
//date and time declared on date here
TextView date = (TextView) convertView.findViewById(R.id.txtInfo);
try {
//actualDate contains date "(i.e)27-Aug-2015 6:20:25 am/pm" in this format
String actualDate = m.getDate();
Date FormatDate = new SimpleDateFormat("dd-MMM-yyyy h:mm:ss a").parse(actualDate);
//actualDate converted from "(i.e)27-Aug-2015 6:20:25 am/pm" to "6:20 pm" in this
//format for display the chat time for every chat message .
dateResult = new SimpleDateFormat("h:mm a").format(FormatDate);
} catch (ParseException e) {
e.printStackTrace();
}
date.setText(dateResult);//date display as like this"6:20pm"
txtMsg.setText(m.getMessage());
} else if (messagesItems.get(position).isSelf() == 0) {
// message belongs to other person, load the left aligned layout
convertView = mInflater.inflate(R.layout.chat_message_left,
null);
TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
//date and time added here
TextView date = (TextView) convertView.findViewById(R.id.txtInfo);
txtMsg.setText(m.getMessage());
date.setText(m.getDate());
}
}
return convertView;
}
}
}
how can i achieve my output as i am expected. Please suggest me what i am need to change.

Try this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:emojicon="http://schemas.android.com/apk/res-auto"
android:id="#+id/view_send_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:layout_margin="10dp"
android:orientation="vertical"
android:visibility="visible">
<TextView
android:id="#+id/txt_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:lineSpacingExtra="1dp"
android:minWidth="150dp"
android:padding="5dp"
android:textColor="#color/lightred"
android:singleLine="false"
android:textSize="18sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="7dp">
<TextView
android:id="#+id/txt_send_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:background="#color/grey"
android:textColor="#color/white"
android:textSize="13sp" />
</LinearLayout>

Related

Textview cannot set text but Imageview working

I have some problem with my code. I cannot set Textview but ImageView is working. This is my xml textview. I using adapter and listener interface.
error : textview on a null object reference
<?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="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto">
<View
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_middle" />
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/spacing_middle"
android:layout_marginRight="#dimen/spacing_middle"
android:visibility="visible"
app:cardCornerRadius="0dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/spacing_medium"
android:layout_marginLeft="#dimen/spacing_large"
android:layout_marginRight="#dimen/spacing_large"
android:layout_marginTop="#dimen/spacing_large"
android:gravity="center_vertical"
android:orientation="horizontal">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imgGambar"
android:layout_width="#dimen/spacing_xxlarge"
android:layout_height="#dimen/spacing_xxlarge"
android:foreground="#color/overlay_light_20"
app:civ_shadow="true"
app:civ_shadow_radius="0"
android:src="#drawable/photo_female_2"
app:civ_border="false" />
<View
android:layout_width="#dimen/spacing_large"
android:layout_height="0dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Emma Richmond"
android:textAppearance="#style/TextAppearance.AppCompat.Subhead"
android:textColor="#color/grey_90" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/spacing_small"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="in "
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_40" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="Hwy, Carthage"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/light_blue_400"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/tvKonten"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/spacing_large"
android:lineSpacingExtra="4dp"
android:text="#string/middle_lorem_ipsum"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_60" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="#dimen/spacing_medium"
android:background="#color/grey_5" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/spacing_xxlarge"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingLeft="#dimen/spacing_large"
android:paddingRight="#dimen/spacing_large">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgLike"
android:layout_width="#dimen/spacing_mlarge"
android:layout_height="#dimen/spacing_mlarge"
android:layout_marginEnd="#dimen/spacing_middle"
android:layout_marginRight="#dimen/spacing_middle"
android:tint="#color/light_green_300"
android:src="#drawable/ic_thumb_up" />
<TextView
android:id="#+id/txtsuka"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="12 likes"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_40" />
</LinearLayout>
<View
android:layout_width="#dimen/spacing_large"
android:layout_height="0dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="#dimen/spacing_mlarge"
android:layout_height="#dimen/spacing_mlarge"
android:layout_marginEnd="#dimen/spacing_middle"
android:layout_marginRight="#dimen/spacing_middle"
android:tint="#color/light_blue_400"
android:src="#drawable/ic_textsms" />
<TextView
android:id="#+id/tvKomentar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="4 Comments"
android:textAppearance="#style/TextAppearance.AppCompat.Caption"
android:textColor="#color/grey_40" />
</LinearLayout>
<TextView
android:id="#+id/tvLalu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="end|right"
android:text="2h ago"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#color/grey_40" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
and this is my adapter : https://pastebin.com/csiW52h4
public class AdapterCardPostList extends RecyclerView.Adapter<AdapterCardPostList.ViewHolder> {
private Context context;
private List<PostItem> list;
private List<Check> checkList;
private OnItemClickListener mOnItemClickListener;
public AdapterCardPostList(Context context, List<PostItem> list, List<Check> checkList, OnItemClickListener monItemClickListener) {
this.context = context;
this.list = list;
this.checkList = checkList;
this.mOnItemClickListener = monItemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public ImageView image, imglike;
public TextView name;
public TextView konten;
public TextView like;
public TextView komentar;
public TextView lalu;
public ViewHolder(View v) {
super(v);
image = (ImageView) v.findViewById(R.id.imgGambar);
name = (TextView) v.findViewById(R.id.tvName);
konten = (TextView) v.findViewById(R.id.tvKonten);
like = (TextView) v.findViewById(R.id.txtsuka);
komentar = (TextView) v.findViewById(R.id.tvKomentar);
lalu = (TextView) v.findViewById(R.id.tvLalu);
imglike = (ImageView) v.findViewById(R.id.imgLike);
imglike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mOnItemClickListener.onItemClick(view, checkList.get(getAdapterPosition()), getAdapterPosition(), list.get(getAdapterPosition()));
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v = layoutInflater.inflate(R.layout.item_post, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
PostItem p = list.get(position);
holder.konten.setText(p.getContent());
holder.like.setText(p.getLike());
holder.name.setText(p.getName());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
// long time = sdf.parse(p.getTanggal()).getTime();
Date date = sdf.parse(p.getTanggal());
long now = System.currentTimeMillis();
CharSequence ago =
DateUtils.getRelativeTimeSpanString(date.getTime(), now, DateUtils.MINUTE_IN_MILLIS);
holder.lalu.setText(ago);
} catch (ParseException e) {
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
holder.komentar.setText(p.getKomen() + " Comments");
Glide.with(context).load("https://graph.facebook.com/" + p.getUid() + "/picture?type=normal").into(holder.image);
if (p.getUid().equals(MainActivity.id)){
holder.imglike.setColorFilter(ContextCompat.getColor(context, R.color.red_200), android.graphics.PorterDuff.Mode.MULTIPLY);
checkList.add(new Check(true));
}else{
holder.imglike.setColorFilter(ContextCompat.getColor(context, R.color.light_green_300), android.graphics.PorterDuff.Mode.MULTIPLY);
checkList.add(new Check(false));
}
}
#Override
public int getItemCount() {
return list.size();
}
}
my error like this
why my imageview working but textview not working
thank you for attention
mOnItemClickListener.onItemClick(view, checkList.get(getAdapterPosition()), getAdapterPosition(), list.get(getAdapterPosition()));
change to
mOnItemClickListener.onItemClick(v, checkList.get(getAdapterPosition()), getAdapterPosition(), list.get(getAdapterPosition()));
This is because the id tvKonten does not exist. In your XML code, the id of the TextView is txtsuka, not tvKonten. Change tvKonten to txtsuka.
Try these options, it might work for you :
Invalidate Caches and Restart
Check if you have a different version of the same layout file in your res folder such as ...v26.xml or something like that ; if you find any then delete the unwanted version of the file.

Android ListView displaying one item per page

I have a listview that uses an adapter who receives a string array as an argument. When I look at the listview it displays 1 item then it shows a lot of blank space behind it that is followed by the next item if I scroll down. What could be the problem?
class CustomAdapter extends ArrayAdapter<String> {
CustomAdapter(Context context, String[] camere) {
super(context, R.layout.custom_row, camere);
}
boolean parola = true;
boolean intra = true;
String player_id, room_id;
String siteul = "some_site";
String site;
HashMap<String, String> hash;
static class ViewHolder {
TextView camera;
TextView players;
TextView max_players;
ImageView privata;
Button Buton;
String room_id, nume;
}
ViewHolder ceva;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
String variabile[] = getItem(position).split("\\s+");
if(convertView == null)
{
LayoutInflater linflater = LayoutInflater.from(getContext());
convertView = linflater.inflate(R.layout.custom_row, parent, false);
holder = new ViewHolder();
holder.camera = (TextView) convertView.findViewById(R.id.Nume);
holder.players = (TextView) convertView.findViewById(R.id.players);
holder.max_players = (TextView) convertView.findViewById(R.id.max_players);
holder.privata = (ImageView) convertView.findViewById(R.id.privata);
holder.Buton = (Button) convertView.findViewById(R.id.Buton);
holder.camera.setText(variabile[0]);
if (!variabile[1].equals("true")) {
parola = false;
holder.privata.setVisibility(View.INVISIBLE);
}
holder.players.setText(variabile[2]);
holder.max_players.setText(variabile[3]);
holder.room_id = variabile[4];
holder.nume = variabile[5];
holder.Buton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int playeri = Integer.parseInt(holder.players.getText().toString());
int maximi = Integer.parseInt(holder.max_players.getText().toString());
if(playeri < maximi)
{
hash = new HashMap<String, String>();
hash.put("name", holder.nume);
hash.put("room", holder.room_id);
if (intra) {
holder.Buton.setText("Iesi");
site = siteul + "/join";
intra = false;
} else {
holder.Buton.setText("Intra");
site = siteul + "/leave";
intra = true;
}
new ATask((ViewHolder) v.getTag()).execute(site);
}
}
});
convertView.setTag(holder);
holder.Buton.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
return convertView;
}
public void CheckStart()
{
site = siteul + "/checkstart";
hash = new HashMap<String, String>();
hash.put("room", room_id);
new ATask(ceva).execute(site);
}
public void CheckPlayers()
{
site = siteul + "/checkplayers";
hash = new HashMap<String, String>();
hash.put("room", room_id);
new ATask(ceva).execute(site);
}
public void openGame(String litera)
{
Intent incercare = new Intent(getContext(), Game.class);
incercare.putExtra("nume", player_id);
incercare.putExtra("room", room_id);
incercare.putExtra("litera", litera);
incercare.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(incercare);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
public class ATask extends AsyncTask<String, Void, String> {
String rez = "";
ViewHolder myHolder;
public ATask(ViewHolder view) {
myHolder = view;
ceva = myHolder;
room_id = myHolder.room_id;
}
#Override
protected String doInBackground(String... urls) {
//try {
try {
Log.e("rasp", site);
URL obj = new URL(site);
try {
Log.e("rasp", obj.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(getPostDataString(hash).getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
Log.e("rasp", "response code-ul e " + Integer.toString(responseCode));
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
rez = response.toString();
}
else {
Log.e("rasp", "POST request not worked");
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
Log.e("naspa", "E corupt!");
}
//} catch (Exception e) {
// Log.e("rasp", "aia e");
//}
return rez;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
if (rez.charAt(0) == 'Y')
openGame(rez.substring(2));
else if (rez.charAt(0) == 'V' && !intra)
{
TextView players_mare = myHolder.players;
players_mare.setText(rez.substring(2));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 1s = 1000ms
CheckStart();
}
}, 1000);
}
else if(rez.charAt(0) == 'G')
CheckPlayers();
else if(rez.charAt(0) == 'Z')
{
TextView players_mare = myHolder.players;
players_mare.setText(rez.substring(2));
}
else if (rez.charAt(0) == 'D')
{
player_id = rez.substring(2);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 1s = 1000ms
CheckStart();
}
}, 400);
}
}
}
}
Here is the xml of "custom_row.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_joc">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:id="#+id/scrollView">
<LinearLayout
android:background="#color/grey"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Nume camera"
android:id="#+id/Nume"
android:textSize="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Runde:"
android:layout_marginTop="-7dp"
android:layout_marginLeft="3dp"
android:id="#+id/textView15" />
<TextView
android:layout_marginTop="15dp"
android:layout_marginLeft="-30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="5"
android:id="#+id/runde"
android:textSize="25dp" />
<ImageView
android:layout_marginTop="18dp"
android:layout_marginLeft="20dp"
android:background="#drawable/buton_lock"
android:layout_width="15dp"
android:layout_height="20dp"
android:id="#+id/privata" />
<TextView
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:id="#+id/players"
android:textSize="30dp" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="? android:attr/textAppearanceMedium"
android:text="/"
android:id="#+id/nu_trebuia_sa_aiba_id"
android:textSize="30dp" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="5"
android:id="#+id/max_players"
android:textSize="30dp" />
<Button
android:layout_marginTop="10dp"
android:layout_width="90dp"
android:layout_height="40dp"
android:text="Intra"
android:id="#+id/Buton"
android:layout_marginLeft="5dp" />
<TextView
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=""
android:id="#+id/e_sa_pacaleasca_match_parentu_de_la_linear_layout"
/>
</LinearLayout>
</ScrollView>
In your custom_row.xml :
change the layout_height of the RelativeLayout, ScrollView and the LinearLayout from fill_parent to wrap_content.
From the R.layout.custom_row we can see that you make the root view(RelativeLayout) fill parent and make the height of ScrollView match_parent. So the Scrollview occupy the full screen. The blank space belongs to scrollview. I think you can remove the scrollview and make the root view(RelativeLayout) wrap content.
Try codes below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/background_joc">
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/grey"
android:orientation="horizontal">
<TextView
android:id="#+id/Nume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:text="Nume camera"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25dp"/>
<TextView
android:id="#+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginTop="-7dp"
android:text="Runde:"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/runde"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="-30dp"
android:layout_marginTop="15dp"
android:text="5"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="25dp"/>
<ImageView
android:id="#+id/privata"
android:layout_width="15dp"
android:layout_height="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="18dp"
android:background="#drawable/buton_lock"/>
<TextView
android:id="#+id/players"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:text="0"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<TextView
android:id="#+id/nu_trebuia_sa_aiba_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="/"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<TextView
android:id="#+id/max_players"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="5"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<Button
android:id="#+id/Buton"
android:layout_width="90dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Intra"/>
<TextView
android:id="#+id/e_sa_pacaleasca_match_parentu_de_la_linear_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</ScrollView>
</RelativeLayout>

onClickListener on a button that is added through a layout inflator

Here is my code so far based on various answers to related questions on SO.
In my Activity
GridView gv = (GridView) findViewById(R.id.gridView1);
MyCustomAdapter mAdapter = new MyCustomAdapter();
mAdapter.addItem("Action1");
mAdapter.addItem("Action2");
mAdapter.addItem("Action3");
gv.setAdapter(mAdapter);
My Adapter
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NumericViewHolder holder = new NumericViewHolder();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.horizontalnumberpicker, null);
holder.textView = (TextView)convertView.findViewById(R.id.txtNPTitle);
holder.minus = (Button)convertView.findViewById(R.id.btnMinus);
holder.plus = (Button)convertView.findViewById(R.id.btnPlus);
holder.value = (TextView)convertView.findViewById(R.id.txtNPValue);
holder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString());
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
if (value > 0) {
value = value - 1;
tv.setText(Integer.toString(value));
}
}
});
holder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString()); <--Error is here
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
value = value + 1;
tv.setText(Integer.toString(value));
}
});
convertView.setTag(holder);
} else {
holder = (NumericViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
XML - Main_Activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rlAddProduct"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/btnSaveProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text="#string/Save" />
<TextView
android:id="#+id/lblSelectCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnSaveProduct"
android:layout_alignBottom="#+id/btnSaveProduct"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:text="#string/selectCategory" />
<Spinner
android:id="#+id/spCategory"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignBottom="#+id/lblSelectCategory"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp"
android:layout_toEndOf="#+id/lblSelectCategory"
android:layout_toRightOf="#+id/lblSelectCategory" />
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lblSelectCategory"
android:layout_below="#+id/btnSaveProduct"
android:layout_marginTop="14dp"
android:numColumns="auto_fit" >
</GridView>
</RelativeLayout>
XML - Horizontalnumberpicker
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtNPTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="EnterTextHere"
android:layout_marginTop="5dp" />
<Button
android:id="#+id/btnPlus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/txtNPValue"
android:layout_alignBottom="#+id/txtNPValue"
android:layout_toRightOf="#+id/txtNPValue"
android:text="+" />
<TextView
android:id="#+id/txtNPValue"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/btnMinus"
android:layout_toRightOf="#+id/btnMinus"
android:gravity="center"
android:text="0"
android:textAppearance="#style/AppBaseTheme"
android:textSize="20dp" />
<Button
android:id="#+id/btnMinus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtNPTitle"
android:layout_marginTop="2dp"
android:text="-" />
</RelativeLayout>
The requirement is that when I press the plus button, I need to increment the value in the corresponding txtNPValue. Similarly with the minus button, I need to decrement the value in the txtNPValue.
The error is
01-31 22:40:10.854: E/AndroidRuntime(32198): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
Also I do not know if this is the right way to program such a requirement and would like some pointers.
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
this will return null pointer exception, as the view that u r getting is of the button or the clicked item..
Use this :-
RelativeLayout rlLayout = (RelativeLayout) v.getParent();
TextView tv = (TextView) rlLayout.findViewById(R.id.txtNPValue);
please remove:
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
from onClick to resolve nullpointerException

ListView not loading, returns null object on textview.setText();

Here is my custom adapter code. I get an error that my textView.setText() is null
"Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference"
I usually retrieve data from my database, but right now I used hardcoded string just to check if the problem is with the database, but the problem persist with the hardcoded string.
public class CardViewAdapter extends BaseAdapter {
Context context;
List<Note> notes;
TextView cardTitleText;
TextView cardDescriptionText;
TextView cardDateText;
ImageView cardImage;
public CardViewAdapter(Context context, ArrayList<Note> notes) {
this.context = context;
this.notes = notes;
}
#Override
public int getCount() {
return notes.size();
}
#Override
public Object getItem(int position) {
return notes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.card_view, parent, false);
cardTitleText = (TextView) view.findViewById(R.id.titleTextCardView);
cardDescriptionText = (TextView) view.findViewById(R.id.descriptionTextView);
cardDateText = (TextView) view.findViewById(R.id.dateTextCardView);
cardImage = (ImageView) view.findViewById(R.id.cardImage);
Note note = notes.get(position);
Log.v("NOTE", note.getTitle() + " " + note.getDescription() + " " + note.getDate());
cardTitleText.setText("Title");
cardDescriptionText.setText("Description");
cardDateText.setText("Date");
return view;
}
}
Here is my card_view layout (item layout for my listView):
<RelativeLayout
android:id="#+id/relativeLayoutCardView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/relative_layout"
android:elevation="6dp"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:id="#+id/titleTextCardView"
android:layout_below="#+id/frameLayoutCardView"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingTop="10dp"
android:text="Example Title"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/descriptionTextCardView"
android:layout_alignParentLeft="true"
android:layout_below="#+id/titleTextCardView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="Example description"
android:textSize="13sp"
android:textStyle="bold" />
<FrameLayout
android:id="#+id/frameLayoutCardView"
android:layout_height="130dp"
android:layout_width="fill_parent">
<ImageView
android:id="#+id/cardImage"
android:layout_height="130dp"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:src="#drawable/placeholder" />
<TextView
android:id="#+id/dateTextCardView"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Example date" />
</FrameLayout> </RelativeLayout>
I know that this is probably a stupid and easy to fix problem, but I just keep banging my head because I don't know how to fix it because I can't see how can my TextView be null.
You have a typo in your XML... this line references an element that does not exist in your XML:
cardDescriptionText = (TextView) view.findViewById(R.id.descriptionTextView);
I think it should be:
cardDescriptionText = (TextView) view.findViewById(R.id.descriptionTextCardView);
based on the XML element:
<TextView
android:id="#+id/descriptionTextCardView"
android:layout_alignParentLeft="true"
android:layout_below="#+id/titleTextCardView"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="Example description"
android:textSize="13sp"
android:textStyle="bold" />

Change inflated row in adapter on click

I have an adapter with buttons and text views. It represents friend requests.
TextView text would be : Do you want to accept X as your friend?
There are 2 buttons : one for accepting, one for declining. Pressing Decline, it would just remove the row from the ListView, while pressing accept will change the text into: X and Y are now friends.
My question is how can I get the position of the row and change it on button press and also save the View for next time I access it?
Adapter : At the moment I don't have proper data structure for the adapter, so for testing purposes, just using a String:
public class FriendRequestAdapter extends BaseAdapter {
String mName;
Context mContext;
public FriendRequestAdapter(String name, Context context) {
this.mName = name;
this.mContext = context;
}
#Override
public int getCount() {
return 1;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.friend_request_layout, null);
}
TextView sender_name = (TextView) convertView.findViewById(R.id.wannabe_name);
if (mName.length() > 11) {
mName = mName.substring(0, 12);
}
sender_name.setText(mName);
ImageButton friend_request_accepted = (ImageButton) convertView.findViewById(R.id.accept_friend_request);
friend_request_accepted.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
new APIService().confirmInvite();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
};
}
});
return convertView;
}
Inflated Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/changing_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/check_in_map_menu"
android:descendantFocusability="blocksDescendants">
<RelativeLayout
android:id="#+id/friend_image_container"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="7dp"
android:background="#drawable/polaroid_frame_friend_list">
<ImageView
android:id="#+id/facebook_friend_pic"
android:layout_width="55dp"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:background="#drawable/category_explore"/>
<TextView
android:id="#+id/name_facebook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/facebook_friend_pic"
android:layout_centerHorizontal="true"
android:text="dummy"
android:textColor="#color/enloop_dark_gray"
android:textSize="9sp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="7dp"
android:layout_toRightOf="#+id/friend_image_container">
<TextView
android:id="#+id/wannabe_name"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:text="dada"
android:textColor="#color/enloop_dark_gray"
android:textSize="15dp"/>
<TextView
android:id="#+id/facebook_friend_name"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/wannabe_name"
android:text=" has sent you a request"
android:textColor="#color/enloop_dark_gray"
android:textSize="15dp"/>
<ImageButton
android:id="#+id/later_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:background="#drawable/btn_nothanks"
android:clickable="false"
android:focusable="false"/>
<ImageButton
android:id="#+id/accept_friend_request"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:layout_toRightOf="#+id/later_button"
android:background="#drawable/btn_accept_text"
android:clickable="false"
android:focusable="false"/>
<ImageButton
android:id="#+id/invite_facebook_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/btn_delete_notification"
android:clickable="false"
android:focusable="false"/>
</RelativeLayout>
</RelativeLayout>

Categories

Resources