I get throuble for view my Spinner Data in XML.
The Toast can show data in selected item, but in spinner view can't show all item.
My code Java
public class LoadCategoryTask extends AsyncTask<Void, Void, Boolean> {
LoadCategoryTask() {
}
#Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
List<NameValuePair> data = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_get_category, "GET", data);
Log.d("All Category: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
category = json.getJSONArray(TAG_CATEGORY);
for (int i = 0; i < category.length(); i++) {
JSONObject c = category.getJSONObject(i);
String id = c.getString(TAG_ID_CATEGORY);
String category = c.getString(TAG_CATEGORY);
HashMap<String, String> map = new HashMap<String, String>();
System.out.println(id + ", " + category);
map.put(TAG_ID_CATEGORY, id);
map.put(TAG_CATEGORY, category);
category_arraylist.add(map);
}
} else {
System.out.println("Category not found");
}
} catch (JSONException e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
simpleAdapter = new SimpleAdapter(PlacesActivity.this, category_arraylist, R.layout.adapter_spinner_category,
new String[] { "category" },new int[]{R.id.lbl_category});
simpleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
public boolean setViewValue(View view, Object data,String textRepresentation) {
TextView textView = (TextView) view;
textView.setTextColor(Color.BLACK);
textView.setText(textRepresentation);
return true;
}
};
simpleAdapter.setViewBinder(viewBinder);
sp_category.setAdapter(simpleAdapter);
sp_category.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
And this XML Code the Activity, activity_places.xml
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sp_categoriy"
android:theme="#style/Base.Widget.AppCompat.Spinner.Underlined" />
This XML Code for Adapter Spinner, adapter_spinner_category.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lbl_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/navigationBarColor"/>
</LinearLayout>
Thanks.
Try This:
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(Contex, R.layout.spinner_textview, ArrayOfElements);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
simple_spinner_dropdown_item layout doesn't have 'lbl_category' id inside.
Make your custom DropDownView layout (just copy simple_spinner_dropdown_item) and set id 'lbl_category' to its CheckedTextView.
Related
I cant send all the rows of list view,Every time just last row of list view is going to the server,i want send all the items of list view when i click place order button.here is edited code my full code:
public class Order_From_App_All_new extends Activity implements View.OnClickListener {
ProgressDialog mProgressDialog
ArrayList<Actor> productlist = new ArrayList<>();
TextView txt1;
Button order;
ListView listview;
ImageView ivImage;
EditText edt2;
String address;
TextView txt17;
int position;
String product_id;
String product_qty;
ListView listview1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orderfromapp);
listview = (ListView) findViewById(R.id.listView1);
order=(Button)findViewById(R.id.button4);
edt2=(EditText)findViewById(R.id.editText2);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new Product_Adapter(Order_From_App_All_new.this, R.layout.row1, productlist);
listview.setAdapter(adapter);
new DownloadJSON().execute();
order.setOnClickListener(this);
}
// #Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
product_name = (String) mySpinner.getSelectedItem();
String product_quantity = edt1.getEditableText().toString();
String addtocartquerystring = "?product_name=" + product_name + "&product_quantity=" + product_quantity;
Log.d("Request : ", "starting 00 " + CC14.GETURL17 + addtocartquerystring);
new GetAddToCart(this, CC14.GETURL17 + addtocartquerystring).execute();
break;
case R.id.button4:
address=edt2.getEditableText().toString();
String[] productid = new String[productlist.size()];
String[] productquantity = new String[productlist.size()];
for (int i = 0; i < productlist.size(); i++) {
productid[i]=productlist.get(i).getProductid();
productquantity[i]=productlist.get(i).getProductquantity();
product_qty=productquantity[i];
product_id=productid[i];
}
String placeorderquerystring = "?address=" + address + "&product_id=" + product_id+"&product_qty="product_qty;
Log.d("Request : ", "starting 00 " + CC14.GETURL23 + placeorderquerystring);
new GetPlaceOrder(Order_From_App_All_new.this, CC14.GETURL23 + placeorderquerystring).execute();
break;
default:
break;
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the WorldPopulation Class
// productlist = new ArrayList<>();
// Create an array to populate the spinner
spinnerlist = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://duraent.net/android_order_app/api/android/orderList.php");
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("product");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
spinnerlist.add(jsonobject.optString("productname"));
// Actor actors = new Actor();
// actors.setProductname("Productname", jsonobject.optString("Productname"));
// actors.setDirectmobileorderprice("directmobileorderprice", jsonobject.getString("directmobileorderprice"));
// productlist.add(actors);
//Populate spinner with country names
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.spinner2);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(Order_From_App_All_new.this,
android.R.layout.simple_spinner_dropdown_item,
spinnerlist));
}
}
public class GetAddToCart extends AsyncTask<String, String, String> {
Http_OrderFromAppNew request = new Http_OrderFromAppNew();
Context ctx;
ListView listview;
TextView txt1;
String latLong_url;
ProgressDialog pd;
private String json;
public GetAddToCart(Context _ctx, String _latong_url) {
ctx = _ctx;
latLong_url = _latong_url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Order_From_App_All_new.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Locate the WorldPopulation Class
// Create an array to populate the spinner
// spinnerlist = new ArrayList<String>();
// JSON file URL address
String json = request
.makeHttpRequest(latLong_url, "GET", null);
// Populate spinner with country names
Log.d("Request Login attempt", json.toString());
return json;
}
#Override
protected void onPostExecute(String json) {
// Locate the spinner in activity_main.xml
//adapter.notifyDataSetChanged();
try {
JSONObject jsonobject = new JSONObject(json);
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("product");
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
// spinnerlist.add(jsonobject.optString("productname"));
Actor actors = new Actor();
actors.setProductname("productname",jsonobject.getString("productname"));
actors.setProductid("productid",jsonobject.getString("productid"));
actors.setSellingprice("sellingprice",jsonobject.getString("sellingprice"));
actors.setPricetotal("pricetotal", jsonobject.getString("pricetotal"));
actors.setProductquantity("productquantity", jsonobject.getString("productquantity"));
productlist.add(actors);
adapter.changeData(productlist);
// ListView listview = (ListView) findViewById(R.id.listView1);
//adapter = new Product_Adapter(getApplicationContext(), R.layout.row1, productlist);
//adapter.notifyDataSetChanged();
//listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class GetPlaceOrder extends AsyncTask<String, String,String> {
Http_OrderFromAppNew request = new Http_OrderFromAppNew();
Context ctx;
ListView listview;
TextView txt1;
String latLong_url;
ProgressDialog pd;
private String json;
public GetPlaceOrder(Context _ctx, String _latong_url) {
ctx = _ctx;
latLong_url = _latong_url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(Order_From_App_All_new.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Locate the WorldPopulation Class
// Create an array to populate the spinner
// spinnerlist = new ArrayList<String>();
// JSON file URL address
String json = request
.makeHttpRequest(latLong_url, "GET", null);
// Populate spinner with country names
Log.d("Request Login attempt", json.toString());
return json;
}
#Override
protected void onPostExecute(String json) {
// Locate the spinner in activity_main.xml
//adapter.notifyDataSetChanged();
try {
TextView txt17=(TextView)findViewById(R.id.textView17);
txt17.append(json);
mProgressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The few lines doing the sending should be inside the for loop:
for (int i = 0; i < productlist.size(); i++) {
productid[i]=productlist.get(i).getProductid();
productquantity[i]=productlist.get(i).getProductquantity();
product_qty=productquantity[i];
product_id=productid[i];
String placeorderquerystring = "?address=" + address + "&product_id=" + product_id+"&product_qty="product_qty;
Log.d("Request : ", "starting 00 " + CC14.GETURL23 + placeorderquerystring);
new GetPlaceOrder(Order_From_App_All_new.this, CC14.GETURL23 + placeorderquerystring).execute();
}
You need to send the cart items as an JSON obj or array to server,
{
"Customer":"Name",
"cart":"Cart ID",
"date":"10-06-2016",
"time":"3.36",
"cartItems":[
{
"ProductID":"1",
"ProductQuantity":"3"
},
{
"ProductID":"2",
"ProductQuantity":"5"
},
{
"ProductID":"6",
"ProductQuantity":"4"
}
]
}
To get the above format, use the following code
private String getItems() {
JSONObject dataObj = new JSONObject();
try {
dataObj.putOpt("Customer", "Name");
dataObj.putOpt("cart", "Cart ID");
dataObj.putOpt("date", "DATE");
dataObj.putOpt("time", "TIME");
JSONArray cartItemsArray = new JSONArray();
JSONObject cartItemsObjedct;
for (int i = 0; i < cartItems.size(); i++) {
cartItemsObjedct = new JSONObject();
cartItemsObjedct.putOpt("ProductID", cartItems.get(i).getId);
cartItemsObjedct.putOpt("ProductQuantity", cartItems.get(i).getProductQuantity);
cartItemsArray.put(cartItemsObjedct);
}
dataObj.put("cartItems", cartItemsArray);
} catch (JSONException e) { // TODO Auto-generated catch bloc
e.printStackTrace();
}
return dataObj.toString();
}
I am trying to populate the result onto a listview once I press the search button. But, when i try to do it, nothing is displayed on the listview.
I am using asynctask to get the data from database and pass it into the listview as a array.
Thanks for the help in advance!
Below are the code:
public class FindFriends extends Activity implements View.OnClickListener {
EditText handphone;
Button searchbtn;
String name,hp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
handphone = (EditText) findViewById(R.id.enterfn);
searchbtn = (Button) findViewById(R.id.searchfor);
searchbtn.setOnClickListener(this);
ListView listview = (ListView) findViewById(R.id.listView);
String[] values = new String[]{name};
ArrayAdapter<String> codeLearnArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listview.setAdapter(codeLearnArrayAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.searchfor:
hp = handphone.getText().toString();
new AttemptLogin().execute(hp);
break;
}
}
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "address_url";
#Override
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("hp", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(FindFriends.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
name = json.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
findfriends.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#drawable/findfriends"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/enterfn"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter handphone number/username to start searching"
android:id="#+id/textView9"
android:textSize="20dp"
android:layout_above="#+id/enterfn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/searchfor"
android:layout_below="#+id/enterfn"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/searchfor"
android:layout_centerHorizontal="true" />
</RelativeLayout>
I'm new in Android.
Anyway I can't see where you update your array, in the AsyncTask you download the data but you don't update values. So you shuld update the array passed to the adapter and then call the it's method notifyDataSetChanged()
Just go through the below code and replcae it with your,
public class FindFriends extends Activity implements View.OnClickListener {
EditText handphone;
Button searchbtn;
String name = "name", hp = "hp";
ListView listview;
ArrayAdapter<String> codeLearnArrayAdapter;
ArrayList<String> values;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
handphone = (EditText) findViewById(R.id.enterfn);
searchbtn = (Button) findViewById(R.id.searchfor);
searchbtn.setOnClickListener(this);
listview = (ListView) findViewById(R.id.listView);
// adding value to arrayList
values.add(name);
codeLearnArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listview.setAdapter(codeLearnArrayAdapter);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.searchfor:
hp = handphone.getText().toString();
new AttemptLogin(new MyHandler()).execute(hp);
break;
}
}
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "address_url";
MyHandler myHandler;
public AttemptLogin(MyHandler myHandler) {
this.myHandler = myHandler;
}
#Override
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("hp", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(FindFriends.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
name = json.getString("name");
Message message = new Message();
message.obj = name;
myHandler.sendMessage(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private class MyHandler extends Handler {
#Override
public void handleMessage(Message msg) {
String response = String.valueOf(msg);
values.add(response);
codeLearnArrayAdapter.notifyDataSetChanged();
}
}
}
And let me know if it works...
you missed adapter.notifyDataSetChanged();
Use this method after data changing
UPD
try this code:
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(FindFriends.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
name = json.getString("name");
values[0]=name;
codeLearnArrayAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Hope it works. Otherwise let me know about it.
P.S. You should also use List instead of array.
AutoCompleteTextView doesn't show any suggestions but data is filled in the adapter
Here is my block of CODE
public class AUTOSuggestion extends AsyncTask<String, String, String> {
String TITLE, id,level;
String response = " ";
ProgressDialog dialogProgress = new ProgressDialog(Home.this);
String tex;
public AUTOSuggestion(String text) {
// TODO Auto-generated constructor stub
tex=text;
}
protected void onPreExecute() {
dialogProgress.setCancelable(true);
dialogProgress.setMessage("Please wait..");
dialogProgress.setIndeterminate(false);
dialogProgress.show();
}
#Override
protected String doInBackground(String... params) {
try {
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("search", tex));
/* param.add(new BasicNameValuePair("catId", id));
param.add(new BasicNameValuePair("level", level));*/
response = CustomHttpClient.executeHttpPost(AUTOSUGGESTION_URL, param);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String response)
{
if (response != "" || response != null) {
try {
ArrayList<String>sug_list=new ArrayList<String>();
JSONObject Obj = new JSONObject(response);
//String status = Obj.getString("TAG_STATUS");
JSONArray jarr=Obj.getJSONArray("0");
for(int i=0;i < jarr.length(); i++){
JSONObject p = (JSONObject) jarr.get(i);
String words = p.getString("title");
sug_list.add(words);
}
item = sug_list.toArray(new String[sug_list.size()]);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e + "", Toast.LENGTH_LONG).show();
finish();
}
}
try {
dialogProgress.dismiss();
} catch (Exception e) {
e.fillInStackTrace();
}
autocomplete = (AutoCompleteTextView) findViewById(R.id.autocomplete);
//Toast.makeText(getBaseContext(), item.toString(), Toast.LENGTH_LONG).show();
adapter = new ArrayAdapter<String>(Home.this,android.R.layout.simple_dropdown_item_1line, item);
// Create adapter
//adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line, item);
autocomplete.setThreshold(1);
autocomplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
While debugging it is showing the words
GUYS help me please :'(
As suggested by other guys here this is the changes i have done
MODIFIED CODE
public class AUTOSuggestion extends AsyncTask<String, String, String> {
String TITLE, id,level;
String response = " ";
ProgressDialog dialogProgress = new ProgressDialog(Home.this);
String tex;
public AUTOSuggestion(String text) {
// TODO Auto-generated constructor stub
tex=text;
}
protected void onPreExecute() {
dialogProgress.setCancelable(true);
dialogProgress.setMessage("Please wait..");
dialogProgress.setIndeterminate(false);
dialogProgress.show();
}
#Override
protected String doInBackground(String... params) {
try {
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("search", tex));
response = CustomHttpClient.executeHttpPost(AUTOSUGGESTION_URL, param);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
protected void onPostExecute(String response)
{
if (response != "" || response != null) {
try {
JSONObject Obj = new JSONObject(response);
//String status = Obj.getString("TAG_STATUS");
JSONArray jarr=Obj.getJSONArray("0");
for(int i=0;i < jarr.length(); i++){
JSONObject p = (JSONObject) jarr.get(i);
String words = p.getString("title");
sug_list.add(words);
}
item = sug_list.toArray(new String[sug_list.size()]);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e + "", Toast.LENGTH_LONG).show();
finish();
}
}
try {
dialogProgress.dismiss();
} catch (Exception e) {
e.fillInStackTrace();
}
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,sug_list);
autocomplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(),sug_list+"",Toast.LENGTH_LONG).show();
}
}
Here is the item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#eaeaea"
android:padding="10dp"
android:textColor="#000"
android:textSize="16sp" >
</TextView>
After spending 6 hours I come to know that I have to add one line
autocomplete.showDropDown();
in onpost of async
check this page
you may need to update the UI.
runOnUiThread(new Runnable(){
public void run(){
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
I done a populating spinner with JSON.But I got a Error in ArrayList: WorldPopulation cannot be resolved.
public class MainActivity extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<WorldPopulation> world;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<WorldPopulation>();
worldlist = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt"); //JSON Functions cannot be resolved Error occured
try {
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setRank(jsonobject.optString("rank"));
worldpop.setCountry(jsonobject.optString("country"));
worldpop.setPopulation(jsonobject.optString("population"));
worldpop.setFlag(jsonobject.optString("flag"));
world.add(worldpop);
worldlist.add(jsonobject.optString("country"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
TextView txtpopulation = (TextView) findViewById(R.id.population);
txtrank.setText("Rank : "
+ world.get(position).getRank());
txtcountry.setText("Country : "
+ world.get(position).getCountry());
txtpopulation.setText("Population : "
+ world.get(position).getPopulation());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
That Same kind of ArrayList error occured many lines in a code.In xml Coding Everything was fine.Anybody tell me how to solve it.
From the link posted it looks like a incomplete tutorial.
//JSON Functions cannot be resolved Error occured
So the tutorial is missing JSONFunctions class and WorldPopulation class.
Have the below and keep the rest of the code the same.
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
{
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<WorldPopulation>();
worldlist = new ArrayList<String>();
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
Log.i("Response is......................",""+_response);
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setRank(jsonobject.optString("rank"));
worldpop.setCountry(jsonobject.optString("country"));
worldpop.setPopulation(jsonobject.optString("population"));
worldpop.setFlag(jsonobject.optString("flag"));
world.add(worldpop);
worldlist.add(jsonobject.optString("country"));
}catch(Exception e)
{
}
return null;
}
Edit:
public class MainActivity extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> worldlist;
ArrayList<WorldPopulation> world;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
world = new ArrayList<WorldPopulation>();
worldlist = new ArrayList<String>();
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://www.androidbegin.com/tutorial/jsonparsetutorial.txt");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
Log.i("Response is......................",""+_response);
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
WorldPopulation worldpop = new WorldPopulation();
worldpop.setRank(jsonobject.optString("rank"));
worldpop.setCountry(jsonobject.optString("country"));
worldpop.setPopulation(jsonobject.optString("population"));
worldpop.setFlag(jsonobject.optString("flag"));
world.add(worldpop);
worldlist.add(jsonobject.optString("country"));
}
}catch(Exception e)
{
}
return null;
}
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
worldlist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
TextView txtpopulation = (TextView) findViewById(R.id.population);
// Set the text followed by the position
txtrank.setText("Rank : "
+ world.get(position).getRank());
txtcountry.setText("Country : "
+ world.get(position).getCountry());
txtpopulation.setText("Population : "
+ world.get(position).getPopulation());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
WorldPopulation.java
public class WorldPopulation {
String rank,country,population,flag;
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPopulation() {
return population;
}
public void setPopulation(String population) {
this.population = population;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
}
activity_main.cml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
android:id="#+id/my_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/my_spinner" />
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rank" />
<TextView
android:id="#+id/population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/country" />
</RelativeLayout>
Snap
Not sure if there is no problem with your WorldPopulation class and its object. I just saw the link again, its not mentioned anywhere what WorldPopulation is,i think it should be a java class- WorldPopulation.java. If you add that, your code should run properly.
It should be like:
public class WorldPopulation {
String rank;
String country;
String population;
String flag;
// getter setters here
//toString if you want
}
i would suggest use Gson instead of a Json Parser. You already have the model class of WorldPopulation, now.. (this will go for all json responses)
Gson gson = new Gson();
ModelClass modelClass= new ModelClass();
modelClass= gson.fromJson(responseContent,ModelClass.class);
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like #SerializedName. (So no need to use Serializable)
In your case responseContent string can just be jObject.get("worldpopulation"), can also make a class containing ArrayList object which will act as a container for the actual response..no need of extracting jobject then
I build this webservice on netbeans,
package in.figures.on.mobile;
import db.koneksi.dbKoneksi;
import java.sql.Statement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import org.json.simple.JSONValue;
/**
*
* #author Setyadi
*/
#WebService()
public class AksesData {
/**
* Web service operation
*/
#WebMethod(operationName = "Kategori")
public String Kategori() {
//TODO write your implementation code here:
dbKoneksi con = new dbKoneksi();
Statement statement;
Properties properties;
List list = new ArrayList();
String sql = "SELECT idPrimary_key, kategori FROM kategori ";
ResultSet hasil;
String kategori = null;
try{
statement = con.getConnection().createStatement();
hasil = statement.executeQuery(sql);
while (hasil.next()) {
properties = new Properties();
properties.put("idPrimary_key", hasil.getString(1));
properties.put("kategori", hasil.getString(2));
list.add(properties);
}
kategori = JSONValue.toJSONString(list);
}
catch(Exception e){
}
return kategori;
}
}
And return a JSON like this
[{"idPrimary_key":"21ye21","kategori":"FirstCategory"},
{"idPrimary_key":"89oy89","kategori":"SecondCategory"},
{"idPrimary_key":"34ew34","kategori":"ThirdCategory"}]
And I try to consume in Android ListView like this, but still got errors,
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE transportSE = new HttpTransportSE(URL);
try {
transportSE.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
result = response.toString();
} catch (Exception e) {
e.printStackTrace();
}
String jsonAN = "{\"kat\":"+result+"}"; //try to build to be like this {"kat":[{blablablaJSON}]}
String kategoriJSONList[][] = new String[99][2];
String katList[] = new String[99]; //tobe shown on listview, derived from two dimensional array above.
try {
jsonObject = new JSONObject(jsonAN);
jsonArray = jsonObject.getJSONArray("kat");
for(int i=0; i < jsonArray.length() ; i++){
kategoriJSONList[i][0] = jsonArray.getJSONObject(i).getString("idPrimary_key").toString();
kategoriJSONList[i][1] = jsonArray.getJSONObject(i).getString("kategori").toString();
}
for(int i=0; i < jsonArray.length(); i++){
katList[i] = kategoriJSONList[i][1];
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView list = (ListView) findViewById(R.id.listKategori);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
WebServiceActivity.this, android.R.layout.simple_list_item_1,katList
);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
final String kategori = (String) ((TextView)arg1).getText();
Toast.makeText(WebServiceActivity.this, kategori,
Toast.LENGTH_LONG).show();
}
});
Need help how to consume the JSONValue that return as shown above to be shown as ListView.
I got stress in this days.
Thanks in advance.
Ok. Try this bellow code. It is full functional to me. You should implement the HttpRequest in the commented line. Pay atention to that the JSON array is hard-coded.
// the Adapter
public class ListViewAdapter extends BaseAdapter {
private Context context = null;
private List<String> fields = null;
public ListViewAdapter(Context context, JSONArray arr) {
this.context = context;
this.fields = new ArrayList<String>();
for (int i=0; i<arr.length(); ++i) {
try {
fields.add(arr.getJSONObject(i).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public int getCount() {
return fields.size();
}
#Override
public Object getItem(int position) {
return fields.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.itemlist, null);
TextView txt = (TextView) convertView.findViewById(R.id.ItemList_txt);
txt.setText(fields.get(position));
return convertView;
}
}
// the activity
public class ListViewActivity extends Activity {
public final String result = "[{\"idPrimary_key\":\"21ye21\",\"kategori\":\"FirstCategory\"},{\"idPrimary_key\":\"89oy89\",\"kategori\":\"SecondCategory\"},{\"idPrimary_key\":\"34ew34\",\"kategori\":\"ThirdCategory\"}]";
public final String obj = "{\"kat\":"+result+"}";
private ListViewAdapter adapter = null;
private ListView myList = null;
private JSONArray items = new JSONArray();
final Handler handler = new Handler() {
#Override
public void handleMessage(android.os.Message msg) {
if (msg.what == 0) { // server returned null, try again
loadFields();
} else if(msg.what == 1) { // error in json
// do something to treat it
} else if (msg.what == 2) { // ready to roll the list
adapter = new ListViewAdapter(ListViewActivity.this, items);
myList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myList = (ListView) findViewById(R.id.Lists_notificationsListview);
loadFields();
}
private void loadFields() {
new Thread() {
#Override
public void run() {
Looper.prepare();
StringBuilder builder = new StringBuilder(obj);
if (builder != null) {
try {
// HERE, you should implement the HTTP request...
items = new JSONObject(obj).getJSONArray("kat");
handler.sendEmptyMessage(2);
} catch (JSONException e) {
handler.sendEmptyMessage(1);
}
} else {
handler.sendEmptyMessage(0);
}
Looper.loop();
}
}.start();
}
And the xml files:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical"
android:isScrollContainer="true">
<ListView
android:id="#+id/Lists_notificationsListview"
android:layout_width="fill_parent" android:layout_height="match_parent">
</ListView>
</RelativeLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<TextView
android:id="#+id/ItemList_txt"
android:layout_width="fill_parent" android:layout_height="wrap_content"/>
</LinearLayout>
As result, it generates the following view:
Of course, you can customize it to create lists that you want, just parsing the jsons!
Hope that I've helped in some way...