How do I retrieve the text of a specific textView? BEcause when I click an ID number it displays '1' in the textview of the next class in every text view I click. I used JSON array so it's kind of tricky for me. And yes I'm completely a beginner.
DisplayListView
package rjj.tutorial_jsonandlistview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DisplayListView extends AppCompatActivity {
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
SearchView sv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_listview_layout);
listView = (ListView)findViewById(R.id.listview);
contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listView.setAdapter(contactAdapter);
json_string = getIntent().getExtras().getString("json_data");
//Searchview
sv = (SearchView)findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
contactAdapter.getFilter().filter(newText);
return true;
}
});
//End of Searchview
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String id ,firstname , surname, age , username, password;
while(count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id = JO.getString("id");
firstname = JO.getString("firstname");
surname = JO.getString("surname");
age = JO.getString("age");
username = JO.getString("username");
password = JO.getString("password");
Contacts contact = new Contacts(id, firstname, surname, age,username,password);
contactAdapter.add(contact);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void hello(View view) {
Intent intent = new Intent(this, Update.class);
TextView textView = (TextView)findViewById(R.id.tx_id);
String id = textView.getText().toString();
intent.putExtra("id", id);
startActivity(intent);
}
}
My ContactAdapter Class:
package rjj.tutorial_jsonandlistview;
import android.content.Context;
import android.support.annotation.LayoutRes;
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.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Julian on 7/20/2017.
*/
public class ContactAdapter extends ArrayAdapter {
List list = new ArrayList();
public ContactAdapter(#NonNull Context context, #LayoutRes int resource) {
super(context, resource);
}
public void add(Contacts object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_id = (TextView)row.findViewById(R.id.tx_id);
contactHolder.tx_firstname = (TextView)row.findViewById(R.id.tx_firstname);
contactHolder.tx_surname = (TextView)row.findViewById(R.id.tx_surname);
contactHolder.tx_age = (TextView)row.findViewById(R.id.tx_age);
contactHolder.tx_username = (TextView)row.findViewById(R.id.tx_username);
contactHolder.tx_password = (TextView)row.findViewById(R.id.tx_password);
row.setTag(contactHolder);
} else{
contactHolder = (ContactHolder)row.getTag();
}
Contacts contacts = (Contacts)this.getItem(position);
contactHolder.tx_id.setText(contacts.getId());
contactHolder.tx_firstname.setText(contacts.getFirstname());
contactHolder.tx_surname.setText(contacts.getSurname());
contactHolder.tx_age.setText(contacts.getAge());
contactHolder.tx_username.setText(contacts.getUsername());
contactHolder.tx_password.setText(contacts.getPassword());
return row;
}
static class ContactHolder{
TextView tx_id, tx_firstname, tx_surname, tx_age, tx_username, tx_password;
}
}
My Update Class:
package rjj.tutorial_jsonandlistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Update extends AppCompatActivity {
String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
id = getIntent().getExtras().getString("id");
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(id);
}
}
My display_listview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.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="rjj.tutorial_jsonandlistview.DisplayListView">
<SearchView
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/search"
android:queryHint="Search..."/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/search"
android:id="#+id/listview">
</ListView>
</android.widget.RelativeLayout>
The row_layout.xml (which I use to display the JSON array)
<?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="75dp">
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_id"
android:layout_alignParentLeft="true"
android:text="ID"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
android:onClick="hello"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_firstname"
android:layout_toRightOf="#+id/tx_id"
android:text="Firstname"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_surname"
android:layout_toRightOf="#+id/tx_firstname"
android:text="Lastname"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_age"
android:layout_toRightOf="#+id/tx_surname"
android:text="Age"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_username"
android:layout_toRightOf="#+id/tx_age"
android:text="Username"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="60dp"
android:layout_height="match_parent"
android:id="#+id/tx_password"
android:layout_toRightOf="#+id/tx_username"
android:text="Password"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
</RelativeLayout>
In method hello(View view) you don't need this string:
TextView textView = (TextView)findViewById(R.id.tx_id);
becouse the view in hello(View view) this is our TextView. Just cast it to TextView and get text from it:
String id = ((TextView)view).getText().toString();
Another and most universal approach: to change
TextView textView = (TextView)findViewById(R.id.tx_id);
to
TextView textView = (TextView)((ViewGroup)(view.getParent())).findViewById(R.id.tx_id);
In this way you can use any R.id for current list item.
Related
So I have this custom list adapter and listview thingy and I can't seem to get it to work. I've spent a couple of days now trying to figure how to fix it. Change this change that, nothing seems to work. Any idea? thanks
MainActivity.class
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActvty";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory_actvity);
Log.d(TAG, "onCreate, Started");
ListView resList = (ListView)findViewById(R.id.inListView);
resClass wood = new resClass("Wood", 10);
resClass iron = new resClass("Iron", 50);
resClass meat = new resClass("Meat", 5);
ArrayList<resClass> resArrayList = new ArrayList<>();
resArrayList.add(wood);
resArrayList.add(iron);
resArrayList.add(meat);
ResListAdapter rsAdapter = new ResListAdapter(this, R.layout.activity_inventory_actvity, resArrayList);
resList.setAdapter(rsAdapter);
}
}
resClass.class
public class resClass {
private String resType;
private int resCount;
public resClass(String resType, int resCount) {
this.resType = resType;
this.resCount = resCount;
}
public String getResType() {
return resType;
}
public void setResType(String resType) {
this.resType = resType;
}
public int getResCount() {
return resCount;
}
public void setResCount(int resCount) {
this.resCount = resCount;
}
}
ResListAdapter.class
I'm guessing there is something wrong with the adapter. But I'm not really sure.
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.TextView;
import java.util.ArrayList;
class ResListAdapter extends ArrayAdapter<resClass>{
private static final String TAG = "ResListAdapter";
private Context mContext;
int mResource;
public ResListAdapter( Context context, int resource, ArrayList<resClass> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
String resType = getItem(position).getResType();
int resCount = getItem(position).getResCount();
resClass res = new resClass(resType, resCount);
LayoutInflater rsInflater = LayoutInflater.from(mContext);
convertView = rsInflater.inflate(mResource, parent, false);
TextView resTypeView = (TextView)convertView.findViewById(R.id.res_name);
TextView resCountView = (TextView)convertView.findViewById(R.id.res_count);
resTypeView.setText(resType);
resCountView.setText(Integer.toString(resCount));
return convertView;
}
}
The xml files
MainActivity
<?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="p_darkness.lonemandevelopmentstudio.com.p_darkness.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp"
android:id="#+id/inListView"/>
</RelativeLayout>
Custom layout for the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:layout_height="match_parent">
<TextView
android:id="#+id/res_name"
android:textColor="#000"
android:textSize="17sp"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:gravity="center"
android:layout_weight="50"
android:text="res_name"
android:textAlignment="center"/>
<TextView
android:id="#+id/res_count"
android:textColor="#000"
android:textSize="15sp"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:gravity="center"
android:layout_weight="50"
android:text="res_count"
/>
</LinearLayout>
It's been really frustrating guys hope I can find the solution by asking this time.
I am trying to feed my custom GridView with data fetched from Facebook Graph API. This data is a list of Album objects containing the picture for the album of the current user and the name of the album.
Fetching data doesn't represent a problem since I can see it in the LOGCAT.
What seems to be a problem is my GridView Adapter I suppose, the program doesn't give any particular error and this makes me confused.
Note that the MainActivity which will not be displayed here serves only to connect a user via Facebook account (there is no problem in this Activity)
Here is my different classes :
----LoggedInActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LoggedInActivity extends Activity {
String name, surname, ID;
TextView nameOfUser;
Button logout;
GridView gridView;
GridViewAdapter gridViewAdapter;
List<Album> albumList = new ArrayList<Album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
ID = inBundle.getString("ID");
setContentView(R.layout.activity_logged_in);
nameOfUser = (TextView) findViewById(R.id.name);
nameOfUser.setText(name + " " + surname);
logout = (Button) findViewById(R.id.logout);
gridView = (GridView) findViewById(R.id.myGridView);
albumList = getAlbums();
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logOut();
Intent login = new Intent(LoggedInActivity.this, MainActivity.class);
startActivity(login);
finish();
}
});
gridViewAdapter = new GridViewAdapter(getBaseContext(), albumList);
gridView.setAdapter(gridViewAdapter);
}
public List<Album> getAlbums() {
albumList = new ArrayList<Album>();
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/albums",
new GraphRequest.Callback() {
Album album = null;
#Override
public void onCompleted(GraphResponse response) {
JSONObject jsonDATA = response.getJSONObject();
JSONArray data = jsonDATA.optJSONArray("data");
for(int i = 0 ; i< data.length(); i++){
try {
JSONObject e = data.getJSONObject(i);
String name = e.optString("name");
JSONObject picture = e.getJSONObject("picture");
JSONObject dataOfPicture = picture.getJSONObject("data");
String url = dataOfPicture.optString("url");
album = new Album(name, url);
albumList.add(album);
Log.d("Mine",name + url);
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "Problem with JSON parsing", Toast.LENGTH_SHORT).show();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "picture,name");
request.setParameters(parameters);
request.executeAsync();
return albumList;
}
}
------Album.java
public class Album {
public String album_name;
public String album_image;
public Album(String album_name, String album_image) {
this.album_name = album_name;
this.album_image = album_image;
}
public String getAlbum_name() {
return album_name;
}
public String getAlbum_image() {
return album_image;
}
public void setAlbum_name(String album_name) {
this.album_name = album_name;
}
public void setAlbum_image(String album_image) {
this.album_image = album_image;
}
}
-----GridViewAdapter.java
import android.content.Context;
import android.graphics.BitmapFactory;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.URL;
import java.util.List;
public class GridViewAdapter extends BaseAdapter {
private List<Album> albumList;
private Context context;
public GridViewAdapter(#NonNull Context context, #NonNull List<Album> objects) {
this.albumList = objects;
this.context = context;
}
#Override
public int getCount() {
return albumList.size();
}
#Nullable
#Override
public Album getItem(int position) {
return albumList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item,null);
}
Album album = getItem(position);
ImageView imageView = (ImageView)v.findViewById(R.id.imageHolder);
TextView description = (TextView)v.findViewById(R.id.albumDesc);
try {
imageView.setImageBitmap(BitmapFactory.decodeStream((new URL(album.getAlbum_image())).openConnection().getInputStream()));
} catch (IOException e) {
Toast.makeText(context, "Problem with input output streams", Toast.LENGTH_SHORT).show();
}
description.setText(album.getAlbum_name());
return v;
}
}
------item.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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageHolder"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:layout_weight="1"
app:srcCompat="#drawable/com_facebook_profile_picture_blank_square" />
<TextView
android:layout_width="wrap_content"
android:text="photo"
android:textSize="15sp"
android:id="#+id/albumDesc"
android:layout_below="#+id/imageHolder"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content" />
</RelativeLayout>
------Activity_logged_in.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="ichou.facebooktest.LoggedInActivity">
<LinearLayout
android:id="#+id/intro"
android:layout_width="368dp"
android:layout_height="40dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:orientation="horizontal">
<TextView
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_marginTop="0dp"
android:paddingTop="10dp"
android:text="username"
android:id="#+id/name"/>
<Button
android:layout_width="70dp"
android:layout_height="35dp"
android:text="logout"
android:id="#+id/logout"/>
</LinearLayout>
<GridView
android:layout_below="#+id/intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/myGridView"
android:layout_marginTop="10dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:numColumns="2"
android:columnWidth="150dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
/>
</RelativeLayout>
write your code like in adapter below...
you do wrong line in inflate layout in getView() method
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item,convertView, false);
}
Album album = getItem(position);
ImageView imageView = (ImageView)v.findViewById(R.id.imageHolder);
TextView description = (TextView)v.findViewById(R.id.albumDesc);
try {
imageView.setImageBitmap(BitmapFactory.decodeStream((new URL(album.getAlbum_image())).openConnection().getInputStream()));
} catch (IOException e) {
Toast.makeText(context, "Problem with input output streams", Toast.LENGTH_SHORT).show();
}
description.setText(album.getAlbum_name());
return v;
}
I'm trying to create a list of Card view using a custom adapter. I have defined the layout of a single row of list, consisting a card view and imageview/textviews in it, in a separate .xml file. I'm using a custom srrsy adapter. My app crashes when I try to open the activity having list view , giving only an Runtime-exception error.
Error:
AndroidRuntime(2583): at graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter.getView(PostArrayAdapter.java:44)
This error is at the line
LayoutInflater li =(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
in custom adapter.
Here is single_card_view.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"
android:id="#+id/ll1">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="#+id/ll2">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:id="#+id/imgIcon"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ll3"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SampleTitle1"
android:layout_marginTop="10dp"
android:background="#00b5ad"
android:textSize="20dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/title"
android:textColor="#ffffff"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sampledisription1"
android:layout_marginTop="10dp"
android:background="#ffffff"
android:textSize="10dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/desciption"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Here is PostArrayAdapter.java
package graph.prathya.com.nextstepz.CustomAdapters;
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.ImageView;
import android.widget.TextView;
import graph.prathya.com.nextstepz.R;
/**
* Created by Prathya on 5/23/2015.
*/
public class PostArrayAdapter extends ArrayAdapter<Post>{
Context context;
Post data[] =null;
int layoutid;
public PostArrayAdapter(Context context, int layoutid, Post data[]) {
super(context,layoutid);
this.data=data;
this.layoutid=layoutid;
}
private class PostHolder{
ImageView imgIcon;
TextView title,description;
}
#Override
public int getCount(){
return data.length;
}
#Override
public View getView(int Position, View convertView, ViewGroup parent){
PostHolder holder;
View v = convertView;
if(v==null){
LayoutInflater li = LayoutInflater.from(context);/* RunTimeExceptio error at this line of code */
v= li.inflate(layoutid,parent,false);
holder = new PostHolder();
holder.imgIcon = (ImageView)v.findViewById(R.id.imgIcon);
holder.title = (TextView)v.findViewById(R.id.title);
holder.description= (TextView)v.findViewById(R.id.desciption);
v.setTag(holder);
}
else {
holder = (PostHolder)v.getTag();
}
Post post = data[Position];
holder.imgIcon.setImageResource(post.imgIcon);
holder.title.setText(post.title);
holder.description.setText(post.description);
return v;
}
}
Here is activity in which listView lies: HomeScreenAvtivity.java
package graph.prathya.com.nextstepz;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import graph.prathya.com.nextstepz.Communicator.Communicater1;
import graph.prathya.com.nextstepz.CustomAdapters.Post;
import graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter;
public class HomeScreenActivity extends ActionBarActivity {
ImageButton passionbtn, eventbtn, projectbtn, groupstudybtn;
Dialog dg;
ListView listView = null;
Post post[] =new Post[] {
new Post(R.drawable.img1,"Cats and Children","Cats can be a fascinating experience for children, but young minds can sometimes confuse a pet for a toy. Teach children how to respect and properly handle your cat for best results."),
new Post(R.drawable.img2,"Android:The Best OS","Android powers hundreds of millions of mobile devices in more than 190 countries around the world.Android’s openness has made it a favorite for consumers."),
new Post(R.drawable.img3,"Beautiful","Monica is an Italian actor and model who started her modelling career at the age of 13 by posing for a local photo enthusiast."),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView)findViewById(R.id.homelist);
listView.setAdapter(new PostArrayAdapter(getApplicationContext(),R.layout.single_card_view,post));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == R.id.nxtsignupitem) {
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.eventitem1) {
Intent in = new Intent(getApplicationContext(), PostDetailActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.postitem11) {
dg = new Dialog(HomeScreenActivity.this);
dg.requestWindowFeature(Window.FEATURE_NO_TITLE);
dg.setContentView(R.layout.fragment_new_post_dialogue);
dg.setTitle("Please choose One option");
dg.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dg.show();
passionbtn = (ImageButton) dg.findViewById(R.id.imageButton1st);
eventbtn = (ImageButton) dg.findViewById(R.id.imageButton2);
projectbtn = (ImageButton) dg.findViewById(R.id.imageButton3);
groupstudybtn = (ImageButton) dg.findViewById(R.id.imageButton4);
passionbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(1);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
eventbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(2);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
projectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(3);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
groupstudybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(4);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
}
return super.onOptionsItemSelected(item);}
#Override
public boolean onCreateOptionsMenu(Menu menu){
// TODO Auto-generated method stub
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_home_screen, menu);
return super.onCreateOptionsMenu(menu);
} }
XML layout file of HomeScreenActivity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/lord"
android:layout_marginBottom="20dp"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/homelist">
</ListView>
</LinearLayout>
</ScrollView>
Post.java used in Adapter
package graph.prathya.com.nextstepz.CustomAdapters;
/**
* Created by Prathya on 5/23/2015.
*/
public class Post {
int imgIcon;
String title,description;
public Post(int imgIcon,String title, String description){
this.imgIcon=imgIcon;
this.title=title;
this.description=description;
}
}
you never assign context in your constructor.
add
this.context = context;
to your constructor
I have use the following code for ListView with custom adapter. The Code is Working fine for me,
In ListView there is one checkbox, TextView, ImageView and Button in every ListView Row. Data will fetched Through HttpPost method and assign in every row of listview there is no problem.
I want to get the all the checkbox which is checked in listview, Click on Button of Main Activity.
I have read many article and example but could not get the proper answer these.
Code for : MainActivity.java file which button is clicked and give the Toast as "button is clicked".
package com.example.listviewimageloadingexample;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
Button processedAllBtn;
CheckBox processAll;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
processedAllBtn=(Button) findViewById(R.id.btnProcessedAllAbove);
processedAllBtn.setOnClickListener(this);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
Object obj=(ListViewAdapter)getLastNonConfigurationInstance();
if(obj==null)
{
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
else
{
adapter=(ListViewAdapter)obj;
setListView();
}
}
#Override
public void onClick(View arg0) {
switch(arg0.getId())
{
case R.id.btnProcessedAllAbove:
//Toast.makeText(getApplicationContext(), "button is clicked "+arg0.getId(), Toast.LENGTH_SHORT).show();
break;
}
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("WEBSERVICE_URL");
try {
// Locate the array name in JSON
//jsonarray = jsonobject.getJSONArray("worldpopulation");
jsonarray = jsonobject.getJSONArray("students");
String flag="";
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobject = jsonarray.getJSONObject(i);
JSONObject student_object = jsonobject.getJSONObject("students");
// Retrive JSON Objects
map.put("rank", student_object.getString("id"));
map.put("country", student_object.getString("name"));
map.put("population", student_object.getString("roll_number"));
flag = student_object.getString("student_photo");
flag = flag.replace(" ", "%20");
map.put("flag", "WEBSERVICE_URL"+flag);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
setListView();
// Close the progressdialog
mProgressDialog.dismiss();
}
}
#Override
public Object onRetainNonConfigurationInstance() {
return adapter;
}
public void setListView()
{
if(adapter==null)
{
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
}
// Set the adapter to the ListView
listview.setAdapter(adapter);
}
}
Code for : ListAdapter.java File
package com.example.listviewimageloadingexample;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
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.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
boolean[] itemChecked;
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>> arraylist)
{
super();
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
itemChecked = new boolean[data.size()];
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder
{
TextView rank;
TextView country;
TextView population;
Button processedBtn;
ImageView flag;
CheckBox processedCheckBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view=convertView;
final ViewHolder viewHolder;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(view == null)
{
view = inflater.inflate(R.layout.listview_item, null);
viewHolder= new ViewHolder();
// Locate the TextViews in listview_item.xml
viewHolder.rank = (TextView) view.findViewById(R.id.rank);
viewHolder.country = (TextView) view.findViewById(R.id.country);
viewHolder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
viewHolder.flag = (ImageView) view.findViewById(R.id.flag);
viewHolder.processedBtn = (Button) view.findViewById(R.id.btnProcessed);
viewHolder.processedCheckBox = (CheckBox)view.findViewById(R.id.processedCheckBox);
view.setTag(viewHolder);
}
else
{
viewHolder=(ViewHolder)view.getTag();
}
// Get the position
resultp = data.get(position);
// Capture position and set results to the TextViews
viewHolder.rank.setText(resultp.get(MainActivity.RANK));
viewHolder.country.setText(resultp.get(MainActivity.COUNTRY));
viewHolder.population.setText(resultp.get(MainActivity.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), viewHolder.flag);
viewHolder.processedBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
viewHolder.processedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
itemChecked[position]=(!itemChecked[position]);
viewHolder.processedCheckBox.setChecked(itemChecked[position]);
}
});
return view;
}
}
Code for : listitem.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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/processedCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:saveEnabled="false" />
<ImageView
android:id="#+id/flag"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center_vertical|center_horizontal"
android:padding="5dp"/>
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="id"
android:textStyle="bold"
android:visibility="gone" />
<TextView
android:id="#+id/country"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Name"
android:textStyle="bold" />
<TextView
android:id="#+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Roll_No"
android:textStyle="bold"
android:visibility="gone" />
<Button
android:id="#+id/btnProcessed"
android:layout_width="90dp"
android:layout_height="30dp"
android:textSize="15sp"
android:layout_gravity="center_vertical|center_horizontal"
android:background="#drawable/buttonshape"
android:text="Processed"
android:textColor="#FFFFFF"
android:layout_marginLeft="2dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#000000" />
</LinearLayout>
</LinearLayout>
Code for : listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/checkAllAbove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select All" />
<Button
android:id="#+id/btnProcessedAllAbove"
android:layout_width="90dp"
android:layout_height="30dp"
android:layout_marginLeft="119dp"
android:background="#drawable/buttonshape"
android:text="Processed"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000000" />
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="320dp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000000" />
</LinearLayout>
</ScrollView>
there is a checkbox getTag() method, use this with some logic and you should be fine
see: http://amitandroid.blogspot.in/2013/03/android-listview-with-checkbox-and.html
Take a look on this very good tutorial:
http://www.vogella.com/tutorials/AndroidListView/article.html#listviewselection
It used the setTag() / getTag() functions.
Thanks to everyone.
I Found answer from these Link. Following code get all the objects from listview.
...
#Override
public void onClick(View arg0)
{
CheckBox cb;
for (int x = 0; x <listview.getChildCount();x++)
{
TextView tvRank=(TextView)listview.getChildAt(x).findViewById(R.id.rank);
TextView tvCountry=(TextView)listview.getChildAt(x).findViewById(R.id.country);
TextView tvPopulation=(TextView)listview.getChildAt(x).findViewById(R.id.population);
String rank=tvId.getText().toString();
String country=tvName.getText().toString();
String population=tvRno.getText().toString();
cb = (CheckBox)listview.getChildAt(x).findViewById(R.id.processedCheckBox);
if(cb.isChecked())
{
Toast.makeText(getApplicationContext(),rank+"-"+country+"-"+population, Toast.LENGTH_SHORT).show();
}
}
}
I have code for creating adapter for ListView:
ListView films=(ListView)findViewById(R.id.listViewCurrentFilms);
ArrayList<HashMap<String, String>> list=getList();
String[] fields=new String[]{"title", "director", "cast"};
int[] resources=new int[]{R.id.textViewFilmName, R.id.textViewDirector, R.id.textViewStart};
SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.film_item, fields, resources);
films.setAdapter(adapter);
But I have an ImageView in film_item, and I also need to bind different images from drawable for each item in ListView. How can I do it? Thank you.
this is a working example
import java.io.ByteArrayInputStream;
import java.util.List;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class StockQuoteAdapter extends ArrayAdapter {
private final Activity activity;
private final List stocks;
public StockQuoteAdapter(Activity activity, List objects) {
super(activity, R.layout.movie , objects);
this.activity = activity;
this.stocks = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
StockQuoteView sqView = null;
if(rowView == null)
{
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.stock, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sqView = new StockQuoteView();
sqView.ticker = (TextView) rowView.findViewById(R.id.ticker_symbol);
sqView.quote = (TextView) rowView.findViewById(R.id.ticker_price);
sqView.time = (TextView) rowView.findViewById(R.id.showtimelist);
sqView.img = (ImageView) rowView.findViewById(R.id.Image);
sqView.btn = (Button) rowView.findViewById(R.id.lmbtn);
sqView.ll = (LinearLayout) rowView.findViewById(R.id.LinearLayout02);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sqView);
} else {
sqView = (StockQuoteView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
final StockQuote currentStock = (StockQuote) stocks.get(position);
sqView.ticker.setText(currentStock.getTickerSymbol());
sqView.quote.setText(currentStock.getT_name());
sqView.time.setText(currentStock.getTime());
try{
byte[] bb = currentStock.getBb();
ByteArrayInputStream imageStream = new ByteArrayInputStream(
bb);
Bitmap theImage = BitmapFactory
.decodeStream(imageStream);
Drawable d = new BitmapDrawable(theImage);
sqView.img.setBackgroundDrawable(d);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
sqView.ll.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return rowView;
}
protected static class StockQuoteView {
protected TextView ticker;
protected TextView quote;
protected TextView time;
protected ImageView img;
protected Button btn;
protected LinearLayout ll;
}
}
add to activity
StockQuoteAdapter aa = new StockQuoteAdapter(this, stocks);
the stock.xml is
<?xml version="1.0" encoding="utf-8" ?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:padding="6dip" android:layout_height="match_parent" android:orientation="horizontal">
- <LinearLayout android:id="#+id/LinearLayout02" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<ImageView android:id="#+id/Image" android:layout_height="80px" android:layout_width="60px" android:layout_margin="15px" />
- <LinearLayout android:id="#+id/LinearLayout01" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="#+id/ticker_symbol" android:textColor="#000000" android:textStyle="bold" />
<TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="#+id/ticker_price" android:textColor="#000000" />
<TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:id="#+id/showtimelist" android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
</LinearLayout>