Using the OpenFileDialog.java class to create the file selection dialog, I did not find a way to get the full path of the selected file upon ok button click.
I tried to use String currentPath and TextView title but without success.
How can I get the full path to the file?
This class was written specifically for Android devices by Sergei Skogun.
(This code writes non-extractive text)
package com.DAG.CoderIC;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.*;
import android.widget.*;
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: Scogun
* Date: 27.11.13
* Time: 10:47
*/
public class OpenFileDialog extends AlertDialog.Builder {
public String currentPath = Environment.getExternalStorageDirectory().getPath();
private List<File> files = new ArrayList<File>();
private TextView title;
private ListView listView;
private FilenameFilter filenameFilter;
private int selectedIndex = -1;
private OpenDialogListener listener;
private Drawable folderIcon;
private Drawable fileIcon;
private String accessDeniedMessage;
private boolean isOnlyFoldersFilter;
public interface OpenDialogListener {
public void OnSelectedFile(String fileName);
}
private class FileAdapter extends ArrayAdapter<File> {
public FileAdapter(Context context, List<File> files) {
super(context, android.R.layout.simple_list_item_1, files);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
File file = getItem(position);
if (view != null) {
view.setText(file.getName());
if (file.isDirectory()) {
setDrawable(view, folderIcon);
} else {
setDrawable(view, fileIcon);
if (selectedIndex == position)
view.setBackgroundColor(getContext().getResources().getColor(android.R.color.holo_blue_dark));
else
view.setBackgroundColor(getContext().getResources().getColor(android.R.color.transparent));
}
}
return view;
}
private void setDrawable(TextView view, Drawable drawable) {
if (view != null) {
if (drawable != null) {
drawable.setBounds(0, 0, 60, 60);
view.setCompoundDrawables(drawable, null, null, null);
} else {
view.setCompoundDrawables(null, null, null, null);
}
}
}
}
public OpenFileDialog(Context context) {
super(context);
isOnlyFoldersFilter = false;
title = createTitle(context);
changeTitle();
LinearLayout linearLayout = createMainLayout(context);
linearLayout.addView(createBackItem(context));
listView = createListView(context);
linearLayout.addView(listView);
setCustomTitle(title)
.setView(linearLayout)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (selectedIndex > -1 && listener != null) {
listener.OnSelectedFile(listView.getItemAtPosition(selectedIndex).toString());
}
if (listener != null && isOnlyFoldersFilter) {
listener.OnSelectedFile(currentPath);
}
}
})
.setNegativeButton(android.R.string.cancel, null);
}
#Override
public AlertDialog show() {
files.addAll(getFiles(currentPath));
listView.setAdapter(new FileAdapter(getContext(), files));
return super.show();
}
public OpenFileDialog setFilter(final String filter) {
filenameFilter = new FilenameFilter() {
#Override
public boolean accept(File file, String fileName) {
File tempFile = new File(String.format("%s/%s", file.getPath(), fileName));
if (tempFile.isFile())
return tempFile.getName().matches(filter);
return true;
}
};
return this;
}
public OpenFileDialog setOnlyFoldersFilter() {
isOnlyFoldersFilter = true;
filenameFilter = new FilenameFilter() {
#Override
public boolean accept(File file, String fileName) {
File tempFile = new File(String.format("%s/%s", file.getPath(), fileName));
return tempFile.isDirectory();
}
};
return this;
}
public OpenFileDialog setOpenDialogListener(OpenDialogListener listener) {
this.listener = listener;
return this;
}
public OpenFileDialog setFolderIcon(Drawable drawable) {
this.folderIcon = drawable;
return this;
}
public OpenFileDialog setFileIcon(Drawable drawable) {
this.fileIcon = drawable;
return this;
}
public OpenFileDialog setAccessDeniedMessage(String message) {
this.accessDeniedMessage = message;
return this;
}
private static Display getDefaultDisplay(Context context) {
return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
}
private static Point getScreenSize(Context context) {
Point screeSize = new Point();
getDefaultDisplay(context).getSize(screeSize);
return screeSize;
}
private static int getLinearLayoutMinHeight(Context context) {
return getScreenSize(context).y;
}
private LinearLayout createMainLayout(Context context) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setMinimumHeight(getLinearLayoutMinHeight(context));
return linearLayout;
}
private int getItemHeight(Context context) {
TypedValue value = new TypedValue();
DisplayMetrics metrics = new DisplayMetrics();
context.getTheme().resolveAttribute(android.R.attr.listPreferredItemHeightSmall, value, true);
getDefaultDisplay(context).getMetrics(metrics);
return (int) TypedValue.complexToDimension(value.data, metrics);
}
private TextView createTextView(Context context, int style) {
TextView textView = new TextView(context);
textView.setTextAppearance(context, style);
int itemHeight = getItemHeight(context);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight));
textView.setMinHeight(itemHeight);
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setPadding(15, 0, 0, 0);
return textView;
}
private TextView createTitle(Context context) {
TextView textView = createTextView(context, android.R.style.TextAppearance_DeviceDefault_DialogWindowTitle);
return textView;
}
private TextView createBackItem(Context context) {
TextView textView = createTextView(context, android.R.style.TextAppearance_DeviceDefault_Small);
Drawable drawable = getContext().getResources().getDrawable(android.R.drawable.ic_menu_directions);
drawable.setBounds(0, 0, 60, 60);
textView.setCompoundDrawables(drawable, null, null, null);
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
File file = new File(currentPath);
File parentDirectory = file.getParentFile();
if (parentDirectory != null) {
currentPath = parentDirectory.getPath();
RebuildFiles(((FileAdapter) listView.getAdapter()));
}
}
});
return textView;
}
public int getTextWidth(String text, Paint paint) {
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
return bounds.left + bounds.width() + 80;
}
private void changeTitle() {
String titleText = currentPath;
int screenWidth = getScreenSize(getContext()).x;
int maxWidth = (int) (screenWidth * 0.99);
if (getTextWidth(titleText, title.getPaint()) > maxWidth) {
while (getTextWidth("..." + titleText, title.getPaint()) > maxWidth) {
int start = titleText.indexOf("/", 2);
if (start > 0)
titleText = titleText.substring(start);
else
titleText = titleText.substring(2);
}
title.setText("..." + titleText);
} else {
title.setText(titleText);
}
}
private List<File> getFiles(String directoryPath) {
File directory = new File(directoryPath);
File[] list = directory.listFiles(filenameFilter);
if(list == null)
list = new File[]{};
List<File> fileList = Arrays.asList(list);
Collections.sort(fileList, new Comparator<File>() {
#Override
public int compare(File file, File file2) {
if (file.isDirectory() && file2.isFile())
return -1;
else if (file.isFile() && file2.isDirectory())
return 1;
else
return file.getPath().compareTo(file2.getPath());
}
});
return fileList;
}
private void RebuildFiles(ArrayAdapter<File> adapter) {
try {
List<File> fileList = getFiles(currentPath);
files.clear();
selectedIndex = -1;
files.addAll(fileList);
adapter.notifyDataSetChanged();
changeTitle();
} catch (NullPointerException e) {
String message = getContext().getResources().getString(android.R.string.unknownName);
if (!accessDeniedMessage.equals(""))
message = accessDeniedMessage;
Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
}
}
private ListView createListView(Context context) {
ListView listView = new ListView(context);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
final ArrayAdapter<File> adapter = (FileAdapter) adapterView.getAdapter();
File file = adapter.getItem(index);
if (file.isDirectory()) {
currentPath = file.getPath();
RebuildFiles(adapter);
} else {
if (index != selectedIndex)
selectedIndex = index;
else
selectedIndex = -1;
adapter.notifyDataSetChanged();
}
}
});
return listView;
}
}
ok, solution found!
wait a minute I'm writing ...
Edit:
First, make sure you have this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Upon ok button click DialogInterface.OnClickListener() getting called, so all you have to do is get the corresponding file in private List<File> files = new ArrayList<File>(); and then get file's absolute path via File.getAbsolutePath()
like so: Log.i("OpenFileDialog", "selected: " + files.get(selectedIndex).getAbsolutePath());
public OpenFileDialog(Context context) {
super(context);
isOnlyFoldersFilter = false;
title = createTitle(context);
changeTitle();
LinearLayout linearLayout = createMainLayout(context);
linearLayout.addView(createBackItem(context));
listView = createListView(context);
linearLayout.addView(listView);
setCustomTitle(title)
.setView(linearLayout)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (selectedIndex > -1 && listener != null) {
listener.OnSelectedFile(listView.getItemAtPosition(selectedIndex).toString());
Log.i("OpenFileDialog", "selected: " + files.get(selectedIndex).getAbsolutePath());
}
if (listener != null && isOnlyFoldersFilter) {
listener.OnSelectedFile(currentPath);
}
}
})
.setNegativeButton(android.R.string.cancel, null);
} }
the sample project can be found here:
https://github.com/raiytu4/training11
Related
i want to change color of my textview inside of cardview when its value is "kritis" or "kurang" but somehow everytime when my textview in position 0 and its value is either kritis or kurang it always change color textiew in position 0 and also position 7, and also when its in position 1 it will set color text view in position 8 too and so... and then i try to use logd to see howmany times my setcolor initiate and its only 1x (when changing color only position 1 and 7) or 2x (when changing color text position 0,1,7,8)(my cardview is inside recyclerview)
this is my adapter code
public class ListAdapter extends RecyclerView.Adapter<form_mhs_04_fragment2.ListAdapter.ViewHolder>
{
private ArrayList<DataNote> dataList;
public ListAdapter(ArrayList<DataNote> data)
{
this.dataList = data;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView textViewIPKcap;
TextView textViewIPKkat;
TextView textViewSKScap;
TextView textViewSKSkat;
TextView textViewCatatan;
TextView textViewSemester;
public ViewHolder(View itemView)
{
super(itemView);
this.textViewSemester = (TextView) itemView.findViewById(R.id.TV04_cardview_semester);
this.textViewIPKcap = (TextView) itemView.findViewById(R.id.TV04_cardview_ipkcap);
this.textViewIPKkat = (TextView) itemView.findViewById(R.id.TV04_cardview_ipkkat);
this.textViewSKScap = (TextView) itemView.findViewById(R.id.TV04_cardview_skscap);
this.textViewSKSkat = (TextView) itemView.findViewById(R.id.TV04_cardview_skskat);
this.textViewCatatan = (TextView) itemView.findViewById(R.id.TV04_cardview_catatan);
}
}
#Override
public form_mhs_04_fragment2.ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.form_mhs_04_cardview, parent, false);
form_mhs_04_fragment2.ListAdapter.ViewHolder viewHolder = new form_mhs_04_fragment2.ListAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(form_mhs_04_fragment2.ListAdapter.ViewHolder holder, final int position)
{
holder.textViewIPKkat.setText(dataList.get(position).getIpkkat());
holder.textViewIPKcap.setText("IPK : "+dataList.get(position).getIpkcap());
holder.textViewSKSkat.setText(dataList.get(position).getSkskat());
holder.textViewSKScap.setText("SKS : "+dataList.get(position).getSkscap()+" SKS");
holder.textViewCatatan.setText(dataList.get(position).getCatatan());
holder.textViewSemester.setText(dataList.get(position).getSemester());
if(holder.textViewSKSkat.getText().equals("kritis") || holder.textViewSKSkat.getText().equals("kurang")){
holder.textViewSKSkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
}
if(holder.textViewIPKkat.getText().equals("kritis") || holder.textViewIPKkat.getText().equals("kurang")){
holder.textViewIPKkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
}
holder.itemView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
}
#Override
public int getItemCount()
{
return dataList.size();
}
}
this is how i send data to adapter
public void initListView(String UserId){
Call<ListForm4Response> getListForm4 = mApiService.getListForm4(
UserId
);
getListForm4.enqueue(new Callback<ListForm4Response>() {
#Override
public void onResponse(Call<ListForm4Response> call, Response<ListForm4Response> response) {
boolean iserror_ = response.body().getError();
if (iserror_ == false) {
List<List_Form4> list = new ArrayList<>();
list = response.body().getEvalMhsf4();
ipk_cap = new String[list.size()];
ipk_kat = new String[list.size()];
sks_cap = new String[list.size()];
sks_kat = new String[list.size()];
catatan = new String[list.size()];
semester = new String[list.size()];
for (int i =0;i<list.size();i++) {
ipk_cap[i] = list.get(i).getIpkMhs();
ipk_kat[i] = list.get(i).getKategoriIpk();
sks_cap[i] = String.valueOf(list.get(i).getSksMhs());
sks_kat[i] = list.get(i).getKategoriSks();
catatan[i] = list.get(i).getCatatan();
semester[i] = list.get(i).getSemester();
}
ArrayList data = new ArrayList<DataNote>();
for (int i = 0; i < list.size(); i++)
{
data.add(
new DataNote
(
ipk_cap[i],
ipk_kat[i],
sks_cap[i],
sks_kat[i],
catatan[i],
semester[i]
));
}
mListadapter = new form_mhs_04_fragment2.ListAdapter(data);
listview.setAdapter(mListadapter);
}
}
#Override
public void onFailure(Call<ListForm4Response> call, Throwable t) {
Toast.makeText(getActivity().getBaseContext(), "Koneksi Jaringan Bermasalah", Toast.LENGTH_SHORT).show();
Log.e("debug", "onFailure: ERROR > " + t.toString());
Intent intent = new Intent(getActivity().getBaseContext(), Form_Mhs_Menu.class);
getActivity().startActivity(intent);
}
});
}
and this is my Datanote
package com.example.bimbinganpasi.Form_04.adapter;
public class DataNote {
String ipkkat,ipkcap,skskat,skscap,catatan,semester;
public DataNote(String ipkcap, String ipkkat, String skscap, String skskat,String catatan ,String semester) {
this.ipkkat = ipkkat;
this.ipkcap = ipkcap;
this.skskat = skskat;
this.skscap = skscap;
this.catatan = catatan;
this.semester = semester;
}
public String getIpkkat() {
return ipkkat;
}
public String getIpkcap() {
return ipkcap;
}
public String getSkskat() {
return skskat;
}
public String getSkscap() {
return skscap;
}
public String getCatatan() {
return catatan;
}
public String getSemester() {
return semester;
}
}
try adding else to set default background color :
if(holder.textViewSKSkat.getText().equals("kritis") || holder.textViewSKSkat.getText().equals("kurang")){
holder.textViewSKSkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
} else {
holder.textViewSKSkat.setTextColor(Color.rgb(0,0,0)); //TODO : SET DEFAULT COLOR
}
if(holder.textViewIPKkat.getText().equals("kritis") || holder.textViewIPKkat.getText().equals("kurang")){
holder.textViewIPKkat.setTextColor(Color.rgb(255,0,0));
Log.d("testing", "ayayaya");
} else {
holder.textViewIPKkat.setTextColor(Color.rgb(0,0,0)); //TODO : SET DEFAULT COLOR
}
In My Case i tried this code..
holder.textview.setColor(ContextCompat.getColor(YourActivity.this,R.color.colorPrimary));
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I have problem is "java.lang.NullPointerException"
I want to know how I can solve it , I want to show dialoge
Look at the picture
I have two of the classes MainActivity and MaterialDialog
See the error message :
> FATAL EXCEPTION: main
> Process: com.example.android.dialoge, PID: 14884
> java.lang.NullPointerException
> at
> com.example.android.dialoge.MaterialDialog$Builder.setTitle(MaterialDialog.java:265)
> at
> com.example.android.dialoge.MaterialDialog$Builder.<init>(MaterialDialog.java:198)
> at
> com.example.android.dialoge.MaterialDialog$Builder.<init>(MaterialDialog.java:179)
> at
> com.example.android.dialoge.MaterialDialog.show(MaterialDialog.java:59)
> at com.example.android.dialoge.MainActivity.test(MainActivity.java:58)
> at
> com.example.android.dialoge.MainActivity$1.onClick(MainActivity.java:28)
> at android.view.View.performClick(View.java:4438)
> at android.view.View$PerformClick.run(View.java:18422)
> at android.os.Handler.handleCallback(Handler.java:733)
> at android.os.Handler.dispatchMessage(Handler.java:95)
> at android.os.Looper.loop(Looper.java:136)
> at android.app.ActivityThread.main(ActivityThread.java:5001)
> 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:785)
> at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
> at dalvik.system.NativeStart.main(Native Method)
// see the first class MainActivity
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
Button clickButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickButton = (Button) findViewById(R.id.button);
clickButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
test();
}
/*
MaterialDialog dialog = new MaterialDialog.Builder(MainActivity.this).build();
RecyclerView list = dialog.getRecyclerView();
// Do something with it
dialog.show();
*/
});
}
void test(){
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
for (int j = 0; j < 38; j++) {
arrayAdapter.add("This is item " + j);
}
ListView listView = new ListView(this);
listView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (8 * scale + 0.5f);
listView.setPadding(0, dpAsPixels, 0, dpAsPixels);
listView.setDividerHeight(0);
listView.setAdapter(arrayAdapter);
final com.example.android.dialoge.MaterialDialog alert = new com.example.android.dialoge.MaterialDialog(this)
.setTitle("ghjghj").setContentView(listView);
alert.setPositiveButton("OK", new View.OnClickListener() {
#Override public void onClick(View v) {
alert.dismiss();
}
});
alert.show();
}
}
// See the Second Class MaterialDialog :
public class MaterialDialog {
private final static int BUTTON_BOTTOM = 9;
private final static int BUTTON_TOP = 9;
private boolean mCancel;
private Context mContext;
private AlertDialog mAlertDialog;
private MaterialDialog.Builder mBuilder;
private View mView;
private int mTitleResId;
private CharSequence mTitle;
private int mMessageResId;
private CharSequence mMessage;
private Button mPositiveButton;
private LinearLayout.LayoutParams mLayoutParams;
private Button mNegativeButton;
private boolean mHasShow = false;
private int mBackgroundResId = -1;
private Drawable mBackgroundDrawable;
private View mMessageContentView;
private int mMessageContentViewResId;
private DialogInterface.OnDismissListener mOnDismissListener;
private int pId = -1, nId = -1;
private String pText, nText;
View.OnClickListener pListener, nListener;
public MaterialDialog(Context context) {
this.mContext = context;
}
public void show() {
if (!mHasShow) {
mBuilder = new Builder();
} else {
mAlertDialog.show();
}
mHasShow = true;
}
public MaterialDialog setView(View view) {
mView = view;
if (mBuilder != null) {
mBuilder.setView(view);
}
return this;
}
public MaterialDialog setContentView(View view) {
mMessageContentView = view;
mMessageContentViewResId = 0;
if (mBuilder != null) {
mBuilder.setContentView(mMessageContentView);
}
return this;
}
/**
* Set a custom view resource to be the contents of the dialog.
*
* #param layoutResId resource ID to be inflated
*/
public MaterialDialog setContentView(int layoutResId) {
mMessageContentViewResId = layoutResId;
mMessageContentView = null;
if (mBuilder != null) {
mBuilder.setContentView(layoutResId);
}
return this;
}
public void dismiss() {
mAlertDialog.dismiss();
}
private int dip2px(float dpValue) {
final float scale = mContext.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
private static boolean isLollipop() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
}
public MaterialDialog setTitle(int resId) {
mTitleResId = resId;
if (mBuilder != null) {
mBuilder.setTitle(resId);
}
return this;
}
public MaterialDialog setTitle(CharSequence title) {
mTitle = title;
if (mBuilder != null) {
mBuilder.setTitle(title);
}
return this;
}
public MaterialDialog setMessage(int resId) {
mMessageResId = resId;
if (mBuilder != null) {
mBuilder.setMessage(resId);
}
return this;
}
public MaterialDialog setMessage(CharSequence message) {
mMessage = message;
if (mBuilder != null) {
mBuilder.setMessage(message);
}
return this;
}
public MaterialDialog setPositiveButton(int resId, final View.OnClickListener listener) {
this.pId = resId;
this.pListener = listener;
return this;
}
public Button getPositiveButton() {
return mPositiveButton;
}
public Button getNegativeButton() {
return mNegativeButton;
}
public MaterialDialog setPositiveButton(String text, final View.OnClickListener listener) {
this.pText = text;
this.pListener = listener;
return this;
}
public MaterialDialog setNegativeButton(int resId, final View.OnClickListener listener) {
this.nId = resId;
this.nListener = listener;
return this;
}
public MaterialDialog setNegativeButton(String text, final View.OnClickListener listener) {
this.nText = text;
this.nListener = listener;
return this;
}
/**
* Sets whether this dialog is canceled when touched outside the window's
* bounds OR pressed the back key. If setting to true, the dialog is
* set to be cancelable if not
* already set.
*
* #param cancel Whether the dialog should be canceled when touched outside
* the window OR pressed the back key.
*/
public MaterialDialog setCanceledOnTouchOutside(boolean cancel) {
this.mCancel = cancel;
if (mBuilder != null) {
mBuilder.setCanceledOnTouchOutside(mCancel);
}
return this;
}
public MaterialDialog setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
this.mOnDismissListener = onDismissListener;
return this;
}
private class Builder{
private TextView mTitleView;
private ViewGroup mMessageContentRoot;
private TextView mMessageView;
private Window mAlertDialogWindow;
private Builder(){
mAlertDialog = new AlertDialog.Builder(mContext).create();
mAlertDialog.show();
mAlertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mAlertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_STATE);
mAlertDialogWindow = mAlertDialog.getWindow();
mAlertDialogWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if (mTitleResId != 0) {
setTitle(mTitleResId);
}
if (mTitle != null) {
setTitle(mTitle);
}
if (mTitle == null && mTitleResId == 0){
mTitleView.setVisibility(View.GONE);
}
if (mMessageResId != 0){
setMessage(mMessageResId);
}
if(mMessage != null){
setMessage(mMessage);
}
if(pId != -1){
mPositiveButton.setVisibility(View.VISIBLE);
mPositiveButton.setText(pId);
mPositiveButton.setOnClickListener(pListener);
if (isLollipop()) {
mPositiveButton.setElevation(0);
}
}
if (nId != -1) {
mNegativeButton.setVisibility(View.VISIBLE);
mNegativeButton.setText(nId);
mNegativeButton.setOnClickListener(nListener);
if (isLollipop()) {
mNegativeButton.setElevation(0);
}
}
if (!isNullOrEmpty(pText)) {
mPositiveButton.setVisibility(View.VISIBLE);
mPositiveButton.setText(pText);
mPositiveButton.setOnClickListener(pListener);
if (isLollipop()) {
mPositiveButton.setElevation(0);
}
}
if (!isNullOrEmpty(nText)) {
mNegativeButton.setVisibility(View.VISIBLE);
mNegativeButton.setText(nText);
mNegativeButton.setOnClickListener(nListener);
if (isLollipop()) {
mNegativeButton.setElevation(0);
}
}
if (isNullOrEmpty(pText) && pId == -1) {
mPositiveButton.setVisibility(View.GONE);
}
if (isNullOrEmpty(nText) && nId == -1) {
mNegativeButton.setVisibility(View.GONE);
}
if (mMessageContentView != null) {
this.setContentView(mMessageContentView);
} else if (mMessageContentViewResId != 0) {
this.setContentView(mMessageContentViewResId);
}
mAlertDialog.setCanceledOnTouchOutside(mCancel);
mAlertDialog.setCancelable(mCancel);
if (mOnDismissListener != null) {
mAlertDialog.setOnDismissListener(mOnDismissListener);
}
}
public void setTitle(int resId) {
mTitleView.setText(resId);
}
public void setTitle(CharSequence title) {
mTitleView.setText(title);
}
public void setMessage(int resId) {
if (mMessageView != null) {
mMessageView.setText(resId);
}
}
public void setMessage(CharSequence message) {
if (mMessageView != null) {
mMessageView.setText(message);
}
}
/**
* set negative button
*
* #param text the name of button
*/
public void setNegativeButton(String text, final View.OnClickListener listener) {
Button button = new Button(mContext);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setText(text);
button.setTextColor(Color.argb(222, 0, 0, 0));
button.setTextSize(14);
button.setGravity(Gravity.CENTER);
button.setPadding(0, 0, 0, dip2px(8));
button.setOnClickListener(listener);
}
public void setView(View view) {
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(layoutParams);
view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override public void onFocusChange(View v, boolean hasFocus) {
mAlertDialogWindow.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
// show imm
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
});
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
if (viewGroup.getChildAt(i) instanceof EditText) {
EditText editText = (EditText) viewGroup.getChildAt(i);
editText.setFocusable(true);
editText.requestFocus();
editText.setFocusableInTouchMode(true);
}
}
for (int i = 0; i < viewGroup.getChildCount(); i++) {
if (viewGroup.getChildAt(i) instanceof AutoCompleteTextView) {
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) viewGroup
.getChildAt(i);
autoCompleteTextView.setFocusable(true);
autoCompleteTextView.requestFocus();
autoCompleteTextView.setFocusableInTouchMode(true);
}
}
}
}
public void setContentView(View contentView) {
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
contentView.setLayoutParams(layoutParams);
if (contentView instanceof ListView) {
setListViewHeightBasedOnChildren((ListView) contentView);
}
}
/**
* Set a custom view resource to be the contents of the dialog. The
* resource will be inflated into a ScrollView.
*
* #param layoutResId resource ID to be inflated
*/
public void setContentView(int layoutResId) {
mMessageContentRoot.removeAllViews();
// Not setting this to the other content view because user has defined their own
// layout params, and we don't want to overwrite those.
LayoutInflater.from(mMessageContentRoot.getContext())
.inflate(layoutResId, mMessageContentRoot);
}
public void setCanceledOnTouchOutside(boolean canceledOnTouchOutside) {
mAlertDialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
mAlertDialog.setCancelable(canceledOnTouchOutside);
}
}
private boolean isNullOrEmpty(String nText) {
return nText == null || nText.isEmpty();
}
private void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
// My lib gardle :
compile 'com.github.afollestad.material-dialogs:core:0.8.5.6#aar'
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
Try this.....
I need the solution for sdk version 17 or below
this is my method.
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
i use this method but cursor value null return
help
use my FileSelector :
how to use :
new FileSelector(this, new String[]{FileSelector.XLS, FileSelector.XLSX}).selectFile(new FileSelector.OnSelectListener() {
#Override
public void onSelect(String path) {
G.toast(path);
}
});
new FileSelector(this, new String[]{".jpg", ".jpeg"}).selectFile(new FileSelector.OnSelectListener() {
#Override
public void onSelect(String path) {
G.toast(path);
}
});
source code : (create class 'FileSelector' and copy/paste)
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Typeface;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
/**
* Created by Javad on 2019-11-28 at 4:43 PM.
*/
public class FileSelector {
private Activity context;
private String[] extensions;
private ArrayList<SelectedFile> itemsData = new ArrayList<>();
public static final String MP4 = ".mp4", MP3 = ".mp3", JPG = ".jpg", JPEG = ".jpeg", PNG = ".png", DOC = ".doc", DOCX = ".docx", XLS = ".xls", XLSX = ".xlsx", PDF = ".pdf";
public FileSelector(Activity context, String[] extensions) {
this.context = context;
this.extensions = extensions;
}
public interface OnSelectListener {
void onSelect(String path);
}
public void selectFile(OnSelectListener listener) {
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
listOfFile(new File(sdCard));
dialogFileList(listener);
}
private void listOfFile(File dir) {
File[] list = dir.listFiles();
for (File file : list) {
if (file.isDirectory()) {
if (!new File(file, ".nomedia").exists() && !file.getName().startsWith(".")) {
Log.w("LOG", "IS DIR " + file);
listOfFile(file);
}
} else {
String path = file.getAbsolutePath();
for (String ext : extensions) {
if (path.endsWith(ext)) {
SelectedFile selectedFile = new SelectedFile();
selectedFile.path = path;
String[] split = path.split("/");
selectedFile.name = split[split.length - 1];
itemsData.add(selectedFile);
Log.i("LOG", "ADD " + selectedFile.path + " " + selectedFile.name);
}
}
}
}
Log.d("LOG", itemsData.size() + " DONE");
}
private void dialogFileList(OnSelectListener listener) {
LinearLayout lytMain = new LinearLayout(context);
lytMain.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
lytMain.setOrientation(LinearLayout.VERTICAL);
int p = convertToPixels(12);
lytMain.setPadding(p, p, p, p);
lytMain.setGravity(Gravity.CENTER);
TextView textView = new TextView(context);
textView.setLayoutParams(new LinearLayout.LayoutParams(screenWidth(), ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setText("JDM File Selecor");
RecyclerView recyclerView = new RecyclerView(context);
lytMain.addView(textView);
lytMain.addView(recyclerView);
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(lytMain);
dialog.setCancelable(true);
dialog.show();
AdapterFile adapter = new AdapterFile(dialog, listener, itemsData);
recyclerView.setAdapter(adapter);
LinearLayoutManager LayoutManager = new LinearLayoutManager(context);
LayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
}
private int convertToPixels(int dp) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
private int screenWidth() {
return context.getResources().getDisplayMetrics().widthPixels;
}
private class SelectedFile {
public String path = "";
public String name = "";
}
private class AdapterFile extends RecyclerView.Adapter<AdapterFile.ViewHolder> {
private ArrayList<SelectedFile> itemsData;
private OnSelectListener listener;
private Dialog dialog;
public AdapterFile(Dialog dialog, OnSelectListener listener, ArrayList<SelectedFile> itemsData) {
this.itemsData = itemsData;
this.listener = listener;
this.dialog = dialog;
}
// Create new views (invoked by the layout manager)
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtName = new TextView(context);
TextView txtPath = new TextView(context);
txtPath.setTypeface(txtPath.getTypeface(), Typeface.ITALIC);
txtPath.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
linearLayout.addView(txtName);
linearLayout.addView(txtPath);
ViewHolder viewHolder = new ViewHolder(linearLayout);
return viewHolder;
}
// inner class to hold a reference to each item of RecyclerView
public class ViewHolder extends RecyclerView.ViewHolder {
public LinearLayout linearLayout;
public TextView txtName;
public TextView txtPath;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
linearLayout = (LinearLayout) itemLayoutView;
txtName = (TextView) linearLayout.getChildAt(0);
txtPath = (TextView) linearLayout.getChildAt(1);
}
}
#Override
public int getItemCount() {
return itemsData.size();
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
final SelectedFile selectedFile = itemsData.get(position);
viewHolder.txtName.setText(selectedFile.name);
viewHolder.txtPath.setText(selectedFile.path);
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
listener.onSelect(selectedFile.path);
}
});
}
}
}
path = uri.getPath(); only this line is used for get the path of selected file.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/vnd.ms-excel");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(getApplicationContext(), "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
// Get the path
try {
path = uri.getPath();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
I'm creating an activity that shows files in the device (including external storage) with '.mp4' extension in a ListView.
Here's my Activity file
public class FindVideoActivity extends AppCompatActivity {
private List<String> fileNames;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_video);
fileNames = new ArrayList<>();
lv = (ListView) findViewById(R.id.find_video_list);
updateFileList();
}
public void updateFileList() {
String path;
String extension = Environment.getExternalStorageState();
if(extension.equals(Environment.MEDIA_MOUNTED)) {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videostreaming/";
} else {
path = Environment.MEDIA_UNMOUNTED;
}
File file = new File(path);
ArrayAdapter<String> fileList = new ArrayAdapter<>(this, R.layout.file_list_item, fileNames);
VideoFinder finder = new VideoFinder();
File[] files = file.listFiles(finder);
for(File f: files) {
fileNames.add(f.getName());
}
lv.setAdapter(fileList);
}
}
In order to filter out the '.mp4' files, I created another class and named it VideoFinder.java. This class implements java.io.FilenameFilter. Here's the code.
public class VideoFinder implements FilenameFilter {
// overriding the method from the FilenameFilter interface.
#Override
public boolean accept(File dir, String filename) {
if(filename.endsWith(".mp4")) {
return true;
}
return false;
}
}
When I run the code above, it returns `NullPointerException` like the following.
Caused by: java.lang.NullPointerException
at com.marshall.videostreaming.FindVideoActivity.updateFileList(FindVideoActivity.java:46)
at com.marshall.videostreaming.FindVideoActivity.onCreate(FindVideoActivity.java:26)
So it says that the for loop in the updateFileList() method is catching the exception. I still cannot catch what I am missing in this code. Can anyone help?
Check your path, because assigning Environment.MEDIA_UNMOUNTED doesn't seem right. also check if Files is null, because this is why you got NPE.
Its my Main Java class
/**
* Created by ravindra on 2/12/15.
*/
public class GalleryScreen extends Activity implements View.OnClickListener{
private ArrayList<String> file_path = new ArrayList<String>();
GridView gridview;
ImageView left_iv;
TextView header_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_screen);
Bundle bundle = getIntent().getExtras();
gettingIds();
gettingOnClickListener();
fetchDeviceGallery();
}
private void fetchDeviceGallery() {
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
Cursor cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
file_path = getFilePaths();
GalleryAdapter adapter = new GalleryAdapter(GalleryScreen.this,file_path);
gridview.setAdapter(adapter);
System.out.println("Gallery images================="+cursor.getCount()+" "+columnIndex);
}
private void gettingIds() {
gridview = (GridView) findViewById(R.id.gridview);
left_iv = (ImageView) findViewById(R.id.left_iv);
header_tv = (TextView) findViewById(R.id.header_tv);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
finish();
// overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
}
private void gettingOnClickListener() {
left_iv.setOnClickListener(this);
}
public ArrayList<String> getFilePaths() {
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null) {
c = GalleryScreen.this.managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst())) {
do {
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try {
dirList.add(tempDir);
} catch (Exception e) {
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for (int i = 0; i < dirList.size(); i++) {
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if (imageList == null)
continue;
for (File imagePath : imageList) {
try {
if (imagePath.isDirectory()) {
imageList = imagePath.listFiles();
}
if (imagePath.getName().contains(".jpg") || imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg") || imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG")
|| imagePath.getName().contains(".mp4") || imagePath.getName().contains(".MP4")
||imagePath.getName().contains(".mp3") || imagePath.getName().contains(".MP3"))
{
System.out.println("RESOURCES ARE====="+imagePath);
String path = imagePath.getAbsolutePath();
resultIAV.add(path);
}
// }
catch (Exception e) {
e.printStackTrace();
}
}
}
return resultIAV;
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.left_iv:
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
break;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
}
And Its adapter class is as follow:-
/**
* Created by ravindra on 2/12/15.
*/
public class GalleryAdapter extends BaseAdapter {
private final DisplayImageOptions options;
private final ImageLoader imageLoader;
Activity activity;
ArrayList<String> arrayList = new ArrayList<String>();
public GalleryAdapter(Activity activity, ArrayList<String> arrayList) {
this.activity = activity;
this.arrayList = arrayList;
imageLoader = ImageLoader.getInstance();
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(activity));
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loader)
.showImageForEmptyUri(R.drawable.loader)
.showImageOnFail(R.drawable.loader)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
ImageView gallery_item;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder _viewHolder;
if (convertView == null) {
_viewHolder = new ViewHolder();
LayoutInflater _layInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = _layInflater.inflate(R.layout.gallery_item, null);
_viewHolder.gallery_item = (ImageView) convertView.findViewById(R.id.gallery_item);
convertView.setTag(_viewHolder);
} else {
_viewHolder = (ViewHolder) convertView.getTag();
}
if (arrayList.get(position).contains(".mp3") || arrayList.get(position).contains(".MP3"))
{
_viewHolder.gallery_item.setImageResource(R.drawable.audio_img);
}
else {
imageLoader.displayImage("file://" + arrayList.get(position), _viewHolder.gallery_item, options, null);
}
return convertView;
}
}
hey i want add hint to MultiSelector from https://github.com/wongk/MultiSelectSpinner
i mixed it with https://github.com/ravivyas84/AndroidSpinnerHint
its look like this i add own SpinnerAdapterProxy that extends ArrayAdapter<String>
public MultiSelectSpinner(Context context) {
super(context);
_proxyAdapter = new SpinnerAdapterProxy(context, android.R.layout.simple_spinner_item);
super.setAdapter(_proxyAdapter);
_context = context;
}
(...)
public void setHint(String hint) {
_proxyAdapter.setHint(hint);
}
adapter
public class SpinnerAdapterProxy extends ArrayAdapter<String> {
private LayoutInflater mInflator;
private TextView text;
private boolean selected = false;
private String hint;
public SpinnerAdapterProxy(Context context, int resource) {
super(context, resource);
// TODO Auto-generated constructor stub
mInflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflator.inflate(android.R.layout.simple_spinner_item, null);
}
text = (TextView) convertView.findViewById(android.R.id.text1);
if (!selected) {
text.setHint(hint);
} else {
text.setHint(this.getItem(position));
}
return convertView;
}
public void setHint(String hint) {
this.hint = hint;
this.notifyDataSetChanged();
this.notifyDataSetInvalidated();
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
and place where i create MultiSelectSpinner and setTitle
province = (MultiSelectSpinner) findViewById(R.id.subregion);
province.setHint(getResources().getString(R.string.choose_province));
province.setItems(getResources().getStringArray(R.array.provinces));
the problem is that after setHint adapter did not refresh and did not show hint
i just fixed by myself
i throw out SpinnerAdapterProxy and just modify MultiSelectSpinner
by change
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (_selection != null) {
String select = null;
if (which < _selection.length) _selection[which] = isChecked;
if (!isAnySelect())
select = _title;
else
select = buildSelectedItemString();
_proxyAdapter.clear();
_proxyAdapter.add(select);
setSelection(0);
}
else {
throw new IllegalArgumentException("Argument 'which' is out of bounds.");
}
}
and
public void setTitle(String title) {
_title = title;
_proxyAdapter.clear();
_proxyAdapter.add(title);
setSelection(0);
}
and added testing finction that test if any item is selected
private boolean isAnySelect() {
for (boolean b : _selection) {
if (b == true) return true;
}
return false;
}
If you use following class you can add hint as following methord
public class MultiSelectionSpinner extends android.support.v7.widget.AppCompatSpinner implements
DialogInterface.OnMultiChoiceClickListener {
String _title;
String[] _items = null;
boolean[] mSelection = null;
ArrayAdapter<String> simple_adapter;
List<KotItems> mKotdata;
int pos;
public MultiSelectionSpinner(Context context)
{
super(context);
simple_adapter = new ArrayAdapter<String>(context,
R.layout.spinneritemstyle);
super.setAdapter(simple_adapter);
}
public MultiSelectionSpinner(Context context, AttributeSet attrs) {
super(context, attrs);
simple_adapter = new ArrayAdapter<String>(context,
R.layout.spinneritemstyle);
super.setAdapter(simple_adapter);
}
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (mSelection != null && which < mSelection.length) {
mSelection[which] = isChecked;
simple_adapter.clear();
simple_adapter.add(buildSelectedItemString());
} else {
simple_adapter.add("N/A");
throw new IllegalArgumentException(
"Argument 'which' is out of bounds.");
}
}
#Override
public boolean performClick() {
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMultiChoiceItems(_items, mSelection, this);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1)
{
mKotdata.get(pos).setKotnote(buildSelectedItemString());
}
});
builder.show();
return true;
}
#Override
public void setAdapter(SpinnerAdapter adapter) {
throw new RuntimeException(
"setAdapter is not supported by MultiSelectSpinner.");
}
//Add Your Hint in this methord
public void setItems(List<String> items) {
if(items.size()>0){
_items = items.toArray(new String[items.size()]);
mSelection = new boolean[_items.length];
simple_adapter.clear();
simple_adapter.add("Add Your Hint Here");
Arrays.fill(mSelection, false);
}
}
public void setArrayList(List<KotItems> mKotdata,int pos){
this.mKotdata = mKotdata;
this.pos = pos;
}
public void setSelection(int index) {
for (int i = 0; i < mSelection.length; i++) {
mSelection[i] = false;
}
if (index >= 0 && index < mSelection.length) {
mSelection[index] = true;
} else {
throw new IllegalArgumentException("Index " + index
+ " is out of bounds.");
}
simple_adapter.clear();
simple_adapter.add(buildSelectedItemString());
}
private String buildSelectedItemString() {
StringBuilder sb = new StringBuilder();
boolean foundOne = false;
for (int i = 0; i < _items.length; ++i) {
if (mSelection[i]) {
if (foundOne) {
sb.append(", ");
}
foundOne = true;
sb.append(_items[i]);
}
}
System.out.println("u8u8 "+sb.toString());
return sb.toString();
}
}