Adding onClick to RecyclerView Android [duplicate] - android

This question already has answers here:
RecyclerView Single Item ID
(2 answers)
Closed 5 years ago.
I have put together some code as shown below which gets data from a JSON file hosted on a server and puts it into a RecyclcerView. This has been working fine but any way I try to add a click method it does not work. I am looking to make it so that if I click one of the rows it will tell me the country it is. I have no idea where I am going wrong but I will attach my code below which gets the JSON data and puts it into the RecyclerView.
Thanks
package com.example.curtisboylan.myapplication;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Objects;
public class MainRecycler extends AppCompatActivity {
private ArrayList countries;
private static String url = "http://curtisboylan.me/mygeek/mygeektest.php";
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
countries = new ArrayList<>();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_recycler);
initViews();
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
TextView txtView = (TextView) findViewById(R.id.textView5);
if (Objects.equals(message, "di1")){
txtView.setText("Diagnostics");
}
else if (Objects.equals(message, "screen1")){
txtView.setText("Screen Repair");
}
setTitle("Available Technicians");
}
private void initViews(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainRecycler.this);
pDialog.setMessage("Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("MyGeek");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
//String email = c.getString("email");
//String address = c.getString("address");
//String gender = c.getString("gender");
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject("phone");
// String mobile = phone.getString("mobile");
// String home = phone.getString("home");
// String office = phone.getString("office");
countries.add(c.getString("name"));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.hide();
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
RecyclerView.Adapter adapter = new DataAdapter(countries);
recyclerView.setAdapter(adapter);
}
}
}

Instead of adding a click listener on the Recycler view, try adding click listener in the adapter class, in the onBindViewHolder method. That is how you will get the exact item on which the click was executed.
#Override
public void onBindViewHolder(Viewholder holder, final int position) {
YourClassObject item = YourClassObjectList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Recycle Click" + position, Toast.LENGTH_SHORT).show();
}
});

Create a interface in your Adapter class
public interface EventsCatalogsAdapter{
void onClickImageCategory(Catalogs catalog);
}
Create a atribute of EventsCatalogsAdapter
private EventsCatalogsAdapter event;
Create constructor
public CatalogsAdapter(EventsCatalogsAdapter event) {
this.event = event;
}
Add setOnClickListener in onBindViewHolder
public void onBindViewHolder(final CatalogsViewHolder holder, final int position){
holder.imageCatalog.setOnClickListener(holder);
}
In you RecyclerView.ViewHolder implements onClickListener event.
class CatalogsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView imageCatalog;
private TextView tvCatalogName;
private View vLegendCatalog;
public CatalogsViewHolder(View itemView) {
super(itemView);
imageCatalog = (ImageView) itemView.findViewById(R.id.i =vCatalogItem);
tvCatalogName = (TextView)itemView.findViewById(R.id.tvCatalogName);
vLegendCatalog = itemView.findViewById(R.id.vLegendCatalog);
}
#Override
public void onClick(View v) {
event.onClickImageCategory(catalogsList.get(getAdapterPosition()));
}
}

Related

How to get specific list item and pass the two values from one activity to another?

I am developing an Android app and I in my SecondActivity I have parsed some JSON values as a listview and I want to open up ThirdActivity when a particular list item is clicked and send the values "name" and "number" to the ThirdActivity.
I have tried by creating an Intent in the OnPostExecute method. But am unable to figure out how to pass the values on to the next activity.
package com.example.acer.videoapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SecondActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView listView1;
Toolbar toolbar1;
String subjectName;
ArrayList<HashMap<String, String>> lessonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//setting title to toolbar
toolbar1 = (Toolbar) findViewById(R.id.toolbar1);
Bundle bundle = getIntent().getExtras();
if(bundle!=null) {
toolbar1.setTitle(bundle.getString("Subject"));
subjectName=toolbar1.getTitle().toString();
}
lessonList = new ArrayList<>();
listView1 = (ListView) findViewById(R.id.list);
new GetLessons().execute();
}
/* Async task class to get json by making HTTP call */
private class GetLessons extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SecondActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = getResources().getString(R.string.lessons_url, subjectName);
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
// Getting JSON Array
JSONArray lessons = new JSONArray(jsonStr);
// looping through All lessons
for (int i = 0; i < lessons.length(); i++) {
JSONObject c = lessons.getJSONObject(i);
String number = c.getString("lessonNo");
String name = c.getString("lessonName");
// tmp hash map for single lesson
HashMap<String, String> lesson = new HashMap<>();
// adding each child node to HashMap key => value
lesson.put("number", number);
lesson.put("name", name);
// adding lesson to lesson list
lessonList.add(lesson);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors!",Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SecondActivity.this, lessonList,R.layout.list_item, new String[]{"number", "name",}, new int[]{R.id.lnumber,R.id.lname});
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
//intent.putExtra("Lesson", listView1.getItemAtPosition(i).toString());
startActivity(intent);
}
});
}
}
}
Can you try this please
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
HashMap<String, String> lesson = lessonList.get(i);
intent.putExtra("number", lesson.get("number"));
intent.putExtra("name", lesson.get("name"));
startActivity(intent);
}});
Similar question has been asked before. You have most of it in place, just use Intent.PutStringArrayListExtra and then getIntent.getStringArrayListExtra to pass objects between the activities.
Check this:
Intent.putExtra List

Convert Fragment Code to Activity Code

I am trying to convert my Fragment Code to Activity code, but when I try to run the Activity, the Activity opens but the data is null. Here my code
Fragment
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArmBicepFragment extends Fragment implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = ArmBicepFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:.......";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public ArmBicepFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("name").equals("bicep")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
And here my convert result from Fragment (Nothing Error or warning)
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Felix on 5/15/2016.
*/
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:............";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public RekomendasiExercise() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
return rootView;
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
onCreateView
is not a part of activity's lifecycle. You need to move stuff from this method to onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
You should put your codes in onCreate . Copy/paste the below codes.
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:............";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public RekomendasiExercise() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.elite.youvaa.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArmBicepFragment extends Activity implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = ArmBicepFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:.......";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public ArmBicepFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(getApplicationContext(), exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getApplicationContext());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("name").equals("bicep")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}

How can I delete an item from an online database via android application?

I started to develop Android recently and I'm having difficulty in solving a thing probably much simpler than what I think.
I am creating a CRUD application that communicates with an online database, I can read and enter data, unfortunately I can't delete and modify the list once it is created.
To manage the data that use JSON and the row in the list that I add is made up of three fields: animal_id, animal_name, animal_type.
The activity data on which I read and on which I want to implement methods to modify and delete via listener is formed by the following code:
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListAnimalActivity extends ListActivity {
ArrayList<HashMap<String,?>> animalList;
JSONParser jParser = new JSONParser();
JSONArray animals = null;
Button button_add;
private static String url_read = "http://example.com/list_animals.php";
private static String url_delete = "http://example.com/delete_animal.php";
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
load_ListAnimalActivity();
}
public void onResume(){
super.onResume();
load_ListAnimalActivity();
}
private void load_ListAnimalActivity(){
setContentView(R.layout.activity_list_animal);
animalList = new ArrayList<HashMap<String,?>>();
new Read_Object().execute();
final ListView listView = (ListView)findViewById(android.R.id.list);
final ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(ListAnimalActivity.this);
adb.setTitle("Attenzione!");
adb.setMessage("Vuoi eliminare l\'elemento \"" + animalList.get(position)+ "\" ?");
final int posizione = position;
adb.setNegativeButton("Annulla",new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {}
});
adb.setPositiveButton("Elimina", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Delete_Object().execute();
}
});
adb.show();
}
});
button_add = (Button)findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ListAnimalActivity.this,CRUDAnimalActivity.class));
}
});
}
class Read_Object extends AsyncTask<String, String, String> {
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Loading ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
List params = new ArrayList();
JSONObject json = jParser.makeHttpRequest(url_read, "POST", params);
try{
Log.d("Animals: ", json.toString());
} catch (NullPointerException e){
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
animals = json.getJSONArray("animals");
for (int i = 0; i < animals.length(); i++) {
JSONObject c = animals.getJSONObject(i);
String id = c.getString("animal_id");
String name = c.getString("animal_name");
String type = c.getString("animal_type");
HashMap map = new HashMap();
map.put("animal_id", id);
map.put("animal_name", name);
map.put("animal_type", type);
animalList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
progressMessage.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
setListAdapter(adapter);
}
});
}
}
class Delete_Object extends AsyncTask<String, String, String>{
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Deleting ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
/*
Code to delete
*/
return null;
}
protected void onPostExecute(String file_url){
}
}
}
When i click on a list Item, the listener show me the object in this format:
{animal_type=firstType, animal_name=firstName, animal_id=1}
So my question is:
How can I collect only animal_id from the array animalList > ?
Your animalList is an array list with HashMaps as its elements, so when you call animalList.get(position), it will return a HashMap. To retrieve an animal_id just use :
(animalList.get(position)).get(animal_id).toString();
you have to create a Modelclass/Pojo Class (Private variable and getters and setters) for Animals,
ArrayList<AnimalModel> animalsArrayList = new ArrayList<AnimalModel>();
add the Animals object/data to animalsArrayList and listview.setAdapter(animalsArrayList);
then
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Object object = speakerListView.getItemAtPosition(position);
AnimalModel animals_data = (AnimalModel) object;
id = animals_data.getAnimal_id()
// call delete Async with thid Id
}
});
You code looks pretty messy. If I were you I would create a Custom Adapter that extends the base adapter and takes as a parameter either a hashmap or a list that you pass in the constructor. There you can have different listeners. Also if you want to notify the activity you can have the "luxury" to pass an interface as a parameter and notify the activity when something changes.
Regarding the json part, I would create two new classes, one which is a Thread Manager that receives tasks and handles them further and another class where u make the http calls and the json parsing.
I have done a similar application that receives data from a nebula interface and displays them to the user.

how to close this progress dialog in post execute in android

I have made a custom progress Dialog,I wan to close it in my postExecute method,I have tried as below,But i don't know how to dismiss it.I have tried as below,Can anyone Please tell me how can i dismiss that custom dialog
main
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class SearchActivity extends Activity {
public com.epe.yehki.uc.Menu searchMenu;
public Header searchHeader;
public EditText et_serach;
JSONObject jsonObj;
private ProgressDialog pDialog;
Intent in = null;
String searchUrl;
int flag;
public Header header;
public Menu menu;
public TextView title;
Bitmap bitmap;;
private ProductAdapter productContent;
// PRODUCTS....
// arrayLists......
public static ArrayList<String> productArray;
public static ArrayList<String> categoryArray;
ProgressBar progressBar;
//
// contacts JSONArray
JSONArray subcategories = null;
JSONArray products = null;
public String catid;
public String id;
public String pid;
String name;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> subcategoryList;
ArrayList<HashMap<String, String>> productList;
// new
public String proname;
public String prodesc;
public String proimg;
public String proMinOrderQty;
public String proMinPrice;
public String proMaxPrice;
public String proTerms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_search);
productList = new ArrayList<HashMap<String, String>>();
searchMenu = (com.epe.yehki.uc.Menu) findViewById(R.id.menusearch);
searchMenu.setSelectedTab(2);
searchHeader = (Header) findViewById(R.id.headersearch);
searchHeader.title.setText("Search");
et_serach = (EditText) findViewById(R.id.et_serach);
lv = (ListView) findViewById(R.id.serch_list);
productContent = new ProductAdapter(SearchActivity.this, productList);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "") != null && !Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "").equals(" ")
&& !Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "").equals("0")) {
in = new Intent(getApplicationContext(), ProductDetailActivity.class);
proname = ((TextView) view.findViewById(R.id.product_label)).getText().toString();
// getting ProductId from the tag...
pid = productList.get(position).get(Const.TAG_PRODUCT_ID);
proimg = productList.get(position).get(Const.TAG_PRODUCT_IMG);
System.out.println(":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY=================" + pid);
in.putExtra(Const.TAG_PRODUCT_ID, pid);
in.putExtra(Const.TAG_PRODUCT_IMG, proimg);
in.putExtra(Const.TAG_PRODUCT_NAME, proname);
startActivity(in);
} else {
in = new Intent(SearchActivity.this, LoginActivity.class);
startActivity(in);
}
}
});
et_serach.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
System.out.println(":::::::::::::::;after text changed called:::");
productList.clear();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() != 0) {
System.out.println(":::::::::::::::;on text changed called:::");
// CALL SEARCH API........!!!
productList.clear();
new GetSearchList().execute();
}
}
});
}
public void addProgressBar(Activity activity) {
final ViewGroup rootFrameLayout = (ViewGroup) activity.getWindow().peekDecorView();
final ViewGroup modal = new RelativeLayout(activity);
progressBar = new ProgressBar(activity);
LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
((android.widget.RelativeLayout.LayoutParams) layoutParams).addRule(RelativeLayout.CENTER_IN_PARENT);
modal.addView(progressBar, layoutParams);
rootFrameLayout.addView(modal, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
rootFrameLayout.invalidate();
}
// SEARCH API()..!!!
private class GetSearchList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
productList.clear();
addProgressBar(SearchActivity.this);// pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
searchUrl = Const.API_PRODUCT + "?product_name=" + et_serach.getText().toString().trim();
System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::" + searchUrl);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(searchUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString(Const.TAG_STATUS).equals("success")) {
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_PRODUCT_DETAIL));
products = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
if (products != null && products.length() != 0) {
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
pid = c.getString(Const.TAG_PRODUCT_ID);
System.out.println("::::::::::::::::::PARSING PRODUCT ID:::::::::::::" + pid);
String proname = c.getString(Const.TAG_PRODUCT_NAME);
String prodesc = c.getString(Const.TAG_LISTING_DESCRIPTION);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
System.out.println("::::::::::::::;products Length:::::::::::" + products.length());
System.out.println(":::::::::::::::My Image Url:::::::::::::" + proimg);
String proMinOrderQty = c.getString(Const.TAG_PRODUCT_MIN_ORDER_QTY);
c.getString(Const.TAG_PRODUCT_MIN_PRICE);
c.getString(Const.TAG_PRODUCT_MAX_PRICE);
c.getString(Const.TAG_PRODUCT_PAYMENT_TERMS);
// for company details..!!!
// new Working
HashMap<String, String> product = new HashMap<String, String>();
product.put(Const.TAG_PRODUCT_ID, pid);
product.put(Const.TAG_PRODUCT_NAME, proname);
product.put(Const.TAG_PRODUCT_IMG, proimg);
product.put(Const.TAG_PRODUCT_MIN_ORDER_QTY, proMinOrderQty);
product.put(Const.TAG_PRODUCT_DESCRIPTION, prodesc);
productList.add(product);
}
}
}
} else {
runOnUiThread(new Runnable() {
public void run() {
Utils.showCustomeAlertValidation(SearchActivity.this, "No Product found", "Yehki", "Ok");
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
productContent.notifyDataSetChanged();
lv.setAdapter(productContent);
}
}
}
Its easy try:
pDialog.dismiss();
STEP 1
Declare progress dialog above on create
private ProgressDialog pDialog;
STEP 2
Define preExecute method
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setTitle("Please wait");
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
pDialog.show();
}
STEP 3
//Your back ground task as it is
STEP 4
ADD postExecute Method
protected void onPostExecute()
{
pDialog.dismiss();
}
You need to just call dismiss() method for ProgressDialog. Like
protected void onPostExecute(){
pDialog.dismiss();
}
You have the progressBar variable that holds a reference to the progress bar in your layout. To hide it, call
progressBar.setVisibility(View.GONE);
The RelativeLayout you're placing the ProgressBar in is unnecessary. Also consider including the ProgressBar statically in your layout and just setting its visibility to VISIBLE/GONE as necessary.

how to get all editext's value from ListItems in android and pass them to api

I have made an activity in that one ListView is ther,In that ListView each listItem is having an editText named "qty",which can be edited,one textView is there which displays "price",I need is when i edit the edittext and if the entered value is more than some limi the textView value will change,After that i have to pass them as a parameter to an api as below:
http://yehki.epagestore.in/app_api/updateCart.php?customer_id=41&product_id=30&quantity=90&product_id=23&quantity=90
from that i will get subtotal's of eact item and have to set them to each item in the list,can anyone please help me for it?My code is as below..Please help me save my life...thank you
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lv.removeViewAt(position);
cartContent.notifyDataSetChanged();
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
}
}
}
In ListAdapter, getItem() should return an item using which you populate the Views
#Override
public HashMap<String, String> getItem(int paramInt) {
return cartArray.get(paramInt);
}
To get all values,
final CartAdapter adapter = (CardAdapter) lv.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
final HashMap<String, String> item = adapter.getItem(i);
final String quantity = item.get(Const.TAG_QUANTITY); // value of EditText of one row
}

Categories

Resources