I have a gridview with 5 columns, how could add in column 4 and 5, images that I have in drawable folder? The problem is that being a String arraylist not catch me drawable because it is an integer.
This is my XML:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrolView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<GridView
android:id="#+id/Grid"
android:numColumns="5"
android:stretchMode="columnWidth"
android:layout_width="match_parent"
android:gravity="center"
android:columnWidth="120dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:layout_height="2000dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"></GridView>
</LinearLayout>
This is the java code where I call carrito.xml, and i make the listview. This list view is filled with a String array.
public class carrito extends Fragment {
protected Context context;
private int numComandesCarrito;
private String[][] CarritoProductes;
private double Total;
DecimalFormat precision = new DecimalFormat("0.00");
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(Total);
public carrito(){
}
public void setContext (Context context){
this.context = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int i, i2;
numComandesCarrito = ((MainActivity) context).getNumComandesCarrito();
// Toast.makeText(context, Integer.toString(numComandesCarrito), Toast.LENGTH_LONG).show();
CarritoProductes = ((MainActivity) context).getCarritoProductes();
Total = 0;
ArrayList<String> lineasPedido = new ArrayList<String>();
ArrayList<Integer> itemsimg = new ArrayList( );
//Afegim la capçalera de la grid
lineasPedido.add("Plat");
lineasPedido.add("Quantitat");
lineasPedido.add("Preu");
for (i= 0; i < numComandesCarrito; i++){
for (i2 = 0; i2<3; i2++){
if (i2 == 2) {
lineasPedido.add(precision.format(Double.parseDouble(CarritoProductes[i2][i])) + " €");
Total = Total + Double.parseDouble(CarritoProductes[i2][i]);
}
else{
lineasPedido.add(CarritoProductes[i2][i]);
}
}
itemsimg.add(R.drawable.botonmenos);
}
lineasPedido.add("");
lineasPedido.add("");
lineasPedido.add("Total: " + (precision.format(Total)) + " €");
View rootView = inflater.inflate(R.layout.carrito, container, false);
GridView grdView = (GridView)rootView.findViewById(R.id.grdComanda);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, lineasPedido);
grdView.setAdapter(adapter);
return rootView;
}
You have to use custom adapter to put image in gridview
activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:verticalSpacing="5dp" >
</GridView>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutbg"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="250dp"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="#+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:paddingLeft="15dp"
android:text="TextView" />
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingRight="15dp"
android:text="TextView" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
FriendAdapter.java
public class FriendAdapter extends ArrayAdapter<FriendBean>{
private Context mCtx;
private ArrayList<FriendBean> items = new ArrayList<FriendBean>();
private ViewHolder mHolder;
ImageLoader imgLoader = new ImageLoader(mCtx);
public LayoutInflater inflater;
int loader = R.drawable.loader;
public FriendAdapter(Context context, int textViewResourceId, ArrayList<FriendBean> items) {
super(context, textViewResourceId, items);
this.items = items;
this.mCtx = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=vi.inflate(R.layout.row, null);
mHolder=new ViewHolder();
mHolder.mImage=(ImageView)v.findViewById(R.id.img);
mHolder.mName=(TextView)v.findViewById(R.id.name);
mHolder.mPh=(TextView)v.findViewById(R.id.num);
mHolder.mlayoutbg=(RelativeLayout)v.findViewById(R.id.layoutbg);
v.setTag(mHolder);
}
else{
mHolder=(ViewHolder)v.getTag();
}
imgLoader.DisplayImage(items.get(position).getImage(), loader, mHolder.mImage);
//mHolder.mImage.setBackgroundResource(items.get(position).getImage());
mHolder.mName.setText(items.get(position).getName());
mHolder.mPh.setText(items.get(position).getPh());
mHolder.mlayoutbg.setBackgroundColor(Color.GREEN);
// if(position%3==1){
// mHolder.mlayoutbg.setBackgroundColor(Color.GRAY);
// }else if(position%3==2){
// mHolder.mlayoutbg.setBackgroundColor(Color.WHITE);
// }else{
// mHolder.mlayoutbg.setBackgroundColor(Color.YELLOW);
// }
return v;
}
public class ViewHolder {
public ImageView mImage;
public TextView mName;
public TextView mPh;
public RelativeLayout mlayoutbg;
}
}
FriendBean.java
package com.example.bean;
public class FriendBean {
private String Image;
private String name;
private String ph;
private String des;
public FriendBean(String Image, String name, String ph, String des) {
this.Image = Image;
this.name = name;
this.ph = ph;
this.des = des;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPh() {
return ph;
}
public void setPh(String ph) {
this.ph = ph;
}
public String getDes() {
return des;
}
public void setDes(String des) {
this.des = des;
}
}
MainActivity.java
public class MainActivity extends Activity {
private GridView mList;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
private FriendAdapter friendAdapter;
String friend_name, friend_phone, url, des;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mList = (GridView) findViewById(R.id.gridView1);
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"gridarray.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("json");
Log.e("Length", "" + jsonarray.length());
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
friend_name = jsonObj.getString("friend_name");
friend_phone = jsonObj.getString("friend_phone");
url = jsonObj.getString("image_url");
des = jsonObj.getString("des");
FriendBean bean = new FriendBean(url, friend_name, friend_phone,
des);
arr.add(bean);
Log.e("u", url);
Log.e("friend_name", friend_name);
Log.e("friend_phone", friend_phone);
}
friendAdapter = new FriendAdapter(MainActivity.this, R.layout.row, arr);
mList.setAdapter(friendAdapter);
mList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Clicked on " + arg2,
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), NewPage.class);
i.putExtra("friend_name", arr.get(arg2).getName());
i.putExtra("friend_phone", arr.get(arg2).getPh());
i.putExtra("url", arr.get(arg2).getImage());
i.putExtra("des", arr.get(arg2).getDes());
startActivity(i);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
gridarray.json (put it in asset folder)
{ "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Madhumoy",
"friend_phone" : "123",
"des" : "Hi I'm Madhumoy"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sattik",
"friend_phone" : "123",
"des" : "Hi I'm Sattik"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Koushik",
"friend_phone" : "123",
"des" : "Hi I'm Koushik"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Himanshu",
"friend_phone" : "123",
"des" : "Hi I'm Himanshu"
},
{ "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
"friend_name" : "Sandy",
"friend_phone" : "123",
"des" : "Hi I'm Sandy"
}
] }
Hope this will work..
Maybe try something like this? The user comments seem to be positive for the most part. http://www.compiletimeerror.com/2013/02/display-images-in-gridview.html#.VRF2I2NTf5w
Related
I have made an Image Editor and it works fine. Now, in my recent edits page, I added a feature select multiple items. But, I get a strange behaviour when I refresh the recycler view. See this ->
https://www.veed.io/view/43fa65a4-24e6-44e8-8cea-468ca8c62d7a.
This is my adapter code ->
public class RecentsAdapter extends RecyclerView.Adapter<RecentsAdapter.ViewHolder>{
private List<ImageFile> files;
private final PopupListener popupListener;
RecentItemListeners recentItemListeners;
public Integer selectedItemsCount = 0;
TextView neEditsTV;
public RecentsAdapter(List<ImageFile> files, PopupListener popupListener, RecentItemListeners listeners, TextView neEditsTV) {
this.files = files;
this.popupListener = popupListener;
this.recentItemListeners = listeners;
this.neEditsTV = neEditsTV;
}
public void updateList(List<ImageFile> filesList){
if (files.size() < filesList.size()){
int dif = filesList.size() - files.size();
this.files = filesList;
for (int i = 0; i < dif; i++) {
notifyItemInserted(i);
}
}else if (files.size() > filesList.size()){
for (int i = 0; i < filesList.size(); i++) {
notifyItemChanged(i);
}
notifyDataSetChanged();
notify();
}else {
this.files = filesList;
for (int i = 0; i < filesList.size(); i++) {
notifyItemChanged(i);
}
}
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(ItemRecentBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
#SuppressLint("NewApi")
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.setData(files.get(position));
}
#Override
public int getItemCount() {
return files.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements TinyDBManager.ValueChangeListener {
ItemRecentBinding binding;
boolean mIsSelected = false;
public ViewHolder(#NonNull ItemRecentBinding itemView) {
super(itemView.getRoot());
binding = itemView;
}
#SuppressLint({"ClickableViewAccessibility", "ResourceAsColor"})
#RequiresApi(api = Build.VERSION_CODES.Q)
public void setData(ImageFile file){
TinyDBManager tinyDBManager = TinyDB.getInstance(itemView.getContext());
tinyDBManager.setValueChangeListener(this);
binding.fileName.setText(file.getName());
binding.preview.setImageURI(Uri.parse(file.getPath()));
Log.d("positionChecker",getAdapterPosition() + "");
#SuppressLint("SimpleDateFormat") String datept1 = new SimpleDateFormat("dd/MM/yyyy").format(file.getLastModified());
#SuppressLint("SimpleDateFormat") String datept3 = new SimpleDateFormat("hh:mm:ss a").format(file.getLastModified());
binding.lastEdited.setText(datept1 + " at " + datept3);
binding.option.setOnClickListener(v -> {
ContextThemeWrapper contextWrapper = new ContextThemeWrapper(itemView.getContext(),R.style.Theme_ImageEditor);
PopupMenu menu = new PopupMenu(contextWrapper, binding.option);
menu.inflate(R.menu.recent_item_menu);
menu.setForceShowIcon(true);
menu.show();
menu.setOnDismissListener(menu1 -> popupListener.onPopupClosed());
popupListener.onPopupOpened();
menu.setOnMenuItemClickListener(item -> {
switch (item.getTitle().toString()){
case "Open":
Intent openIntent = new Intent();
openIntent.setAction(Intent.ACTION_VIEW);
openIntent.setDataAndType(Uri.parse(file.getPath()), "image/*");
openIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
itemView.getContext().startActivity(openIntent);
break;
case "Share":
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(file.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
shareIntent.setType("image/*");
itemView.getContext().startActivity(Intent.createChooser(shareIntent, "Share image via..."));
break;
case "Edit":
Intent editIntent = new Intent(itemView.getContext(), ImageEditorActivity.class);
editIntent.putExtra("filePath",file.getPath());
editIntent.putExtra("position",getAdapterPosition());
Toast.makeText(contextWrapper, "" + file.getName(), Toast.LENGTH_SHORT).show();
editIntent.putExtra("name",file.getName());
editIntent.putExtra("new",false);
v.getContext().startActivity(editIntent);
break;
case "Remove from list":
TinyDBManager tinyDB = TinyDB.getInstance(v.getContext());
List<ImageFile> imageFiles = tinyDB.get("files",null);
imageFiles.remove(getAdapterPosition());
files.remove(getAdapterPosition());
tinyDB.put("files",imageFiles);
notifyItemRemoved(getAdapterPosition());
break;
case "Delete":
CustomAlertDialog dialog = new CustomAlertDialog(itemView.getContext(),null);
View.OnClickListener[] clickListeners = new View.OnClickListener[2];
clickListeners[0] = v1 -> dialog.dismiss();
clickListeners[1] = v1 -> {
dialog.dismiss();
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + file.getName();
boolean deleteFile = new File(path).delete();
Log.d("path:",file.getPath());
if (deleteFile)
Toast.makeText(contextWrapper, "success", Toast.LENGTH_SHORT).show();
else Toast.makeText(contextWrapper, "fail", Toast.LENGTH_SHORT).show();
MediaScannerConnection.scanFile(itemView.getContext(), new String[] { Environment.getExternalStorageDirectory().toString() }, null, (path1, uri) -> {
Log.i("ExternalStorage", "Scanned " + path1 + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
});
};
dialog.show(itemView.getContext(), "Delete image","Are you sure you want to delete the image?\nThis action cannot be reverted.", new String[]{"No","Yes"},clickListeners);
}
return true;
});
});
binding.share.setOnClickListener(v -> {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(file.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
shareIntent.setType("image/*");
itemView.getContext().startActivity(Intent.createChooser(shareIntent, "Share image via..."));
});
binding.getRoot().setOnClickListener(v -> {
if (selectedItemsCount != 0) {
if (mIsSelected) {
mIsSelected = false;
selectedItemsCount--;
binding.getRoot().setCardBackgroundColor(Color.WHITE);
binding.lastEdited.setTextColor(Color.GRAY);
binding.fileName.setTextColor(Color.BLACK);
binding.option.setImageTintList(ColorStateList.valueOf(Color.GRAY));
recentItemListeners.onItemClick(getAdapterPosition(), 1, file.getPath(),file);
} else {
recentItemListeners.onItemClick(getAdapterPosition(), 0, file.getPath(),file);
binding.getRoot().setCardBackgroundColor(itemView.getContext().getColor(R.color.primary));
binding.lastEdited.setTextColor(Color.WHITE);
binding.fileName.setTextColor(Color.WHITE);
binding.option.setImageTintList(ColorStateList.valueOf(Color.WHITE));
mIsSelected = true;
selectedItemsCount++;
}
}else {
mIsSelected = false;
binding.getRoot().setCardBackgroundColor(Color.WHITE);
binding.lastEdited.setTextColor(Color.GRAY);
binding.fileName.setTextColor(Color.BLACK);
binding.option.setImageTintList(ColorStateList.valueOf(Color.GRAY));
}
});
binding.getRoot().setOnLongClickListener(v -> {
mIsSelected = true;
binding.getRoot().setCardBackgroundColor(itemView.getContext().getColor(R.color.primary));
binding.lastEdited.setTextColor(Color.WHITE);
binding.fileName.setTextColor(Color.WHITE);
binding.option.setImageTintList(ColorStateList.valueOf(Color.WHITE));
recentItemListeners.onItemLongClick(getAdapterPosition(), file.getPath(), file);
selectedItemsCount++;
return true;
});
}
#Override
public <E> void onValueAdded(String key, E value) {
files = (List<ImageFile>) value;
files.sort(Comparator.comparing(obj -> obj.getLastModified()));
Collections.reverse(files);
notifyDataSetChanged();
neEditsTV.setVisibility(files.size() == 0 ? View.VISIBLE : View.GONE);
}
#Override
public void onKeyRemoved(String key) {
}
#Override
public void onAllKeysRemoved() {
}
}
}
And now my activity interface listener which are passed to the adapter ->
#Override
public void onItemClick(int position, int action, String filePath, ImageFile file) {
if (selectedItems.contains(file) && action == 1) {
selectedItemsCount--;
filePaths.remove(position);
selectedItems.remove(selectedItems.get(position));
if (selectedItemsCount == 0){
binding.toolbar.setTitle(getString(R.string.app_name));
binding.toolbar.getMenu().clear();
binding.toolbar.setNavigationIcon(null);
canUpdate = true;
}else {
binding.toolbar.setTitle("" + selectedItemsCount);
binding.toolbar.getMenu().clear();
binding.toolbar.inflateMenu(R.menu.multi_select_options);
binding.toolbar.setNavigationIcon(R.drawable.left);
canUpdate = false;
}
}else {
selectedItemsCount++;
selectedItems.add(file);
filePaths.add(filePath);
binding.toolbar.setTitle(selectedItemsCount + " Selected");
binding.toolbar.getMenu().clear();
binding.toolbar.inflateMenu(R.menu.multi_select_options);
binding.toolbar.setNavigationIcon(R.drawable.left);
canUpdate = false;
}
}
#Override
public void onItemLongClick(int position, String filePath, ImageFile file) {
if (selectedItems.contains(file)) return;
selectedItemsCount++;
selectedItems.add(file);
filePaths.add(filePath);
binding.toolbar.setTitle(selectedItemsCount + " Selected");
binding.toolbar.getMenu().clear();
binding.toolbar.inflateMenu(R.menu.multi_select_options);
binding.toolbar.setNavigationIcon(R.drawable.left);
canUpdate = false;
}
And my item file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="#dimen/_65sdp"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="#dimen/_6sdp"
android:padding="#dimen/_10sdp"
app:cardElevation="2dp"
android:layout_marginTop="#dimen/_12sdp"
android:layout_marginHorizontal="#dimen/_6sdp"
android:background="?selectableItemBackground">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="?selectableItemBackground">
<ImageView
android:id="#+id/preview"
android:layout_width="#dimen/_70sdp"
android:layout_height="match_parent"
tools:src="#tools:sample/backgrounds/scenic"
android:scaleType="centerCrop"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="#dimen/_10sdp"
android:paddingVertical="#dimen/_2sdp"
android:gravity="center">
<TextView
android:id="#+id/fileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sample file.png"
style="#style/TextAppearance.AppCompat.Title"
android:gravity="center_vertical"
android:ellipsize="end"
android:maxLines="1"
android:layout_weight="1"/>
<TextView
android:id="#+id/lastEdited"
style="#style/TextAppearance.AppCompat.Subhead"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_vertical"
android:maxLines="1"
android:text="Sample file.png"
android:textColor="#android:color/darker_gray"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/option"
android:layout_width="#dimen/_24sdp"
android:layout_height="0dp"
android:src="#drawable/more_vert"
android:padding="#dimen/_2sdp"
android:background="?selectableItemBackgroundBorderless"
app:tint="#android:color/darker_gray"
android:layout_weight="1"/>
<ImageView
android:id="#+id/share"
android:layout_width="#dimen/_24sdp"
android:layout_height="0dp"
android:src="#drawable/share"
android:padding="#dimen/_2sdp"
android:background="?selectableItemBackgroundBorderless"
app:tint="#android:color/holo_red_light"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
How can I prevent this behaviour?
I want to add objects inside to JSONObj when onClick and display in another Activity inside of a ListView as a CardView.
I tried something but nothing appears, no errors and I have no clue what's the problem.
Here is my code for JSONObj:
private void writeJSON(String metodaPlata) throws JSONException {
String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
JSONObject jsonData;
JSONArray dateJSON;
JSONObject obj;
JSONArray arrayForList;
if (jsonDataFromShared.equals("")) {
jsonData = new JSONObject();
dateJSON = new JSONArray();
obj = new JSONObject();
arrayForList = new JSONArray();
JSONObject objListaSiModalitate = new JSONObject();
// arrayForList.put(stock_list.toString());
objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", 0);
obj.put("detaliiCos", objListaSiModalitate);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON.toString());
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
} else {
jsonData = new JSONObject(jsonDataFromShared);
dateJSON = jsonData.getJSONArray("jsonData");
obj = new JSONObject();
JSONObject objListaSiModalitate = new JSONObject();
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("produseSelectate", listaProdusePreview.getAdapter().getCount());
int totalPrice = 0;
for (VanzatorProduse v : Util.getInstance().getVanzatorProduse()) {
int vPrice = Integer.parseInt(v.getPret());
totalPrice = totalPrice + vPrice;
}
obj.put("sumaProduse", totalPrice);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
obj.put("detaliiCos", objListaSiModalitate);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON);
System.out.println("jsonData" + dateJSON);
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
}
}
My JSONManager :
//Create list of Cards because we need to show list for date selected
public List<Card> readJSON(String dateFromCalendar) throws JSONException {
String JSON = SharedPreference.getString(Util.get(), SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
String numeVanzator = SharedPreference.getString(Util.get(), SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR,"");
JSONObject jsonObj = new JSONObject(JSON);
JSONArray contacts = jsonObj.getJSONArray("jsonData");
List<Card> listCard = null;
Card card = null;
listCard = new ArrayList<>();
for (int i =0; i< contacts.length();i++) {
JSONObject c = contacts.getJSONObject(i);
String data = c.getString("data");
if (data.equals(dateFromCalendar)){
String numeVanzato = c.getString("numeVanzator");
if (numeVanzato.equals(numeVanzator)){
String numarClient = c.getString("numarClient");
String sumaProduse = c.getString("sumaProduse");
String produseselectate = c.getString("produseSelectate");
card = new Card(numarClient, produseselectate, sumaProduse);
listCard.add(card);
}
}
}
return listCard;
}}
Card Object :
public class Card {
public String numarCumparator;
public String listaProduse;
public String sumaProduse;
public Card(String numarCumparator, String listaProduse, String sumaProduse) {
this.numarCumparator = numarCumparator;
this.listaProduse = listaProduse;
this.sumaProduse = sumaProduse;
}
public Card() {
}
public String getNumarCumparator() {
return numarCumparator;
}
public void setNumarCumparator(String numarCumparator) {
this.numarCumparator = numarCumparator;
}
public String getListaProduse() {
return listaProduse;
}
public void setListaProduse(String listaProduse) {
this.listaProduse = listaProduse;
}
public String getSumaProduse() {
return sumaProduse;
}
public void setSumaProduse(String sumaProduse) {
this.sumaProduse = sumaProduse;
}
}
Card Adapter :
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
static class CardViewHolder {
TextView line1;
TextView line2;
TextView line3;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.txtViewNumarCumparator);
viewHolder.line2 = (TextView) row.findViewById(R.id.listaProduse);
viewHolder.line3 = (TextView) row.findViewById(R.id.sumaProduse);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getNumarCumparator());
viewHolder.line2.setText(card.getListaProduse());
viewHolder.line3.setText(card.getSumaProduse());
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
}
Layout for Card:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:descendantFocusability="beforeDescendants">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:descendantFocusability="afterDescendants"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp">
<TextView
android:id="#+id/txtViewNumarCumparator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="NumarCumparator" />
<TextView
android:id="#+id/listaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtViewNumarCumparator"
android:layout_marginTop="10dp"
android:text="NumarProduse" />
<TextView
android:id="#+id/sumaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="SumaProdsue" />
</RelativeLayout>
Layout for ListView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/gray_color">
<ListView
android:id="#+id/listViewVanzatorActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/btnAdaugaProduse"
android:layout_below="#+id/textViewDataCurenta"/>
</RelativeLayout>
Hope you understand my question..
The standard way to send data from Activity to another is to pass parcelable data in the Intent bundle.
Make card implement Parcelable
Pass the items to the intent
public void startSecondActivity(List<Card> cards) {
Intent i = new Intent(this, SecondActivity.class);
i.putParcelableArrayListExtra("EXTRA_CARDS", new ArrayList<Card>(cards));
startActivity(i);
}
Retrieve it like this in the second activity
Bundle bundle = getIntent().getExtras();
List<Card> cards = (ArrayList<Card>)bundle.getParcelableArrayList("EXTRA_CARDS");
I am working on android application and I am facing one problem. When I run my app then nothing showing in recycle view but when i check application in debug mode then data successfully showing in recycle view. I have checked my web service working fine and successfully giving data. How can i achieve this ?
ManageQuestionActivity,java
public class ManageQuestionActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener{
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private QuestionsListAdapter listAdapter;
private List<QuestionsItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
public static String id, message, token, encodedString;
int pageCount, totalPages;
SQLiteHandler db;
SessionManager session;
ConnectionDetector cd;
EditText edtSearch;
Boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_question);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
edtSearch = (EditText) findViewById(R.id.edtSearch);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.questions, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "20");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
}
activity_manage_question.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#null" />
</LinearLayout>
QuestionsItem.java
public class QuestionsItem {
private int id;
private String question, ansOne, ansTwo, ansThree, ansFour, answer;
public QuestionsItem() {
}
public QuestionsItem(int id, String question, String ansOne, String ansTwo, String ansThree, String ansFour, String answer) {
super();
this.id = id;
this.question = question;
this.ansOne = ansOne;
this.ansTwo = ansTwo;
this.ansThree = ansThree;
this.ansFour = ansFour;
this.answer = answer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnsOne() {
return ansOne;
}
public void setAnsOne(String ansOne) {
this.ansOne = ansOne;
}
public String getAnsTwo() {
return ansTwo;
}
public void setAnsTwo(String ansTwo) {
this.ansTwo = ansTwo;
}
public String getAnsThree() {
return ansThree;
}
public void setAnsThree(String ansThree) {
this.ansThree = ansThree;
}
public String getAnsFour() {
return ansFour;
}
public void setAnsFour(String ansFour) {
this.ansFour = ansFour;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
QuestionsListAdapter.java
public class QuestionsListAdapter extends RecyclerView.Adapter<QuestionsListAdapter.ViewHolder> {
private List<QuestionsItem> timeLineItems;
String message, storyId, token, ide;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
ConnectionDetector cd;
Boolean isInternetPresent = false;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
int newPosition;
public QuestionsListAdapter(List<QuestionsItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.questios_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
pDialog = new ProgressDialog(context);
pDialog.setCancelable(false);
db = new SQLiteHandler(context);
// session manager
session = new SessionManager(context);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
token = user.get("token");
//Getting the particular item from the list
QuestionsItem item = timeLineItems.get(position);
holder.txtQues.setText(item.getQuestion());
holder.txtAnsOne.setText(item.getAnsOne());
holder.txtAnsTwo.setText(item.getAnsTwo());
holder.txtAnsThree.setText(item.getAnsThree());
holder.txtAnsFour.setText(item.getAnsFour());
holder.txtAns.setText(item.getAnswer());
holder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
String ques = String.valueOf(m.getQuestion());
String Option1 = String.valueOf(m.getAnsOne());
String Option2 = String.valueOf(m.getAnsTwo());
String Option3 = String.valueOf(m.getAnsThree());
String Option4 = String.valueOf(m.getAnsFour());
String answer = String.valueOf(m.getAnswer());
Intent intent = new Intent(context, UpdateQuestionActivity.class);
intent.putExtra("id", ide);
intent.putExtra("ques", ques);
intent.putExtra("option1", Option1);
intent.putExtra("option2", Option2);
intent.putExtra("option3", Option3);
intent.putExtra("option4", Option4);
intent.putExtra("answer", answer);
context.startActivity(intent);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
newPosition = holder.getAdapterPosition();
ide = String.valueOf(m.getId());
alertBox();
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtQues, txtAnsOne, txtAnsTwo, txtAnsThree, txtAnsFour, txtAns, btnEdit, btnDelete;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
txtQues = (TextView) itemView.findViewById(R.id.txtQues);
txtAnsOne = (TextView) itemView.findViewById(R.id.txtAnsOne);
txtAnsTwo = (TextView) itemView.findViewById(R.id.txtAnsTwo);
txtAnsThree = (TextView) itemView.findViewById(R.id.txtAnsThree);
txtAnsFour = (TextView) itemView.findViewById(R.id.txtAnsFour);
txtAns = (TextView) itemView.findViewById(R.id.txtAns);
btnEdit = (TextView) itemView.findViewById(R.id.btnEdit);
btnDelete = (TextView) itemView.findViewById(R.id.btnDelete);
}
}
public void alertBox(){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("Do you want to delete question ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Check for empty data in the form
cd = new ConnectionDetector(context);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent){
DeleteQuestion(token, ide);
}else {
final SweetAlertDialog alert = new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Question");
alert.show();
}
private void DeleteQuestion(final String token, final String qid) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.updateQues, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
if (error) {
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
timeLineItems.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, timeLineItems.size());
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("qid", qid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
questios_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtQues"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsTwo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsThree"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 4 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsFour"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Answer : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAns"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView android:id="#+id/btnEdit"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Edit"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
<TextView
android:id="#+id/btnDelete"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Delete"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listView.setAdapter should not be here cut
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter); // Cut from Here
And paste in this method:
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
listView.setAdapter(adapter); //Paste Here
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Basically this question is an update for this question
Just to rewind again, this is the country_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
android:id="#+id/gambar_saja"
android:layout_width="150dp"
android:layout_height="160dp"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/n1"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/detail_country"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_toRightOf="#+id/gambar_saja"
android:layout_toEndOf="#+id/gambar_saja"
android:orientation="vertical"
android:layout_marginLeft="4dp">
<TextView
android:id="#+id/code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="24sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/code"
android:layout_below="#+id/code"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/continent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_below="#+id/name"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/region"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/continent"
android:layout_below="#+id/continent"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</RelativeLayout>
</RelativeLayout>
and here is cari_studio.xml to populate the country_info into listview (listView1) :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/area"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal" >
<TextView
android:id="#+id/isiArea"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="#drawable/text_selector"
android:gravity="center_vertical"
android:paddingBottom="10dp"
android:paddingLeft="35dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:text="#string/area"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="visible"/>
<Spinner
android:id="#+id/textArea"
android:layout_marginRight="15dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/area"
android:textColor="#color/black"
android:inputType="text"
android:textSize="14sp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/list_area_studio"
android:layout_below="#+id/area"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/cari_studio" android:textSize="20sp" />
<EditText android:id="#+id/myFilter" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="#string/studio_hint">
<requestFocus />
</EditText>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="#drawable/navbar_background"
>
<RadioButton
android:id="#+id/btnAll"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_allselector"
android:text="All"
/>
<RadioButton
android:id="#+id/btnPicture"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_pictureselector"
android:text="Pictures"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnVideo"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_videoselector"
android:text="Videos"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnFile"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_fileselector"
android:text="Files"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnMore"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_moreselector"
android:text="More"
android:layout_marginLeft="5dp"
/>
</RadioGroup>
<LinearLayout
android:id="#+id/floatingmenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/laysemitransparentwithborders"
android:orientation="vertical"
android:layout_marginBottom="-4dp"
android:visibility="gone"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Contacts"
android:textColor="#ffffff"
android:textSize="16dp"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ff999999"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Calendar"
android:textColor="#ffffff"
android:textSize="16dp"
/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
and here is the Cari Studio Class to get JSONArray result (use post) and I already success get the result :
public class CariStudio extends Activity{
final Context context = this;
MyCustomAdapter dataAdapter = null;
RadioButton radioButton1, radioButton2, radioButton3, radioButton4, radioButton5;
TextView flexlocationid;
Spinner flexlocation;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> provincelist;
ArrayList<ProvinceModel> province;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cari_studio);
//Generate list View from ArrayList
new DownloadJSON().execute();
addListenerOnButton();
}
public void addListenerOnButton() {
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
radioButton1 = (RadioButton) findViewById(R.id.btnAll);
radioButton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, home.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton2 = (RadioButton) findViewById(R.id.btnPicture);
radioButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariKelas.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton3 = (RadioButton) findViewById(R.id.btnVideo);
radioButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariStudio.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton4 = (RadioButton) findViewById(R.id.btnFile);
radioButton4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, HotStuff.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton5 = (RadioButton) findViewById(R.id.btnMore);
radioButton5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, MyAccount.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
flexlocation = (Spinner) findViewById(R.id.textArea);
flexlocationid = (TextView) findViewById(R.id.isiArea);
}
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
runOnUiThread(new Runnable() {
public void run() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country(studio_name,address, "Website:"+ website,
"Fasilitas:"+ seo_url);
countryList.add(country);
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
});
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the CariStudio Class
province = new ArrayList<ProvinceModel>();
// Create an array to populate the spinner
provincelist = new ArrayList<String>();
// JSON file URL address
final String url_flexlocation = Constant.URI_BASE_FLEXLOCATION;
Utils.log("url_flexlocation: " + url_flexlocation);
try {
// Locate the NodeList name
HttpGet httppost = new HttpGet(url_flexlocation);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Utils.log("data: " + data);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
ProvinceModel worldpop = new ProvinceModel();
worldpop.setId(jsonobject.optString("flex_id"));
worldpop.setProvince(jsonobject.optString("name"));
province.add(worldpop);
// Populate spinner with province names
provincelist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in cari_studio.xml
Spinner mySpinner = (Spinner) findViewById(R.id.textArea);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(CariStudio.this,
R.layout.spinner_white,
provincelist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in cari_studio.xml
TextView flexlocationid = (TextView) findViewById(R.id.isiArea);
// Set the text followed by the position
flexlocationid.setText(province.get(position).getId());
String areaid = flexlocationid.getText().toString();
Utils.log("area id:" + areaid);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(areaid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
private CountryFilter filter;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new CountryFilter();
}
return filter;
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
private class CountryFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<Country> filteredItems = new ArrayList<Country>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
Country country = originalList.get(i);
if(country.toString().toLowerCase().contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}
}
the result that I got from Utils.log("daftar isi studio: " + responseAsText) :
[{"id":"8","studio_name":"Dodi fit","seo_url":"dodi-fit","address":"Komp. Pertanian Blok 5 No 3","postcode":"87473","area_phone":"","phone":"+62876543","area_phone_second":"","phone_second":"+62","website":"sucifir.com","region_id":"12","lokasi_id":"138","booking_window":"7","facebook":"dodifitfb","twitter":"dodifittw","how_to_get_there":"over there, by trun left and right","priority":"5"},{"id":"11","studio_name":"inu fit","seo_url":"inu-fit","address":"","postcode":"","area_phone":"","phone":"+6221324234","area_phone_second":"","phone_second":"","website":"","region_id":"11","lokasi_id":"137","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"5","studio_name":"Vstudio","seo_url":"vstudio","address":"Plaza Indonesia Ground Floor #541","postcode":"","area_phone":"","phone":"+6221453787","area_phone_second":"","phone_second":"","website":"www.jkiij.com","region_id":"12","lokasi_id":"137","booking_window":"0","facebook":"face","twitter":"twy","how_to_get_there":"","priority":"5"},{"id":"7","studio_name":"Infovendor","seo_url":"infovendor","address":"","postcode":"","area_phone":"","phone":"+6221123452","area_phone_second":"","phone_second":"","website":"www.kidsdngf.com","region_id":"12","lokasi_id":"135","booking_window":"1","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"12","studio_name":"Seleb Fitnes One","seo_url":"selebfitnesone-57","address":"Kelapa gading timur no 17","postcode":"","area_phone":"","phone":"+6221453777","area_phone_second":"","phone_second":"","website":"selebfirnes.com","region_id":"12","lokasi_id":"138","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"14","studio_name":"Riri Studio","seo_url":"riristudio-57","address":"Mall Kelapa Gading, Lt 5","postcode":"","area_phone":"","phone":"+6221459325","area_phone_second":"","phone_second":"","website":"riri-riri.com","region_id":"12","lokasi_id":"135","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"19","studio_name":"NF Studio","seo_url":"nf-studio","address":"Ruko Mediterania Blok A4 No 79Jalan Ahmad Yani Kav A5, Kota Bekasi","postcode":"13536","area_phone":"","phone":"+62265111222","area_phone_second":"","phone_second":"","website":"nfstudio.com","region_id":"11","lokasi_id":"137","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"}]
and the result that I got from looping Utils.log("studio_name: " + studio_name) are :
studio_name: Dodi fit
studio_name: inu fit
studio_name: Vstudio
studio_name: Infovendor
studio_name: Seleb Fitnes One
studio_name: Riri Studio
studio_name: NF Studio
It means I already got all of it use looping.
But the problem is the result did not populate into listview (it show as one one last result NF Studio, the other did not appear).
What I need is populate this into 4 texview from country_info (I disable imageview) :
String studio_name, address, website, seo_url
What is the correct code to show/populate that into listview?
Add the values into a List and pass it to the Adapter class of your ListView inside onPostExecute()
You don't need a thread, that's the whole point of async.
List View code is in the for loop
UI code belongs to PostExecute() not doInBackground()
You reinitialized the list inside of the loop
Try like this:
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
private ArrayList<Country> countryList = new ArrayList<Country>();
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
Country country = new Country(studio_name,address, "Website:"+ website,"Fasilitas:"+ seo_url);
countryList.add(country);
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
}
This question already has an answer here:
JSON String is incorrectly mapped to textviews
(1 answer)
Closed 9 years ago.
I have a JSON request which returns a response from youtube containing the comments for a particular video. I currently have 3 textviews: one for the name/uploader, one for the content, and one for the date published - which are then populated with the data from my JSON response.
My problem is - only the first comment, date published and uploader appear.
I belive I'll need to replace my textviews with a list view and parse the 3 fields to it - I simply do not know how.
JAVA
public class Player extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
String title = getIntent().getStringExtra("title");
String uploader = getIntent().getStringExtra("uploader");
String viewCount = getIntent().getStringExtra("viewCount");
TextView titleTv = (TextView) findViewById(R.id.titleTv);
TextView uploaderTv = (TextView) findViewById(R.id.uploaderTv);
TextView viewCountTv = (TextView) findViewById(R.id.viewCountTv);
titleTv.setText(title);
uploaderTv.setText("by" + uploader + " |");
viewCountTv.setText(viewCount + " views");
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
return false;
}
});
GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(handler , viewCount);
task.execute();
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(), "onInitializationFailure()",
Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
String video_id = getIntent().getStringExtra("id");
player.loadVideo(video_id);
}
}
public final class GetYouTubeUserCommentsTask extends
AsyncTask<Void, Void, Void> {
public static final String LIBRARY = "CommentsLibrary";
private final Handler replyTo;
private final String username;
String video_id = getIntent().getStringExtra("id");
public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet(
"http://gdata.youtube.com/feeds/api/videos/"
+ video_id
+ "/comments?v=2&alt=json&start-index=1&max-results=50&prettyprint=true");
HttpResponse response = client.execute(request);
String jsonString = StreamUtils.convertToString(response
.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONArray jsonArray = json.getJSONObject("feed").getJSONArray(
"entry");
List<Comments> comments = new ArrayList<Comments>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject entry = jsonArray.getJSONObject(i);
JSONArray authorArray = entry.getJSONArray("author");
JSONObject publishedObject = entry.getJSONObject("published");
String published = publishedObject.getString("$t");
JSONObject contentObject = entry.getJSONObject("content");
String content = contentObject.getString("$t");
JSONObject authorObject = authorArray.getJSONObject(0);
JSONObject nameObject = authorObject.getJSONObject("name");
String name = nameObject.getString("$t");
comments.add(new Comments(name, content, published));
CommentsLibrary lib = new CommentsLibrary(published, content, name);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
}
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView comments = (ListView) findViewById(R.id.comments);
comments.setFilterText(com.idg.omv.domain.CommentsLibrary.getName());
}
}
}
CommentsLibrary
public class CommentsLibrary implements Serializable{
// The username of the owner of the comment
private static String name;
// The comment
private static String content;
// The date the comment was published
private static String published;
public CommentsLibrary(String name, String content, String published) {
this.name = name;
this.content = content;
this.published = published;
}
/**
* #return the user name
*/
public static String getName() {
return name;
}
/**
* #return the videos
*/
public static String getContent() {
return content;
}
/**
* #return the videos
*/
public static String getPublished() {
return published;
}
}
XML
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:text="" />
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/name"
android:layout_weight="1"
android:gravity="left"
android:text="" />
<TextView
android:id="#+id/published"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/content"
android:layout_weight="1"
android:gravity="left"
android:text="" />
Continuing my answer from your previous question # JSON String is incorrectly mapped to textviews
First you need a listview in your layout xml
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Declare list as a instance variable
ArrayList<CommentsLibrary> list = new ArrayList<CommentsLibrary>();
Then
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.optString("name","defaultValue");
String content = jsonObject.optString("content","defaultValue");
String published = jsonObject.optString("published","defaultValue");
list.add(new CommentsLibrary(name, content, published));
}
Then initialize listview
ListView lv =(ListView)findViewById(R.id.list);
CustomAdapter cus = new CustomAdapter(ActivityName.this,list);
lv.setAdapter(cus);
Define a custom layout with 3 textviews. (list_item.xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="18dp"
android:layout_marginTop="31dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_marginRight="24dp"
android:text="TextView" />
</RelativeLayout>
Then define a custom adapter by extending a base adapter. Override getView inflate the custom layout and set text views there.
public class CustomAdapter extends BaseAdapter
{
LayoutInfalter mInflater;
ArrayList<CommentsLibrary> list;
public CustomAdapter(Context context,ArrayList<CommentsLibrary> list)
{
mInflater = LayoutInfalter.from(context);
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null)
{
convertView =minflater.inflate(R.layout.list_item, parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.tv3 = (TextView) convertView.findViewById(R.id.textView3);
convertView.setTag(holder);
}
else
{
holder= (ViewHolder) convertView.getTag();
}
holder.tv1.setText(list.get(position).getName());
holder.tv2.setText(list.get(position).getContent());
holder.tv3.setText(list.get(position).getPublished());
return convertView;
}
static class ViewHolder
{
TextView tv1,tv2,tv3
}
}
You need to add a list view in your layout and populate it using an ArrayAdapter. Here's a tutorial that shows you how - http://www.vogella.com/articles/AndroidListView/article.html#arrayAdapter