Related
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());
}
});
}
}
private class getArticles extends AsyncTask<Void, Void, Void> {
String url;
getArticles(String paramUrl) {
this.url = paramUrl;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(App.this);
mProgressDialog.setMessage("Učitavanje artikala...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
arraylist = new ArrayList<>();
try {
Document document = Jsoup.connect(url).get();
Elements els = document.select("ul.category3 > li");
for (Element el : els) {
HashMap<String, String> map = new HashMap<>();
Elements slika = el.select("div.category3-image > a > img");
Elements naslov = el.select("div.category3-text > a.main-headline");
Element datum_noformat = el.select("div.category3-text > div.headlines-info > ul.headlines-info > li").first();
Element datum = datum_noformat.html(datum_noformat.html().replaceAll("Posted ", ""));
Elements desc = el.select("div.category3-text > p");
Elements link = el.select("div.category3-text > a.main-headline");
Element br_kom = el.select("div.category3-text > div.headlines-info > ul.headlines-info > li.comments-icon").first();
map.put("naslov", naslov.text());
map.put("datum", datum.text());
map.put("desc", desc.text());
map.put("ikona", slika.attr("src"));
map.put("link", link.attr("abs:href"));
map.put("brkom", br_kom.text());
arraylist.add(map);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ArtikliAdapter(App.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
I searched for a lot of codes for onlistview scrolling, but didn't know how to implement it. The problem is, when I call my asynctask, I have an url param,
like new getArticles("http://example.com").execute();
I want to implement an onscrolllistener, but it goes like this, my param is usually set to: http://www.example.com/category/categoryname/, so the second page goes like http://www.example.com/category/categoryname/page/2/, the third one goes http://www.example.com/category/categoryname/page/3/ and so on. Each page has got 7 items that need to be parsed.
How could I implement onscrolllistener, because of the url param?
Thanks in advance.
Base on this link, I have written following solution to add elements ( 30 elements at a time, i.e page size = 30) to listview asynchronously.
Create a class named EndlessListView as follows:
public class EndlessListView extends ListView implements OnScrollListener {
private View footer;
private boolean isLoading;
private EndlessListener listener;// listner
private EndlessAdapter endlessAdapter;// adapter.
private int maxNoOfElement;
public EndlessListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.setOnScrollListener(this);
}
public EndlessListView(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnScrollListener(this);
}
public EndlessListView(Context context) {
super(context);
this.setOnScrollListener(this);
}
public void setListener(EndlessListener listener) {
this.listener = listener;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (getAdapter() == null)
return;
if (getAdapter().getCount() == 0 || getAdapter().getCount() <= 5)
return;
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !isLoading) {
// It is time to add new data. We call the listener
Log.e("LOAD", "DATA");
isLoading = true;
listener.loadData();
}
}
public void setMaxElemnt(int maxNoOfElement) {
this.maxNoOfElement = maxNoOfElement;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void setLoadingView(int resId) {
LayoutInflater inflater = (LayoutInflater) super.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
footer = (View) inflater.inflate(resId, null);
this.addFooterView(footer);
}
public void setAdapter(EndlessAdapter adapter) {
super.setAdapter(adapter);
this.endlessAdapter = adapter;
}
public void addNewData(List<Integer> data) {
endlessAdapter.setData(data);
endlessAdapter.notifyDataSetChanged();
isLoading = false;
}
public static interface EndlessListener {
public void loadData();
}
}
After this we have to create the adapter for it,called
EndlessAdapter
public class EndlessAdapter extends BaseAdapter {
private List<Integer> mIntegers;
private Context context;
public EndlessAdapter(Context context) {
this.context = context;
}
public void setData(List<Integer> mIntegers) {
this.mIntegers = mIntegers;
}
#Override
public int getCount() {
if (mIntegers == null)
return 0;
return mIntegers.size();
}
#Override
public Integer getItem(int index) {
if (mIntegers == null) {
return null;
} else {
return mIntegers.get(index);
}
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView textView;
}
#Override
public View getView(int index, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.rows, viewGroup, false);
holder.textView = (TextView) view.findViewById(R.id.mtext);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.textView.setText(getItem(index) + "");
return view;
}
}
Now in xml of the activity we could use EndlessListView(in com.example.stackoverflow package) as follows :
<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" >
<com.example.stackoverflow.EndlessListView
android:id="#+id/endlessListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
After this step we need to make following change in the MainActivity
public class MainActivity extends Activity implements EndlessListener {
private EndlessAdapter adapter;
private EndlessListView endlessListView;
private List<Integer> data;
private int gStartIndex = 30;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
endlessListView = (EndlessListView) findViewById(R.id.endlessListView);
adapter = new EndlessAdapter(this);
data = new ArrayList<Integer>();
endlessListView.setLoadingView(R.layout.footer);
// endlessListView.showFooter();
endlessListView.setListener(this);
endlessListView.setAdapter(adapter);
gStartIndex = 0;
fillData(gStartIndex);
}
private void fillData(int startIndex) {
new AsyncLoadData().execute(startIndex);
}
#Override
public void loadData() {
fillData(gStartIndex);
}
private class AsyncLoadData extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
int gendIndex = params[0] + 30;
gStartIndex = gendIndex;
/***
* Here you could add your n/w code. To simulate the n/w comm. i am
* adding elements to list and making it sleep for few sec.
* */
for (int i = params[0]; i < gendIndex; i++) {
publishProgress(i);
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
data.add(values[0]);
}
#Override
protected void onPostExecute(Void result) {
endlessListView.addNewData(data);
}
}
}
This custom ScrollListView that I just found has OnBottomReachedListener which you can implement from your Activity or Fragment and receive events when user hits the bottom of the page. You would also need to track the current page and when bottom is hit to download the next page. The latest data should be added to your existing ArrayList and you should call notifyDataSetChanged() on your adapter so ListView can render the new data. You don't have to create new adapter, you just need to update the data source which is your ArrayList.
If you support orientation change you would must to save in onSaveInstanceState() your current page number so when Activity or Fragment is recreated it can continue from correct page. And you would have to keep the ArrayList data source safe of configuration changes because you don't want to downloaded it again. I would suggest using the Fragment with setRetainInstance() set to true to persist ArrayList.
Here is my custom code for keeping data around using RetainFragment:
/**
* A simple non-UI Fragment that stores a single Object
* and is retained over configuration changes.
*/
public class RetainFragment<E extends Object> extends Fragment {
/** Object for retaining. */
private E mObject;
/**
* Empty constructor as per the Fragment documentation
*/
public RetainFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this Fragment.
*
* #param object The object to store
*/
public void setObject(E object) {
mObject = object;
}
/**
* Get the stored object.
*
* #return The stored object
*/
public E getObject() {
return mObject;
}
}
Example of RetainFragment usage in your Activity:
FragmentManager fm = getFragmentManager();
mRetainFragment = (RetainFragment<ArrayList>) fm.findFragmentByTag(RETAIN_FRAG);
if (mRetainFragment == null) {
mRetainFragment = new RetainFragment<>();
mRetainFragment.setObject(new ArrayList());
fm.beginTransaction().add(mRetainFragment, RETAIN_FRAG).commit();
}
ArrayList yourArrayList = mRetainFragment.getObject();
// Now your ArrayList is saved accrossed configuration changes
here what you want fist add onscrolllistner to listview
boolean loading_flage = false;
yourlistview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(
AbsListView view,
int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view,
int firstVisibleItem,
int visibleItemCount,
int totalItemCount) {
final int lastItem = firstVisibleItem
+ visibleItemCount;
if ((lastItem == totalItemCount)
& loading_flage == false) {
//this to prevent the list to make more than one request in time
loading_flage = true;
//you can put the index for your next page here
loadMore(int page);
}
}
});
and then in loading more after loading the page set the loading with false and parse the data add it to the data that you aleardy have
//notify the adapter
adapter.notifyDataSetChanged();
loading_flage = false;
You can achieve by adding the scrolllistener on listview and check condition if list last visible item is last in ArrayList then call the asynctask with incremented page number and update the listview,mean while add the view on listview and after getting the result from server remove the loading more view from the listview like this -
AndroidListViewLoadMoreActivity.java
public class AndroidListViewLoadMoreActivity extends Activity {
ArrayList<Country> countryList;
MyCustomAdapter dataAdapter = null;
int page = 0;
boolean loadingMore = false;
View loadMoreView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView = (ListView) findViewById(R.id.listView1);
loadMoreView = ((LayoutInflater)this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.loadmore, null, false);
listView.addFooterView(loadMoreView);
//create an ArrayAdaptar from the String Array
countryList = new ArrayList<Country>();
dataAdapter = new MyCustomAdapter(this,
R.layout.country_info, countryList);
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
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();
}
});
listView.setOnScrollListener(new OnScrollListener(){
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if((lastInScreen == totalItemCount) && !(loadingMore)){
String url = "http://10.0.2.2:8080/CountryWebService" +
"/CountryServlet";
grabURL(url);
}
}
});
String url = "http://example.com";
grabURL(url);
}
public void grabURL(String url) {
Log.v("Android Spinner JSON Data Activity", url);
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
private String content = null;
private boolean error = false;
private ProgressDialog dialog =
new ProgressDialog(AndroidListViewLoadMoreActivity.this);
protected void onPreExecute() {
dialog.setMessage("Getting your data... Please wait...");
dialog.show();
}
protected String doInBackground(String... urls) {
String URL = null;
loadingMore = true;
try {
URL = urls[0];
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
//add name value pair for the country code
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("page",String.valueOf(page)));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
} else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e );
content = e.getMessage();
error = true;
cancel(true);
} catch (IOException e) {
Log.w("HTTP3:",e );
content = e.getMessage();
error = true;
cancel(true);
}catch (Exception e) {
Log.w("HTTP4:",e );
content = e.getMessage();
error = true;
cancel(true);
}
return content;
}
protected void onCancelled() {
dialog.dismiss();
Toast toast = Toast.makeText(AndroidListViewLoadMoreActivity.this,
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
protected void onPostExecute(String content) {
dialog.dismiss();
Toast toast;
if (error) {
toast = Toast.makeText(AndroidListViewLoadMoreActivity.this,
content, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
} else {
displayCountryList(content);
}
}
}
private void displayCountryList(String response){
JSONObject responseObj = null;
try {
Gson gson = new Gson();
responseObj = new JSONObject(response);
JSONArray countryListObj = responseObj.getJSONArray("countryList");
//countryList = new ArrayList<Country>();
if(countryListObj.length() == 0){
ListView listView = (ListView) findViewById(R.id.listView1);
listView.removeFooterView(loadMoreView);
}
else {
for (int i=0; i<countryListObj.length(); i++){
//get the country information JSON object
String countryInfo = countryListObj.getJSONObject(i).toString();
//create java object from the JSON object
Country country = gson.fromJson(countryInfo, Country.class);
//add to country array list
countryList.add(country);
dataAdapter.add(country);
}
page++;
dataAdapter.notifyDataSetChanged();
loadingMore = false;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Make MyCustomAdapter.java as adapter
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> countryList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
}
public void add(Country country){
Log.v("AddView", country.getCode());
this.countryList.add(country);
}
#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 = this.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;
}
}
}
Create Country.Java as pojo -
public class Country {
String code = null;
String name = null;
String continent = null;
String region = null;
Double lifeExpectancy = null;
Double gnp = null;
Double surfaceArea = null;
int population = 0;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public Double getLifeExpectancy() {
return lifeExpectancy;
}
public void setLifeExpectancy(Double lifeExpectancy) {
this.lifeExpectancy = lifeExpectancy;
}
public Double getGnp() {
return gnp;
}
public void setGnp(Double gnp) {
this.gnp = gnp;
}
public Double getSurfaceArea() {
return surfaceArea;
}
public void setSurfaceArea(Double surfaceArea) {
this.surfaceArea = surfaceArea;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
Create main.xml for main layout
<?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">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/some_text" android:textSize="20sp" />
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Create 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" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Code: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="Name: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:text="Continent: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView3"
android:layout_below="#+id/textView3"
android:text="Region: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/continent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView3"
android:layout_alignBottom="#+id/textView3"
android:layout_toRightOf="#+id/textView3"
android:text="TextView" />
<TextView
android:id="#+id/region"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView4"
android:layout_alignBottom="#+id/textView4"
android:layout_alignLeft="#+id/continent"
android:text="TextView" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_toRightOf="#+id/textView3"
android:text="TextView" />
<TextView
android:id="#+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_alignLeft="#+id/name"
android:text="TextView" />
</RelativeLayout>
Footer View Text - loadmore.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:padding="3dp"
android:layout_height="fill_parent">
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:padding="5dp"
android:text="Loading more data..."/>
</LinearLayout>
Don't forget to mention internet permission with -
<uses-permission android:name="android.permission.INTERNET" />
First, you need a OnScrollListener method like this:
private OnScrollListener onScrollListener() {
return new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listView.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= count - threshold && pageCount < 2) {
Log.i(TAG, "loading more data");
// Execute LoadMoreDataTask AsyncTask
//It reached ListView bottom
getDataFromUrl(url_page2);
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
};
}
set List View scroll listener by listView.setOnScrollListener(onScrollListener());
I have a full tutorial post HERE! You can visit it!
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