Android studio: list view with check boxes - java

This activity consists of typing an ingredient (then showing it) and check a checkbox next to it. I have the following bugs that I can't get rid of (I've been searching for 5 hours for a solution):
If I press back so the keyboard hides,when I click on the search view,it never shows again but for going to the home screen and entering back again.
If I check a checkbox and scroll,there will be other checkboxes randomly checked.
How can I put in an array the ingredients that I have checked and send that array to the next activity?(activity_ingredient list)
Here is the code:
package ro.mosgoreanu.andu.foodholic;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.Arrays;
public class typing_window extends AppCompatActivity implements view.OnClickListener {
private static Button button;
String[] items;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_typing_window);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
editText = (EditText) findViewById(R.id.txtsearch);
initList();
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().equals("")){
initList();
}
else {
searchItem(s.toString());
}
}
});
}
public void buttononClick()
{
startActivity(new Intent("ro.mosgoreanu.andu.foodholic.ingredient_list"));
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
buttononClick();
break;
}
}
public void searchItem(String textToSearch){
for(String item:items) {
if(!item.contains(textToSearch)){
listItems.remove(item);
}
}
adapter.notifyDataSetChanged();
}
public void initList(){
items = new String[]{"breadcumb","butter","capiscum","carrot","cheese","cherry","chicken cutlets","cucumber","egg","flour","garlic","ham","lemon juice","mayonnaise","milk","mushroom","onion (red)","onion (white)","peas","pepper","pork","pickles","potato (red)","potato (white)","soy sauce","tomato","yogurt"};
listItems = new ArrayList<>(Arrays.asList(items));
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.txt, listItems );
listView.setAdapter(adapter);
}
}
and the xml for the activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="ro.mosgoreanu.andu.foodholic.typing_window"
android:background="#89913f">
<include layout="#layout/content_typing_window" />
<EditText
android:id="#+id/txtsearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search Ingredient"
android:textAlignment="textStart"
android:paddingLeft="50dp"
android:layout_toLeftOf="#+id/imageButton"
android:layout_toStartOf="#+id/imageButton"
android:allowUndo="true" />
<SearchView
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingEnd="0dp"
android:paddingLeft="0dp"
android:translationY="-5dp"
android:focusable="true"
android:clickable="true" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View list"
android:id="#+id/button"
android:layout_marginRight="26dp"
android:layout_marginEnd="26dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#00ffffff"
android:translationX="280dp"
android:translationY="-2dp"
android:clickable="true"
android:allowUndo="true" />
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:foregroundTint="#ffffff"
android:paddingTop="50dp" />
</android.support.design.widget.CoordinatorLayout>
and the layout 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">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="19dp"
android:text="Add"
android:id="#+id/checkBox"
android:layout_gravity="right"
android:translationY="25dp"
android:translationX="0dp"
android:layout_marginLeft="280dp"
android:focusable="false"/>
<TextView
android:id="#+id/txt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
/>
</LinearLayout>

Hey i have done one with using ArrayAdapter and SearchViewHolder
Check it and Provide any Response.
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static Button button;
String[] items;
private Fruits[] itemss;
ArrayList<String> listItems;
ArrayAdapter<Fruits> adapter;
ListView listView;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_typing_window);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
listView = (ListView) findViewById(R.id.listview);
editText = (EditText) findViewById(R.id.txtsearch);
initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Fruits it = adapter.getItem(position);
it.toggleChecked();
SelectViewHolder viewHolder = (SelectViewHolder) view.getTag();
viewHolder.getCheckBox().setChecked(it.isChecked());
}
});
}
private void initList() {
itemss = (Fruits[]) getLastNonConfigurationInstance();
ArrayList<Fruits> items = new ArrayList<Fruits>();
items.add(new Fruits("breadcumb"));
items.add(new Fruits("butter"));
items.add(new Fruits("capiscum"));
items.add(new Fruits("carrot"));
items.add(new Fruits("cheese"));
items.add(new Fruits("cherry"));
items.add(new Fruits("chicken cutlets"));
items.add(new Fruits("cucumber"));
items.add(new Fruits("egg"));
items.add(new Fruits("flour"));
items.add(new Fruits("garlic"));
items.add(new Fruits("ham"));
items.add(new Fruits("lemon juice"));
items.add(new Fruits("mayonnaise"));
items.add(new Fruits("milk"));
items.add(new Fruits("mushroom"));
items.add(new Fruits("onion (red)"));
items.add(new Fruits("onion (white)"));
items.add(new Fruits("peas"));
items.add(new Fruits("pepper"));
items.add(new Fruits("pork"));
items.add(new Fruits("pickles"));
items.add(new Fruits("potato (red)"));
items.add(new Fruits("potato (white)"));
items.add(new Fruits("soy sauce"));
items.add(new Fruits("tomato"));
items.add(new Fruits("yogurt"));
adapter = new ActivityAdapter(this, items);
listView.setAdapter(adapter);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.this.adapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private static class Fruits {
private String name = "";
private boolean checked = false;
public Fruits() {
}
public Fruits(String name) {
this.name = name;
}
public Fruits(String name, boolean checked) {
this.name = name;
this.checked = checked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public String toString() {
return name;
}
public void toggleChecked() {
checked = !checked;
}
}
private static class SelectViewHolder {
private CheckBox checkBox;
private TextView textView;
public SelectViewHolder() {
}
public SelectViewHolder(TextView textView, CheckBox checkBox) {
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox() {
return checkBox;
}
public void setCheckBox(CheckBox checkBox) {
this.checkBox = checkBox;
}
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
}
private static class ActivityAdapter extends ArrayAdapter<Fruits>{
private LayoutInflater inflater;
public ActivityAdapter(Context context, List<Fruits> list) {
super(context, R.layout.content_typing_window, R.id.txt, list);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruits fruit = (Fruits) this.getItem(position);
CheckBox checkBox;
TextView textView;
if (convertView == null) {
convertView = inflater.inflate(R.layout.content_typing_window, null);
textView = (TextView) convertView
.findViewById(R.id.txt);
checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(new SelectViewHolder(textView, checkBox));
checkBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Fruits li = (Fruits) cb.getTag();
li.setChecked(cb.isChecked());
}
});
}
else {
SelectViewHolder viewHolder = (SelectViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
checkBox.setTag(fruit);
checkBox.setChecked(fruit.isChecked());
textView.setText(fruit.getName());
return convertView;
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
break;
}
}
// public void initList(){
// items = new String[]{"breadcumb","butter","capiscum","carrot","cheese","cherry"
// ,"chicken cutlets","cucumber","egg","flour","garlic","ham","lemon juice","mayonnaise",
// "milk","mushroom","onion (red)","onion (white)","peas","pepper","pork","pickles","potato (red)",
// "potato (white)","soy sauce","tomato","yogurt"};
// listItems = new ArrayList<>(Arrays.asList(items));
// adapter = new ArrayAdapter<mItems>(this, R.layout.content_typing_window, R.id.txt, listItems );
// listView.setAdapter(adapter);
// }
#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_main, 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);
}
}

Related

Android list view with adapter displays only the first item (several times)

I created a ListView and a custom adapter to use with the list view. For some reason, if I add more than one item to the list, it does show several items, but all of them are identical to the first one.
At first I used a layout file to create each item but then I gave up and dynamically created a text view just to test it. It didn't work in both ways.
List with same item
Here is my code:
ArtistAdapter.java
package com.example.list2;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ArtistAdapter extends BaseAdapter
{
private ArrayList<String> artists;
private Context context;
private LayoutInflater inflater;
public ArtistAdapter(Context context, ArrayList<String> artists)
{
super();
this.context = context;
this.artists = artists;
this.inflater = LayoutInflater.from(context);
}
public ArtistAdapter(Context context)
{
this(context, new ArrayList<String>());
}
#Override
public int getCount() {
return artists.size();
}
#Override
public String getItem(int i) {
return artists.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if(v == null)
{
//LayoutInflater li = ((Activity)context).getLayoutInflater();
//v = inflater.inflate(R.layout.item,viewGroup,false);
//((TextView)v.findViewById(R.id.name)).setText((String)getItem(i));
v = new TextView(context);
((TextView)v).setText(getItem(i));
((TextView)v).setTextSize(50);
}
return v;
}
public void add(String name)
{
artists.add(name);
notifyDataSetChanged();
}
}
MainActivity.java
package com.example.list2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
//ArrayAdapter<String> aa;
ArtistAdapter aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
//aa = new ArrayAdapter<String>(this,R.layout.item,new ArrayList<String>());
aa = new ArtistAdapter(this);
l.setAdapter(aa);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
aa.add(inp);
//aa.notifyDataSetChanged();
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
activity_main.xml
<?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"
android:orientation="vertical"
tools:context=".MainActivity"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/input"
android:hint="Something..."
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/submit"
android:text="Submit!"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list"
android:animateLayoutChanges="true"
></ListView>
</LinearLayout>
Do you need to use a custom Adapter? Otherwise this code works well using ArrayAdapter:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
ArrayAdapter<String> artistAdapter;
List<String> listItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
artistAdapter = new ArrayAdapter<String>(this,R.layout.item, R.id.textView,listItems);
l.setAdapter(artistAdapter);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
listItems.add(inp);
artistAdapter.notifyDataSetChanged();
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
You need to update the arraylist and then set the adapter. For some reason notify adapter is not working. Here's the solution:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
ArtistAdapter artistAdapter;
ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
artistAdapter = new ArtistAdapter(this, arrayList);
l.setAdapter(artistAdapter);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
arrayList.add(inp);
l.setAdapter(artistAdapter);
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
====
public class ArtistAdapter extends BaseAdapter
{
private ArrayList artists;
private Context context;
public ArtistAdapter(Context context, ArrayList<String> artists)
{
super();
this.context = context;
this.artists = artists;
}
#Override
public int getCount() {
return artists.size();
}
#Override
public String getItem(int i) {
return artists.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if(v == null)
{
v = new TextView(context);
((TextView)v).setText(getItem(i));
((TextView)v).setTextSize(50);
}
return v;
}
}

Android load full image with recyclerview, cardview and volley from php mysql

The code below downloads images from a server and displays them in a recyclerview using php mysql and volley library as seen in the attached image. As of now when one clicks the image only toasts the image name. I want a user to be able to view the full image on click. Sorry to post all the code but its a desperate situation.
RecyclerView code
<?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_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
CardView code
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/ImageNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/VolleyImageView"
android:layout_toRightOf="#+id/VolleyImageView"
android:text="JSon Image Name"
android:textColor="#000"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
MainActivity
package com.ny.fetchallimages;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://*************.php";
String Image_URL_JSON = "image_data";
String Image_Name_JSON = "image_tag";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(MainActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
RecyclerViewAdapter
package com.ny.fetchallimages;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import android.content.Context;
import android.view.LayoutInflater;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
ImageAdapter
package com.ny.fetchallimages;
import android.graphics.Bitmap;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.RequestQueue;
import android.content.Context;;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.Cache;
import androidx.collection.LruCache;
import com.android.volley.Network;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HurlStack;
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
DataAdapter
package com.ny.fetchallimages;
public class DataAdapter
{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageTitle() {
return ImageTitle;
}
public void setImageTitle(String Imagetitlename) {
this.ImageTitle = Imagetitlename;
}
}
This worked by creating a new activity, then in on item click, get the item clicked position URL, send an intent to the activity with the image URL as extras. Get the image url from the intent in the activity then load the image.

Android full image with recyclerview, cardview and volley from php mysql

The code below downloads images from a server and displays them in a recyclerview using php mysql and volley library as seen in the image. As of now when one clicks the image it only toasts the image name. I want a user to be able to view the full image on click. Sorry to post all the code but its a desperate situation.
RECYCLERVIEW CODE
<?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_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
CARDVIEW CODE
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:id="#+id/ImageNameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toEndOf="#+id/VolleyImageView"
android:layout_toRightOf="#+id/VolleyImageView"
android:text="JSon Image Name"
android:textColor="#000"
android:textSize="15dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
MAIN ACTIVITY
package com.ny.fetchallimages;
import android.os.Bundle;
import org.json.JSONArray;
import java.util.ArrayList;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://*************.php";
String Image_URL_JSON = "image_data";
String Image_Name_JSON = "image_tag";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListOfdataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(MainActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
RECYCLERVIEWADAPTER
package com.ny.fetchallimages;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import java.util.List;
import com.android.volley.toolbox.ImageLoader;
import android.content.Context;
import android.view.LayoutInflater;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
IMAGEADAPTER
package com.ny.fetchallimages;
import android.graphics.Bitmap;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.RequestQueue;
import android.content.Context;;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.Cache;
import androidx.collection.LruCache;
import com.android.volley.Network;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.HurlStack;
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
DATAADAPTER
package com.ny.fetchallimages;
public class DataAdapter
{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageTitle() {
return ImageTitle;
}
public void setImageTitle(String Imagetitlename) {
this.ImageTitle = Imagetitlename;
}
}
just when the user clicked on an item do like me...
Intent i = new Intent(context,BigImageActivity);
intent.putExtra("image_url",iamge_url);
context.startActivity(i);
in big_image_layout.xml
<ImageView
android:id="#+id/iv_big_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
in onCreate BigImageActivity:
String img_url = getIntent.getStringExtra("image_url");
and for showing image use Glide:
Glide.with(context)
.load(img_url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.dontAnimate()
.into(iv_big_image);
and done!!!
I hope this useful for you.
I made it to show full images by fetching the url and parsing it to a new activity. Thanks for the positive responses

onClick child item in ExpandableListView

I need to add onClick to the child items in ExpandableListView. I have reviewed other posts regarding this, but I could not integrate the code into mine, possibly due to a different variation of ExpandableListView codes.
It would be great if you can provide some in code explanation as well. Many thanks.
Here are my source codes:
activity_main.xml
`<?xml version="1.0" encoding="utf-8"?>
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ExpandableListView
android:id="#+id/expLV"
android:layout_width="match_parent"
android:layout_height="match_parent"></ExpandableListView>
</RelativeLayout>`
list_parent.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/listP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="?
android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="20dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"
/>
</LinearLayout>
list_child.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">
<TextView
android:id="#+id/listC"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="?
android:attr/expandableListPreferredChildPaddingLeft"
android:textSize="14dp"
android:paddingBottom="20dp"
android:paddingTop="20dp"/>
</LinearLayout>
ExpandableListAdapter.java
package com.example.ehsan.myexplistview;
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> listDataHeader;
private HashMap<String, List<String>> listHashMap;
public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
}
#Override
public int getGroupCount() {
return listDataHeader.size();
}
#Override
public int getChildrenCount(int i) {
return listHashMap.get(listDataHeader.get(i)).size();
}
#Override
public Object getGroup(int i) {
return listDataHeader.get(i);
}
#Override
public Object getChild(int i, int i1) {
return listHashMap.get(listDataHeader.get(i)).get(i1);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
String parentText = (String)getGroup(i);
if (view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.list_parent, null);
}
TextView listP = (TextView)view.findViewById(R.id.listP);
listP.setTypeface(null, Typeface.BOLD);
listP.setText(parentText);
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
final String childText = (String)getChild(i,i1);
if (view == null)
{
LayoutInflater inflater = (LayoutInflater)this.context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view=inflater.inflate(R.layout.list_child, null);
}
TextView listC = (TextView)view.findViewById(R.id.listC);
listC.setText(childText);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(i1==0){
Intent intent = new Intent(activity,OneTwoThree.class);
activity.startActivity(intent);
}
else if (i1 ==1){
Intent intent = new Intent(activity,FourFiveSix.class);
activity.startActivity(intent);
}
else if (i1 ==2){
Intent intent = new Intent(activity,SevenEightNine.class);
activity.startActivity(intent);}
else if (i1 ==3){
Intent intent = new Intent(activity,TenElevenTwelve.class);
activity.startActivity(intent);}
}
});
return view;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
MainActivity.java
package com.example.ehsan.myexplistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ExpandableListView expandableListView;
private ExpandableListAdapter expandableListAdapter;
private List<String> listP;
private HashMap<String, List<String>> listC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expandableListView = (ExpandableListView)findViewById(R.id.expLV);
initData();
expandableListAdapter = new ExpandableListAdapter(this, listP, listC);
expandableListView.setAdapter(expandableListAdapter);
}
private void initData(){
listP = new ArrayList<>();
listC = new HashMap<>();
listP.add("ABC");
listP.add("DEF");
listP.add("GHI");
listP.add("JKL");
List <String> abc = new ArrayList<>();
abc.add("123");
List <String> def = new ArrayList<>();
def.add("456");
def.add("789");
List <String> ghi = new ArrayList<>();
ghi.add("101112");
ghi.add("131415");
ghi.add("161718");
List <String> jkl = new ArrayList<>();
jkl.add("192021");
jkl.add("222324");
jkl.add("252627");
jkl.add("282930");
listC.put(listP.get(0),abc);
listC.put(listP.get(1),def);
listC.put(listP.get(2),ghi);
listC.put(listP.get(3),jkl);
}
}
You can set child click of expandable list in two ways
1.write child click event inside the getChildView() method.
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Page page =(Page) getChild(groupPosition, childPosition);
convertView = inflater.inflate(R.layout.child_list_layout, null);
Button mButton=(Button)convertView.findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Your code goes here ....
}
});
return convertView;
}
2.write click directly from expandable listview.
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(
ExpandableListView parent, View v,
int groupPosition, int childPosition,
long id) {
GoCategory(mainMenusList.get(groupPosition)
.getPagesList().get(childPosition));
return false;
}
});

RecyclerView Data is not showing up

I am trying to create Navigation Drawer with RecyclerView. I am following a tutorial on YouTube to do this because I am new to this. The problem is RecyclerView does not show any data from the adapter. I need help. Any suggestion on this is appreciated.
NavigationDrawerFragment.java
package com.pixalstudio.cakedekho;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
int i=0;
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private InfoAdapter adapter;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private View containerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new InfoAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.seven1, R.drawable.seven2, R.drawable.seven3, R.drawable.seven4};
String[] titles = {"Login", "Location", "Home", "About Us"};
for (int i=0; i < titles.length && i < icons.length; i++) ;
{
Information current = new Information();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
Information.java
package com.pixalstudio.cakedekho;
/**
* Created by akkie on 7/10/2015.
*/
public class Information {
int iconId;
String title;
}
InfoAdapter.java
package com.pixalstudio.cakedekho;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
/**
* Created by akkie on 7/10/2015.
*/
public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.MyViewHolder> {
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
public InfoAdapter(Context context, List<Information> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
customrow.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="horizontal"
>
<ImageView
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:src="#drawable/seven1" />
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:text="Dummy Text" />
</LinearLayout>
fragment_navigation_drawer.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:background="#DADADA"
tools:context="com.pixalstudio.cakedekho.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FB8C00">
<ImageView
android:layout_width="240dp"
android:layout_height="140dp"
android:src="#drawable/ic_abstract1" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_below="#+id/containerDrawerImage"
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Please let me know if anyone needs any other information to fix my problem. Thank you in advance.

Categories