listview item is not added on button click - android

I have an issue with adapter adding data to listview on button click.
I have a activity called createteam that has name and email edittext and a createplayer button. On click createplayer button, the name and email should be added to list view.
I want to use an adapter for doing that(so that I can learn).
Update:
Onclicking the button the the first entry gets added but when I fill in the
edittexts again, the listview does get updated. I am notifying the adapter when I update
the data but only first entry gets and remains added to list view
create_team.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/teamname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/blue"
android:hint="Team Name"
android:gravity="center"
android:textStyle="bold">
</EditText>
<Button
android:id="#+id/addplayer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/blue"
android:text="Add Player"
android:layout_gravity="center"
android:textStyle="bold">
</Button>
<LinearLayout
android:id="#+id/view_addplayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="#+id/createplayer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/red"
android:text="Create Player"
android:layout_gravity="center"
android:textStyle="bold">
</Button>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/blue"
android:hint="Name"
android:gravity="center"
android:textStyle="bold">
</EditText>
<EditText
android:id="#+id/email"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/blue"
android:hint="Email "
android:textStyle="bold"
android:gravity="center">
</EditText>
</LinearLayout>
<ListView
android:id="#+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
</ScrollView>
add_player_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView android:id="#+id/name"
android:textSize="20sp"
android:textStyle="bold"
android:color="#color/blue"
android:textColor="#FFFF00"
android:layout_width="wrap_content"
android:layout_height="50dp"/>
<TextView android:id="#+id/email"
android:textSize="15sp"
android:textStyle="bold"
android:color="#color/mustard"
android:layout_width="wrap_content"
android:layout_height="50dp"/>
</LinearLayout>
CreateTeamActivity.java
package com.recscores.android;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.Toast;
import com.recscores.android.PlayerInfo;
public class CreateTeamActivity extends ListActivity {
Button createPlayer;
EditText Email;
EditText Name;
private ArrayList<PlayerInfo> newList;
private PlayerAddAdapter newAdpt;
private int i = 0;
private ListView lv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_team);
newList = new ArrayList<PlayerInfo>();
// CREATE TEAM
getWindow().setBackgroundDrawableResource(R.drawable.app_background2);
createPlayer = (Button)findViewById(R.id.createplayer);
Email = (EditText)findViewById(R.id.email);
Name = (EditText)findViewById(R.id.name);
lv = (ListView)findViewById(android.R.id.list);
newAdpt = new PlayerAddAdapter(CreateTeamActivity.this,android.R.id.list,newList);
lv.setAdapter(newAdpt);
createPlayer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// newList = new ArrayList<PlayerInfo>();
PlayerInfo info = new PlayerInfo();
info.SetName(Name.getText().toString());
info.SetEmail(Email.getText().toString());
newList.add(info);
newAdpt.notifyDataSetChanged();
//Thread.sleep(2000);
Name.setText("");
Email.setText("");
}
});
}
}
PlayerAddAdapter.java
package com.recscores.android;
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;
public class PlayerAddAdapter extends ArrayAdapter<PlayerInfo> {
private Activity activity;
//private final Context mContext;
private ArrayList<PlayerInfo> items;
public PlayerAddAdapter(Activity a, int textViewResourceId, ArrayList<PlayerInfo> items){
super(a,textViewResourceId,items);
this.items=items;
this.activity = a;
}
public static class ViewHolder{
public TextView name;
public TextView email;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi.inflate(R.layout.add_player_listview, null);
holder = new ViewHolder();
holder.name = (TextView)v.findViewById(R.id.name);
holder.email = (TextView)v.findViewById(R.id.email);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final PlayerInfo custom = items.get(position);
if (custom != null) {
**holder.name.setText(custom.GetName());
holder.email.setText(custom.GetEmail());
}
return v;
}
}
PlayerInfo.java
package com.recscores.android;
public class PlayerInfo {
private String name="";
private String email="";
public void SetName(String name){
this.name = name;
}
public String GetName(){
return this.name;
}
public void SetEmail(String email){
this.email = email;
}
public String GetEmail(){
return this.email;
}
}

LayoutInflater vi =(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.add_player_listview, null);
Change your code like this. You are not setting values to v variable.

onClick of your button call list.notifyDataSetChanged(). It will refresh your list.
Incase if doesn't work just check getCount() of your adapter what value it is returning. If it is returning 0 your list will not show any data even you call list.notifyDataSetChanged().
Make an arrayList in your adapter and add new items into that. and from getCount() return size of arrayList.

Related

How to fix OnItemClickListener on ListView

This is java class MainActivity.java
package com.example.mhn.intercoapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.mhn.intercoapp.Adapters.EmployeeDirAdapter;
import com.example.mhn.intercoapp.static_class.EmployeeDir;
import java.util.ArrayList;
public class EmployeeDirectoryActivity extends AppCompatActivity {
ListView listView;
ImageView back_button;
EmployeeDir obj;
ArrayList <EmployeeDir> empDir ;
EmployeeDirAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_directory);
listView = (ListView) findViewById(R.id.listView_emp_directory_xml);
back_button = (ImageView) findViewById(R.id.back_button_header_emp_directory_activity_xml);
obj = new EmployeeDir();
empDir = new ArrayList<>();
adapter = new EmployeeDirAdapter(getApplicationContext(),empDir);
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
finish();
}
});
obj.setEmp_name("Hafiz Sadique Umar");
obj.setEmp_email("hsu#gmail.com");
obj.setEmp_contact_num("+923045607057");
empDir.add(obj);
empDir.add(obj);
empDir.add(obj);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Intent intent= new Intent(getApplicationContext(),DoneActivity.class);
startActivity(intent);
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
This is activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".EmployeeDirectoryActivity">
<RelativeLayout
android:id="#+id/relatice_layout_header_emp_directory_activity_xml"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_alignParentTop="true"
android:layout_height="56dp">
<ImageView
android:id="#+id/back_button_header_emp_directory_activity_xml"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:src="#drawable/back_arrow_header"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Employee Directory"
android:textColor="#fff"
android:textSize="18dp"
android:textStyle="bold"
android:layout_centerInParent="true"
/>
</RelativeLayout>
<ListView
android:clickable="true"
android:id="#+id/listView_emp_directory_xml"
android:layout_below="#id/relatice_layout_header_emp_directory_activity_xml"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</RelativeLayout>
This is Adapter
package com.example.mhn.intercoapp.Adapters;
import android.content.Context;
import android.content.Intent;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mhn.intercoapp.MainActivity;
import com.example.mhn.intercoapp.R;
import com.example.mhn.intercoapp.static_class.EmployeeDir;
import java.util.ArrayList;
public class EmployeeDirAdapter extends BaseAdapter {
Context context;
private LayoutInflater inflater;
private ArrayList<EmployeeDir> menuData=new ArrayList<>();
public EmployeeDirAdapter(Context context, ArrayList<EmployeeDir>EmpDir)
{
this.context = context;
this.menuData=EmpDir;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return menuData.size();
}
#Override
public Object getItem(int i) {
return menuData.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderEmpDir holder;
if (convertView == null) {
holder = new ViewHolderEmpDir();
convertView = inflater.inflate(R.layout.emp_directory_list_row_layout, parent, false);
holder.name = (TextView) convertView.findViewById(R.id.name_textView_emp_directory_list_row_layout);
holder.email = (TextView) convertView.findViewById(R.id.email_textView_emp_directory_list_row_layout);
holder.phone = (TextView) convertView.findViewById(R.id.phone);
holder.pic = (ImageView) convertView.findViewById(R.id.emp_pic_emp_directory_list_row_layout);
holder.viewButton = (ImageView) convertView.findViewById(R.id.view_button_emp_dir_list_row_layout);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderEmpDir) convertView.getTag();
}
holder.name.setText(menuData.get(position).getEmp_name());
holder.email.setText(menuData.get(position).getEmp_email());
holder.phone.setText(menuData.get(position).getEmp_contact_num());
//Linkify.addLinks(holder.email,Linkify.EMAIL_ADDRESSES);
//Linkify.addLinks(holder.phone,Linkify.PHONE_NUMBERS);
holder.pic.setImageResource(R.drawable.user_sign_up);
holder.viewButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,MainActivity.class);
}
});
//downloadImage(position,holder);
return convertView;
}
// private void downloadImage(int position,ViewHolderShowAllBooking holder)
// {
// Picasso.with(context)
// .load("http://www.efefoundation.net/inklink/uploads/artist/"+menuData.get(position).getArtistId()+".jpg")
// .fit() // will explain later
// .into(holder.profile);
// }
static class ViewHolderEmpDir
{
TextView name;
TextView email;
TextView phone;
ImageView pic;
ImageView viewButton;
}
}
This is list_row_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="4"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_marginTop="5dp"
android:layout_centerHorizontal="true"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="70dp"
android:background="#color/colorAccent">
<ImageView
android:id="#+id/emp_pic_emp_directory_list_row_layout"
android:layout_marginTop="5dp"
android:layout_width="80dp"
android:layout_height="70dp"
android:layout_marginBottom="5dp"
android:src="#drawable/user_sign_up"/>
</RelativeLayout>
<RelativeLayout
android:background="#color/colorAccent"
android:layout_marginTop="5dp"
android:layout_width="0dp"
android:layout_height="70dp"
android:layout_weight="3">
<TextView
android:id="#+id/name_textView_emp_directory_list_row_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textColor="#fff"
android:textSize="18dp"
android:layout_alignParentLeft="true"
android:text="Husnain"/>
<TextView
android:id="#+id/phone"
android:layout_toRightOf="#id/name_textView_emp_directory_list_row_layout"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:autoLink="phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="***********"
android:textColor="#fff"/>
<TextView
android:id="#+id/email_textView_emp_directory_list_row_layout"
android:layout_alignParentLeft="true"
android:layout_below="#id/name_textView_emp_directory_list_row_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="mhn786#gmail.com"
android:autoLink="email"
android:layout_marginLeft="10dp"
android:textSize="18dp"
android:textColor="#fff"
/>
<ImageView
android:id="#+id/view_button_emp_dir_list_row_layout"
android:src="#drawable/view"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
When I apply OnItemClickListener it does not do any action like intent inside the func not called. I tried toast too but nothing shown on clicking the listView Items.
I also tried OnItemSlectedListener , it also not worked for me.
What is the problem here with this code. ?
Thanks Every One. Issue was with autolink on email and phone, I make their focusable=false but nothing happened.Then I remove it and guess what? Clicklistener also starts working.
The attribute android:clickable="true" in your ListView could be overriding all of click events of its child views, you should probably remove it:
<ListView
android:clickable="true" <!-- Remove this attribute -->
android:id="#+id/listView_emp_directory_xml"
android:layout_below="#id/relatice_layout_header_emp_directory_activity_xml"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

Run-time Expandable Listview with Edittext and Spinner

My intention is to get data from the run-time growing listview (as shown in below figures) which has Edittext and Spinners and send this data to remote server using json.
Am I on the correct path or there is another kind of method to be used for this.
I want to access Edittext and Spinner from the listview which is expanded at runtime.
My Problem is, whenever a new view is added, it overlaps on the previous view.
Instead, it should get added below the 1st view. (Solved this. See the edited code).
Another thing is how to access edittext & spinner from each view? I want to accept this data from user & save it in the device. How to do that? (in private void SaveUserData() {} method).
Below is my full code.
Edited on 20 Mar 2018
MainActivity.java
package tandel.amit.expandablelistview;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView listView;
Button buttonSave;
FloatingActionButton fab;
Adapter adapter;
int count = 0;
String[] Heading = {"User 1","User 2","User 3","User 4"};
String Name = "Name";
String ID = "ID";
String Gender = "Gender";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
buttonSave = findViewById(R.id.btnSave);
fab = findViewById(R.id.fabAdd);
buttonSave.setOnClickListener(onClickListener);
fab.setOnClickListener(onClickListener);
adapter = new Adapter(getApplicationContext(), R.layout.row_layout);
listView.setAdapter(adapter);
AddView(count++);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnSave:
SaveUserData(); // Save the data to Local Database
break;
case R.id.fabAdd:
AddView(count++); // Add new View in listview
break;
default:
break;
}
}
};
private void AddView(int i) {
DataProvider dataProvider = new DataProvider(Heading[i],Name,Gender,ID);
adapter.add(dataProvider);
adapter.notifyDataSetChanged();
}
private void SaveUserData() {
}
}
Adapter.java
package tandel.amit.expandablelistview;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/*
* Created by Amit Tandel on 2/2/2018.
*/
public class Adapter extends ArrayAdapter{
List list = new ArrayList();
public Adapter(#NonNull Context context, int resource) {
super(context, resource);
}
#Override
public void add(#Nullable Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return this.list.get(position);
}
static class DataHandler{
TextView Heading,Name,Gender,ID;
EditText UserName,UserID;
Spinner UserGender;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
DataHandler dataHandler = new DataHandler();
if (convertView == null){ // If row is empty, we need to create row
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHandler.Heading = convertView.findViewById(R.id.tvHeading);
dataHandler.Name = convertView.findViewById(R.id.tvName);
dataHandler.Gender = convertView.findViewById(R.id.tvGender);
dataHandler.ID = convertView.findViewById(R.id.tvID);
dataHandler.UserName = convertView.findViewById(R.id.etName);
dataHandler.UserID = convertView.findViewById(R.id.etID);
dataHandler.UserGender = convertView.findViewById(R.id.spGender);
convertView.setTag(dataHandler);
}else {
dataHandler = (DataHandler) convertView.getTag(); // If row already present then get that row
}
DataProvider dataProvider;
dataProvider = (DataProvider) this.getItem(position);
if (dataProvider != null) {
dataHandler.Heading.setText(dataProvider.getHeading());
dataHandler.Name.setText(dataProvider.getName());
dataHandler.Gender.setText(dataProvider.getGender());
dataHandler.ID.setText(dataProvider.getID());
}
return convertView;
}
}
DataProvider.java
package tandel.amit.expandablelistview;
/*
* Created by Amit Tandel on 2/2/2018.
*/
public class DataProvider {
private String Heading;
private String Name;
private String Gender;
private String ID;
public DataProvider(String Heading, String Name, String Gender, String ID) {
this.setHeading(Heading);
this.setName(Name);
this.setGender(Gender);
this.setID(ID);
}
public String getHeading() {
return Heading;
}
public void setHeading(String heading) {
Heading = heading;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
}
activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="tandel.amit.expandablelistview.MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
n
<Button
android:id="#+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Save" />
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:id="#+id/fabAdd"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:src="#drawable/plus"
android:layout_marginBottom="80dp" />
</RelativeLayout>
row_layout.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="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="#+id/tvHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="User 1"
android:textSize="18sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tvName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name"
android:textSize="16sp" />
<EditText
android:id="#+id/etName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tvGender"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gender"
android:textSize="16sp" />
<Spinner
android:id="#+id/spGender"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tvID"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ID"
android:textSize="16sp" />
<EditText
android:id="#+id/etID"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="8dp"
android:background="#000000" />
</LinearLayout>

I want to create an Android Page which looks like this

I am beginner Android Developer. I want to create an Android Page which will dynamically display Three things 1. Question No. 2. Your Answer 3. Right Answer. How can I do this? It should look like this and can grow dynamically
What about something like this (Uses a listview):
Mainactivity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList<Question> questionArrayList;
private void fillList(){
questionArrayList = new ArrayList<>();
for (int i = 0; i < 12; i++) {
questionArrayList.add(new Question(i,"myans","yourans"));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillList();
ListView mlIstView = (ListView)findViewById(R.id.mListview);
QuestionAdapter adapter = new QuestionAdapter(this,R.layout.listviewlayout,questionArrayList);
mlIstView.setAdapter(adapter);
}
}
Question.java
public class Question {
private int numberOfQuestion;
private String yourAnswer;
private String correctAnswer;
public Question(int numberOfQuestion, String yourAnswer, String correctAnswer) {
this.numberOfQuestion = numberOfQuestion;
this.yourAnswer = yourAnswer;
this.correctAnswer = correctAnswer;
}
public int getNumberOfQuestion() {
return numberOfQuestion;
}
public String getYourAnswer() {
return yourAnswer;
}
public String getCorrectAnswer() {
return correctAnswer;
}
}
QuestionAdapter
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by waro on 6/4/17.
*/
public class QuestionAdapter extends ArrayAdapter<Question> {
private ArrayList<Question> arrayList;
public QuestionAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull ArrayList<Question> objects) {
super(context, resource, objects);
arrayList = objects;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listviewlayout,parent,false);
}
Question question = arrayList.get(position);
TextView questiontv = (TextView)convertView.findViewById(R.id.question);
TextView yourans = (TextView)convertView.findViewById(R.id.yourans);
TextView correctans = (TextView)convertView.findViewById(R.id.correctans);
questiontv.setText(Integer.toString(question.getNumberOfQuestion()));
yourans.setText(question.getYourAnswer());
correctans.setText(question.getCorrectAnswer());
return convertView;
}
}
activity_mail.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.suprentive.waro.myapplication.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:id="#+id/mLinearLayout">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Question"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Your answer"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Right answer"
android:layout_weight="1"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mListview"
android:layout_below="#id/mLinearLayout">
</ListView>
</RelativeLayout>
listviewlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/question"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/yourans"
android:layout_weight="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/correctans"
android:layout_weight="1"/>
</LinearLayout>
Result
Hopefully this helps you out.

there are no any display on listView with baseadapter

every one,
I am a beginning learner on android system ,
I create a small app that could get specific data , like foreign exchange rate from bank website ,
this app uses Jsoup , ListView , BaseAdapter etc...
finally , the only problem is the listView has no any display ,
could any one tell me , how to fix it.
Thanks.
Category.java
public class Category
{
String bank_name;
String page_url;
Category(String bank_name,String url)
{
this.bank_name=bank_name;
this.page_url=url;
}
#Override
public String toString()
{
return bank_name;
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity
{
ArrayList<Category> items;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<Category>();
items.add(new Category("台灣銀行","http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm"));
ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(this , android.R.layout.simple_list_item_1 ,items);
ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(adapter);
lv.setOnItemClickListener(itemClick);
}
OnItemClickListener itemClick = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> av , View v , int position , long id)
{
Category category = items.get(position);
Intent intent = new Intent();
intent.setClass(MainActivity.this , RateActivity.class );
intent.putExtra("bank_name", category.bank_name);
intent.putExtra("page_url" , category.page_url);
startActivity(intent);
}
};
RateBean.java
public class RateBean
{
private String currency;
private String cashBuy;
private String cashSold;
private String spotBuy;
private String spotSold;
public RateBean()
{
currency = "";
cashBuy = "";
cashSold = "";
spotBuy = "";
spotSold = "";
}
public RateBean(String [] strArr)
{
this.currency=strArr[0];
this.cashBuy=strArr[1];
this.cashSold=strArr[2];
this.spotBuy=strArr[3];
this.spotSold=strArr[4];
}
public RateBean(String currency , String cashBuy , String cashSold , String spotBuy ,String spotSold)
{
setCurrency(currency);
setCashBuy(cashBuy);
setCashSold(cashSold);
setSpotBuy(spotBuy);
setSpotSold(spotSold);
}
//Currency setter and getter
public void setCurrency(String currency)
{
this.currency = currency ;
}
public String getCurrency()
{
return currency;
}
//Cash buy setter and getter
public void setCashBuy(String cashBuy)
{
this.cashBuy = cashBuy;
}
public String getCashBuy()
{
return cashBuy;
}
//Cash sold setter and getter
public void setCashSold(String cashSold)
{
this.cashSold = cashSold;
}
public String getCashSold()
{
return cashSold;
}
//Spot buy setter and getter
public void setSpotBuy(String spotBuy)
{
this.spotBuy = spotBuy;
}
public String getSpotBuy()
{
return spotBuy;
}
//Spot sold setter and getter
public void setSpotSold(String spotSold)
{
this.spotSold = spotSold;
}
public String getSpotSold()
{
return spotSold;
}
}
RateActivity.java
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
public class RateActivity extends ListActivity
{
Context context ;
ArrayList<RateBean> rateBean_item;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate_show);
TextView updateTime = (TextView)findViewById(R.id.updateTime_textView);
Intent intent = getIntent();
String category = intent.getStringExtra("bank_name");
String page_url = intent.getStringExtra("page_url");
setTitle(category);
context=this;
ConnectThread thread = new ConnectThread(context , rateBean_item , page_url , updateTime);
thread.start();
}
public class ConnectThread extends Thread
{
Context context;
ArrayList<RateBean> rateBean_item;
String page_url ;
TextView updateTime;
RateAdapter adapter;
RateBean rateBean;
int i =0;
public ConnectThread(Context context , ArrayList<RateBean> rateBean_item , String page_url , TextView updateTime )
{
this.context=context;
this.rateBean_item=rateBean_item;
this.page_url=page_url;
this.updateTime=updateTime;
}
#Override
public void run()
{
try
{
String currency="";
String cashBuy="";
String cashSold="";
String spotBuy="";
String spotSold="";
Document doc = Jsoup.connect(page_url).get();
rateBean_item = new ArrayList<>();
String temp=doc.select("td[style=width:326px;text-align:left;vertical-align:top;color:#0000FF;font-size:11pt;font-weight:bold;]").text();
String time=temp.substring(12);
updateTime.setText("匯率更新時間:\n" + time);
for( Element title:doc.select("td.titleLeft"))
{
currency=title.text();
if( i < doc.select("td.decimal").size())
{
cashBuy=doc.select("td.decimal").eq(i++).text();
cashSold=doc.select("td.decimal").eq(i++).text();
spotBuy=doc.select("td.decimal").eq(i++).text();
spotSold=doc.select("td.decimal").eq(i++).text();
rateBean = new RateBean( a , b , c ,d , e );
rateBean_item.add(rateBean);
}
}
adapter = new RateAdapter(context , rateBean_item);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
catch( Exception exception )
{
exception.printStackTrace();
}
}
}
}
RateAdapter.java
import java.util.ArrayList;
import android.util.Log;
import android.widget.BaseAdapter;
import android.view.*;
import android.widget.*;
import android.content.*;
public class RateAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private ArrayList<RateBean> list ;
public RateAdapter()
{
}
public RateAdapter(Context context , ArrayList<RateBean> list )
{
this.inflater = LayoutInflater.from(context);
this.list = list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public static class ViewHolder
{
TextView currency_name;
TextView cash_buy;
TextView cash_sold;
TextView spot_buy;
TextView spot_sold;
}
#Override
public View getView( int position , View convertView , ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.rate_item , null);
holder = new ViewHolder();
holder.currency_name = (TextView)convertView.findViewById(R.id.xml_currency);
holder.cash_buy = (TextView)convertView.findViewById(R.id.xml_cashBuy);
holder.cash_sold = (TextView)convertView.findViewById(R.id.xml_cashSold);
holder.spot_buy = (TextView)convertView.findViewById(R.id.xml_spotBuy);
holder.spot_sold = (TextView)convertView.findViewById(R.id.xml_spotSold);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
RateBean rateItem = list.get(position);
holder.currency_name.setText(rateItem.getCurrency());
holder.cash_buy.setText(rateItem.getCashBuy());
holder.cash_sold.setText(rateItem.getCashSold());
holder.spot_buy.setText(rateItem.getSpotBuy());
holder.spot_sold.setText(rateItem.getSpotSold());
return convertView;
}
}
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/title_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="銀行查詢選擇"/>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_rate_show.xml
<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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/updateTime_textView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="updateTime"/>
<Button
android:id="#+id/fresh_button"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="onClick"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/button_fresh"/>
</LinearLayout>>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/currency"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_sold"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_sold"/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
rate_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/xml_currency"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:textAppearance="?android:attr/textAppearanceLarge"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
</LinearLayout>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Your listview needs a height, it cannot be wrap_content. Give it a height like 500dp or match_parent.

Different Column name in grid view in android

Hi i am developing android application. Now at this stage i am developing calendar which is in week view. For doing that i have use grid view.In grid view there is 7 columns per week days. Each column have one textview which display name of the week day.Now i want to display different week days in each column.But I don't know how to achieve this as i am new in this field. i am using custom adapter for this.Here is code Any help is appreciated.
Here on 6 in want to display Name of week days.
package com.gridlayoutdemo;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
public class GridLayoutDemo extends Activity {
/** Called when the activity is first created. */
public String[] weekdays={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new MyAdapter(this));
}
}
class MyAdapter extends BaseAdapter {
Context context;
public MyAdapter(Context context) {
this.context = context;
}
public int getCount() {
return 7;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater li = LayoutInflater.from(context);
convertView = li.inflate(R.layout.main1, null);
holder = new ViewHolder();
holder. tvWeekDay = (TextView)convertView.findViewById(R.id.tvWeekDayName);
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.DAY_OF_WEEK));
holder.tvWeekDay.setText(weekdays[position]);
}
}
// holder.tvWeekDay.setText(Integer.toString(Calendar.MONTH));
TextView tvDate = (TextView)convertView.findViewById(R.id.tvDate);
TextView tvNotes = (TextView)convertView.findViewById(R.id.tvNotes1);
convertView.setTag(holder);
//tvWeekday.setText(c.get(Calendar.MONTH));
tvNotes.setText(" Click here for new Note");
tvNotes.setTextSize(10);
tvNotes.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(" Click is successful");
}
});
TextView tv2 = (TextView)convertView.findViewById(R.id.tvNotes2);
tv2.setText(" Click here for new Note" );
tv2.setTextSize(10);
tv2.setLayoutParams(new LayoutParams(140, 200));
tv2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("1.Click is successful");
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.DAY_OF_WEEK));
return convertView;
}
static class ViewHolder {
TextView tvWeekDay;
}
}
//main1.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/LlHeader"
android:background="#drawable/calendar_top_header">
<TextView
android:id="#+id/tvWeekDayName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginLeft="5dp"
android:singleLine="true"
android:textColor="#FFFFFF"
android:text="Friday"/>
<TextView
android:id="#+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textStyle="bold"
android:layout_marginBottom="5dp"
android:singleLine="true"
android:textColor="#FFFFFF"
android:text="25-NOV-2011"/>
</LinearLayout>
<TextView android:id="#+id/tvNotes1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView android:id="#+id/tvNotes2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:background="#f5f5f5"
android:layout_height="fill_parent">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:background="#drawable/calendar_top_header">
<ImageView
android:id="#+id/imgleftarrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src = "#drawable/cal_left_arrow_off">
</ImageView>
<TextView
android:id="#+id/tvMonthName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginTop="5dp"
android:layout_marginLeft="80dp"
android:singleLine="true"
android:textColor="#FFFFFF"
android:text="November"/>
<ImageView
android:id="#+id/imgrightarrow"
android:layout_width="wrap_content"
android:layout_marginLeft="95dp"
android:layout_height="wrap_content"
android:src = "#drawable/cal_right_arrow_off">
</ImageView>
<!-- </LinearLayout> -->
</LinearLayout>
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:numColumns="2"
android:layout_height="fill_parent"
android:background="#f5f5f5"
/>
</LinearLayout>

Categories

Resources