ExpandableListView won't inflate/initialise in fragment code - java

I keep getting a null pointer exception when ever I try to run a fragment that must use an expandable list view item. I'm guessing it has something to do with the fragment because the similar code runs on an activity.
Here is the error (Logcat) message:
11-02 14:11:27.136 12947-12947/com.example.vhuhwavho.ctistudentportal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.vhuhwavho.ctistudentportal, PID: 12947
java.lang.NullPointerException
at com.example.vhuhwavho.ctistudentportal.ForYouFragment.onCreateView(ForYouFragment.java:117)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1453)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5487)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Here is the fragment code:
package com.example.vhuhwavho.ctistudentportal;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by Vhuhwavho on 2017/10/31.
*/
public class ForYouFragment extends Fragment {
// To keep track of the counter, we need to add a global variable to the project,
// along with a key for saving and restoring.
static final String KEY_STUDENT_NUMBER = "studentNumber";
String studentNumber = "";
private static final int CODE_GET_REQUEST = 1024;
private static final int CODE_POST_REQUEST = 1025;
private Button mSubmit;
private Context mContext;
private LayoutInflater mInflater;
private View view;
private List < String > listHeadings;
private List < String > image_urls;
private List < Bitmap > images;
private List < String > messages;
private LinkedHashMap < String, GroupInfo > gMessages = new LinkedHashMap < String, GroupInfo > ();
private ArrayList < GroupInfo > list = new ArrayList < GroupInfo > ();
private ExpandableListAdapter listAdapter;
private ExpandableListView simpleExpandableListView;
//Connectivity manage instance
private ConnectivityManager mConnMgr;
// Image view reference
private ImageView imageView;
int imageCounter = 0, imageCounterSize = 0;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.for_you_fragment, container, false);
String extraStr;
try {
extraStr = getArguments().getString("studentNumber");
Log.e("try studentNumber", "tried student number");
} catch (NullPointerException e) {
studentNumber = "PT2014-1282";
Log.e("catch studentNumber", "catched student number");
}
requestForYou();
//get reference of the ExpandableListView
simpleExpandableListView = (ExpandableListView) this.getActivity().findViewById(R.id.simpleExpandableListView);
if ( simpleExpandableListView == null )
Log.d("Null or Not", "simpleExpandableList == null");
// create the adapter by passing your ArrayList data
listAdapter = new ExpandableListAdapter (this.getActivity().getApplicationContext(), list);
// attach the adapter to the expandable list view
simpleExpandableListView.setAdapter(listAdapter);
//expand all the Groups
expandAll();
// setOnChildClickListener listener for child row click
simpleExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
//get the group header
GroupInfo headerInfo = list.get(groupPosition);
//get the child info
ChildInfo detailInfo = headerInfo.getHeadingList().get(childPosition);
//display it or do something with it
Toast.makeText(getActivity(), " Clicked on :: " + headerInfo.getHeading()
+ "/" , Toast.LENGTH_LONG).show();
return false;
}
});
// setOnGroupClickListener listener for group heading click
simpleExpandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//get the group header
GroupInfo headerInfo = list.get(groupPosition);
//display it or do something with it
return false;
}
});
listHeadings = new ArrayList<>();
messages = new ArrayList<>();
image_urls = new ArrayList<>();
return view;
} // end of onCreateView method
// To receive notifications of application state change, 2 methods are needed
// the onSaveInstanceState() and onRestoreInstanceState() methods
#Override
public void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_STUDENT_NUMBER, studentNumber);
}
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated (savedInstanceState);
if (savedInstanceState != null) {
studentNumber = savedInstanceState.getString(KEY_STUDENT_NUMBER);
}
}
// save the data before the activity closes
#Override
public void onPause () {
super.onPause();
SharedPreferences settings = this.getActivity().getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(KEY_STUDENT_NUMBER, studentNumber);
editor.commit();
}
//method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.expandGroup(i);
}
}
//method to collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
simpleExpandableListView.collapseGroup(i);
}
}
private void requestForYou () {
PerformNetworkRequest request = new PerformNetworkRequest(API.URL_REQUEST_FOR_YOU, CODE_GET_REQUEST);
request.execute();
}
private void refreshForYou( JSONArray forYou) throws JSONException {
for ( int i = 0; i < forYou.length(); i++ ) {
JSONObject whats_happening = forYou.getJSONObject(i);
String heading = whats_happening.getString( "heading" );
String image_url = whats_happening.getString( "url" );
String message = whats_happening.getString( "message" );
listHeadings.add ( heading ) ;
messages.add ( message );
image_urls.add ( image_url );
Log.d("ForYouFragment", "refreshForYou");
}
imageCounterSize = listHeadings.size();
if ( mConnMgr != null ) {
// Get active network info
NetworkInfo networkInfo = mConnMgr.getActiveNetworkInfo();
// If any active network is available and internet connection is available
if ( networkInfo != null && networkInfo.isConnected() ) {
for ( String url : image_urls ) {
// Start a new Image Download Async Task
new DownloadImageTask().execute( url );
}
} else {
// If network is off or internet is not available, inform the user
Toast.makeText(this.getActivity(), "Network not Available", Toast.LENGTH_SHORT).show();
}
}
Log.d("ForYouFragment", "Finished refreshForYou");
for ( int loadData = 0; loadData < imageCounterSize; loadData++ ) {
addMessage ( listHeadings.get( loadData ) , messages.get( loadData ) , images.get( loadData ));
}
}
//here we maintain our products in various departments
private int addMessage ( String heading, String message, Bitmap image ){
int groupPosition = 0;
//check the hash map if the group already exists
GroupInfo headerInfo = gMessages.get(heading);
//add the group if doesn't exists
if( headerInfo == null ) {
headerInfo = new GroupInfo();
headerInfo.setHeading(heading);
gMessages.put(heading, headerInfo);
list.add(headerInfo);
}
//get the children for the group
ArrayList<ChildInfo> productList = headerInfo.getHeadingList();
//size of the children list
int listSize = productList.size();
//add to the counter
listSize++;
//create a new child and add that to the group
ChildInfo detailInfo = new ChildInfo();
detailInfo.setSequence ( String.valueOf( listSize ) );
detailInfo.setMessage ( message );
productList.add ( detailInfo );
headerInfo.setHeadingList ( productList );
//find the group position inside the list
groupPosition = list.indexOf(headerInfo);
return groupPosition;
}
public class PerformNetworkRequest extends AsyncTask<Void, Void, String> {
String url;
HashMap < String, String > params; // Store the names of the subjects enrolled
int requestCode;
PerformNetworkRequest ( String URL, int code ) {
url = URL;
requestCode = code;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute( String s ) {
Log.d("fetchWhatsHappening", "onPostExecute Register Response: " + s.toString());
super.onPostExecute( s );
try {
JSONObject root_object = new JSONObject( s );
JSONArray array = root_object.getJSONArray("for_you");
Log.d("GET URL", "Checking URL... " + API.URL_REQUEST_FOR_YOU );
if (!root_object.getBoolean("error")) {
Toast.makeText( getActivity(), root_object.getString("message"), Toast.LENGTH_SHORT ).show();
refreshForYou ( array );
} else {
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
#Override
protected String doInBackground(Void... voids) {
RequestHandler requestHandler = new RequestHandler();
if (requestCode == CODE_POST_REQUEST)
return requestHandler.sendPostRequest(url, params);
if (requestCode == CODE_GET_REQUEST)
return requestHandler.sendGetRequest(url);
return null;
} // end of doInBackground method
} // end of PerformNetworkRequest class
/*--------------------------- Setting ListView and Downloading Images ------------------------*/
public class GroupInfo {
private String heading;
private Bitmap image;
private ArrayList < ChildInfo > list = new ArrayList < ChildInfo >();
public String getHeading() {
return heading;
}
public void setHeading ( String heading ) {
this.heading = heading;
}
public void setImage (Bitmap image) {
this.image = image;
}
public Bitmap getImage () {
return image;
}
public ArrayList < ChildInfo > getHeadingList() {
return list;
}
public void setHeadingList(ArrayList<ChildInfo> headingList) {
this.list = headingList;
}
}
public class ChildInfo {
private String sequence = "";
private String message = "";
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
LayoutInflater inflater;
private ArrayList<GroupInfo> forYou;
public ExpandableListAdapter (Context applicationContext, ArrayList<GroupInfo> forYou ) {
this.context = context;
this.forYou = forYou;
inflater = ( LayoutInflater.from( applicationContext ) );
}
#Override
public Object getChild( int groupPosition, int childPosition ) {
ArrayList < ChildInfo > headingList = forYou.get(groupPosition).getHeadingList();
return headingList.get(childPosition);
}
#Override
public long getChildId( int groupPosition, int childPosition ) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View view, ViewGroup parent) {
view = inflater.inflate(R.layout.for_you_list_item, null);
ChildInfo detailInfo = (ChildInfo) getChild( groupPosition, childPosition );
TextView childItem = (TextView) view.findViewById( R.id.forYouMessage );
childItem.setText( detailInfo.getMessage().trim() );
return view;
}
#Override
public int getChildrenCount ( int groupPosition ) {
ArrayList < ChildInfo > headingList = forYou.get( groupPosition ).getHeadingList();
return headingList.size();
}
#Override
public Object getGroup(int groupPosition) {
return forYou.get(groupPosition);
}
#Override
public int getGroupCount() {
return forYou.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view,
ViewGroup parent) {
view = inflater.inflate(R.layout.for_you_heading_list_view, null);
GroupInfo headerInfo = (GroupInfo) getGroup(groupPosition);
TextView heading = (TextView) view.findViewById(R.id.forYouHeading);
ImageView image = (ImageView) view.findViewById(R.id.forYouIcon);
heading.setText(headerInfo.getHeading().trim());
image.setImageBitmap(headerInfo.getImage());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
} // end of ExpandableListAdapter
private class DownloadImageTask extends AsyncTask < String, Void, Bitmap > {
#Override
protected Bitmap doInBackground(String... urls) {
return downloadImage ( urls[0] );
}
#Override
protected void onPostExecute (Bitmap bitmap) {
if ( imageCounter < imageCounterSize ) {
if (bitmap == null) {
Drawable vectorDrawable = ResourcesCompat.getDrawable(getActivity().getResources(), R.drawable.no_image, null);
Bitmap no_image = ((BitmapDrawable) vectorDrawable).getBitmap();
images.add(no_image);
}
else if (bitmap != null) { // Add the newly downloaded image to the list
images.add( bitmap );
}
imageCounter++;
}
} // end of onPostExecute
}
public Bitmap downloadImage (String path) {
final String TAG = "Download Task";
Bitmap bitmap = null;
InputStream inStream;
try {
// Create a URL Connection object and set its parameters
URL url = new URL(path);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
// Set connection time out of 5 seconds
urlConn.setConnectTimeout(5000);
// Set connection time out of 2.5 seconds
urlConn.setReadTimeout(2500);
// Set HTTP request method
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
// Perform network request
inStream = urlConn.getInputStream();
// Convert the input stream to Bitmap object
bitmap = BitmapFactory.decodeStream(inStream);
} catch (MalformedURLException e) {
Log.e(TAG, "URL error : " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "Download Failed : " + e.getMessage());}
return bitmap;
}
}
Here's the for_you_fragment.xml file with the ExpandableListView:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ExpandableListView
android:id="#+id/simpleExpandableListView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:divider="#f00"
android:childDivider="#0f0"
android:dividerHeight="1dp" />
</RelativeLayout>
Here's the list_item.xml code:
<?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">
<TextView
android:id="#+id/forYouMessage"
android:textSize="16dip"
android:paddingLeft="10dp"
android:paddingStart="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Here is the list_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/forYouIcon"
android:layout_width="fill_parent"
android:layout_height="200dp" />
<TextView
android:id="#+id/forYouHeading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/forYouIcon"
android:text="..."
android:textStyle="bold" />
</RelativeLayout>

You are passing wrong context here:
//get reference of the ExpandableListView
simpleExpandableListView = (ExpandableListView) this.getActivity().findViewById(R.id.simpleExpandableListView);
You have to pass the view which you are inflating as follow:
simpleExpandableListView = (ExpandableListView) view.findViewById(R.id.simpleExpandableListView);

Related

Handle empty recycle viewr within fragments

I am trying to make an application where using Recycle View and Volley to get data from server and also I used Navigation drawer and fragments,Everything working fine except When no data on recycle-view I want to show a notice like "there is no data!"I searched over internet multiple times but haven't get a proper solution or I couldn't understand properly because I am totally beginner.
bellow is my java files
1.Adapter
package com.eworld.myapplication;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ExchangesAdapter extends RecyclerView.Adapter<ExchangesViewHolder> {
private List<ExchangesSetterGetter>exchangeList;
private Context context;
public ExchangesAdapter(List<ExchangesSetterGetter> exchangeList, Context context) {
this.exchangeList = exchangeList;
this.context = context;
}
#NonNull
#Override
public ExchangesViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardlayout,viewGroup,false);
ExchangesViewHolder viewHolder=new ExchangesViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExchangesViewHolder exchangesViewHolder, int i) {
String status="";
final ExchangesSetterGetter exchangesPosition=exchangeList.get(i);
if (exchangesPosition.getStatus().equals("1")) {
status = "Awaiting Confirmation";
} else if (exchangesPosition.getStatus().equals("2")) {
status = "Awaiting Payment";
} else if (exchangesPosition.getStatus().equals("3")) {
status = "Processing";
} else if (exchangesPosition.getStatus().equals("4")) {
status = "proceed";
} else if (exchangesPosition.getStatus().equals("5")) {
status = "Timeout";
} else if (exchangesPosition.getStatus().equals("6")) {
status = "Denied";
} else if (exchangesPosition.getStatus().equals("7")) {
status = "Canceled";
} else if (exchangesPosition.getStatus().equals("8")) {
status = "Unknown";
}
exchangesViewHolder.gatewayFrom.setText(exchangesPosition.getAmountFrom() + " " + exchangesPosition.getCurrencyFrom() + " " + exchangesPosition.getExchangeFrom());
exchangesViewHolder.gatewayTo.setText(exchangesPosition.getAmountTo() + " " + exchangesPosition.getCurrencyTo() + " " + exchangesPosition.getExchangeTo());
exchangesViewHolder.status.setText(status);
Picasso.get().load("https://eworld.ltd/" + exchangesPosition.getImgSend()).into(exchangesViewHolder.imgSendFrom);
Picasso.get().load("https://eworld.ltd/" + exchangesPosition.getImgReceived()).into(exchangesViewHolder.imgSendTo);
}
#Override
public int getItemCount() {
return exchangeList.size();
}
}
2.View Holder
package com.eworld.myapplication;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ExchangesViewHolder extends RecyclerView.ViewHolder {
ImageView imgSendFrom,imgSendTo;
TextView gatewayFrom,gatewayTo,status;
public ExchangesViewHolder(#NonNull View itemView) {
super(itemView);
imgSendFrom=itemView.findViewById(R.id.img1);
imgSendTo=itemView.findViewById(R.id.img2);
gatewayFrom=itemView.findViewById(R.id.tv1);
gatewayTo=itemView.findViewById(R.id.tv2);
status=itemView.findViewById(R.id.tv3);
}
}
3.Getter and Setter(Data model)
package com.eworld.myapplication;
public class ExchangesSetterGetter {
private String exchangeFrom,exchangeTo,status,imgSend,imgReceived,currencyFrom,currencyTo,amountFrom,amountTo;
public ExchangesSetterGetter(String exchangeFrom, String exchangeTo, String status, String imgSend, String imgReceived, String currencyFrom, String currencyTo, String amountFrom, String amountTo) {
this.exchangeFrom = exchangeFrom;
this.exchangeTo = exchangeTo;
this.status = status;
this.imgSend = imgSend;
this.imgReceived = imgReceived;
this.currencyFrom = currencyFrom;
this.currencyTo = currencyTo;
this.amountFrom = amountFrom;
this.amountTo = amountTo;
}
public String getCurrencyFrom() {
return currencyFrom;
}
public void setCurrencyFrom(String currencyFrom) {
this.currencyFrom = currencyFrom;
}
public String getCurrencyTo() {
return currencyTo;
}
public void setCurrencyTo(String currencyTo) {
this.currencyTo = currencyTo;
}
public String getAmountFrom() {
return amountFrom;
}
public void setAmountFrom(String amountFrom) {
this.amountFrom = amountFrom;
}
public String getAmountTo() {
return amountTo;
}
public void setAmountTo(String amountTo) {
this.amountTo = amountTo;
}
public String getExchangeFrom() {
return exchangeFrom;
}
public void setExchangeFrom(String exchangeFrom) {
this.exchangeFrom = exchangeFrom;
}
public String getExchangeTo() {
return exchangeTo;
}
public void setExchangeTo(String exchangeTo) {
this.exchangeTo = exchangeTo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getImgSend() {
return imgSend;
}
public void setImgSend(String imgSend) {
this.imgSend = imgSend;
}
public String getImgReceived() {
return imgReceived;
}
public void setImgReceived(String imgReceived) {
this.imgReceived = imgReceived;
}
}
4.And finally my fragment Activity with recycle-view
package com.eworld.myapplication;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ExchangesFrag extends Fragment {
RecyclerView recyclerView;
ExchangesAdapter adapter;
List<ExchangesSetterGetter> listItems;
SharedPrefManager sharedPreferences;
int uid;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View exchanges=inflater.inflate(R.layout.exchanges_layout,container,false);
recyclerView=exchanges.findViewById(R.id.rview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
listItems=new ArrayList<>();
sharedPreferences=new SharedPrefManager(getActivity());
uid = sharedPreferences.getUser().getId();
loadData();
return exchanges;
}
public void loadData() {
StringRequest stringRequest=new StringRequest(Request.Method.GET, URLs.url+uid, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject receive = jsonArray.getJSONObject(i);
ExchangesSetterGetter exchangesSetterGetter = new ExchangesSetterGetter(
receive.getString("exchangeFrom"),
receive.getString("exchangeTo"),
receive.getString("status"),
receive.getString("imgSend"),
receive.getString("imgReceive"),
receive.getString("sendCurrency"),
receive.getString("receiveCurrency"),
receive.getString("amount_send"),
receive.getString("amount_receive")
);
listItems.add(exchangesSetterGetter);
}
adapter = new ExchangesAdapter(listItems, getContext());
recyclerView.setAdapter(adapter);
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(),"error on volley",Toast.LENGTH_LONG).show();
}
});
RequestQueue queue= Volley.newRequestQueue(getContext());
queue.add(stringRequest);
}
}
You can handle the empty state by having a TextView in your layout, which switch its visibility state depending upon the array size you are getting in your response as:
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject receive = jsonArray.getJSONObject(i);
ExchangesSetterGetter exchangesSetterGetter = new ExchangesSetterGetter(
receive.getString("exchangeFrom"),
receive.getString("exchangeTo"),
receive.getString("status"),
receive.getString("imgSend"),
receive.getString("imgReceive"),
receive.getString("sendCurrency"),
receive.getString("receiveCurrency"),
receive.getString("amount_send"),
receive.getString("amount_receive")
);
listItems.add(exchangesSetterGetter);
}
adapter = new ExchangesAdapter(listItems, getContext());
recyclerView.setAdapter(adapter);
recyclerView.setVisibilty(View.VISIBLE);
noDataText.setVisibilty(View.GONE);
} else {
recyclerView.setVisiblity(View.GONE);
noDataText.setVisiblity(View.VISIBLE);
}
Add an extra textview in your fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tv_no_data"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:textSize="22sp"
android:visibility="gone" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_ride_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
And then in your activity
JSONArray jsonArray = jsonObject.getJSONArray("data");
if(jsonArray.length() > 0){
//process data and initialize adapter
}else{
//Set Text view visible
}
There is a simple solution for that inside your fragment xml where recycler view is being loaded take a relative layout and add a textview with your desired message at last and set it's alignment as per your requirement and inside on create of your fragment set visiblity of your text view to View.INVISIBLE and later on after api is called simply pass an if condition stating that
if(response==null){ textview.setVisiblity = View.Visible}
The way I like to handle this is to wrap your RecyclerView and your NoContentView (this can be whatever you like) in a ViewFlipper like so
<ViewFlipper>
</RecyclerView>
<NoContentView>
</NoContentView>
</ViewFlipper>
Then all you do is to check to see if you have list items and display the appropriate child layout of the ViewFlipper
if(listItems.size() == 0)
{
viewFlipper.setDisplayedChild(1)
}

Recycler view list items are showing duplicate few items at the bottom of listview

I have one recycle list view .In this I have one button .on click list view item button shows.On button click I hit one api to perform action .After performing action ,at the bottom of list automatically one item get repeat. when ever I perform api hit action same time items add at the bottom of list .Like as I perform api hit action 4 times then every time one-one item get add at the bottom of list . Please provide me solution to resolve this.
Below I'm providing code of my adapter class :-
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.dockedinDoctor.app.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pojo.AvailableTimeSlots;
import pojo.GetBlockedTimings;
import pojo.GetDoctorScheduleDetail;
import utils.Common;
import utils.ItemClickListener;
import utils.NetworkManager;
import utils.NetworkResponseListenerJSONObject;
import utils.SessionManager;
import utils.ShowMessage;
import static utils.Common.createProgressDialog;
public class MyScheduleAdapter extends RecyclerView.Adapter<MyScheduleAdapter.ViewHolder> {
private static final String TAG = "MyScheduleTwoAdapter";
private ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails;
private ArrayList<GetBlockedTimings> getBlockedTimingses = new ArrayList<>();
private ArrayList<AvailableTimeSlots> availableTimeSlotses = new ArrayList<>();
Context context;
private LayoutInflater inflater = null;
private int mSelectedItemPosition = -1;
Activity parentActivity;
ProgressDialog pd;
int fk_time_id;
int fk_schedule_id;
int fkscheduleid;
int getFk_schedule_id;
int block_time_slot_id;
int time_slot_id;
String DateofSlot;
String BlockDateOfSlot;
int blockid;
SessionManager manager = new SessionManager();
int Doc_Id;
ArrayList<Integer> compare= new ArrayList<Integer>();
ArrayList<Integer> compare_fk= new ArrayList<Integer>();
public MyScheduleAdapter(Context context, ArrayList<GetDoctorScheduleDetail> getDoctorScheduleDetails) {
this.context = context;
this.getDoctorScheduleDetails = getDoctorScheduleDetails;
inflater = LayoutInflater.from(context);
// setHasStableIds(true);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.row_item_get_doctor_schedule, parent, false);
MyScheduleAdapter.ViewHolder holder = new MyScheduleAdapter.ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final GetDoctorScheduleDetail pojo = getDoctorScheduleDetails.get(position);
fkscheduleid = pojo.getScheduleId();
DateofSlot = pojo.getDateOfSlot();
try {
Doc_Id = manager.getPreferencesInt(context, "DocId");
Log.e(TAG, "DOCID" + Doc_Id);
holder.bindDataWithViewHolder(pojo, position);
//getting data from availavle timeslots
holder.tv_time_of_slot.setText(pojo.getAvailableTimeSlots().get(position).getTimeOfSlot());
time_slot_id = pojo.getAvailableTimeSlots().get(position).getTimeSlotId();
//want to ge
block_time_slot_id = pojo.getGetBlockedTimings().get(position).getFkTimeId();
BlockDateOfSlot = pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot();
blockid = pojo.getGetBlockedTimings().get(position).getBlockId();
Log.e(TAG, "values_blockk" + time_slot_id +" "+ block_time_slot_id);
compare.add(time_slot_id);//compare is an arraylist using to save Availablearray-->timeslot id
compare_fk.add(block_time_slot_id);//compare_fk is an arraylist using to save getblocktimeid-->fktime id
Log.e(TAG, "compare" + compare);
Log.e(TAG, "compare_fk" + compare_fk);
/*erlier I was using this*/
/*ArrayList<Integer> x = compare;
ArrayList<Integer> y = compare_fk;
for (int i = 0; i < x.size(); i++) {
Integer xval = y.get(i);
for (int j = 0; j < y.size(); j++) {
if (xval.equals(x.get(j))) {
Toast.makeText(context,"same_list"+y.get(j),Toast.LENGTH_SHORT).show();
holder.tv_time_of_slot.setTextColor(Color.RED);
}
}
}*/
int array1Size = compare.size();
int array2Size = compare_fk.size();
if (compare.size() > compare_fk.size()) {
int k = 0;
for (int i = 0; i < compare_fk.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer)compare_fk.get(i))) {
System.out.println((Integer)compare_fk.get(i));
Log.e("values_adapter", String.valueOf(((Integer)compare_fk.get(i))));
}
k = i;
}
}
else {
int k = 0;
for (int i = 0; i < compare.size(); i++) {
if (((Integer)compare.get(i)).equals((Integer) compare_fk.get(i))) {
System.out.println((Integer) compare.get(i));
Log.e("values_adapter11",String.valueOf(((Integer)compare.get(i))));
}
k = i;
}
}
if (time_slot_id == block_time_slot_id)
{
holder.tv_time_of_slot.setTextColor(Color.RED);
}
if (!(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot().equals("")))
{
holder.tv_d.setText(pojo.getGetBlockedTimings().get(position).getBlockDateOfSlot());
holder.tv_b.setText(pojo.getGetBlockedTimings().get(position).getBlockId());
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
// //iterate on the general list
// for (int i = 0; i < availableTimeSlotses.size(); i++) {
// int timeSlotId = availableTimeSlotses.get(i).getTimeSlotId();
// if (getFk_time_id == timeSlotId) {
//
// holder.tv_time_of_slot.setText(pojo.getDateOfSlot());
// }
// }
// block api
holder.btn_block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.popup_no_yes);
TextView tv_titiel = (TextView) lDialog.findViewById(R.id.tv_titiel);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msgs);
Button btnno = (Button) lDialog.findViewById(R.id.popup_no_btn);
Button btnyes = (Button) lDialog.findViewById(R.id.popup_yes_btn);
btnno.setTransformationMethod(null);
btnyes.setTransformationMethod(null);
tv_titiel.setText("Schedule");
textMsg.setText("Are you sure you want to block this slot?");
btnno.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
btnyes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("notification_fragment"));
slotBlockingApi(fkscheduleid, time_slot_id);
lDialog.dismiss();
}
});
lDialog.show();
}
});
}
#Override
public int getItemCount() {
return getDoctorScheduleDetails.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void slotBlockingApi(int _fk_schedule_id, int _fk_time_id) {
isOnline();
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"fkScheduledId\":\"" + _fk_schedule_id +
"\",\"fkTimeId\":\"" + _fk_time_id +
"\",\"DoctorId\":\"" + Doc_Id +
"\"}'";
Log.e(TAG, "requset body of slotBlockingApi : " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorCheckForAppointmentBeforeSlotBlocking",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
Log.e(TAG, "response of slotBlockingApi : " + data.toString());
try {
JSONObject jsonObject = new JSONObject(data.toString());
JSONObject ResponseJsonObject1 = jsonObject.getJSONObject("Response");
int ResponseCode = ResponseJsonObject1.getInt("ResponseCode");
String ResponseText = ResponseJsonObject1.getString("ResponseText");
// JSONObject jsonObjectDetail = jsonObject.getJSONObject("Detail");
// Log.e(TAG, "jsonObjectDetail : " + jsonObjectDetail);
// int doc_id = jsonObjectDetail.getInt("DocId");
// if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
if (ResponseText == "No Appointment" || ResponseText.equals("No Appointment") || ResponseText.equalsIgnoreCase("No Appointment")) {
// if (ResponseText =="No Appointment" || ResponseText.equals("No Appointment")) {
pd = createProgressDialog(context);
pd.show();
final String requestBody = "'{\"utcTimeOffset\":\"" + "330" +
"\",\"BlockedScheduledDate\":\"" + DateofSlot +
"\",\"fkScheduledId\":\"" + fkscheduleid +
"\",\"fkTimeId\":\"" + time_slot_id +
"\"}'";
Log.e(TAG, "requset body of slotBlocking: " + requestBody);
NetworkManager.getInstance(context).makeNetworkRequestForJSON(
Request.Method.POST,
Common.BASE_URL + "/PostDoctorBlockTimeSlot",
null,
requestBody,
null,
new NetworkResponseListenerJSONObject() {
#Override
public void onDataReceived(Object data) {
pd.dismiss();
new ShowMessage(context, "Block Slot","Time slot blocked Successfully");
Log.e(TAG, "response of slotBlocking: " + data.toString());
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
} else {
final Dialog lDialog = new Dialog(context);
lDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
lDialog.setCancelable(false);
lDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
lDialog.getWindow().setDimAmount(.7f);
lDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
lDialog.getWindow().setElevation(4);
}
lDialog.setContentView(R.layout.custom_popup);
TextView textTitle = (TextView) lDialog.findViewById(R.id.popup_title);
TextView textMsg = (TextView) lDialog.findViewById(R.id.popup_msg);
Button okButton = (Button) lDialog.findViewById(R.id.popup_ok_btn);
okButton.setTransformationMethod(null);
textTitle.setText("Schedule");
textMsg.setText("An appointment has been booked on this slot.");
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lDialog.dismiss();
}
});
lDialog.show();
}
// else if (ResponseCode == 0 || ResponseCode == 2) {
// new ShowMessage(context, ResponseText);
// }
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onDataFailed(VolleyError error) {
pd.dismiss();
String json = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
switch (response.statusCode) {
case 302:
Toast.makeText(context, "No Internet Connection Found.", Toast.LENGTH_SHORT).show();
break;
}
//Additional cases
}
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
new ShowMessage(context, "Network error","Internet not available, Cross check your internet connectivity and try again");
}
return true;
}
/**
* VIEW HOLDER CLASS DEFINE HERE
*/
public class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ll_row_item_get_doctor_schedule)
LinearLayout ll_row_item_get_doctor_schedule;
#BindView(R.id.tv_time_of_slot)
TextView tv_time_of_slot;
#BindView(R.id.btn_block)
Button btn_block;
#BindView(R.id.btn_unblock)
Button btn_unblock;
#BindView(R.id.tv_d)
TextView tv_d;
#BindView(R.id.tv_b)
TextView tv_b;
GetDoctorScheduleDetail doctorScheduleDetail = null;
ItemClickListener clickListener;
private ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
ll_row_item_get_doctor_schedule.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Handling for background selection state changed
int previousSelectState = mSelectedItemPosition;
mSelectedItemPosition = getAdapterPosition();
//notify previous selected item
notifyItemChanged(previousSelectState);
//notify new selected Item
notifyItemChanged(mSelectedItemPosition);
//Your other handling in onclick
}
});
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
#OnClick
public void onClickMethod(View v) {
clickListener.onClick(v, getPosition(), false);
}
public void bindDataWithViewHolder(GetDoctorScheduleDetail schedulePojo, int currentPosition) {
this.doctorScheduleDetail = schedulePojo;
//Handle selection state in object View.
if (currentPosition == mSelectedItemPosition) {
btn_block.setVisibility(View.VISIBLE);
} else {
btn_block.setVisibility(View.GONE);
}
//other View binding logics like setting text , loading image etc.
}
}
}

How to implement setOnItemLongClickListener(), to select a folder in the list view?

I am using, setonItemClickListener() to select a file (and get its path in the edittext) at this time (means working).
I was trying hard to implement setOnItemLongClickListener() to select folder when long touch on folder to get its path.
Before it I was using, getparent() of the file choosed, to take the parent folder path to get the folder path in the edittext when the folder radio button is selected.
Question: How to implement setOnItemLongClickListener(), to select a folder in the list view?
Is it possible to give the functionality setonItemLongClickListener() for folder along with setonItemClickListener() for file or creation of all the code files for folder is also required, as for files?
All answers are appreciated.
Code files already working to get files, and folder path (by doing getparent() of the file) are:
MainFragment.java
String curFileName;
String filePath;
EditText edittext;
String AppendedForFullPath;
edittext = (EditText) view.findViewById(R.id.editText); //Done for File Exploring, EditText, Browse Button.
Button b1 = (Button) view.findViewById(R.id.skipButton); //Browse button
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(v.getContext(), FileChooser.class);
startActivityForResult(intent1, REQUEST_PATH);
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// See which child activity is calling us back.
if (requestCode == REQUEST_PATH) {
if (resultCode == Activity.RESULT_OK) {
curFileName = data.getStringExtra("GetFileName");
filePath = data.getStringExtra("GetPath");
AppendedForFullPath = filePath + "/" + curFileName;
edittext.setText(AppendedForFullPath);
/*File file = new File(filePath);
File parentDir = file.getParentFile(); // to get the parent dir
String parentDirName = file.getParent(); // to get the parent dir name
edittext.setText(parentDirName);*/
}
}
}
private List<File> getListFiles(File parentDir) { //Used in algorithms to traverse files and subfolders.
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
//Toast.makeText(getActivity().getApplicationContext(), "Hello, I am a folder.", Toast.LENGTH_SHORT).show();
inFiles.addAll(getListFiles(file));
} else {
if (file.isFile()) {
//Toast.makeText(getActivity().getApplicationContext(), "Hello, I am a file", Toast.LENGTH_SHORT).show();
inFiles.add(file);
}
}
}
return inFiles;
}
FileChooser.java
/**
* Created by hp on 01-06-2016.
*/
import java.io.File;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.text.DateFormat;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir=new File("/sdcard/");
fill(currentDir);
}
private void fill(File f)
{
File[]dirs=f.listFiles();
this.setTitle("Current Dir: "+f.getName());
List<Item>dir=new ArrayList<Item>();
List<Item>fls=new ArrayList<Item>();
try{
for(File ff: dirs)
{
Date lastModDate=new Date(ff.lastModified());
DateFormat formater=DateFormat.getDateTimeInstance();
String date_modify=formater.format(lastModDate);
if(ff.isDirectory()){
File[] fbuf=ff.listFiles();
int buf=0;
if(fbuf != null){
buf=fbuf.length;
}
else
buf=0;
String num_item=String.valueOf(buf);
if(buf == 0)
num_item=num_item+" item";
else
num_item=num_item+" items";
//String formated = lastModDate.toString();
dir.add(new Item(ff.getName(), num_item, date_modify, ff.getAbsolutePath(), "directory_icon"));
}
else
{
fls.add(new Item(ff.getName(), ff.length()+" Byte", date_modify, ff.getAbsolutePath(), "file_icon"));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0, new Item("..", "Parent Directory", "", f.getParent(), "directory_up"));
adapter=new FileArrayAdapter(FileChooser.this, R.layout.file_view, dir);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Item o = adapter.getItem(position);
if(o.getImage().equalsIgnoreCase("directory_icon") || o.getImage().equalsIgnoreCase("directory_up"))
{
currentDir=new File(o.getPath());
fill(currentDir);
}
else
{
onFileClick(o);
}
}
private void onFileClick(Item o)
{
//Toast.makeText(this, "Folder Clicked: "+ currentDir, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("GetPath", currentDir.toString());
intent.putExtra("GetFileName", o.getName());
setResult(RESULT_OK, intent);
finish();
}
}
FileArrayAdapter.java
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FileArrayAdapter extends ArrayAdapter<Item>{
private Context c;
private int id;
private List<Item>items;
public FileArrayAdapter(Context context, int textViewResourceId, List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i){
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
//convertView = ( RelativeLayout ) inflater.inflate( resource, null );
final Item o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if(t1 != null)
t1.setText(o.getName());
if(t2 != null)
t2.setText(o.getData());
if(t3 != null)
t3.setText(o.getDate());
}
return v;
}
}
Item.java
public class Item implements Comparable<Item>{
private String name;
private String data;
private String date;
private String path;
private String image;
public Item(String n,String d, String dt, String p, String img)
{
name = n;
data = d;
date = dt;
path = p;
image = img;
}
public String getName()
{
return name;
}
public String getData()
{
return data;
}
public String getDate()
{
return date;
}
public String getPath()
{
return path;
}
public String getImage() {
return image;
}
public int compareTo(Item o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
}
}
file_view.xml
<?xml version="1.0" encoding="utf-8"?>
<!--<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>-->
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_width="fill_parent">
<ImageView
android:id="#+id/fd_Icon1"
android:layout_width="50dip"
android:layout_height="50dip"
/>
<TextView
android:text="#+id/TextView01"
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textStyle="bold"
android:layout_toRightOf="#+id/fd_Icon1"
android:layout_marginTop="5dip"
android:layout_marginLeft="5dip"
/>
<TextView
android:text="#+id/TextView02"
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/fd_Icon1"
android:layout_below="#+id/TextView01"
android:layout_marginLeft="10dip">
</TextView>
<TextView
android:text="#+id/TextViewDate"
android:id="#+id/TextViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView01"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dip">
</TextView>
</RelativeLayout>

Set Json Array values to AutoCompleteTextView in Android

I am new in Android development, I want to bind a Json array to android AutocompleteTextView in Form (Registration form).
the Json array is showed in below
{"Status":true,"errorType":null,"InstituteList":[{"InstituteID":"1","InstituteName":"Demo Institute"},{"InstituteID":"16","InstituteName":"Sheridan College"},{"InstituteID":"17","InstituteName":"iCent Prosp"},{"InstituteID":"18","InstituteName":"Seneca College"}]}
here the Type Institution Name is the auto completeTextView. The main requirement is that, I can bind the values like in the Json response InstituteName on the front end and When click on the Submit Button it needs to take the InstituteID Object.
Currently I can bind the InstituteName Object to AutocompleteTextView and Working fine.
But the Submit Action was not performing perfectly.
I cant getting the InstituteID in my codes for performing
Here is my code.
Getting response from web service as json array and binding in asyncTask.
#Override
protected void onPostExecute(String res) {
try
{
Log.i("Intitute List",res);
JSONObject responseObject = new JSONObject(res);
String status=responseObject.getString("Status");
ArrayList<String> listInstituteNames = new ArrayList<>();
JSONArray detailsArray = responseObject.getJSONArray("InstituteList");
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i);
listInstituteNames.add(obj.getString("InstituteName"));
}
//Log.i("InstituteName", String.valueOf(listInstituteNames));
myStringArray = listInstituteNames;
AutoCompleteAdapter adapter = new AutoCompleteAdapter(SignUpActivity.this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, listInstituteNames);
autoTextView.setThreshold(1);
autoTextView.setAdapter(adapter);
}
catch (JSONException e1) {
e1.printStackTrace();
}
AutoCompleteAdapter.java
package Adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> fullList;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
public AutoCompleteAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {
super(context, resource, textViewResourceId, objects);
fullList = (ArrayList<String>) objects;
mOriginalValues = new ArrayList<String>(fullList);
}
#Override
public int getCount() {
return fullList.size();
}
#Override
public String getItem(int position) {
return fullList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return super.getView(position, convertView, parent);
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}
private class ArrayFilter extends Filter {
private Object lock;
#Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();
if (mOriginalValues == null) {
synchronized (lock) {
mOriginalValues = new ArrayList<String>(fullList);
}
}
if (prefix == null || prefix.length() == 0) {
synchronized (lock) {
ArrayList<String> list = new ArrayList<String>(mOriginalValues);
results.values = list;
results.count = list.size();
}
} else {
final String prefixString = prefix.toString().toLowerCase();
ArrayList<String> values = mOriginalValues;
int count = values.size();
ArrayList<String> newValues = new ArrayList<String>(count);
for (int i = 0; i < count; i++) {
String item = values.get(i);
if (item.toLowerCase().contains(prefixString)) {
newValues.add(item);
}
}
results.values = newValues;
results.count = newValues.size();
}
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if(results.values!=null){
fullList = (ArrayList<String>) results.values;
}else{
fullList = new ArrayList<String>();
}
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
AutoCompleteTextView Section in XML File..
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="#+id/autoCompt"
android:orientation="vertical">
<AutoCompleteTextView
android:id="#+id/instname_field"
android:layout_width="match_parent"
android:hint="Type Institution Name"
android:paddingLeft="10dp"
android:textColor="#fff"
android:background="#b8d1e5"
android:layout_height="40dp"
android:textSize="20dp"
android:ems="10"/>
</LinearLayout>
How can I solve this Issue. Thanks.
You can see #blackBelt comment that is the right way to do that.
But here i am explain you another method which is easy to understand using Hashmap instead of Object class .
HashMap<String, String> map_name_value = new HashMap<String, Stirng>();
for (int i = 0; i <detailsArray.length() ; i++) {
JSONObject obj = detailsArray.getJSONObject(i)
listInstituteNames.add(obj.getString("InstituteName"))
map_name_value.put(obj.getString("InstituteName"),obj.getString("InstituteID"));
}
Then while clicking the item.
Do this:
autoTextView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int pos,
long id) {
Editable message = autoTextView.getText();
String item_name = message.toString();
String item_id = map_name_value.get(item_name);
//your stuff
}
});
//item_name is name of institute
// item_id is id of institute

Issue with checkbox checked

i am use this for setting checkbox in listview i have follow all step as per given tutorial, but there are some critical issue with output, is that when i am select first checkbox and scroll down it will change selected item and automatically appear 3rd.
so i think there are something wrong with getview. so please help me out this ....
here is my code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
public class Favorites extends ListActivity {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
ArrayList alAppName;
float[] rate;
boolean[] bSelected;
ArrayList<Comment> alPackagenm;
Drawable[] alIcon;
ViewHolder holder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
for (int i = 0; i < strAr.length; i++) {
System.out.println("strAr[" + i + "] " + strAr[i]);
}
for (String s : strAr) {
list.add(new RowModel(s));
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar,
float rating, boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
}
});
holder.chkbxFavrowsel.setTag(mlist.get(position));
holder.ratingBar1.setOnRatingBarChangeListener(l);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
return (row);
}
}
}
I really don't understand your code exactly what you are trying to do. I haven't seen before this you are checking holder == null where as it should be convertView == null. If you have a scrolling issue you can check my blog post
holder = (ViewHolder) row.getTag();
if (holder == null) {
holder = new ViewHolder(row);
row.setTag(holder);
...
}
else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
Use Below Code to your MainActivity.java file.
public class ListViewActivity extends Activity {
ListView mLstView1;
Button mBtn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLstView1 = (ListView) findViewById(R.id.mLstView1);
String[] lv_items = { "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil", "Dipak", "Rahul", "Hiren", "Nandlal", "Keyur",
"Kapil" };
;
mLstView1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, lv_items));
mLstView1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Using a List to hold the IDs, but could use an array.
List<Integer> checkedIDs = new ArrayList<Integer>();
// Get all of the items that have been clicked - either on or
// off
final SparseBooleanArray checkedItems = mLstView1
.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
// And this tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if (isChecked) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// Put the value of the id in our list
checkedIDs.add(position);
System.out.println("Position is:- " + position);
}
}
}
});
}
}

Categories