How to load image from api into gridview using adapter in android studio? - android-studio

public class MainActivityFragment extends Fragment {
static String[] str1;
GridView gridview;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.refresh_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateWeather() {
fetchMovies movieTask=new fetchMovies();
movieTask.execute("hi");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_main, container, false);
gridview=(GridView)rootview.findViewById(R.id.gridview);
//gridview.setAdapter(new ImageAdapter(getActivity()));
return rootview;
}
public class fetchMovies extends AsyncTask<String,Void,String[]> {
private final String LOG_TAG = fetchMovies.class.getSimpleName();
private String[] getMovieDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
String[] resultStrs = new String[movieArray.length()];
for(int i = 0; i < movieArray.length(); i++) {
JSONObject getMovie = movieArray.getJSONObject(i);
String moviePosterPathImage=getMovie.getString("poster_path");
String movieOverview=getMovie.getString("overview");
String split_release_date=getMovie.getString("release_date");
String[] Segments = split_release_date.split("-");
String release_date=Segments[1]+"-"+Segments[2]+"-"+Segments[0];
String title=getMovie.getString("title");
Double vote_Average=getMovie.getDouble("vote_average");
resultStrs[i] = moviePosterPathImage + " - " + movieOverview + " - " + release_date + " - " + title + " - " + vote_Average;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection urlConnection=null;
BufferedReader reader=null;
//will contain the raw json response as a string
String forecastJsonStr=null;
int Format_Cnt_Value=7;
String Format_Api="api_key";
try {
String Format_Mode="sort_by";
String Format_Mode_Val="popularity.desc";
String OPEN_MOVIES_API_KEY="-----My Api Key------";
String baseUrl="http://api.themoviedb.org/3/discover/movie?";
Uri builtUri=Uri.parse(baseUrl).buildUpon()
.appendQueryParameter(Format_Mode,Format_Mode_Val)
.appendQueryParameter(Format_Api,OPEN_MOVIES_API_KEY)
.build();
URL url=new URL(builtUri.toString());
Log.v(LOG_TAG,"test_Uri= " + builtUri);
urlConnection= (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream=urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JsonString:=" + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
};
try {
return getMovieDataFromJson(forecastJsonStr,Format_Cnt_Value);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] Strings) {
if (Strings != null) {
//adp.clear();
str1 = new String[Strings.length];
for (int i = 0; i < Strings.length; i++) {
String[] getImage=Strings[i].split("-");
str1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
}
adp=new ImageAdapter(getActivity(),str1);
gridview.setAdapter(adp); //error
}
}
}
}
what should I do now....
I also have ImageAdapter class
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds;
public ImageAdapter(Context c,String[] str2) {
mContext = c;
mThumbIds=str2;
}
#Override
public int getCount() {
if(mThumbIds!=null)
{
return mThumbIds.length;
}
else
{
return 0;
}
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(500,500));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
// imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
return imageView;
}
}
Please help.
I have loaded data from api and want to fill the gridview.
I am getting images in string[]...how to populate gridview..
I need your help to populate gridview using adapter
billions of thanks in advance.

Use Picasso library to load url images in your grid view.Check out this link on how to use picasso.
In your adapter getView() method add this line:
Picasso.with(mContext).load(mThumbIds[position]).into(imageView);

Related

How to save the content of custom array class and adapter in list view save into text in android

I need your help I am new in android programming. How can I save all the content in the list view save into text file this is my code of try to save the file but the problem is how can i put the listview array list to get the data i don't know how to put it where to put it please help how to do it to save the content of my listview
Button code:
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
for (int i = 0; i < ChatBubbles.length; i++) {
myOutWriter.append(ChatBubbles[i] +"\n");
}
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
Chatbubble class:
package com.example.ezminute;
public class ChatBubble {
private String content;
private boolean myMessage;
public ChatBubble(String content, boolean myMessage) {
this.content = content;
this.myMessage = myMessage;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
}
MessageAdapter:
package com.example.ezminute;
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.left_chat_bubble;
} else {
layoutResource = R.layout.right_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime. Value 2 is returned because of left and right views.
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
}
}
}

Loading image from URL to ListView

I am trying to make a list view. I did it successfully without the photos loading from url without using a custom array adapter. However how can I implement loading images from url without using a custom array adapter?
I am trying to use the working codes from this thread but it is giving an error for holder.
Error Part
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
DoctorsActivity.java
public class DoctorsActivity extends AppCompatActivity {
private JSONArray arrayAdapter;
private static final String URL_FOR_BALANCE = "http://192.168.1.28/api2/doctors.php";
String cancel_req_tag = "login";
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctors);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_doctors);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003764")));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String pid = sharedPreferences.getString(Config.UID_SHARED_PREF, null);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_BALANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray contacts = jObj.getJSONArray("user");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String doctorTitle = c.getString("title");
String doctorName = c.getString("first_name");
String doctorSurname = c.getString("last_name");
String doctorPhoto = c.getString("photo"); //image URL
String doctorMobile = c.getString("mobile");
String doctorFullName = doctorTitle+" "+doctorName+" "+doctorSurname;
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("photo", icon);
contact.put("doctor", doctorFullName);
contact.put("mobile", doctorMobile);
// adding contact to contact list
contactList.add(contact);
}
ListAdapter adapter = new SimpleAdapter(
DoctorsActivity.this, contactList,
R.layout.activity_doctors_list_item, new String[]{"photo", "doctor",
"mobile"}, new int[]{R.id.photo,
R.id.doctor, R.id.mobile});
lv.setAdapter(adapter);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("uid", pid);
params.put("lang", Locale.getDefault().getDisplayLanguage());
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
}
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
}
Why not use a 3rd party lib like https://github.com/bumptech/glide?
Relevant code:
// ...
new Glide
.with(convertView.getContext())
.load(url)
.centerCrop()
.placeholder(R.drawable.noimage)
.crossFade()
.into(bmImage);
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
// ...
For everyone who wants to have listView with images this my corrected working Custom Adapter:
public class DoctorAdapter extends ArrayAdapter<Doctors>{
ArrayList<Doctors> doctorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public DoctorAdapter(Context context, int resource, ArrayList<Doctors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
doctorList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.photo);
holder.tvName = (TextView) v.findViewById(R.id.doctor);
holder.tvMobile = (TextView) v.findViewById(R.id.mobile);
holder.callButton = (Button) v.findViewById(R.id.btnCall);
holder.callButton.setTag(holder);
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
String message= viewHolder.tvMobile.getText().toString();
Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
}
});
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.noimage);
new DownloadImageTask(holder.imageview).execute(doctorList.get(position).getImage());
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvMobile;
public Button callButton;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

How to refresh adapter and deselect all items each time when user clicks on multispinner?

I want to refresh the getview() of baseadapter each time when user click on multispinner. Also wants to deselect all the selected checkbox.
Anybody please help.
Blockquote
Below is my multispinner java class
public class MultiSpinnerSearch extends Spinner implements OnCancelListener {
private static final String TAG = MultiSpinnerSearch.class.getSimpleName();
private List<KeyPairBoolData> items;
private String defaultText = "";
private String spinnerTitle = "";
private SpinnerListener listener;
private int limit = 0;
private int selected = 0;
private LimitExceedListener limitListener;
MyAdapter adapter;
public static AlertDialog.Builder builder;
public static AlertDialog ad;
public MultiSpinnerSearch(Context context) {
super(context);
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
TypedArray a = arg0.obtainStyledAttributes(arg1, R.styleable.MultiSpinnerSearch);
limit = a.getIndexCount();
for (int i = 0; i < limit; ++i) {
int attr = a.getIndex(i);
if (attr == R.styleable.MultiSpinnerSearch_hintText) {
spinnerTitle = a.getString(attr);
defaultText = spinnerTitle;
break;
}
}
Log.i(TAG, "spinnerTitle: " + spinnerTitle);
a.recycle();
}
public MultiSpinnerSearch(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
}
public void setLimit(int limit, LimitExceedListener listener) {
this.limit = limit;
this.limitListener = listener;
}
public List<KeyPairBoolData> getSelectedItems() {
List<KeyPairBoolData> selectedItems = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItems.add(item);
}
}
return selectedItems;
}
public List<Long> getSelectedIds() {
List<Long> selectedItemsIds = new ArrayList<>();
for (KeyPairBoolData item : items) {
if (item.isSelected()) {
selectedItemsIds.add(item.getId());
}
}
return selectedItemsIds;
}
#Override
public void onCancel(DialogInterface dialog) {
// refresh text on spinner
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
String spinnerText = spinnerBuffer.toString();
if (spinnerText.length() > 2)
spinnerText = defaultText;
else
spinnerText = defaultText;
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{spinnerText});
setAdapter(adapterSpinner);
if (adapter != null)
adapter.notifyDataSetChanged();
listener.onItemsSelected(items);
}
#Override
public boolean performClick() {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.Material_App_Dialog));
builder.setTitle(spinnerTitle);
final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.alert_dialog_listview_search, null);
builder.setView(view);
final ListView listView = (ListView) view.findViewById(R.id.alertSearchListView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setFastScrollEnabled(false);
adapter = new MyAdapter(getContext(), items);
listView.setAdapter(adapter);
final TextView emptyText = (TextView) view.findViewById(R.id.empty);
listView.setEmptyView(emptyText);
final EditText editText = (EditText) view.findViewById(R.id.alertSearchEditText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i(TAG, " ITEMS : " + items.size());
dialog.cancel();
}
});
builder.setOnCancelListener(this);
ad = builder.show();
return true;
}
public void setItems(List<KeyPairBoolData> items, int position, SpinnerListener listener) {
this.items = items;
this.listener = listener;
StringBuilder spinnerBuffer = new StringBuilder();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
spinnerBuffer.append(items.get(i).getName());
spinnerBuffer.append(", ");
}
}
if (spinnerBuffer.length() > 2)
defaultText = spinnerBuffer.toString().substring(0, spinnerBuffer.toString().length() - 2);
ArrayAdapter<String> adapterSpinner = new ArrayAdapter<>(getContext(), R.layout.textview_for_spinner, new String[]{defaultText});
setAdapter(adapterSpinner);
if (position != -1) {
items.get(position).setSelected(true);
//listener.onItemsSelected(items);
onCancel(null);
}
}
public interface LimitExceedListener {
void onLimitListener(KeyPairBoolData data);
}
//Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<KeyPairBoolData> arrayList;
List<KeyPairBoolData> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<KeyPairBoolData> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.i(TAG, "getView() enter");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_listview_multiple, parent, false);
holder.textView = (TextView) convertView.findViewById(R.id.alertTextView);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.alertCheckbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final int backgroundColor = (position % 2 == 0) ? R.color.list_background : R.color.list_background;
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), backgroundColor));
if (position==0)
{
holder.textView.setTextColor(Color.BLACK);
}
if (position==3)
{
holder.textView.setTextColor(Color.GREEN);
convertView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.list_selected));
}
final KeyPairBoolData data = arrayList.get(position);
holder.textView.setText(data.getName());
holder.textView.setTypeface(null, Typeface.NORMAL);
holder.checkBox.setChecked(data.isSelected());
convertView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (data.isSelected()) { // unselect
selected--;
} else if (selected == limit) { // select with limit
if (limitListener != null)
limitListener.onLimitListener(data);
return;
} else { // selected
selected++;
}
final ViewHolder temp = (ViewHolder) v.getTag();
temp.checkBox.setChecked(!temp.checkBox.isChecked());
data.setSelected(!data.isSelected());
Log.i(TAG, "On Click Selected Item : " + data.getName() + " : " + data.isSelected());
}
});
holder.checkBox.setTag(holder);
return convertView;
}
#SuppressLint("DefaultLocale")
#Override
public Filter getFilter() {
return new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (List<KeyPairBoolData>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<KeyPairBoolData> FilteredArrList = new ArrayList<>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
Log.i(TAG, "Filter : " + mOriginalValues.get(i).getName() + " -> " + mOriginalValues.get(i).isSelected());
String data = mOriginalValues.get(i).getName();
if (data.toLowerCase().contains(constraint.toString())) {
FilteredArrList.add(mOriginalValues.get(i));
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
}
}
}
And from my main activity
MultiSpinnerSearch searchSpinner = (MultiSpinnerSearch) findViewById(R.id.searchMultiSpinner);
searchSpinner.setItems(listArray, -1, new SpinnerListener() {
#Override
public void onItemsSelected(List<KeyPairBoolData> items) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isSelected()) {
Log.i("TAG", i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
FlashMessage(i + " : " + items.get(i).getName() + " : " + items.get(i).isSelected());
if (GroupName.equals(""))
{
GroupName=GroupName+items.get(i).getName();
Group_stuid=Group_stuid+student_idlist[i+1];
}
else
{
GroupName=GroupName+","+items.get(i).getName();
Group_stuid=Group_stuid+"#"+student_idlist[i+1];
}
}
}
FlashMessage("grp name : "+GroupName);
FlashMessage("grp id : "+Group_stuid);
Audiofilename=appfunct.checkfile(eventType,acdses_sct,class_sct,category_sct,subject_sct,test_sct,Group_stuid,GroupName);
outfolder=appfunct.outfldr();
Group_stuid=Group_stuid.replaceAll("/","-");
File create_stuid=new File(outfolder.toString()+"/"+Group_stuid);
if(!create_stuid.exists()) {
create_stuid.mkdirs();
}
FlashMessage(""+GroupFoldername);
Group_listFiles=appfunct.showlistfiles(GroupFoldername);
if (Group_listFiles != null)
{
final CustomGroupFolder_ListDispaly adapter1 = new CustomGroupFolder_ListDispaly(Group_recording.this,R.layout.group_item_listview,Group_listFiles);
group_listview.setAdapter(adapter1);
}
GroupName="";
Group_stuid="";
selected_students=appfunct.getSelectedNamesGroup(GroupFoldername);
}
});
FlashMessage("out : grp id "+Group_stuid);
searchSpinner.setLimit(2, new MultiSpinnerSearch.LimitExceedListener() {
#Override
public void onLimitListener(KeyPairBoolData data) {
Toast.makeText(getApplicationContext(),
"Limit exceed ", Toast.LENGTH_LONG).show();
}
});
apply this to your adapter adapter.notifyDataSetChanged();

spinner setOnItemSelectedListener doesn't work

I have a spinner that I put its items dynamically from my database but the problem is I can't know which item is selected by the method setOnItemSelectedListener
Here is my java code :
public class Choix extends Activity {
JSONArray ja1 = null;
List<String> list = new ArrayList<String>();
ArrayAdapter<String> dataAdapter;
Spinner spinner;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choix_espace);
spinner = (Spinner) findViewById(R.id.spinner);
liste_ecoles k = new liste_ecoles();
k.execute();
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+arg2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private class liste_ecoles extends AsyncTask<String, Integer, Object> {
String ch1="";
#Override
protected Object doInBackground(String... params) {
JSONArray ja = null;
try {
URL twitter = new URL("...");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
ja = new JSONArray(line);
}
} catch (Exception e) {
}
return ja;
}
#Override
protected void onPostExecute(Object resultat) {
JSONArray ja = (JSONArray) resultat;
if (resultat != null) {
try {
for (int i = 0; i < ja.length(); i++) {
JSONObject jo1 = null;
jo1 = ja.getJSONObject(i);
ch1 = jo1.getString("nom_ecole");
list.add(ch1);
}
}
catch (Exception e) {
}
}
}
}
}
so can someone helps me please ?
I solved my problem ; I've just added " dataAdapter.notifyDataSetChanged(); " after adding items on my spinner

Android app - using AsyncTask - stops opening a URL in WebView, it is opened by the default browser if I call another URL

I'm beginning to develop in android using the material from http://developer.android.com.
I took one of their examples and modified it, so that my application can connect to a webpage. It works well when it is opened but if I click on an actionBar item which should open another page the new page isn't opened in the WebView, but it's launched the default browser.
I tried in many way to understand how to avoid that, but my little experience didn't allow me to fixe the problem.
Can you help me?
Many thanks.
Nino
public class MainActivity extends Activity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
public static String PAGINA ="http://www.kibao.org/simu/wap.php?lng=";
public static String BASE ="http://www.kibao.org";
public static String ATTUALE ="";
public static String lng = "";
final Context context = this;
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
public static boolean refreshDisplay = true;
public static String sPref = null;
public static String pagina = "";
private NetworkReceiver receiver = new NetworkReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
lng = getResources().getString(R.string.lng);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onStart() {
super.onStart();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sPref = sharedPrefs.getString("listPref", "Wi-Fi");
updateConnectedFlags();
if (refreshDisplay) {
ATTUALE=PAGINA.concat(lng);
loadPage(ATTUALE);
}
}
#Override
public void onDestroy() {
super.onStop();
String ciao = getResources().getString(R.string.ciao);
show_toast(ciao);
if (receiver != null) {
this.unregisterReceiver(receiver);
}
}
private void updateConnectedFlags() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
} else {
wifiConnected = false;
mobileConnected = false;
}
}
private void loadPage(String pgUrl) {
if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
|| ((sPref.equals(WIFI)) && (wifiConnected))) {
new DownloadWebpageTask().execute(pgUrl);
} else {
showErrorPage();
}
}
// Displays an error if the app is unable to load content.
private void showErrorPage() {
....
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu1:
if (refreshDisplay) {
ATTUALE=BASE.concat("/partite.php?lng=");
ATTUALE=ATTUALE.concat(lng);
loadPage(ATTUALE);
}
return true;
....
default:
return super.onOptionsItemSelected(item);
}
}
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
} else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadWebpageFromNetwork(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
#Override
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl(ATTUALE);
}
}
private String loadWebpageFromNetwork(String urlString) throws IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
pagina = getStringFromInputStream(stream);
} finally {
if (stream != null) {
stream.close();
}
}
return pagina;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
........
}
This DownloadWebpageTask tries to "download" a webpage into a string, using a webview. This is not the correct way to do it. You are using the wrong tutorial. Don't use AsyncTasks for this. Start all over, using this:
http://developer.android.com/reference/android/webkit/WebView.html
or
http://www.mkyong.com/android/android-webview-example/
Simply call webview.loadUrl(url) again with a different url if you want to load a different page. It's as simple as that.
I've found another solution that works. I added the line
myWebView.setWebViewClient(new WebViewClient());
in the onPostExecute:
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(ATTUALE);
}
Thanks, Frank.
PS I've tried to add a comment to the last Frank's post, but I didn't succeed!

Resources