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

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);
}
}
}

Related

How to delete the item from database and listview by position

I need to delete the item from database and ListView. I can delete the item from ListView but i can't delete it from database. I think the problem is in getting the position of the item from the database i tried to do it in my own but it does not work. I don't know what should I do.Help me to slove this.
myDB = new DbHandler(this);
userList = new ArrayList<>();
data = myDB.getListContents();
numRows = data.getCount();
if (numRows == 0) {
Toast.makeText(AddCount.this, "No Items", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
user = new User(data.getString(1), data.getString(2));
userList.add(user);
}
}
adapter = new Two_columnListAdapter(this, R.layout.list_item_layout, userList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> arg0, View arg1, final int arg2, final long arg3) {
final AlertDialog.Builder delete = new AlertDialog.Builder(AddCount.this);
delete.setIcon(R.drawable.ic_baseline_delete_24);
delete.setTitle("Are you sure");
delete.setMessage("Do you want to delete this item?");
delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
DbHandler db = new DbHandler(getApplicationContext());
myDB.deleteData(userList.get(arg2));
userList.remove(arg2);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted" ,Toast.LENGTH_SHORT).show();
}
});`
`Two_columnAdapter.java
public class Two_columnListAdapter extends ArrayAdapter<User> {
private LayoutInflater layoutInflater;
private ArrayList<User>users;
private int mviewResourceId;
public Two_columnListAdapter(Context context,int textViewResourceId,ArrayList<User>users){
super(context,textViewResourceId,users);
this.users = users;
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mviewResourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parents){
convertView = layoutInflater.inflate(mviewResourceId,null);
User user= users.get(position);
if (user != null){
TextView text = (TextView)convertView.findViewById(R.id.title);
TextView num = (TextView)convertView.findViewById(R.id.value);
if (text != null){
text.setText(user.getText());
}
if (num != null){
num.setText(user.getNum());
}
}
return convertView;
}
DatabaseHelpher(delete the single row from database)
public void deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_Inputs, KEY_ID + " =?", new String[]{id});
db.close();
}
You can save the return data inside a model class instead of a list. Then call the setOnLongClickListener in your adapter class, inside onBindViewHolder.
class listHolder extends RecyclerView.ViewHolder{
private View view;
public listHolder(#NonNull View itemView) {
super(itemView);
view = itemView;
}
}
#Override
public void onBindViewHolder(#NonNull listHolder listHolder, int position, #NonNull userModel userModel) {
viewHolder.view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do somethings....
}
});
For more info you can check out this link, Hope this helps!

behavior explanation: Using LiveData to update adapter with DiffUtil

I am updating my recyclerview by using LiveData as below:
viewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
viewModel.getPurchaseList().observe(getViewLifecycleOwner(), new Observer<List<ProductsObject>>() {
#Override
public void onChanged(#Nullable List<ProductsObject> productsObjects) {
adapter.submitList(productsObjects);
//adapter.notifyDataSetChanged();
}
});
And I am using a FloatActionButton to change the value of my MutableLiveData as below:
FloatingActionButton fab = view.findViewById(R.id.cart_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewModel.setPurchasePrice(0, 101.2);
}
});
All the data gets changed and onChanged is called as expected, but it only updates my recyclerview when I enable the adapter.notifyDataSetChanged();
If I create a new ProductsObject inside the FAB and submit a new list, the recyclerview gets updated without calling adapter.notifyDataSetChanged(); as below:
FloatingActionButton fab = view.findViewById(R.id.cart_fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//viewModel.setPurchaseAmount(0, 101.2);
ProductsObject prod = new ProductsObject("6666", 5, 152.2, "new product");
List<ProductsObject> prodList = new ArrayList<>();
prodList.add(prod);
adapter.submitList(prodList);
}
});
I appreciate if anyone could explain why.
Here is my adapter:
public class CartFragAdapter extends RecyclerView.Adapter<CartFragAdapter.CartFragViewHolder> {
private static final String TAG = "debinf PurchaseAdap";
private static final DiffUtil.ItemCallback<ProductsObject> DIFF_CALLBACK = new DiffUtil.ItemCallback<ProductsObject>() {
#Override
public boolean areItemsTheSame(#NonNull ProductsObject oldProduct, #NonNull ProductsObject newProduct) {
Log.i(TAG, "areItemsTheSame: old is "+oldProduct.getCode()+" ; new is "+newProduct.getCode());
return oldProduct.getCode().equals(newProduct.getCode());
}
#Override
public boolean areContentsTheSame(#NonNull ProductsObject oldProduct, #NonNull ProductsObject newProduct) {
Log.i(TAG, "areContentsTheSame: old is "+oldProduct.getPrice()+" ; new is "+newProduct.getPrice());
return oldProduct.getPrice() == newProduct.getPrice();
}
};
private AsyncListDiffer<ProductsObject> differ = new AsyncListDiffer<ProductsObject>(this, DIFF_CALLBACK);
#NonNull
#Override
public CartFragViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_purchase, parent, false);
return new CartFragViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CartFragViewHolder holder, int position) {
final ProductsObject purchaseList = differ.getCurrentList().get(position);
holder.mCode.setText(purchaseList.getCode());
holder.mPrice.setText(String.valueOf(purchaseList.getPrice()));
holder.mDescription.setText(purchaseList.getDescription());
}
#Override
public int getItemCount() {
Log.i(TAG, "getItemCount");
return differ.getCurrentList().size();
}
public void submitList(List<ProductsObject> products){
Log.i(TAG, "submitList: products.size is "+products.size());
differ.submitList(products);
}
public class CartFragViewHolder extends RecyclerView.ViewHolder {
public TextView mCode, mPrice, mDescription;
public CartFragViewHolder(#NonNull View itemView) {
super(itemView);
mCode = (TextView) itemView.findViewById(R.id.item_productCode);
mPrice = (TextView) itemView.findViewById(R.id.item_productPrice);
mDescription = (TextView) itemView.findViewById(R.id.item_productDescription);
}
}
}
And here is my ViewModel:
public class MyViewModel extends ViewModel {
MutableLiveData<List<ProductsObject>> purchaseList = new MutableLiveData<>();
public LiveData<List<ProductsObject>> getPurchaseList() {
return purchaseList;
}
public void setPurchasePrice(int position, double price) {
List<ProductsObject> itemList = purchaseList.getValue();
if (itemList != null && itemList.get(position) != null) {
Log.i("debinf ViewModel", "setPurchaseAmount: "+itemList.get(position).getPrice());
itemList.get(position).setPrice(price);
purchaseList.postValue(itemList);
}
}
}
AsyncListDiffer saves only the reference of the list. This means that if you submit a modified list instead of submitting a new list, AsncListDiffer won't be able to detect any difference because both the previous list and the new list are referencing the same list with the same items.
To fix this you need to create a new list and new item. Change MyViewModel#setPurchasePrice as below:
public void setPurchasePrice(int position, double price) {
List<ProductsObject> itemList = purchaseList.getValue();
if (itemList != null && itemList.get(position) != null) {
List<ProductsObject> newList = new ArrayList<>();
for (int i = 0; i < itemList.size(); i++) {
ProductsObject prevProd = itemList.get(i);
if (i != position) {
newList.add(prevProd);
} else {
ProductsObject newProd = new ProductsObject(..., price, ...);
newList.add(newProd);
}
}
purchaseList.postValue(newList);
}
}

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 load image from api into gridview using adapter in 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);

messed up dynamic radio buttons in ArrayAdapter

when i run my app, i get much more radiobuttons than i need. It seems the radiobuttons repeat themselves in the same group. I don't really understand what is is going on. Here is my custom ArrayAdapter. I would like to know the problem here
public class QuestionsListAdapter extends ArrayAdapter<QuestionProperties> {
List<QuestionProperties> list;
Context test;
public QuestionsListAdapter(Context context, int resource, List<QuestionProperties> list2) {
super(context,resource,list2);
test = context;
list =list2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
final RadioButton[] rB;
RadioHolder holder = new RadioHolder();
view= convertView;
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
if(view == null)
{
LayoutInflater inflator = ((Activity) test).getLayoutInflater();
view = inflator.inflate(R.layout.question_list_row, null);
holder.questionTV = (TextView) view.findViewById(R.id.qTextView);
holder.radiogroup = (RadioGroup) view.findViewById(R.id.radio_group);
view.setTag(holder);
}
else{
//view = convertView;
holder = (RadioHolder) view.getTag();
}
holder.questionTV.setText(String.valueOf(list.get(position).getQuestionNo())+"."+" " + list.get(position).getQuestion());
rB=new RadioButton[list.get(position).possibleAns.length];
for(int count = 0; count<(list.get(position).possibleAns.length);count++)
{
rB[count]= new RadioButton(test);
rB[count].setId(count);
rB[count].setText(list.get(position).possibleAns[count]);
layoutParams.weight=1.0f;
layoutParams.setMargins(15, 0, 5, 10);
rB[count].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String a = String.valueOf(v.getId());
Toast.makeText(QActivity.context, "Radio Button "+ a,Toast.LENGTH_SHORT).show();
}
});
holder.radiogroup.addView(rB[count],layoutParams);
}
return view;
}
static class RadioHolder {
protected TextView questionTV;
protected RadioGroup radiogroup;
}
Finally after some hacks i solved it! i removed all the radio buttons in the else clause.
The solution..
public class QuestionsListAdapter extends ArrayAdapter<QuestionProperties> {
List<QuestionProperties> list;
RadioButton rB;
Context test;
RadioHolder holder;
String chkBtn;
LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
public QuestionsListAdapter(Context context, int resource, List<QuestionProperties> list2) {
super(context,resource,list2);
test = context;
list =list2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
holder = new RadioHolder();
view= convertView;
Log.v("ConvertView", String.valueOf(position));
if(view == null)
{
LayoutInflater inflator = ((Activity) test).getLayoutInflater();
view = inflator.inflate(R.layout.question_list_row, parent,false);
holder.questionTV = (TextView) view.findViewById(R.id.qTextView);
holder.radiogroup = (RadioGroup) view.findViewById(R.id.radio_group);
//holder.radiogroup.check(list.get(position).getSelectedAns());
view.setTag(holder);
//((RadioHolder) view.getTag()).radiogroup.setTag(list.get(position));
Log.v("holder setTag", String.valueOf(position));
}
else{
view = convertView;
holder = (RadioHolder)view.getTag();
//((RadioHolder)view.getTag()).radiogroup.getTag();
holder.radiogroup.removeAllViews();
}
holder.questionTV.setText(String.valueOf(list.get(position).getQuestionNo())+"."+" " + list.get(position).getQuestion());
configureRadioButtons(position);
chkBtn = String.valueOf(list.get(position).getSelectedAns());
holder.radiogroup.check(Integer.valueOf(chkBtn));
return view;
}
static class RadioHolder {
protected TextView questionTV;
protected RadioGroup radiogroup;
}
public void configureRadioButtons(int pos){
final int position = pos;
//rB=new RadioButton(test);
for(int count = 0; count<(list.get(position).possibleAns.length);count++)
{
rB= new RadioButton(test);
rB.setId(count);
rB.setText(list.get(position).possibleAns[count]);
layoutParams.weight=1.0f;
layoutParams.setMargins(15, 0, 5, 10);
holder.radiogroup.addView(rB,layoutParams);
rB.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String a = String.valueOf(v.getId());
list.get(position).setSelectedAns(v.getId());
chkBtn = String.valueOf(list.get(position).getSelectedAns());
Toast.makeText(QActivity.context, "Radio Button "+ a,Toast.LENGTH_SHORT).show();
}
});
rB.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
});
holder.radiogroup.clearCheck();
Log.v("rB added to radiogroup", String.valueOf(position));
}
}

Resources