I am trying to learn populating data from the server to Listview.
I am new to android
MainActivity.java
public class MainActivity extends Activity {
// url to make request
private static String url = "http://URL:7002/";
private static String url1 = "http://URL:7002/XXX";
//private HashMap<Integer, String> TimeMap = new HashMap<Integer, String>();
List<Item> yourData = new ArrayList<Item>();
List<Item> yourData1 = new ArrayList<Item>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiating ProgressDialog with onCreate method
progressDialog=new ProgressDialog(MainActivity.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
// getting JSON string from URL
JSONArray json1 = jParser.getJSONFromUrl(url1);
try {
for (int i = 0; i < json1.length(); i++) {
JSONObject c = json1.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt("_id");
String TIME = c.getString("RestaurantTime");
yourData1.add(new Item(TIME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
//TextView timedisplay=(TextView) findViewById(R.id.RestaurantTimeID);
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(MainActivity.this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
// remaining code
ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tt = null;
TextView time=null;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
time = (TextView) v.findViewById(R.id.RestaurantTimeID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
if (time != null) {
time.setText(""+p.getTime());
}
}
return v;
}
}
Item.java
public class Item{
private String Name;
private String Time;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
public void Time(String time){
this.Time = time;
}
public String getTime(){
return Time;
}
}
How can i resolve this
I have posted required classes above
Using List for populating the data is i am looking at
Any ideas,
Thanks.
You set TIME to yourdata1 and NAME to yourdata. The objects of yourdata1 only contains TIME and the NAME is null. The objects of yourdata only contains NAME and the TIME is null.
Please set NAME and TIME in one object and store it in one List which will be passed to ListAdapter.
I hope you can understand me.
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
// getting JSON string from URL
JSONArray json1 = jParser.getJSONFromUrl(url1);
// assume json's length is the same as json1's
try {
for (int i = 0; i < json1.length(); i++) {
JSONObject c = json1.getJSONObject(i);
Item item = new Item();
// Storing each json item in variable
int id = c.getInt("_id");
String TIME = c.getString("RestaurantTime");
item.setTime(TIME);
c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
item.setName(NAME);
yourData.add(item);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
and
public class Item{
private String Name;
private String Time;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
}
Related
I am developing an android app in which i store data from json.
everything is working fine but i am trying to implement multilayout Recyclerview where i show first and second category list items in a box with horizontal scroll and third list which we get from Category_id from json in vertical list
i get data from server in json where category list is open with unique category id just like
http://example.com/file_path&Category_id=3
and i get json data like
json data for category
[
{
"Category_ID":"3",
"Category_name":"Camera",
"Category_image":"upload\/images\/7089-2015-07-09.png"
},
{
"Category_ID":"9",
"Category_name":"Cars",
"Category_image":"upload\/images\/7789-2015-07-09.png"
},
]
json data for category list item
category list item json data. Every category list have unique id.
[
{
"Menu_ID":"19",
"Menu_name":"Sample 6",
"Price":"380",
"Menu_image":"upload\/images\/8611-2015-02-11.jpg"
},
{
"Menu_ID":"18",
"Menu_name":"Sample 5",
"Price":"500",
"Menu_image":"upload\/images\/8119-2015-02-11.jpg"
}
]
i am using recyclerview to show category and by clicking on category item category list is open
but i dont know how to call diffrent category list item from diffrent json category_id in a same recyclerview just like this image
Code is something like
MainActivity.java
public class ActivityProductList extends AppCompatActivity {
List<DataProductAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http: //example.com";
String Menu_Price_JSON = "Price";
String Menu_ID_JSON = "Menu_ID";
String Menu_Name_JSON = "Menu_name";
String Menu_Image_JSON = "Menu_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
public static ArrayList<Long> Menu_ID = new ArrayList<Long>();
public static ArrayList<String> Menu_name = new ArrayList<String>();
public static ArrayList<Double> Menu_price = new ArrayList<Double>();
public static ArrayList<String> Menu_image = new ArrayList<String>();
ProgressBar prgLoading;
SwipeRefreshLayout swipeRefreshLayout = null;
EditText edtKeyword;
ImageButton btnSearch;
TextView txtAlert;
public static double Tax;
public static String Currency;
String MenuAPI;
String TaxCurrencyAPI;
int IOConnect = 0;
long Category_ID;
String Category_name;
String Keyword;
// create price format
DecimalFormat formatData = new DecimalFormat("#.##");
private RecViewProductAdapter mla;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
ImageTitleNameArrayListForClick = new ArrayList<>();
mla = new RecViewProductAdapter(ActivityProductList.this);
// menu API url
MenuAPI = examplelink+"&category_id=";
// tax and currency API url
TaxCurrencyAPI = examplelink2;
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
Category_name = iGet.getStringExtra("category_name");
MenuAPI += Category_ID;
ListOfdataAdapter = new ArrayList<>();
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
edtKeyword = (EditText) findViewById(R.id.edtKeyword);
btnSearch = (ImageButton) findViewById(R.id.btnSearch);
txtAlert = (TextView) findViewById(R.id.txtAlert);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_prod);
recyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManagerOfrecyclerView);
recyclerViewadapter = new RecViewProductAdapter(ListOfdataAdapter, getApplicationContext());
recyclerView.setAdapter(recyclerViewadapter);
// JSON_HTTP_CALL();
new getTaxCurrency().execute();
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
IOConnect = 0;
clearData();
new getDataTask().execute();
}
}, 3000);
}
});
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View arg1, int position)
{
// TODO: Implement this method
AdapterView<?> arg0;
long arg3;
Intent iDetail = new Intent(ActivityProductList.this, ActivityMenuDetail.class);
iDetail.putExtra("menu_id", Menu_ID.get(position));
startActivity(iDetail);
}
})
);
}
public class getTaxCurrency extends AsyncTask<Void, Void, Void>{
// show progressbar first
getTaxCurrency(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataTax();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if internet connection and data available request menu data from server
// otherwise, show alert text
if((Currency != null) && IOConnect == 0){
new getDataTask().execute();
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
public void parseJSONDataTax(){
try {
// request data from tax and currency API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(TaxCurrencyAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into tax and currency variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
JSONObject object_tax = data.getJSONObject(0);
JSONObject tax = object_tax.getJSONObject("tax_n_currency");
Tax = Double.parseDouble(tax.getString("Value"));
JSONObject object_currency = data.getJSONObject(1);
JSONObject currency = object_currency.getJSONObject("tax_n_currency");
Currency = currency.getString("Value");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
IOConnect = 1;
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// clear arraylist variables before used
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(View.VISIBLE);
txtAlert.setVisibility(View.GONE);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(View.GONE);
// if data available show data on list
// otherwise, show alert text
if(Menu_ID.size() > 0){
recyclerView.setVisibility(View.VISIBLE);
recyclerView.setAdapter(mla);
}else{
txtAlert.setVisibility(View.VISIBLE);
}
}
}
void clearData(){
Menu_ID.clear();
Menu_name.clear();
Menu_price.clear();
Menu_image.clear();
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from menu API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(MenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data"); // this is the "items: [ ] part
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject menu = object.getJSONObject("Menu");
Menu_ID.add(Long.parseLong(menu.getString("Menu_ID")));
Menu_name.add(menu.getString("Menu_name"));
Menu_price.add(Double.valueOf(formatData.format(menu.getDouble("Price"))));
Menu_image.add(menu.getString("Menu_image"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//mla.imageLoader.clearCache();
recyclerView.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
}
adapter class
public class RecViewProductAdapter extends RecyclerView.Adapter<RecViewProductAdapter.ViewHolder> {
Context context;
List<DataProductAdapter> dataAdapters;
ImageLoader imageLoader;
private ActivityProductList _mainActivity;
private Activity activity;
public RecViewProductAdapter(ActivityProductList activity){
this._mainActivity=activity;
}
public RecViewProductAdapter(Activity act) {
this.activity = act;
}
public RecViewProductAdapter(List<DataProductAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.lsv_item_menu_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
View convertView = null;
holder.menuname.setText(ActivityProductList.Menu_name.get(position));
holder.menuprice.setText(ActivityProductList.Menu_price.get(position)+" "+ActivityProductList.Currency);
Picasso.with(activity).load(Config.ADMIN_PANEL_URL+"/"+ActivityProductList.Menu_image.get(position)).placeholder(R.drawable.loading).into(holder.imgThumb);
}
#Override
public int getItemCount() {
return ActivityProductList.Menu_ID.size();
// return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtText, txtSubText;
ImageView imgThumb;
public TextView menuname, menuprice, menunid;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
menuname = (TextView) itemView.findViewById(R.id.txtText);
menuprice = (TextView) itemView.findViewById(R.id.txtSubText);
imgThumb = (ImageView) itemView.findViewById(R.id.imgThumb);
}
}
}
any idea how can i achieve that layout with above code?
thankx
In this i want to cancel the asynctask i called aysnc task in listview onclickitem...
so if there is no data in particular row's then it will stop execution and remain on same activity.
I called the class in click and if condition if false as file_path is null then it will remain on same activity will not proceed further in another activity.
but in my case it will move to another activity i tried lot many things on this like oncancelled(), cancel(), etc methods but they are not working i put all in loop as well as switch case to break.
public class EAdFragment extends Fragment {
ListView lvAdSurvey;
JSONObject json = null;
public static final String FIRST_COLUMN = "Upl_ID";
public static final String SECOND_COLUMN = "File_Description";
JSONArray jarray = null;
JSONObject jsonObj = null;
String upload_type;
String upl_id;
File f;
String imgurl;
ProgressDialog pDialog;
String upl_ID, type_of_upload, file_description, amount;
String file_path = null;
String file_type, related_to, country, state, city, Number_of_user,
type_illegal;
GetData task;
ViewHolder holder;
public ListAdapter adapter;
String text;
public List<EAdvertActivityData> listData = new ArrayList<EAdvertActivityData>();
public void onViewCreated(View view, Bundle savedInstanceState) {
lvAdSurvey = (ListView) view.findViewById(R.id.lvAdSurvey);
new GetList().execute();
lvAdSurvey.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// String text =
// lvAdSurvey.getItemAtPosition(position).toString();
holder = (ViewHolder) view.getTag();
text = holder.txtFirstColumn.getText().toString();
Log.d("text:", text);
task = new GetData();
task.execute();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ead, container,
false);
return rootView;
}
private class GetList extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected JSONObject doInBackground(String... args) {
String url = "url";
JSONParser jParser = new JSONParser();
jsonObj = jParser.getJSONFromUrl(url);
try {
jarray = jsonObj.getJSONArray("result");
Log.d("lengtharray:", String.valueOf(jarray.length()));
for (int i = 0; i < jarray.length(); i++) {
EAdvertActivityData data = new EAdvertActivityData();
JSONObject jobject = new JSONObject(jarray.get(i)
.toString());
upload_type = jobject.optString("Upl_ID").toString();
String description = jobject.optString("File_description")
.toString();
/*
* Log.d("upload_type",upload_type);
* Log.d("description",description);
*/data.setUpl_ID(upload_type);
data.setFile_description(description);
listData.add(data);
Log.d("data:", listData.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObject) {
EAdListViewAdapter adapter = new EAdListViewAdapter(getActivity(),
listData);
lvAdSurvey.setAdapter(adapter);
}
}
private class GetData extends AsyncTask<String, String, String> {
int flag=0;
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
SharedPreferences pref = getActivity().getSharedPreferences(
"SoundSettings", Context.MODE_PRIVATE);
String user_id = pref.getString("user_id", LoginActivity.userid);
String url = "url"
+ text;
JSONParser jParser = new JSONParser();
try {
json = jParser.getJSONFromUrl(url);
Log.d("jsonadvert:", json.toString());
String status = json.getString("fetchdata");
if (status.equals("Success")) {
type_of_upload = json.getString("Type_of_Upload");
file_description = json.getString("File_description");
amount = json.getString("Amount");
file_path = json.getString("file_path");
file_type = json.getString("File_type");
related_to = json.getString("Related_to");
country = json.getString("Country");
// state = json.getString("state");
Number_of_user = json.getString("Number_of_usr");
type_illegal = json.getString("Type_llegal");
Log.d("type_illegal:", type_illegal);
Log.d("file_path:", file_path);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String args) {
pDialog.dismiss();
if(file_path==null){
Toast.makeText(getActivity(), "Image does not exists", Toast.LENGTH_LONG).show();
pDialog.cancel();
task.cancel(true);
}else{
imgurl = "http://sharpersofttech.com/sign_up/" + file_path;
Intent in = new Intent(getActivity(), AdvertActivity.class);
in.putExtra("upl_id", text);
in.putExtra("file_description", file_description);
in.putExtra("imgurl", imgurl);
startActivity(in);
((Activity) getActivity()).overridePendingTransition(0, 0);
}
}
}
}
I'm trying to make a project using Android Eclipse and I'm new to this.
Here's my problem:
I have a table whose columns are id, service_name, price, detail. I already knew how to fetch data from Spinner.
I want to ask if how am I going to query data and display it into my TextView which are txtPrice and txtDetail upon selecting Spinner.
Here is my code, which I got from androidhive.info, thanks!
public class TransactionActivity extends Activity implements OnItemSelectedListener {
private Button btnAddNewService;
//private TextView txtService;
private Spinner spinnerService;
// array list for spinner adapter
private ArrayList<ServiceList> servicesList;
ProgressDialog pDialog;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://localhost/food_api/new_category.php";
// Url to get all categories
private String URL_CATEGORIES = "http://localhost/FlawlessAdmin/storescripts/create_transaction/get_service.php";
////////////////////////////////
private EditText editTextService;
List<String> listService=new ArrayList<String>();
////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transaction);
btnAddNewService = (Button) findViewById(R.id.btnTransact);
spinnerService = (Spinner) findViewById(R.id.spinService);
editTextService = (EditText) findViewById(R.id.txtService);
servicesList = new ArrayList<ServiceList>();
// spinner item select listener
spinnerService.setOnItemSelectedListener(this);
editTextService=(EditText) findViewById(R.id.txtService);
// Add new Service click event
btnAddNewService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editTextService.getText().toString().trim().length() > 0) {
// new category name
String newService = editTextService.getText().toString();
// Call Async task to create new category
new AddNewService().execute(newService);
} else {
Toast.makeText(getApplicationContext(),
"Please enter service name", Toast.LENGTH_SHORT)
.show();
}
}
});
new GetCategories().execute();
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
editTextService.setText("");
for (int i = 0; i < servicesList.size(); i++) {
lables.add(servicesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerService.setAdapter(spinnerAdapter);
//////////////Copying from spinner to EditText
listService.addAll(lables);
}
/**
* Async task to get all food categories
* */
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TransactionActivity.this);
pDialog.setMessage("Fetching service categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("services");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
ServiceList cat = new ServiceList(catObj.getInt("id"),
catObj.getString("service_name"));
servicesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
/**
* Async task to create a new food category
* */
private class AddNewService extends AsyncTask<String, Void, Void> {
boolean isNewCategoryCreated = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TransactionActivity.this);
pDialog.setMessage("Creating new services..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String newCategory = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", newCategory));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
isNewCategoryCreated = true;
} else {
Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (isNewCategoryCreated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// fetching all categories
new GetCategories().execute();
}
});
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
/////////////////////////////////////
String strAge=listService.get(position).toString();
editTextService.setText(strAge);
/////////////////////////////////////
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}}
I know that the code I gave doesn't have the reference for price and detail. My table's columns are id, service_name, price and detail. And what I want for my activity is to have a Spinner for service_name, and TextView for the price and detail. Now, my problem is when I select for service_name, the TextView should display what the equivalent price and detail. Thanks. Thanks for the help!
public class ServiceList {
private int id;
private String name;
public ServiceList(){}
public ServiceList(int id, String name){
this.id = id;
this.name = name;
}
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
}
If you want your ServiceList class to contain price and detail properties, you need to add them to the existing class, and create setters and getters for the properties. For convenience, you could also create another constructor. I am making the assumption that the price property is a String.
public class ServiceList {
private int id;
private String name;
private String price;
private String detail;
public ServiceList(){}
public ServiceList(int id, String name){
this.id = id;
this.name = name;
}
public ServiceList(int id, String name, String price, String detail){
this.id = id;
this.name = name;
this.price = price;
this.detail = detail;
}
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setPrice(String price){
this.price = price;
}
public void setDetail(String detail){
this.detail = detail;
}
public int getId(){
return this.id;
}
public String getName(){
return this.name;
}
public String getPrice(){
return this.price;
}
public String getDetail(){
return this.detail;
}
}
Modify the ServiceList constructor in the doInBackground method of your GetCategories async task class to the newly created ServiceList constructor.
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("services");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
int id = catObj.getInt("id");
String serviceName = catObj.getString("service_name");
String detail = catObj.getString("detail");
String price = catObj.getString("price");
ServiceList cat = new ServiceList(id, serviceName, price, detail);
servicesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
In your onItemSelected method, set the text for price and detail as you desire.
My advice is that you consider learning Java and Android properly. I recommend the Java and Android classes on Udacity. You could choose the FREE option, so you do not have to pay.
I hope this helps.
I have a API which responds in JSON. When I clicked a button I am comfortably parse the JSON and implement it in the listview. The problem is When I go back to the previous activity and clicked the button once again I am getting the values repeat. i.e. previous values also, even I had called finish(); in on pause state of the listview activity. Following is my code.
Invoice Class
public class Invoice extends Activity{
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
boolean tree = true;
ArrayList<String> KEY = new ArrayList<String>();
ListView mListView;
ProgressBar mProgress;
JSONObject json;
JSONArray Module_list = null;
Invoice_adapter adapter;
public static String KEY_SUCCESS = "success";
public static String KEY_ERROR = "error";
public static String KEY_ERROR_MSG = "error_msg";
public static String KEY_MODULELIST_MODULEHEADER = "moduleHeader";
public static String KEY_MODULELIST_MODULELIST = "moduleList";
public static String KEY_MODULELIST_DATAFOUND = "datafound";
public static String KEY_INVOICE_INVOICENO = "";
public static String KEY_INVOICE_SUBJECT = "";
public static String KEY_INVOICE_SALESORDER = "";
public static String KEY_INVOICE_STATUS = "";
public static String KEY_INVOICE_TOTAL = "";
public static String KEY_INVOICE_ASSIGNEDTO = "";
public static String KEY_INVOICE_RECORDID = "";
public static String KEY_INVOICE_ACTION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_module_data);
mListView = (ListView) findViewById(R.id.module_list);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
try {
json = new ParseDATA().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
String data_found = json.getString(KEY_MODULELIST_DATAFOUND);
if (data_found.equals("Data Found!")){
JSONArray array = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count1 = array.length();
String Count1 = Integer.toString(count1);
Log.d("Count_array", Count1);
JSONObject keyarray = array.getJSONObject(0);
#SuppressWarnings("rawtypes")
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEY.add(curentkey);
}
Collections.sort(KEY, String.CASE_INSENSITIVE_ORDER);
KEY_INVOICE_ACTION = KEY.get(0);
KEY_INVOICE_ASSIGNEDTO = KEY.get(1);
KEY_INVOICE_INVOICENO = KEY.get(2);
KEY_INVOICE_RECORDID = KEY.get(3);
KEY_INVOICE_SALESORDER = KEY.get(4);
KEY_INVOICE_STATUS = KEY.get(5);
KEY_INVOICE_SUBJECT = KEY.get(6);
KEY_INVOICE_TOTAL = KEY.get(7);
Log.d("Parsing Json class", " ---- KEYS---- " + KEY);
Module_list = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count = Module_list.length();
String Count = Integer.toString(count);
Log.d("Count_Module_LIST", Count);
// looping through All Contacts
for(int i = 0; i < Module_list.length(); i++){
JSONObject c = Module_list.getJSONObject(i);
// Storing each json item in variable
String mAction = c.getString(KEY_INVOICE_ACTION);
String mAssignedTo = c.getString(KEY_INVOICE_ASSIGNEDTO);
String mInvoice = c.getString(KEY_INVOICE_INVOICENO);
String mRecordid = c.getString(KEY_INVOICE_RECORDID);
String mSalesorder = c.getString(KEY_INVOICE_SALESORDER);
String mStatus = c.getString(KEY_INVOICE_STATUS);
String mSubject = c.getString(KEY_INVOICE_SUBJECT);
String mTotal = c.getString(KEY_INVOICE_TOTAL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_INVOICE_ACTION, mAction);
map.put(KEY_INVOICE_ASSIGNEDTO, mAssignedTo);
map.put(KEY_INVOICE_INVOICENO, mInvoice);
map.put(KEY_INVOICE_RECORDID, mRecordid);
map.put(KEY_INVOICE_SALESORDER, mSalesorder);
map.put(KEY_INVOICE_STATUS, mStatus);
map.put(KEY_INVOICE_SUBJECT, mSubject);
map.put(KEY_INVOICE_TOTAL, mTotal);
// adding HashList to ArrayList
ModuleName.add(map);
}
}else
{
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
return;
}
}
mProgress.setVisibility(View.INVISIBLE);
adapter = new Invoice_adapter(Invoice.this, ModuleName);
mListView.setAdapter(adapter);
mListView.setVisibility(View.VISIBLE);
//mListView.invalidateViews();
}
else
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ERROR, "Error");
ModuleName.add(map);
//JSONObject json_user = json.getJSONObject("user");
//error_message = json_user.getString(KEY_ERROR_MSG);
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong.Please try again.!!", Toast.LENGTH_LONG).show();
}
}
class ParseDATA extends AsyncTask<Void, String,JSONObject >
{
ProgressDialog dialog = new ProgressDialog(Invoice.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setTitle("Loading");
dialog.setIndeterminate(true);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected JSONObject doInBackground(
Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getModuleList("1", "20", "Invoice");
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getApplicationContext(), "PAUSE STATE", Toast.LENGTH_LONG).show();
finish();
}}
Adapter class
public class Invoice_adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public Invoice_adapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_module_data_detail, null);
TextView title = (TextView)vi.findViewById(R.id.textView1); // category title name
//ImageView moduleImage = (ImageView) vi.findViewById(R.id.recipe_image);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
Log.i("list", ""+data.get(position));
//Log.i("list", data);
String ff = song.get(Invoice.KEY_INVOICE_SUBJECT);
title.setText(ff);
//moduleImage.setImageResource(mModuleImages[position]);
return vi;
}}
Please Help.. !! I dnt know what Is I am doing wrong.
Thanks in advance.
The problem is with the "static" key word for the ArrayList
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
static variables are initialized only when the class is loaded, that means the value will be persisted till the end of the application process.
Either remove static keyword for array list or clear the array list before you load new data.
ModuleName.clear();
I put JSON data to the ListView. I want data in the list("ItemTitle", "ItemText", "latit", "longit", "date") can transfer to another activity(result.java)when item is clicked. Here are the code:
activity:
public class Earthquake extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake);
getData();
}
private void getData() {
// TODO Auto-generated method stub
ListView list = (ListView)findViewById(R.id.earthquake);
try {
List<News> newes = GetJson.update();
List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
for(News news : newes){
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("ItemTitle", news.getPlace());
item.put("ItemText", "Magnitude: "+news.getMag());
item.put("latit", news.getLatit());
item.put("longit", news.getLongit());
item.put("date", news.getTime());
data.add(item);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.list_earthquake,
new String[]{"ItemTitle", "ItemText", "latit", "longit", "date"},
new int[]{R.id.ItemTitle, R.id.ItemText, R.id.latit, R.id.longit, R.id.date});
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
//intent
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetJson.java:
public class GetJson {
public static List<News> update() throws Exception, IOException {
// TODO Auto-generated method stub
String path = "http://earthquake.usgs.gov/earthquakes/feed/geojson/all/hour";
HttpURLConnection conn = (HttpURLConnection)new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
InputStream json = conn.getInputStream();
return parseJSON(json);
}
return null;
}
private static List<News> parseJSON(InputStream jsonStream) throws Exception {
// TODO Auto-generated method stub
List<News> list = new ArrayList<News>();
byte[] data = StreamTool.read(jsonStream);
String json = new String(data);
//start decoad JSON
JSONObject jsonObject1 = new JSONObject(json);
String object1 = jsonObject1.getString("features");
JSONArray features = new JSONArray(object1);
for(int i = 0; i < features.length(); i++){
JSONObject object2 = features.getJSONObject(i);
JSONObject properties = object2.getJSONObject("properties");
String place = properties.getString("place");
int mag = properties.getInt("mag");
String time = properties.getString("time");
JSONObject geometry = object2.getJSONObject("geometry");
JSONArray coordinates = geometry.getJSONArray("coordinates");
String longit = coordinates.getString(0);
String latit = coordinates.getString(1);
list.add(new News(mag, longit, latit, place, time));
}
return list;
}
}
News.java:
public class News {
private Integer mag;
private String longit;
private String latit;
private String place, time;
public News(){}
public News(Integer mag, String longit, String latit, String place, String time){
this.mag = mag;
this.longit = longit;
this.latit = latit;
this.place = place;
this.time = time;
}
public Integer getMag(){
return mag;
}
public String getLongit(){
return longit;
}
public String getLatit(){
return latit;
}
public String getPlace(){
return place;
}
public String getTime(){
return time;
}
}
Thanks!!
I suggest you rewrite your SimpleAdapter to extends ArrayAdapter<News>. Creating another List of HasMaps is quite useless and consumes additional memory. Than make your News class implement Parcelable. And in onClick() you call something like:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News news = parent.getItem(position);
if (news != null) {
Intent intent = new Intent(...);
intent.put("news", news);
startActivity(intent);
}
}
Always use a non-UI thread to fetch data from servers. Looking at your code it looks like you are using the UI thread to fetch data. You may use AsyncTask and paste the code written in the GetJson class in the doInBackground method of an AsyncTask object.
Now about your problem to pass the clicked list item data to the next activity. You will have to either make the class News implement Parcelable or Serializable interface. implementing these classes allows you to send the custom object data to another activity. The most efficient way is to implement Parcelable.
Check the following links for more details:
http://developer.android.com/reference/android/os/Parcelable.html
http://developer.android.com/reference/java/io/Serializable.html
Hope this explanation helps.