Android - Expandable list view - child data - java

I have small application written in android. I have tried to implement ExpandableListView into my main layout, but child data do not exists. Collapse works fine but, no data provided.
I have run debugger and see that my list have data.
Here is my code:
main layout - activity_post_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_post_details"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="hedza.com.durmitortourism.PostDetailsActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:gravity="center"
android:id="#+id/postDetailsTitleText"
android:textSize="32dp"
android:textStyle="bold"
android:textAlignment="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:textSize="16dp"
android:layout_marginTop="18dp"
android:id="#+id/postDescText" />
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:id="#+id/ExplistDetails"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/postGalleryBtn"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="20dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/postLocationBtn"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="20dp"
/>
</RelativeLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
group_item - expandable_list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/listTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textColor="#android:color/black"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
</LinearLayout>
expandable_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/expandedListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:paddingTop="10dp"
android:textColor="#000000"
android:textSize="16dp"
android:paddingBottom="10dp" />
</LinearLayout>
ExpandableListAdapter.class
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<String>> expandableListDetail;
public ExpandableListAdapter(Context context, List<String> expandableListTitle,
HashMap<String, List<String>> expandableListDetail)
{
this.context = context;
this.expandableListTitle = expandableListTitle;
this.expandableListDetail = expandableListDetail;
}
#Override
public Object getChild(int listPosition, int expandedListPosition)
{
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.get(expandedListPosition);
}
#Override
public long getChildId(int listPosition, int expandedListPosition) {
return expandedListPosition;
}
#Override
public View getChildView(int listPosition, final int expandedListPosition,
boolean isLastChild, View convertView, ViewGroup parent)
{
final String expandedListText = (String) getChild(listPosition, expandedListPosition);
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.expandable_list_item, null);
}
TextView expandedListTextView = (TextView) convertView
.findViewById(R.id.expandedListItem);
expandedListTextView.setText(expandedListText);
return convertView;
}
#Override
public int getChildrenCount(int listPosition) {
return this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.size();
}
#Override
public Object getGroup(int listPosition) {
return this.expandableListTitle.get(listPosition);
}
#Override
public int getGroupCount() {
return this.expandableListTitle.size();
}
#Override
public long getGroupId(int listPosition) {
return listPosition;
}
#Override
public View getGroupView(int listPosition, boolean isExpanded,
View convertView, ViewGroup parent)
{
String listTitle = (String) getGroup(listPosition);
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.expandable_list_group, null);
}
TextView listTitleTextView = (TextView) convertView
.findViewById(R.id.listTitle);
listTitleTextView.setTypeface(null, Typeface.BOLD);
listTitleTextView.setText(listTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int listPosition, int expandedListPosition) {
return true;
}
}
PostDetailsActivity.class
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PostDetailsActivity extends AppCompatActivity {
SharedPreferences languageSharedPreferences;
private TextView postTitleTextView;
private TextView postDescTextView;
private ExpandableListView expandableListView;
private ExpandableListAdapter expandableListAdapter;
private List<String> detailsList;
private HashMap<String, List<String>> expandableListDetail;
private Button galleryBtn;
private Button locationBtn;
String locationJSON = null;
String title = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_details);
// setting icon in the action bar
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
// get postID from post activity bundle
Intent intent = getIntent();
String postID = intent.getStringExtra("postID");
// getting language from shared preferences
languageSharedPreferences = getSharedPreferences("LanguagePreferences",
Context.MODE_PRIVATE);
String language = languageSharedPreferences.getString("lang", "me");
final ArrayList<String> viewPagerImages = new ArrayList<>();
// expandable list details initialization
detailsList = new ArrayList<String>();
expandableListDetail = new HashMap<String, List<String>>();
// initialize elements
postTitleTextView = (TextView) findViewById(R.id.postDetailsTitleText);
postDescTextView = (TextView) findViewById(R.id.postDescText);
expandableListView = (ExpandableListView) findViewById(R.id.ExplistDetails);
galleryBtn = (Button) findViewById(R.id.postGalleryBtn);
locationBtn = (Button) findViewById(R.id.postLocationBtn);
// get data from DB by post id
final PostSQLiteManager postObject = new PostSQLiteManager(getApplicationContext());
postObject.openConnection();
JSONObject posts = postObject.getPostsById(postID);
postObject.close();
try
{
JSONArray array = posts.getJSONArray("DATA");
JSONObject arrayObject = array.getJSONObject(0);
String[] images = arrayObject.getString("IMAGES").split(",");
for(int i = 0; i < images.length; i++){
viewPagerImages.add(images[i]);
}
title = arrayObject.getString("TITLE");
// set properties values
postTitleTextView.setText(arrayObject.getString("TITLE"));
postDescTextView.setText(arrayObject.getString("DESC"));
String postWebsite = arrayObject.getString("WEBSITE");
String postEmail = arrayObject.getString("EMAIL");
String postTelephone = arrayObject.getString("TELEPHONE");
locationJSON = arrayObject.getString("LOCATION");
// handling languages
if(language.contentEquals("me"))
{
detailsList.add("Web Stranica: "+postWebsite);
detailsList.add("Telefon: "+postTelephone);
detailsList.add("E-pošta: "+postEmail);
expandableListDetail.put("Detalji", detailsList);
galleryBtn.setText(R.string.galleryPostME);
locationBtn.setText(R.string.locationPostME);
}
else
{
detailsList.add("Website: "+postWebsite);
detailsList.add("Telephone: "+postTelephone);
detailsList.add("E-mail: "+postEmail);
expandableListDetail.put("Details", detailsList);
galleryBtn.setText(R.string.galleryPostEN);
locationBtn.setText(R.string.locationPostEN);
}
final List<String> listTitles = new ArrayList<>(expandableListDetail.keySet());
// generate list
expandableListAdapter = new ExpandableListAdapter(this, listTitles,
expandableListDetail);
expandableListView.setAdapter(expandableListAdapter);
// click on gallery button
galleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!viewPagerImages.isEmpty()){
Intent galleryIntent = new Intent(getApplicationContext(), GalleryActivity.class);
galleryIntent.putStringArrayListExtra("images", viewPagerImages);
startActivity(galleryIntent);
}else{
Toast.makeText(getApplicationContext(), "Nema slika", Toast.LENGTH_SHORT)
.show();
}
}
});
// click on location button
locationBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent locationIntent = new Intent(getApplicationContext(), MapActivity.class);
locationIntent.putExtra("location", locationJSON);
locationIntent.putExtra("title", title);
startActivity(locationIntent);
}
});
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listTitles.get(groupPosition) + " List Expanded.",
Toast.LENGTH_SHORT).show();
}
});
}
catch(JSONException exception) {
exception.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
super.onCreateOptionsMenu(menu);
languageSharedPreferences = getSharedPreferences("LanguagePreferences",
Context.MODE_PRIVATE);
String language = languageSharedPreferences.getString("lang", "me");
// generate menu and its items
MenuInflater myMenu = getMenuInflater();
myMenu.inflate(R.menu.menu_layout, menu);
// change menu items depending on selected language
switch(language)
{
case "me":
menu.findItem(R.id.languageID).setTitle(R.string.languageME);
menu.findItem(R.id.aboutID).setTitle(R.string.aboutME);
menu.findItem(R.id.sponsorID).setTitle(R.string.sponsorME);
break;
case "en":
menu.findItem(R.id.languageID).setTitle(R.string.languageEN);
menu.findItem(R.id.aboutID).setTitle(R.string.aboutEN);
menu.findItem(R.id.sponsorID).setTitle(R.string.sponsorEN);
break;
default:
menu.findItem(R.id.languageID).setTitle(R.string.languageME);
menu.findItem(R.id.aboutID).setTitle(R.string.aboutME);
menu.findItem(R.id.sponsorID).setTitle(R.string.sponsorME);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.languageID:
Intent languageIntent = new Intent(getApplicationContext(), LanguageActivity.class);
startActivity(languageIntent);
return true;
case R.id.aboutID:
Intent aboutIntent = new Intent(getApplicationContext(), AboutActivity.class);
startActivity(aboutIntent);
return true;
case R.id.sponsorID:
Intent sponsorIntent = new Intent(getApplicationContext(), SponsorActivity.class);
startActivity(sponsorIntent);
default:
return true;
}
}
}
Does anyone have an idea what's wrong here?
Thank you in advance.

Related

Clickable element of ListView with gridView inside (Android)

I want to make listView element clickable.
When i add gridView inside listView then i cant click on listView element..
How to make listView element clickable when gridView is inside listView?
I try to set focusable, descendantFocusability, clickable...
ProductsFragment.java
package pl.pieczolap.ui.products;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import pl.globoox.pieczolap.R;
import pl.pieczolap.API.getProducts;
import pl.pieczolap.MyGridView;
public class ProductsFragment extends Fragment {
private ProductsViewModel StampViewModel;
ArrayList<String> product_uid_shop = new ArrayList();
ArrayList<String> product_uid_product = new ArrayList();
ArrayList<String> product_name = new ArrayList();
ArrayList<String> product_info = new ArrayList();
ArrayList<String> product_stamps = new ArrayList();
ArrayList<String> product_clientStamps = new ArrayList();
MyGridView gridView_stamps;
ListView listView_products;
SharedPreferences sharedPref;
Integer clientStamps;
Integer needStamps;
ImageView imageView_loadingData;
TextView textView_winner;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
StampViewModel =
ViewModelProviders.of(this).get(ProductsViewModel.class);
View root = inflater.inflate(R.layout.fragment_products, container, false);
// LOAD GIF LOADING IMAGE
imageView_loadingData = root.findViewById(R.id.imageView_loadingData);
Glide.with(root).load(R.drawable.loadingdots).placeholder(R.drawable.loadingdots).into(imageView_loadingData);
listView_products = root.findViewById(R.id.listView_products);
sharedPref = getActivity().getApplicationContext().getSharedPreferences("pl.piecozlap", Context.MODE_PRIVATE);
Bundle arguments = this.getArguments();
String uid_shop = arguments.getString("uid_shop", "none");
// GET ALL STAMPS
Response.Listener<String> responseListenerUserComments = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
// CANT CONNECT TO DATABASE
if (errorCode == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().getApplicationContext());
builder.setMessage("Brak połączenia z bazą danych!").setNegativeButton("PONÓW", null).create().show();
}
// GET STAMP AND PRODUCT INFO
if (errorCode == 2) {
JSONArray products = jsonResponse.getJSONArray("products");
for (int i = 0; i < products.length(); i++) {
JSONObject jsonObject = products.getJSONObject(i);
product_uid_shop.add(jsonObject.getString("uid_shop"));
product_uid_product.add(jsonObject.getString("uid_product"));
product_name.add(jsonObject.getString("name"));
product_info.add(jsonObject.getString("info"));
product_stamps.add(jsonObject.getString("stamps"));
product_clientStamps.add(jsonObject.getString("clientStamps"));
}
// HIDE LOADING GIF
imageView_loadingData.setVisibility(View.INVISIBLE);
ProductsAdapter productsAdapter = new ProductsAdapter();
listView_products.setAdapter(productsAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
getProducts getStamps = new getProducts(sharedPref.getString("uid_client", "none"), uid_shop, responseListenerUserComments);
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(getStamps);
return root;
}
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
// LISTVIEW CUSTOMADAPTER
public class ProductsAdapter extends BaseAdapter {
#Override
public int getCount() {
return product_uid_shop.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_products, null);
clientStamps = Integer.valueOf(product_clientStamps.get(position));
needStamps = Integer.valueOf(product_stamps.get(position));
TextView textView_product_name = convertView.findViewById(R.id.textView_product_name);
TextView textView_product_info = convertView.findViewById(R.id.textView_product_info);
textView_product_name.setText(String.valueOf(clientStamps));
textView_product_info.setText(product_info.get(position));
// WINNER TEXTVIEW
TextView textView_winner = convertView.findViewById(R.id.textView_winner);
if (clientStamps == needStamps) {
textView_winner.setVisibility(View.VISIBLE);
} else {
textView_winner.setVisibility(View.INVISIBLE);
}
// -------------------- //
// CLICK ON SHOP //
// -------------------- //
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAGA", "sasdadsa");
new AlertDialog.Builder(getActivity().getApplicationContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Continue with delete operation
}
})
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
gridView_stamps = convertView.findViewById(R.id.gridView_stamps);
StampsAdapter stampAdapter = new StampsAdapter();
gridView_stamps.setAdapter(stampAdapter);
gridView_stamps.setClickable(false);
return convertView;
}
}
// STAMP GRIDVIEW
// STAMP GRIDVIEW
// STAMP GRIDVIEW
// STAMP GRIDVIEW
public class StampsAdapter extends BaseAdapter {
#Override
public int getCount() {
return needStamps;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_onestamp, null);
if (position < clientStamps) {
final ImageView imageView = convertView.findViewById(R.id.imgageView_onestamp);
Picasso.get().load("http://pieczolap.pl/admin/shops/999/stamp.jpg").into(imageView);
}
return convertView;
}
}
}
customlayout_products.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content"
android:layout_height="400dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="50dp"
android:background="#drawable/customlayout_shops_background"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:background="#drawable/customlayout_shops_background">
<TextView
android:id="#+id/textView_product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Info"
android:textSize="15dp" />
<TextView
android:id="#+id/textView_product_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView_product_name"
android:layout_margin="5dp"
android:text="Info"
android:textSize="10dp" />
</RelativeLayout>
<pl.pieczolap.MyGridView
android:id="#+id/gridView_stamps"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:columnWidth="100dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:padding="10dp"
android:stretchMode="spacingWidth"
android:verticalSpacing="10dp"
app:layout_constraintTop_toBottomOf="#id/relativeLayout"
tools:ignore="MissingConstraints" />
<TextView
android:id="#+id/textView_winner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:gravity="center"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:rotation="-6"
android:layout_margin="5dp"
android:textColor="#FF0000"
android:textStyle="bold"
android:text="Zebrano wszystkie!"
android:textSize="30dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_products.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:focusable="true"
android:layout_height="match_parent">
<ListView
android:id="#+id/listView_products"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:divider="#null"
android:focusable="true"
android:clickable="true"
android:dividerHeight="10dp"
android:padding="4dp"
android:layout_marginBottom="70dp"
app:layout_constraintTop_toBottomOf="#+id/button_addShop" />
<ImageView
android:id="#+id/imageView_loadingData"
android:layout_width="350dp"
android:layout_height="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

ListView order get's mixed up when scrolling

I am developing an Android application and I am facing a seemingly well-known problem (I found a lot of similar questions but no answer works for me).
I use a ListView that displays an EditText and 2 TextView by adding an item in an ArrayList each time a user presses the button enter. However when I scroll the ListView the order of the elements changes and I can not fix this problem. I understand that the problem comes from the GetView which is recharged each time and therefore, on the view each item changes position but I do not know how to adjust it.
Thanks for your help.
I have already tried to overload the getViewTypeCount () and getItemViewType functions, I also tried to remove the maximum action in the (if convertView == null) but nothing has fixed my problem.
main_game.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#android:color/black">
<ListView android:id="#+id/MyList" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:descendantFocusability="beforeDescendants">
</ListView>
</LinearLayout>
activity_game.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.benjamin.realhacksimulatorgame.Game"
android:background="#android:color/black">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ll_game_vertical"
android:paddingTop="0sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/ll_game"
android:paddingTop="0sp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/user_name"
android:text="#string/name_user"
android:textColor="#android:color/holo_green_dark"
android:textSize="15sp"
android:textStyle="bold" />
<EditText
android:id="#+id/editText_game"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/holo_green_dark"
android:backgroundTint="#android:color/holo_green_dark"
android:background="#android:color/transparent"
android:textSize="15sp"
android:layout_marginLeft="10dp"
android:textCursorDrawable="#drawable/color_cursor"
android:inputType="text" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/reponse"
android:layout_below="#+id/editText_game"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/editText_game"
android:layout_alignEnd="#+id/editText_game"
android:textColor="#android:color/holo_green_dark"/>
</LinearLayout>
</RelativeLayout>
And finally the java class Game.java
package com.benjamin.realhacksimulatorgame;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Game extends Activity {
//DECLARATION
ListView myList;
private MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_game);
Intent i = getIntent();
myList = (ListView) findViewById(R.id.MyList);
myList.setItemsCanFocus(true);
myAdapter = new MyAdapter();
myList.setAdapter(myAdapter);
}
protected void FonctionTest(String test, ViewHolder holder) {
if (test.equalsIgnoreCase("ls") || test.equalsIgnoreCase("ls "))
holder.caption_text.setText("aucun fichier a affiché");
else if (test.equalsIgnoreCase("mkdir") || test.equalsIgnoreCase("mkdir "))
holder.caption_text.setText("Impossible de creer un fichie pour le moment");
else if (test.equalsIgnoreCase(""))
holder.caption_text.setText("Vous n'avez rien entré");
else if (test.equalsIgnoreCase("a "))
holder.caption_text.setText("lettre a");
else
holder.caption_text.setText("Commande inconnu\n\n\ndesole");
}
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ArrayList myItems = new ArrayList();
public MyAdapter() {
// mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListItem listItem = new ListItem();
myItems.add(listItem);
notifyDataSetChanged();
}
//GET SIZE LIST
public int getCount() {
return myItems.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// if (convertView == null || ((ViewHolder)convertView.getTag()).id != holder.caption_edit.getId()) {
if (convertView == null ) {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.activity_game, null);
holder = new ViewHolder();
holder.caption_edit = (EditText) convertView.findViewById(R.id.editText_game);
holder.caption_text = (TextView) convertView.findViewById(R.id.reponse);
holder.caption_name = (TextView) convertView.findViewById(R.id.user_name);
//holder.id = holder.caption_edit.getId();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.caption_edit.setId(position);
//we need to update adapter once we finish with editing
final ViewHolder finalHolder = holder;
holder.caption_edit.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
//FILTER
if (event.getAction()!=KeyEvent.ACTION_DOWN) {
Toast.makeText(Game.this, "le retrun true prend effet" , Toast.LENGTH_LONG).show();
return true;
}
//IF USER CLICK ON ENTER BUTTON
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
//DISABLED OLD EDITTEXT
finalHolder.caption_edit.setEnabled(false);
FonctionTest(finalHolder.caption_edit.getText().toString(), finalHolder);
//NEXT ITEM
final int position = v.getId();
final EditText Caption = (EditText) v;
final TextView Caption_text = (TextView) v;
final TextView Caption_name = (TextView) v;
((ListItem) myItems.get(position)).caption_edit = Caption.getText().toString();
((ListItem) myItems.get(position)).caption_text = Caption.getText().toString();
((ListItem) myItems.get(position)).caption_name = Caption.getText().toString();
//Toast.makeText(Game.this, "Ceci est l'editeur numero " + position, Toast.LENGTH_LONG).show();
//CREATE NEW ITEM
ListItem listItem = new ListItem();
myItems.add(listItem);
}
return true;
}
});
return convertView;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
}
class ViewHolder {
int id;
EditText caption_edit;
TextView caption_text;
TextView caption_name;
}
class ListItem {
int id;
String caption_edit;
String caption_text;
String caption_name;
}
}

Why item on menu drawer can't click ? Android Navigation

I have a really interesting problem with my Navigator menu. I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image. I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
image - this trouble
image - can't click
this my code :
menu_bar.java
package com.database.m.lyburan;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.database.m.lyburan.adapter.EventAdapter;
import com.database.m.lyburan.app.AppController;
import com.database.m.lyburan.data.EventData;
import com.database.m.lyburan.util.Server;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static com.database.m.lyburan.Buddies.TAG_MESSAGE;
import static com.database.m.lyburan.Login.TAG_USERNAME;
import static com.database.m.lyburan.R.id.parent;
public class menu_bar extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {
Toolbar toolbar;
DrawerLayout drawer;
NavigationView navigationView;
FragmentManager fragmentManager;
Fragment fragment = null;
ListView list;
SharedPreferences sharedpreferences;
SwipeRefreshLayout swipe;
List<EventData> eventList = new ArrayList<EventData>();
private static final String TAG = menu_bar.class.getSimpleName();
private static String url_list = Server.URL + "event.php?offset=";
private int offSet = 0;
int no;
EventAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
private Boolean isFabOpen = false;
private FloatingActionButton fab, fab1, fab2;
private CardView card1, card2;
private Animation fab_open, fab_close, rotate_forward, rotate_backward, card_open, card_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bar);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
fragment = new Root();
callFragment(fragment);
}
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
list = (ListView) findViewById(R.id.list_event);
eventList.clear();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(menu_bar.this, Buddies.class);
intent.putExtra(TAG_ID, eventList.get(position).getId());
startActivity(intent);
}
});
adapter = new EventAdapter(menu_bar.this, eventList);
list.setAdapter(adapter);
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
});
list.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callEvent(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
Button meet_buddies = (Button) findViewById(R.id.meet_buddies);
meet_buddies.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,Buddies.class);
startActivity(intent);
}
});
Button upcoming = (Button) findViewById(R.id.upcoming);
upcoming.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(menu_bar.this,asd.class);
startActivity(intent);
}
});
fab = (FloatingActionButton) findViewById(R.id.fab);
fab1 = (FloatingActionButton) findViewById(R.id.fab1);
fab2 = (FloatingActionButton) findViewById(R.id.fab2);
card1 = (CardView) findViewById(R.id.card1);
card2 = (CardView) findViewById(R.id.card2);
/*kenalkan animasi*/
fab_open = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_open);
fab_close = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fab_close);
rotate_forward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_forward);
rotate_backward = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate_backward);
card_open=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_open);
card_close=AnimationUtils.loadAnimation(getApplicationContext(), R.anim.card_close);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
animateFAB();
}
});
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(menu_bar.this,Addhome.class);
startActivity(intent);
}
});
fab2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(menu_bar.this, "New Call", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bar, menu);
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profile) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_payment) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.nav_help) {
fragment = new Import();
callFragment(fragment);
} else if (id == R.id.btn_logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layouts);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Action Settings", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_containers, fragment)
.commit();
}
public void animateFAB() {
/*jika fab dalam keadaan false*/
if (isFabOpen) {
fab.startAnimation(rotate_backward);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
card1.startAnimation(card_close);
card2.startAnimation(card_close);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
} else {
/*jika dalam keadaan true*/
fab.startAnimation(rotate_forward);
fab1.startAnimation(fab_open);
fab2.startAnimation(fab_open);
card1.startAnimation(card_open);
card2.startAnimation(card_open);
fab1.setClickable(true);
fab2.setClickable(true);
isFabOpen = true;
}
}
#Override
public void onRefresh() {
eventList.clear();
adapter.notifyDataSetChanged();
callEvent(0);
}
private void callEvent(int page){
swipe.setRefreshing(true);
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
EventData news = new EventData();
no = obj.getInt(TAG_NO);
news.setId(obj.getString(TAG_ID));
news.setJudul(obj.getString(TAG_JUDUL));
if (!Objects.equals(obj.getString(TAG_GAMBAR), "")) {
news.setGambar(obj.getString(TAG_GAMBAR));
}
news.setDatetime(obj.getString(TAG_TGL));
news.setIsi(obj.getString(TAG_ISI));
// adding news to news array
eventList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}
activity_menu_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layouts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_menu_bar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<Button
android:id="#+id/meet_buddies"
android:layout_width="fill_parent"
android:drawableLeft="#drawable/ic_profil_w"
android:background="#color/ijo"
android:textColor="#android:color/background_light"
android:layout_height="wrap_content"
android:padding="15dp"
android:onClick="meet"
android:layout_marginTop="70dp"
android:text="Meet Buddies"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/upcoming"
android:layout_width="170dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Notification"
android:layout_marginTop="135dp" />
<Button
android:id="#+id/myshared"
android:layout_width="190dp"
android:background="#color/white"
android:textColor="#color/ijo"
android:layout_height="wrap_content"
android:padding="15dp"
android:layout_marginLeft="190dp"
android:layout_marginTop="135dp"
android:text="My Shared"
/>
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:stateListAnimator="#null"
android:src="#drawable/ic_plus_w"
app:backgroundTint="#color/colorAccent"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="130dp"
android:stateListAnimator="#null"
android:layout_marginRight="#dimen/fab_margin"
android:visibility="invisible"
android:src="#drawable/ic_menu_camera"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="140dp"
android:layout_marginRight="75dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Event" />
</android.support.v7.widget.CardView>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="80dp"
android:layout_marginRight="#dimen/fab_margin"
android:src="#drawable/ic_beranda"
android:visibility="invisible"
app:backgroundTint="#ffffff"
app:elevation="6dp"
app:pressedTranslationZ="12dp" />
<android.support.v7.widget.CardView
android:id="#+id/card1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="90dp"
android:layout_marginRight="70dp"
android:visibility="invisible">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Add Homestay" />
</android.support.v7.widget.CardView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Event"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="198dp" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_marginTop="222dp"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list_event"
android:layout_width="wrap_content"
android:layout_height="330dp"
android:divider="#null"
android:dividerHeight="2dp"
android:layout_marginTop="222dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
i've tried, how can i fix it ? anyone please help me. thanks.
Anyone else having similar problem. It appears the order in the XML matters too.
I had my NavigationView and after it I had a layout included and I couldn't click an item on the NavigationView.
After I switched them, so that my layout was being included AND THEN AFTER IT I had my NavigationView, it worked ...
this adapter.java
public class Adapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<DataModel> item;
public Adapter(Activity activity, List<DataModel> item) {
this.activity = activity;
this.item = item;
}
#Override
public int getCount() {
return item.size();
}
#Override
public Object getItem(int location) {
return item.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_buddies, null);
TextView txt_nama = (TextView) convertView.findViewById(R.id.custom_list_item_text1);
txt_nama.setText(item.get(position).getNama());
return convertView;
}
}
You need to create this type of your layout xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_menu_bar"
app:menu="#menu/activity_menu_bar_drawer" />
</android.support.v4.widget.DrawerLayout>
In FrameLayout you need to replace all fragment one by one like
private void callFragment(Fragment fragment) {
fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Note: You can write your Coordinator layout and other in fragment itself, may be helpful for you.

RecyclerView with CardView does not work

I am really sorry for such an abstract question but I am loosing my mind here. HERE is my code for RecyclerView activity.
Please tell me what am I missing, because I am new to Android and I've tried for 4 days to figure the CardView out.
The error is
02-26 13:17:36.570 1138-1138/com.parse.starter E/CrashReporting﹕ ParseCrashReporting caught a NullPointerException exception for com.parse.starter. Building report.
02-26 13:17:36.580 1138-1138/com.parse.starter E/CrashReporting﹕ Handling exception for crash
java.lang.NullPointerException
at com.misha.adaptor.ContactAdapter.onBindViewHolder(ContactAdapter.java:31)
at com.misha.adaptor.ContactAdapter.onBindViewHolder(ContactAdapter.java:14)
The main Activity class
package com.parse.starter;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.misha.adaptor.ContactAdapter;
import com.misha.to.ContactInfo;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class CardActivity extends Activity {
String column;
TextView name;
String result;
List<ContactInfo> resultContacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
// getContacts()
List<ContactInfo> list = new ArrayList<>();
ContactInfo ci = new ContactInfo();
ci.name = "Mihail";
ci.gender = "male";
ci.email = "test#gmail.com";
ci.phone = "4152346153";
list.add(ci);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
ContactAdapter adapter = new ContactAdapter(list);
recList.setAdapter(adapter);
// name = (TextView) findViewById(R.id.txtName);
// getMessage("fevK9QPFUW", "Message");
}
public void getMessage(String key, String columnName) {
this.column = columnName;
ParseQuery<ParseObject> query = ParseQuery.getQuery("Messages");
query.getInBackground(key, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
name.setText(object.getString(column).toString());
} else {
result = "did not work";
}
}
});
}
public List<ContactInfo> getContacts() {
resultContacts = new ArrayList<>();
ParseQuery<ParseObject> contacts = ParseQuery.getQuery("Messages");
List<ParseQuery<ParseObject>> queries = new ArrayList<>();
queries.add(contacts);
ParseQuery<ParseObject> mainQuery = ParseQuery.or(queries);
mainQuery.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> results, ParseException e) {
if (e == null) {
for (ParseObject obj : results) {
String s = obj.getString("Message");
ContactInfo ci = new ContactInfo();
ci.name = s;
ci.email = "email";
ci.phone = "phone";
ci.gender = "gender";
resultContacts.add(ci);
}
}
}
});
return resultContacts;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_card, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
The Adaptor
package com.misha.adaptor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.misha.to.ContactInfo;
import com.parse.starter.R;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
System.out.println("The ContactInfo = " + ci);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vPhone.setText(ci.phone);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vGender.setText(ci.gender);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.activity_card, viewGroup, false);
return new ContactViewHolder(itemView);
}
public class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vPhone;
protected TextView vEmail;
protected TextView vGender;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vPhone = (TextView) v.findViewById(R.id.txtPhone);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vGender = (TextView) v.findViewById(R.id.txtGender);
}
}
}
and Here are my layOuts:
activity_card.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".CardActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtName"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/bkg_card"
android:text="Name"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp" />
<TextView
android:id="#+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp" />
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtPhone"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp" />
<TextView
android:id="#+id/txtGender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="#id/txtEmail" />
</RelativeLayout>
</android.support.v7.widget.CardView>
contactViewHolder.vName is null in your example.
You need to call the constructor for ContactViewHolder in the ContactAdapter constructor.
Got it
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
the R.layout.card_layout was set to R.layout.my_activity

How to set this listview when you clicked/tapped opens into a different activity/intent

See this site: http://www.androidbegin.com/tutorial/android-search-filter-listview-images-and-texts-tutorial/
How do I set it to open into different activity/intent.
MainActivity.java
package com.androidbegin.filterlistviewimg;
import java.util.ArrayList;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] country;
String[] population;
int[] flag;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
// Generate sample data
rank = new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
country = new String[] { "China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
"Russia", "Japan" };
population = new String[] { "1,354,040,000", "1,210,193,422",
"315,761,000", "237,641,326", "193,946,886", "182,912,000",
"170,901,000", "152,518,015", "143,369,806", "127,360,000" };
flag = new int[] { R.drawable.china, R.drawable.india,
R.drawable.unitedstates, R.drawable.indonesia,
R.drawable.brazil, R.drawable.pakistan, R.drawable.nigeria,
R.drawable.bangladesh, R.drawable.russia, R.drawable.japan };
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
for (int i = 0; i < rank.length; i++)
{
WorldPopulation wp = new WorldPopulation(rank[i], country[i],
population[i], flag[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
WorldPopulation.java
package com.androidbegin.filterlistviewimg;
public class WorldPopulation {
private String rank;
private String country;
private String population;
private int flag;
public WorldPopulation(String rank, String country, String population,
int flag) {
this.rank = rank;
this.country = country;
this.population = population;
this.flag = flag;
}
public String getRank() {
return this.rank;
}
public String getCountry() {
return this.country;
}
public String getPopulation() {
return this.population;
}
public int getFlag() {
return this.flag;
}
}
listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/search" />
</RelativeLayout>
ListViewAdapter.java
package com.androidbegin.filterlistviewimg;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.content.Intent;
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.view.View.OnClickListener;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
public ListViewAdapter(Context context,
List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position)
.getPopulation());
// Set the results into ImageView
holder.flag.setImageResource(worldpopulationlist.get(position)
.getFlag());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank",
(worldpopulationlist.get(position).getRank()));
// Pass all data country
intent.putExtra("country",
(worldpopulationlist.get(position).getCountry()));
// Pass all data population
intent.putExtra("population",
(worldpopulationlist.get(position).getPopulation()));
// Pass all data flag
intent.putExtra("flag",
(worldpopulationlist.get(position).getFlag()));
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (WorldPopulation wp : arraylist) {
if (wp.getCountry().toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
listview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ranklabel" />
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/ranklabel" />
<TextView
android:id="#+id/countrylabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ranklabel"
android:text="#string/countrylabel" />
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rank"
android:layout_toRightOf="#+id/countrylabel" />
<TextView
android:id="#+id/populationlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/countrylabel"
android:text="#string/populationlabel" />
<TextView
android:id="#+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/country"
android:layout_toRightOf="#+id/populationlabel" />
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:padding="1dp" />
</RelativeLayout>
SingleItemView.java
package com.androidbegin.filterlistviewimg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class SingleItemView extends Activity {
// Declare Variables
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
String rank;
String country;
String population;
int flag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.singleitemview);
// Get the intent from ListViewAdapter
Intent i = getIntent();
// Get the results of rank
rank = i.getStringExtra("rank");
// Get the results of country
country = i.getStringExtra("country");
// Get the results of population
population = i.getStringExtra("population");
// Get the results of flag
flag = i.getIntExtra("flag", flag);
// Locate the TextViews in singleitemview.xml
txtrank = (TextView) findViewById(R.id.rank);
txtcountry = (TextView) findViewById(R.id.country);
txtpopulation = (TextView) findViewById(R.id.population);
// Locate the ImageView in singleitemview.xml
imgflag = (ImageView) findViewById(R.id.flag);
// Load the results into the TextViews
txtrank.setText(rank);
txtcountry.setText(country);
txtpopulation.setText(population);
// Load the image into the ImageView
imgflag.setImageResource(flag);
}
}
singleitemview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ranklabel" />
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/ranklabel" />
<TextView
android:id="#+id/countrylabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/ranklabel"
android:text="#string/countrylabel" />
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rank"
android:layout_toRightOf="#+id/countrylabel" />
<TextView
android:id="#+id/populationlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/countrylabel"
android:text="#string/populationlabel" />
<TextView
android:id="#+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/country"
android:layout_toRightOf="#+id/populationlabel" />
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:padding="1dp" />
</RelativeLayout>

Categories