I've a major isse with an adapter to show every single row item in a ListView and I only get the first value of the index position.
I've an array of comments from a webservice in android. It's an array inside an array.
The main JSONArray it's "noticias" with has a lot of the previews jsonobject. Now: "comments" it's another array.
This is my ContenidoNews.java class. I pass the "comment" array in a intent from the previews Activity:
public class ContenidoNews extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
private ActionBar bar;
String tituloDetail;
String fullDetail;
String imagenDetail;
String permalink;
String author;
String authorimg;
String dayofmonth;
String month;
String views;
String totalcomments;
String arraycomments;
private SquareImageView mainPic;
private CircularImageView authorpic;
private TextView authors;
private TextView contentTxt;
private ScrollView scollMain;
private TextView mainTxt;
private Animation animSlideDown;
private RelativeLayout relativeAnim;
private RelativeLayout namereceipt;
private Typeface texto;
private Button btnshare;
// Universal Image Loader
private DisplayImageOptions options;
private ImageLoader il = ImageLoader.getInstance();
private DisplayImageOptions opts;
private File cacheDir;
private String imgauthor;
private TextView tvday;
private TextView tvmonth;
private Typeface textofat;
private LinearLayout datestv;
private WebView webview;
private ArrayList links;
private String urlscap;
private String newstring;
private String copyfull;
private String youtube;
private YouTubePlayerView youTubePlayerView;
private String youtubeb;
private String youtubec;
private String youtubed;
private TextView tvtotal;
private TextView tvvisitas;
private String youtubee;
private String youtubef;
private JSONArray arrayComment;
ArrayList<HashMap<String, String>> arrayofcomments;
private ListView listcomment;
private ListAdapter adapter;
private TextView numbcomment;
private TextView tvcomment;
static String AUTHOR = "comauthor";
static String COMMENT = "comtext";
// Grab URLs from text
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contenido);
bar = getActionBar();
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradiente));
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle("");
webview = (WebView) findViewById(R.id.wvhit);
webview.getSettings().setJavaScriptEnabled(true);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
Intent i = getIntent();
// Get the result of titulo
tituloDetail = i.getStringExtra("titulo").replace("“", "\"").replace("”", "\"").replace("…", "...").replace("–", "-");
// Get the result of full
fullDetail = i.getStringExtra("full");
// Get the result of imagen
imagenDetail = i.getStringExtra("imagen");
// Get the result of permalink
permalink = i.getStringExtra("permalink");
// Get the result of author
author = i.getStringExtra("author");
// Get the result of authorimg
authorimg = i.getStringExtra("authorimg");
int urlimg = authorimg.lastIndexOf("s=128&");
imgauthor = "http://" + authorimg.substring(9, urlimg + 5);
// Get the result of dayofmonth
dayofmonth = i.getStringExtra("dayofmonth");
// Get the result of month
month = i.getStringExtra("month");
// Get the result of views
views = i.getStringExtra("views");
// Get the result of total comments
totalcomments = i.getStringExtra("totalcomments");
// Get the result of array comments
arraycomments = i.getStringExtra("arraycomments");
webview.setWebViewClient(new WebViewClient());
webview.loadUrl(permalink);
pullLinks(fullDetail);
copyfull = fullDetail;
new JSONParser().execute();
texto = Typeface.createFromAsset(this.getAssets(),
"Light.ttf");
textofat = Typeface.createFromAsset(this.getAssets(),
"Bold.ttf");
listcomment = (ListView) findViewById(R.id.listofcomments);
datestv = (LinearLayout) findViewById(R.id.datestv);
tvday = (TextView) findViewById(R.id.tvday);
tvmonth = (TextView) findViewById(R.id.tvmonth);
tvday.setText(dayofmonth);
tvmonth.setText(month);
tvtotal = (TextView) findViewById(R.id.totalvisitas);
tvtotal.setText(views);
tvtotal.setTypeface(textofat);
tvvisitas = (TextView) findViewById(R.id.TVvisitas);
if(views.contentEquals("1")){
tvvisitas.setText("VISITA");
}else{
tvvisitas.setText("VISITAS");
}
tvvisitas.setTypeface(texto);
tvday.setTypeface(textofat);
tvmonth.setTypeface(texto);
mainPic = (SquareImageView) findViewById(R.id.fullimg);
authorpic = (CircularImageView) findViewById(R.id.profile_settings_img);
btnshare = (Button) findViewById(R.id.btnshare);
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
if (scrollView instanceof Parallaxor) {
((Parallaxor) scrollView).parallaxViewBy(mainPic, 0.6f);
}
relativeAnim = (RelativeLayout) findViewById(R.id.animtext);
animSlideDown = AnimationUtils.loadAnimation(getApplicationContext(),
R.animator.slidetodown);
relativeAnim.startAnimation(animSlideDown);
il.displayImage(imagenDetail, mainPic,opts,new ImageLoadingListener() {
#Override
public void onLoadingStarted(String s, View itemView) {
}
#Override
public void onLoadingFailed(String s, View itemView, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View itemView, Bitmap bitmap) {
SquareImageView imageView = (SquareImageView) itemView;
if (bitmap != null) {
FadeInBitmapDisplayer.animate(imageView, 500);
}
}
#Override
public void onLoadingCancelled(String s, View view) {
}
});
il.displayImage(imgauthor, authorpic,opts,new ImageLoadingListener() {
#Override
public void onLoadingStarted(String s, View itemView) {
}
#Override
public void onLoadingFailed(String s, View itemView, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View itemView, Bitmap bitmap) {
CircularImageView imageView = (CircularImageView) itemView;
if (bitmap != null) {
FadeInBitmapDisplayer.animate(imageView, 500);
}
}
#Override
public void onLoadingCancelled(String s, View view) {
}
});
contentTxt = (TextView) findViewById(R.id.textnoti);
if(links.size() != 0 && urlscap.contains("youtu")){
youTubePlayerView.setVisibility(View.VISIBLE);
contentTxt.setText(newstring);
}else{
youTubePlayerView.setVisibility(View.GONE);
contentTxt.setText(fullDetail);
}
authors = (TextView) findViewById(R.id.authors);
authors.setText(author);
authors.setTypeface(texto);
mainTxt = (TextView) findViewById(R.id.tituloreceipt);
mainTxt.setText(tituloDetail);
mainTxt.setTypeface(texto);
namereceipt = (RelativeLayout) findViewById(R.id.namereceipt);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.image);
final Random random = new Random();
//Genrate a random index in the range
int randomInt = random.nextInt(myImages.length());
// Generate the drawableID from the randomInt
int drawableID = myImages.getResourceId(randomInt, -1);
namereceipt.setBackgroundResource(drawableID);
numbcomment = (TextView) findViewById(R.id.numbofcomments);
numbcomment.setText(totalcomments);
tvcomment = (TextView) findViewById(R.id.textforcomments);
if(totalcomments.contentEquals("1")){
tvcomment.setText("COMENTARIO");
}else{
tvcomment.setText("COMENTARIOS");
}
}
My AsyncTask
private class JSONParser extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
arrayofcomments = new ArrayList<HashMap<String, String>>();
arrayComment = new JSONArray(arraycomments);
for(int e = 0; e < arrayComment.length(); e++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject come = arrayComment.getJSONObject(e);
map.put("comauthor", come.getString("comment_author"));
map.put("comtext", come.getString("comment_content"));
arrayofcomments.add(map);
}
} catch (Exception e1) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
adapter = new ListAdapter(getApplicationContext(), arrayofcomments);
listcomment.setAdapter(adapter);
}
}
The result of arrayComment it's:
[
{
"comment_author_url": "http://www.xxxx.com",
"comment_type": "",
"comment_author_IP": "xxxx",
"comment_author": "Mariano xxxx",
"comment_parent": "0",
"comment_agent": "xxxx",
"comment_karma": "0",
"comment_author_email": "xxxx#xxxx.com",
"comment_date": "2014-10-08 17:31:58",
"comment_post_ID": "593",
"comment_ID": "8",
"comment_content": "Prueba",
"user_id": "2",
"comment_date_gmt": "2014-10-08 20:31:58",
"comment_approved": "1"
},
{
"comment_author_url": "",
"comment_type": "",
"comment_author_IP": "xxxx",
"comment_author": "Susana A xxxx",
"comment_parent": "0",
"comment_agent": "xxxx",
"comment_karma": "0",
"comment_author_email": "xxxxxx#yahoo.com.ar",
"comment_date": "2014-10-08 08:28:00",
"comment_post_ID": "593",
"comment_ID": "7",
"comment_content": "una clarísima definición",
"user_id": "0",
"comment_date_gmt": "2014-10-08 11:28:00",
"comment_approved": "1"
}
]
So far so good... now I need to pass all this to my adapter:
public class ListAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
private HashMap<String, String> resultp;
public ListAdapter(Context context,
ArrayList<HashMap<String, String>> d) {
this.context = context;
data = d;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView author;
TextView comment;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.comment_item, parent, false);
resultp = new HashMap<String, String>();
final int pos = position;
resultp = data.get(position);
Log.e("data", data.get(position).toString());
author = (TextView) itemView.findViewById(R.id.tvauthorcomment);
author.setText(resultp.get(ContenidoNews.AUTHOR));
author.setTypeface(textofat);
comment = (TextView) itemView.findViewById(R.id.tvofcomment);
comment.setText(resultp.get(ContenidoNews.COMMENT));
comment.setTypeface(texto);
return itemView;
}
}
The result of Log.e("data full", data.toString()); its:
10-08 22:33:40.564: E/data full(26463): [{comtext=Prueba, comauthor=Mariano xxxx}, {comtext=una clarísima definición, comauthor=Susana A xxxx}]
Which, by the way, prints 7 times in the log... but it has the 2 values as I need.
Now... this it's what Log.e("data", data.get(position).toString()); gives me:
10-08 22:21:11.444: E/data(24618): {comtext=Prueba, comauthor=Mariano xxxx}
And:
author.setText(resultp.get(ContenidoNews.AUTHOR));
comment.setText(resultp.get(ContenidoNews.COMMENT));
In the adapter also only gave me the first value in my listview (comment_item.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="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvauthorcomment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:paddingLeft="20dp"
android:text="Autor Comentario"
android:textColor="#707070"
android:textSize="20sp" />
<TextView
android:id="#+id/tvofcomment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:paddingLeft="30dp"
android:paddingRight="20dp"
android:text="Contenido del comentario"
android:textColor="#707070"
android:textSize="19sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#BBBBBB" />
</LinearLayout>
</LinearLayout>
I can only get the first value... I can't fix this. I'm stock since a lot of hours and nothing. I don't understand what it's the problem. Please, help!
I would thanks any answer in advance!
EDIT: This is my contenido.xml with the scrollview and the listview
<?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/com.renderas.suup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" xmlns:app1="http://schemas.android.com/apk/res/com.mkiisoft.masradio">
<WebView
android:id="#+id/wvhit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<com.mkiisoft.masradio.utils.SquareImageView
android:id="#+id/fullimg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:scaleType="centerCrop" />
<LinearLayout
android:id="#+id/datestv"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:background="#90000000" >
<TextView
android:id="#+id/tvday"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:text="04"
android:textColor="#FFF"
android:textSize="24sp" />
<TextView
android:id="#+id/tvmonth"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Octubre"
android:textColor="#FFF"
android:textSize="24sp" />
</LinearLayout>
<uk.co.chrisjenx.paralloid.views.ParallaxScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="none" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="240dp" >
<FrameLayout
android:id="#+id/imagecontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/namereceipt"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:background="#drawable/bggreenyl" >
<TextView
android:id="#+id/tituloreceipt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top|left"
android:paddingBottom="8dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="8dp"
android:text="Noticia Titulo"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFF"
android:textSize="24sp" />
</RelativeLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/animtext"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/imagecontainer"
android:background="#FFFFFF" >
<com.mkiisoft.masradio.utils.CircularImageView
android:id="#+id/profile_settings_img"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/emptypro" />
<TextView
android:id="#+id/authors"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/profile_settings_img"
android:gravity="center_vertical"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#606060"
android:textSize="21sp" />
<LinearLayout
android:id="#+id/linearviews"
android:layout_width="wrap_content"
android:layout_height="22dp"
android:layout_below="#id/authors"
android:layout_marginLeft="15dp"
android:layout_marginTop="8dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgvisitas"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:layout_marginTop="2dp"
android:alpha="0.7"
android:src="#drawable/eyeviewsblack" />
<TextView
android:id="#+id/totalvisitas"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:text="7"
android:textColor="#606060"
android:textSize="17sp" />
<TextView
android:id="#+id/TVvisitas"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:text="VISITAS"
android:textColor="#606060"
android:textSize="17sp" />
</LinearLayout>
<Button
android:id="#+id/btnshare"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="#id/linearviews"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="12dp"
android:background="#drawable/share_btn"
android:text="COMPARTIR"
android:textColor="#color/checktxt" />
<TextView
android:id="#+id/textnoti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btnshare"
android:paddingBottom="20dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="10dp"
android:text="Texto de la noticia"
android:textColor="#707070"
android:textSize="18sp" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/textnoti"
android:layout_marginBottom="20dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="5dp" />
<LinearLayout
android:id="#+id/linearofcomments"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_below="#id/youtubeplayerview"
android:layout_marginLeft="15dp"
android:gravity="center_vertical|left" >
<TextView
android:id="#+id/numbofcomments"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="0"
android:textColor="#707070"
android:textSize="23sp" />
<TextView
android:id="#+id/textforcomments"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:text="COMENTARIOS"
android:textColor="#707070"
android:textSize="23sp" />
</LinearLayout>
<ListView
android:id="#+id/listofcomments"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#id/linearofcomments"
android:layout_marginBottom="30dp"
android:layout_marginTop="5dp" >
</ListView>
</RelativeLayout>
</RelativeLayout>
</uk.co.chrisjenx.paralloid.views.ParallaxScrollView>
</RelativeLayout>
We shouldn’t use ListView inside the ScrollView because the list view is already ScrollView, the items in list view are already scrollable..
If you use then the list view will show only one item from the adapter.
Check this post ListView inside scrollview for more details...
Related
hello guys i'm back again on a question conserning my final project.
i have made a googlemap app with navigation drawer using activity( no fragment). i think you know about that. then rather than using header and menu, i have use a layout where the header should be so that i can make there a listview to display events all of this is clear.
screenshot
MapActivity :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
DrawerLayout drawerLayout;
LinearLayout drawer_up;
FloatingActionsMenu mainfloating;
FloatingActionButton profile, evennement, historique,reglage,aidesupport;
ImageButton zoomin,zoomout,showtail,zoom_auto,showgeofence,maplayer,drawermenugroit,drawermenugauche;
ProgressDialog progressDialog;
private Dialog mDialog;
private GoogleMap map;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
RelativeLayout nodata_layout;
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
ImageButton map_layer_icon;
private AsyncTask downloadingAsync;
#Bind(R.id.listevent)
ListView listevent;
#Bind(R.id.clearAllEvents)
Button clearAllEvents;
#Bind(R.id.list) ListView list;
#Bind(R.id.nodata_layout) RelativeLayout nodata_layout1;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
Boolean isAllFabsVisible;
RelativeLayout content_layout;
//fin de declaration a garder en tete
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
setContentView(R.layout.activity_map);
//devices elements
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
final String api_key = (String) DataSaver.getInstance(MapActivity.this).load("api_key");
final EventsAdapter adapter = new EventsAdapter(this);
listevent.setAdapter(adapter);
//deviceIdSmallMarkerInfo = new HashMap<>();
//delaration des boutons pour le compte de floatingButton, etc...;
drawermenugroit = findViewById(R.id.drawermenudroit);
drawer_up = findViewById(R.id.drawerup);
drawermenugauche = findViewById(R.id.drawermenugauche);
drawerLayout = findViewById(R.id.drawer);
// profile = findViewById(R.id.profile);
mainfloating = findViewById(R.id.mainFloatingBtn);
evennement = findViewById(R.id.evennements);
historique = findViewById(R.id.historiques);
reglage = findViewById(R.id.reglages);
aidesupport = findViewById(R.id.aide_support);
zoomin = findViewById(R.id.zoom_in);
LinearLayout list_event = findViewById(R.id.list_event);
zoomout = findViewById(R.id.zoom_out);
showtail = findViewById(R.id.showtails);
zoom_auto = findViewById(R.id.autozoom);
listevent = (ListView) findViewById(R.id.listevent);
list = (ListView) findViewById(R.id.list);
showgeofence = findViewById(R.id.geofences);
maplayer = findViewById(R.id.map_layer);
map_layer_icon = (ImageButton) findViewById(R.id.map_layer);
//loading_bar = (ProgressBar) findViewById(R.id.loading_progBar);
content_layout = (RelativeLayout) findViewById(R.id.content_layout);
nodata_layout = (RelativeLayout) findViewById(R.id.nodata_layout);
//fin de declaration de boutons
//chargement des données
progressDialog = new ProgressDialog(this);
progressDialog = new ProgressDialog(MapActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Chargement de la carte"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
// fni de chargement des données
//open drawer and load list data in drawer layout button
drawermenugauche.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDrawer(drawerLayout);
API.getApiInterface(MapActivity.this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
#Override
public void success(ApiInterface.GetEventsResult result, Response response) {
adapter.setArray(result.items.data);
if(result.items.data.size() != 0)
listevent.setVisibility(View.VISIBLE);
else
nodata_layout1.setVisibility(View.VISIBLE);
listevent.setVisibility(View.GONE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
});
drawer_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeDrawer(drawerLayout);
}
});
zoomin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomIn());
}
});
zoomout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomOut());
}
});
zoom_auto.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
isAutoZoomEnabled = !isAutoZoomEnabled;
if (isAutoZoomEnabled)
{
zoom_auto.setImageResource(R.drawable.icon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Activé", Toast.LENGTH_SHORT).show();
} else
{
zoom_auto.setImageResource(R.drawable.disableicon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Désactivé", Toast.LENGTH_SHORT).show();
}
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// ouverture et fermeture de drawer
private static void openDrawer(DrawerLayout drawerLayout){
drawerLayout.openDrawer(GravityCompat.START);
}
private static void closeDrawer(DrawerLayout drawerLayout){
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
//fin ouverture et fermeture drawer
......etc...
see my EventsAdapter code below:
public class EventsAdapter extends AwesomeAdapter<Event> {
public EventsAdapter(Context context) {
super(context);
}
ArrayList<Event> original;
#Override
public void setArray(ArrayList<Event> array) {
super.setArray(array);
if(original == null)
original = array;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
Event item = getItem(position);
TextView device_name = (TextView) convertView.findViewById(R.id.device_name);
device_name.setText(item.device_name);
TextView date = (TextView) convertView.findViewById(R.id.date);
date.setText(item.time);
TextView message = (TextView) convertView.findViewById(R.id.message);
message.setText(item.message);
TextView geofence_name = (TextView) convertView.findViewById(R.id.geofence_name);
geofence_name.setText(item.geofence_name);
return convertView;
}
ItemFilter mFilter = new ItemFilter();
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint)
{
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final ArrayList<Event> nlist = new ArrayList<>();
for(Event item : original)
{
if(item.fitForFilter(filterString))
nlist.add(item);
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
setArray((ArrayList<Event>) results.values);
notifyDataSetChanged();
}
}
}
then in my adapter_event layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/whitesplash"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/instance"
android:layout_width="16dp"
android:layout_height="22dp"
android:src="#drawable/custom_floating_button" />
<TextView
android:id="#+id/device_nam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="Info Balise"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/device_nam"
android:outlineAmbientShadowColor="#color/blue" />
<TextView
android:id="#+id/device_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_nam"
android:layout_marginStart="16dp"
android:fontFamily="#font/fjallaoneregular"
android:text="device name"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/textspeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_nam"
android:fontFamily="#font/fjallaoneregular"
android:text="Vitesse"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_name"
android:fontFamily="#font/fjallaoneregular"
android:text="speed"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/message1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_toRightOf="#+id/textspeed"
android:fontFamily="#font/fjallaoneregular"
android:text="message"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/speed"
android:fontFamily="#font/fjallaoneregular"
android:text="massage"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<View
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name" />
<TextView
android:id="#+id/datetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="date:"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/datetext"
android:fontFamily="#font/fjallaoneregular"
android:text="date"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<TextView
android:id="#+id/geofence_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="geofence_name"
android:fontFamily="#font/lobsterregular"
android:layout_below="#+id/date"
android:layout_marginStart="3dp"
android:layout_toRightOf="#+id/instance"
android:textSize="8dp"
android:textColor="#color/blue"/>
</RelativeLayout>
in this adpater_events i have found no mistake. and in the drawer_tracesas i said before( i am not using menu and header in navigationDrawer i would like to use a layout that i called drawer_traces) like below
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/drawerup"
android:orientation="horizontal"
android:background="#color/blue">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/objects"
android:src="#drawable/ic_menu_24"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:text="#string/objects" />
</LinearLayout>
<TextView
android:id="#+id/Liste_Balises"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/drawerup"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_balises"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_balises"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
android:layout_below="#+id/Liste_Balises"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<TextView
android:id="#+id/list_events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_balises"
android:layout_marginTop="10dp"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_evennemT"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_event"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#+id/list_events"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/listevent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<RelativeLayout
android:id="#+id/nodata_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/list_event"
android:layout_above="#+id/clearAllEvents"
android:background="#ffffff"
android:visibility="gone"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/noEventsData"/>
</RelativeLayout>
<Button
android:id="#+id/clearAllEvents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_event"
android:fontFamily="#font/fjallaoneregular"
android:text="Effacer Evennements"/>
</RelativeLayout>
this layout (drawer_trace) will be displayed in mapActivity as a navigation Drawer. we are ok for that.
and then i have my Events Model:
public class Event
{
public int id, user_id, device_id, position_id, alert_id;
// geofence_id
public String message;
public String address;
public float altitude;
// course
public float latitude, longitude;
// power
public float speed;
public String time;
// deleted
public String device_name, geofence_name;
public boolean fitForFilter(String filterString) {
if(message.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(address.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(time.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(device_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(geofence_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
return false;
}
i am using REST API in backend and retrofit.
everything is ok untill i try to eun the app.
it says ERROR MESSAGE:
Process: com.gabontech.gprstest, PID: 14460
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabontech.gprstest/com.gabontech.gprstest.activities.MapActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3433)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3572)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2097)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7663)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.gabontech.gprstest.activities.MapActivity.onCreate(MapActivity.java:139)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
i think about the adapter where in EventsAdapter.class line ref:::::
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
ihave spent two days there. please if you can help it will give me a hand for my exam. Thank so much guys
So I am displaying a recylerview with an Image and the name of a person. Below that is a seekbar, which the user can move to rate that person.
Now I want to store the ratings (=progress) of each seekbar in a list. However right now it only stores the rating of the last seekbar in the list.
So it stores only the progress of the last seekbar right now. I would like that when the user clicks the button that every current rating value of every seekbar is stored in a list.
Thank you very much.
That is is my layout_listitem:
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:id="#+id/parent_layoutREC"
android:orientation="horizontal"
android:layout_marginTop="13dp"
android:gravity="center">
<de.hdodenhof.circleimageview.CircleImageView
android:paddingTop="2dp"
android:paddingLeft="2dp"
android:layout_width="73dp"
android:layout_height="73dp"
android:id="#+id/kunde_imageREC"
android:src="#mipmap/ic_launcher"/>
<TextView
android:layout_marginLeft="40dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Canada"
android:id="#+id/kunde_nameREC"
android:textColor="#000"
android:textSize="19sp"
android:textStyle="bold"/>
</LinearLayout>
<SeekBar
android:layout_marginRight="35dp"
android:layout_marginLeft="35dp"
android:layout_marginTop="8dp"
android:id="#+id/seek_Bar"
android:max="10"
android:progress="5"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0 1 2 3 4 5"
android:textSize="20sp"/>
That is my RecyclerViewAdapter class:
public class RecyclerViewAdap extends
RecyclerView.Adapter<RecyclerViewAdap.ViewHolder> {
private static final String TAG = "RecyclerViewAdap";
private ArrayList<String> mImageUrl = new ArrayList<>();
private ArrayList<String> mKundeNamen = new ArrayList<>();
public ArrayList<Integer> mBewertungen = new ArrayList<>();
private Context mContext;
public String bewertung;
private TextView progressSeekbar;
public RecyclerViewAdap(ArrayList<String> imageUrl, ArrayList<String> kundeNamen, Context context) {
mImageUrl = imageUrl;
mKundeNamen = kundeNamen;
mContext = context;
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView imageView;
TextView kundeName;
LinearLayout parentLayout;
SeekBar seekBar1;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.kunde_imageREC);
kundeName = itemView.findViewById(R.id.kunde_nameREC);
parentLayout = itemView.findViewById(R.id.parent_layoutREC);
seekBar1 = itemView.findViewById(R.id.seek_Bar);
progressSeekbar = itemView.findViewById(R.id.progress_seekbar);
seekBar1.setOnSeekBarChangeListener(seekBarChangeListener);
//int progress = seekBar1.getProgress();
//String.valueOf(Math.abs((long)progress)).charAt(0);
//progressSeekbar.setText("Bewertung: " +
// String.valueOf(Math.abs((long)progress)).charAt(0) + "." + String.valueOf(Math.abs((long)progress)).charAt(1));
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder = new ViewHolder(view);
Log.d(TAG, "onCreateViewHolder: ");
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Glide.with(mContext)
.load(mImageUrl.get(position))
.into(holder.imageView);
holder.kundeName.setText(mKundeNamen.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, mKundeNamen.get(position),
Toast.LENGTH_SHORT).show();
}
});
holder.seekBar1.setTag(position);
}
#Override
public int getItemCount() {
return mImageUrl.size();
}
SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// updated continuously as the user slides the thumb
progressSeekbar.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// called when the user first touches the SeekBar
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// called after the user finishes moving the SeekBar
if (seekBar.getTag().toString().equals("1")) {
mBewertungen.add(seekBar.getProgress());
if (mBewertungen.size() == 2) {
mBewertungen.remove(0);
Toast.makeText(mContext, "onProgressChanged: " + mBewertungen.toString(), Toast.LENGTH_SHORT).show();
}
}
if (seekBar.getTag().toString().equals("2")) {
mBewertungen.add(seekBar.getProgress());
if (mBewertungen.size() == 3) {
mBewertungen.remove(1);
Toast.makeText(mContext, "onProgressChanged: " + mBewertungen.toString(), Toast.LENGTH_SHORT).show();
}
}
}
};
}
That is the activity where the Recyclerview is being displayed:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BewertungEsserActvity"
android:orientation="vertical"
app:layoutManager="LinearLayoutManager"
android:background="#drawable/gradient_background">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="14dp"
android:text="Bewerte deine Gäste"
android:textColor="#color/colorDarkGrey"
android:textSize="30sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorBlack"
android:layout_marginBottom="10dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view">
</androidx.recyclerview.widget.RecyclerView>
<ProgressBar
android:visibility="invisible"
android:id="#+id/progressbar_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="13dp" />
<Button
android:layout_marginRight="66dp"
android:layout_marginLeft="66dp"
android:id="#+id/bewerten_Btn"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_marginTop="10dp"
android:background="#drawable/btn_background_profil"
android:padding="10dp"
android:text="Bewerten"
android:textAllCaps="false"
android:textColor="#color/colorWhite"
android:textSize="16sp"
android:textStyle="normal" />
<View
android:layout_marginBottom="10dp"
android:layout_marginTop="34dp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#color/colorBlack" />
</LinearLayout>
</ScrollView>
You can do it in multiple ways:
1- You can store seekbars value as a property in your model and update that property on OnSeekBarChangeListener and when the user hits the button get the data source from the adapter and then run a loop on it and call getter of that attribute.
2- You can store seekbars value as a List<> in your adapter and whenever the user hits the button get the list from the adapter.
I want to fit widget CardView to all kinds of screens,and my layout is embed CardViewin RecycleView, I add setLayoutParams() in ViewHolder,but after it,my content in CardViewdoes not show,I don't know how to deal with it,Hope somebody could help me.Here is my code:
cardview.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cv_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground">
<LinearLayout
android:id="#+id/layoutView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="20dp" />
<TextView
android:id="#+id/texttitle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="#color/black"
android:textSize="25dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="9dp" />
<TextView
android:id="#+id/textcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="#color/black" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="20dp" />
<View
android:id="#+id/colorfulview"
android:layout_width="20dp"
android:layout_height="5dp"
android:layout_gravity="center_horizontal"
android:background="#color/black"></View>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="18dp" />
</LinearLayout>
and my adapter.java:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.TextViewHolder> {
private final LayoutInflater mLayoutInflater;
private final Context mContext;
private int mScreenHeight, mScreenWidth;
private String[] mTitles;
private String[] mContents;
private int[] mColors = {R.color.qing, R.color.zi, R.color.fenhong, R.color.juhuang, R.color.qianzi, R.color.lan};
public RecyclerViewAdapter(Context context, int screenHeight, int screenWidth) {
mTitles = context.getResources().getStringArray(R.array.titles);
mContents = context.getResources().getStringArray(R.array.contents);
mContext = context;
mLayoutInflater = LayoutInflater.from(context);
mScreenHeight = screenHeight;
mScreenWidth = screenWidth;
}
#Override
public TextViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new TextViewHolder(mLayoutInflater.inflate(R.layout.item_main_recycler, parent, false));
}
#Override
public void onBindViewHolder(TextViewHolder holder, int position) {
holder.mTextTitle.setText(mTitles[position]);
holder.mTextContent.setText(mContents[position]);
holder.mColorfulView.setBackgroundResource(mColors[position]);
holder.mLayoutView.setLayoutParams(new CardView.LayoutParams(mScreenWidth / 2, (int) (mScreenHeight * 0.24)));
}
#Override
public int getItemCount() {
return mTitles == null ? 0 : mTitles.length;
}
public static class TextViewHolder extends RecyclerView.ViewHolder {
#InjectView(R.id.texttitle)
TextView mTextTitle;
#InjectView(R.id.textcontent)
TextView mTextContent;
#InjectView(R.id.colorfulview)
View mColorfulView;
#InjectView(R.id.layoutView)
LinearLayout mLayoutView;
TextViewHolder(View view) {
super(view);
ButterKnife.inject(this, view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("NormalTextViewHolder", "onClick--> position = " + getPosition());
}
});
}
}
}
try this in onCreateViewHolder:
View itemView = mLayoutInflater.inflate(R.layout.view_item, parent, false);
int height = screenWidth/2;
int width = screenHeight*24/100;
itemView.setMinimumHeight(height);
itemView.setMinimumWidth(width );
return new TextViewHolder(itemView);
Try to do the following:
LayoutParams params = holder.itemView.getLayoutParams();
params.height = screenWidth/2;
params.width = screenHeight*24/100;
holder.itemView.setLayoutParams(params);
Here is my code so far based on various answers to related questions on SO.
In my Activity
GridView gv = (GridView) findViewById(R.id.gridView1);
MyCustomAdapter mAdapter = new MyCustomAdapter();
mAdapter.addItem("Action1");
mAdapter.addItem("Action2");
mAdapter.addItem("Action3");
gv.setAdapter(mAdapter);
My Adapter
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
NumericViewHolder holder = new NumericViewHolder();
if (convertView == null) {
convertView = mInflater.inflate(R.layout.horizontalnumberpicker, null);
holder.textView = (TextView)convertView.findViewById(R.id.txtNPTitle);
holder.minus = (Button)convertView.findViewById(R.id.btnMinus);
holder.plus = (Button)convertView.findViewById(R.id.btnPlus);
holder.value = (TextView)convertView.findViewById(R.id.txtNPValue);
holder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString());
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
if (value > 0) {
value = value - 1;
tv.setText(Integer.toString(value));
}
}
});
holder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
int value = Integer.parseInt(tv.getText().toString()); <--Error is here
Toast.makeText(getApplicationContext(), Integer.toString(value), Toast.LENGTH_SHORT).show();
value = value + 1;
tv.setText(Integer.toString(value));
}
});
convertView.setTag(holder);
} else {
holder = (NumericViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
XML - Main_Activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rlAddProduct"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/btnSaveProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:text="#string/Save" />
<TextView
android:id="#+id/lblSelectCategory"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/btnSaveProduct"
android:layout_alignBottom="#+id/btnSaveProduct"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="20dp"
android:layout_marginStart="20dp"
android:text="#string/selectCategory" />
<Spinner
android:id="#+id/spCategory"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignBottom="#+id/lblSelectCategory"
android:layout_marginLeft="33dp"
android:layout_marginStart="33dp"
android:layout_toEndOf="#+id/lblSelectCategory"
android:layout_toRightOf="#+id/lblSelectCategory" />
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/lblSelectCategory"
android:layout_below="#+id/btnSaveProduct"
android:layout_marginTop="14dp"
android:numColumns="auto_fit" >
</GridView>
</RelativeLayout>
XML - Horizontalnumberpicker
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtNPTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="EnterTextHere"
android:layout_marginTop="5dp" />
<Button
android:id="#+id/btnPlus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/txtNPValue"
android:layout_alignBottom="#+id/txtNPValue"
android:layout_toRightOf="#+id/txtNPValue"
android:text="+" />
<TextView
android:id="#+id/txtNPValue"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/btnMinus"
android:layout_toRightOf="#+id/btnMinus"
android:gravity="center"
android:text="0"
android:textAppearance="#style/AppBaseTheme"
android:textSize="20dp" />
<Button
android:id="#+id/btnMinus"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtNPTitle"
android:layout_marginTop="2dp"
android:text="-" />
</RelativeLayout>
The requirement is that when I press the plus button, I need to increment the value in the corresponding txtNPValue. Similarly with the minus button, I need to decrement the value in the txtNPValue.
The error is
01-31 22:40:10.854: E/AndroidRuntime(32198): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
Also I do not know if this is the right way to program such a requirement and would like some pointers.
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
this will return null pointer exception, as the view that u r getting is of the button or the clicked item..
Use this :-
RelativeLayout rlLayout = (RelativeLayout) v.getParent();
TextView tv = (TextView) rlLayout.findViewById(R.id.txtNPValue);
please remove:
TextView tv = (TextView) v.findViewById(R.id.txtNPValue);
from onClick to resolve nullpointerException
Following some tutorials, I managed to make a custom list.
But the whole screen is just a list
And now want to put the list below the form. And to make the whole screen make scroll along with the list (see the last item in the list, the form needs to rise)
The log (Toasty) says that the item was added, but nothing appears. I do not know if the problem is in how I add, or is the way I try to display
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:fillViewport="true"
android:padding="5dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/cliente" />
<EditText
android:id="#+id/venda_form_cliente"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_cliente" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/produto" />
<EditText
android:id="#+id/venda_form_prod"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:cursorVisible="false"
android:focusable="false"
android:hint="#string/selecione_um_produto" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/quantidade" />
<EditText
android:id="#+id/venda_form_qtd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/um" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/valor" />
<EditText
android:id="#+id/venda_form_valor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/desconto" />
<EditText
android:id="#+id/venda_form_desc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:selectAllOnFocus="true"
android:text="#string/zero" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/subtotal" />
<EditText
android:id="#+id/venda_form_subtotal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:focusable="false"
android:inputType="none" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/venda_form_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="#string/adicionar" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:scrollbars="none" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
And my activity
public class VendaFormActivity extends Activity {
private Cliente cliente;
// private Spinner condicaoSelect;
private Produto produto;
private TextWatcher somar;
private ItemVenda itemVenda;
private ListaAdapter listaAdapter;
private EditText inputQuantidade;
private EditText inputDesconto;
private EditText inputSubTotal;
private EditText inputProduto;
private EditText inputValor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_venda_form);
inputProduto = ((EditText) findViewById(R.id.venda_form_prod));
inputValor = ((EditText) findViewById(R.id.venda_form_valor));
((EditText) findViewById(R.id.venda_form_cliente)).setOnClickListener(new ClickListener(this, ClienteActivity.class, MainActivity.REQUEST_CLIENTE));
inputProduto.setOnClickListener(new ClickListener(this, ProdutoActivity.class, MainActivity.REQUEST_PRODUTO));
//condicaoSelect = (Spinner) findViewById(R.id.venda_form_condicao);
//new CondicaoHelper(this).popular(condicaoSelect);
bindCamposValores();
fazerLista();
bindBtnAdd();
}
private void limparCamposValores() {
inputDesconto.setText("0.00");
inputQuantidade.setText("1");
inputSubTotal.getText().clear();
inputProduto.getText().clear();
}
private void bindBtnAdd() {
((Button) findViewById(R.id.venda_form_btn)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
Double quantidade = Double.parseDouble( inputQuantidade.getText().toString() );
Double desconto = Double.parseDouble( inputDesconto.getText().toString() );
itemVenda = new ItemVenda();
itemVenda.setDesconto(desconto);
itemVenda.setProduto(produto);
itemVenda.setQuantidade(quantidade);
listaAdapter.setNotifyOnChange(true);
listaAdapter.getItens().add(itemVenda);
listaAdapter.notifyDataSetChanged();
Toast.makeText(getApplication(), "Foi", Toast.LENGTH_SHORT).show();
limparCamposValores();
} catch (Exception e) {
Toast.makeText(getApplication(), "Invalido", Toast.LENGTH_SHORT).show();
// NPE no produto
// NumberFormat nos valores
}
}
});
}
private void fazerLista() {
listaAdapter = new ListaAdapter(getApplicationContext());
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
}
static class ViewHolder {
protected TextView descricao;
protected TextView codigo;
protected TextView ean;
protected TextView referencia;
protected TextView quantidade;
protected TextView valor_unit;
protected TextView valor_item;
}
private class ListaAdapter extends ArrayAdapter<ItemVenda>{
private final Context context;
private final List<ItemVenda> itens;
public ListaAdapter(Context context) {
super(context, R.layout.produto_list);
this.context = context;
this.itens = new LinkedList<ItemVenda>();
}
public ListaAdapter(Context context, List<ItemVenda> itens) {
super(context, R.layout.produto_list, itens);
this.context = context;
this.itens = itens;
}
public List<ItemVenda> getItens() {
return itens;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.produto_list_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.descricao = (TextView) view.findViewById(R.id.descricao);
viewHolder.codigo = (TextView) view.findViewById(R.id.codigo);
viewHolder.ean = (TextView) view.findViewById(R.id.ean);
viewHolder.referencia = (TextView) view.findViewById(R.id.referencia);
viewHolder.quantidade = (TextView) view.findViewById(R.id.quantidade);
viewHolder.valor_unit = (TextView) view.findViewById(R.id.valor_unit);
viewHolder.valor_item = (TextView) view.findViewById(R.id.valor_item);
view.setTag(viewHolder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
ItemVenda item = itens.get(position);
holder.descricao.setText(item.getProduto().getNome());
holder.codigo.setText(item.getProduto().getCodigo());
holder.ean.setText(item.getProduto().getEan());
holder.referencia.setText(item.getProduto().getReferencia());
holder.quantidade.setText(item.getQuantidade().toString());
holder.valor_unit.setText(item.getProduto().getPreco().toString());
holder.valor_item.setText(item.getSubTotal().toString());
return view;
}
}
private void bindCamposValores() {
inputQuantidade = ((EditText) findViewById(R.id.venda_form_qtd));
inputDesconto = ((EditText) findViewById(R.id.venda_form_desc));
inputSubTotal = ((EditText) findViewById(R.id.venda_form_subtotal));
somar = new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
#Override
public void afterTextChanged(Editable arg0) {
Double sub = 0.0;
try{
itemVenda = new ItemVenda();
itemVenda.setQuantidade(Double.parseDouble(inputQuantidade.getText().toString()));
itemVenda.setDesconto(Double.parseDouble(inputDesconto.getText().toString()));
itemVenda.setProduto(produto);
sub = itemVenda.getSubTotal();
} catch (Exception e) {
// algum campo não é numero/está vazio
}
inputSubTotal.setText(""+sub);
}
};
// Se mudar o valor
inputQuantidade.addTextChangedListener(somar);
inputDesconto.addTextChangedListener(somar);
// quando sair do campo
inputQuantidade.setOnFocusChangeListener(new Focus("1"));
inputDesconto.setOnFocusChangeListener(new Focus("0.00"));
}
private class Focus implements OnFocusChangeListener {
private final String padrao;
public Focus(String padrao){
this.padrao = padrao;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus){
Editable text = ((EditText) v).getText();
if(null == text || "".equals(text.toString())){
text.append(padrao);
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_venda_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_copiar:
copiar();
return true;
case R.id.menu_simulacao:
simulacao();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void copiar() {
Toast.makeText(getApplication(), "Nada ainda", Toast.LENGTH_SHORT).show();
}
private void simulacao() {
Intent intent = new Intent(getApplicationContext(), SimulacaoPagtoActivity.class);
startActivityForResult(intent, MainActivity.REQUEST_SIMULACAO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == MainActivity.REQUEST_CLIENTE) {
if (resultCode == RESULT_OK) {
cliente = (Cliente) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
((EditText) findViewById(R.id.venda_form_cliente)).setText(cliente.getNome());
}
} else if (requestCode == MainActivity.REQUEST_PRODUTO) {
if (resultCode == RESULT_OK) {
produto = (Produto) intent.getSerializableExtra(MainActivity.RESULT_MODEL_LIST);
inputProduto.setText(produto.getNome());
inputValor.setText(""+produto.getPreco());
somar.afterTextChanged(null);
}
} else if(requestCode == MainActivity.REQUEST_SIMULACAO){
// o que fazer quando voltar da simulação ?
}
}
}
Finally, my item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/descricao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#333"
android:textSize="16sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/codigo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="CODIGO" />
<TextView
android:id="#+id/ean"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="EAN" />
<TextView
android:id="#+id/referencia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="REFERENCIA" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantidade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="QUANT." />
<TextView
android:id="#+id/valor_unit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR UNIT" />
<TextView
android:id="#+id/valor_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="VLR ITEM" />
</LinearLayout>
</LinearLayout>
UPDATE
When I add an item in the list, nothing is shown. But after I click a TextEdit, and the virtual keyboard up, after typing some value, I close the keyboard, then the adapter.getView () is called and the list appears
I think I found your problem. Shouldn't the following code:
((ListView) findViewById(android.R.id.list)).setAdapter(listaAdapter);
Be:
((ListView) findViewById(R.id.list)).setAdapter(listaAdapter);
instead?
You are trying to find a default Android view, rather than the view that you have created, which means that you are not actually setting the adapter for your ListView.
I am not sure about that, but if you want the list to be scrollable with the activity, you should use ScrollView, and then check if you scroll the list or the view itself. Try it
You can also try to see with debugger if the item was actually added to the list. I hope you will find an error.
Found the solution
1) The adapter have 2 constructors, but just 1 with List<ItemVenda> itens, and it isn't called.
I fixed it.
2) To add an item on the list, I need to call adapter.add() and not adapter.getItens().add()`. I think this trigger others methods.
3) Finally, to take the scroll list, and apply the scroll across the screen, I need to increase the size of the list. Then I override the method adapter.add(), and calculate the new height of the list, and add android:scrollbars="none" on ListView
Thanks to all, especially to #Marek