Populating Spinner with JSON - android

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

Related

Error parsing data org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

Im still new with android and json please help me Im also getting Null Pointer Exception. What should I do? Thanks In Advance
Heres my code:
JSONArray ass=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ass_list);
new JSONParse().execute();
}
//JSON
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl("http://192.168.43.252/mobappproj/asslist.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
final ArrayList<String> ids = new ArrayList<String>();
final ArrayList<String> assname = new ArrayList<String>();
final ArrayList<String> duedate = new ArrayList<String>();
final ArrayList<String> course = new ArrayList<String>();
final ArrayList<String> note = new ArrayList<String>();
try {
ass = json.getJSONArray("ass");
for(int i=0; i<ass.length(); i++){
JSONObject student = ass.getJSONObject(i);
ids.add(student.getString("id"));
assname.add(student.getString("assname"));
duedate.add(student.getString("duedate"));
course.add(student.getString("course"));
note.add(student.getString("note"));
}
final ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AssList.this,android.R.layout.simple_list_item_1, android.R.id.text1, course);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item value                       
String ass_id = ids.get(position);
String ass_name = assname.get(position);
String ass_date = duedate.get(position);
String ass_course = course.get(position);
String ass_note = note.get(position);
Intent i = new Intent(AssList.this, ViewAss.class);
i.putExtra("ass_id", ass_id);
i.putExtra("ass_name", ass_name);
i.putExtra("ass_date", ass_date);
i.putExtra("ass_course", ass_course);
i.putExtra("ass_note", ass_note);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This the error I get:
07-20 19:20:35.635 30660-30711/com.example.shaishai.assignmenttrackertry E/JSON Parser: Error parsing data org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject

how to send all the list view items to the server in android

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();
}

Android populate spinner with string array

Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {
public static String page;
TextView textName;
Spinner spinner;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rune_activity);
GetRunes getRunes = new GetRunes();
getRunes.execute();
spinner = (Spinner) findViewById(R.id.rune_selector);
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
class GetRunes extends AsyncTask<String, String, JSONObject> {
private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
String region = MainActivity.region.toLowerCase();
String id = StatsActivity.sumID;
String encodedKey = null;
String encodedRegion = null;
String encodedId = null;
String url = null;
// JSON Node Names
String TAG_NAME = "name";
String TAG_CURRENT = "current";
String TAG_SLOTS = "slots";
String TAG_RUNEID = "runeId";
String TAG_RUNESLOTID = "runeSlotId";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
// Assign views
textName = (TextView) findViewById(R.id.name);
// Encode URL variables
encodedId = URLEncoder.encode(id, "UTF-8");
encodedKey = URLEncoder.encode(api_key, "UTF-8");
encodedRegion = URLEncoder.encode(region, "UTF-8");
url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
Log.i("..........", url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.i("............", "" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();

To get Id of selected item in spinner android

Here, It is my java file
public class Create_Event extends SherlockFragment
implements OnClickListener {
class Organizer extends AsyncTask<Void, Void, Object> {
private ProgressDialog pdia;
protected void onPreExecute() {
super.onPreExecute();
pdia = new ProgressDialog(getActivity());
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected Object doInBackground(Void... params) {
try {
HttpClient httpclient1 = new DefaultHttpClient();
HttpPost httppost1 = new HttpPost(Constants.BASE_URL
+ "mobile_logins/all_my_event");
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1);
nameValuePairs1.add(new BasicNameValuePair("id", Constants.id));
httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
HttpResponse response1 = httpclient1.execute(httppost1);
String _response1 = EntityUtils.toString(response1.getEntity());
Log.e("test", _response1);
jsobj1 = new JSONObject(_response1);
orr = jsobj1.getJSONArray("organizers");
String orggg = orr.toString();
Log.e("Organization", orggg);
return jsobj1;
} catch (Exception e) {
e.printStackTrace();
Log.e("Fail 1", e.toString());
return e;
}
}
protected void onPostExecute(Object jsobj) {
pdia.dismiss();
String post = jsobj.toString();
Log.e("event_rese", post);
int len = orr.length();
Log.e("json_posexe", orr.toString());
Log.e("Onpostexe_arrlength", String.valueOf(len));
try {
JSONArray JA = orr;
JSONObject json1 = null;
final String[] host1 = new String[orr.length()];
final String[] host_id=new String[orr.length()];
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
}
List<String> list = new ArrayList<String>();
for(int i = 0; i < host1.length; i++) {
list.add(host1[i]);
}
Log.e("onpostexe_list",list.toString());
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
organization=sp.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
} catch(Exception e) {
Log.e("Fail 3", e.toString());
}
if (json instanceof JSONObject) {
asyncrun = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
} else {
ExecptionHandler.register(getActivity(), (Exception) jsobj);
}
}
}
}
}
Here, I need id of the selected organization from spinner. The id and organization name came from Jsonobject(here jsobj1). How to get id of selected item from jsonobject? Is it possible?? Please Help...
Create a Organization bean as below with method #Override toString()
public class Organization {
private Integer orgId; // Long etc.
private String orgName;
// more properties if you need
#Override // Mandatory
public String toString() {
return orgName; // Return anything, what you want to show in spinner
}
// Getter & Setter
}
Then Create a java.util.List<Organization> organizationList; from your API response JSONArray or any other way. And make and set ArrayAdapter<Organization> to load Spinner options.
List<Organization> organizationList = ... // init using JSON Data OR any how;
ArrayAdapter<Organization> orgAdapter = new ArrayAdapter<Organization>(this, android.R.layout.simple_spinner_item, organizationList);
orgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner mySpinner = findViewById(R.id.orgSpinner);
mySpinner.setAdapter(orgAdapter);
Now get selected Organization and its Properties in any Click/Change Event like below
// In any OnClick / OnSelect event
Organization selectedOrganization = (Organization) mySpinner.getSelectedItem();
Integer orgId = selectedOrganization.getOrgId();
String orgName = selectedOrganization.getOrgName();
// and if you have more properties
Yes,it is Possible, try like below.
HashMap<String,String> map_values = new HashMap<String,String>();
for(int i = 0; i < len; i++) {
json1 = JA.getJSONObject(i);
host1[i] = json1.getString("name");
host_id[i] = json1.getString("id");
map_values.put(host1[i],host_id[i]);
}
and spinner
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
String value = sp.getSelectedItem().toString();
String id = map_values.get(value);
Log.v("id",""+id);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
mSpinner.getSelectedItemId(); // here is your selected item's Id.
BTW google first, ask later :)

Parsing JSON Data to a list View

I am trying to parse the data into the list View in android
JSON:: http://54.218.73.244:7000/
It has a JSON output :: [{"restaurantID":1,"restaurantNAME":"CopperChimney"},{"restaurantID":2,"restaurantNAME":"Aroy"},{"restaurantID":3,"restaurantNAME":"MarkBoulevard"}]
I am trying to display the CopperChimney, Aroy, MarkBoulevard in a
list view
I figured some small parts but can someone help me fill
AndroidJSONParsingActivity.java part of the code which invoolves putting data in a collection and displaying it
Any ideas ?
JSONParser
public class JSONParser {
static InputStream is = null;
static JSONArray jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Item.java
public class Item{
private String Name;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
}
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;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
}
return v;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listViewID"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center">
</ListView>
</LinearLayout>
itemlistrow.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
<TableRow android:layout_width="fill_parent"
android:id="#+id/TableRow01"
android:layout_height="wrap_content">
<TextView
android:id="#+id/RestaurantNameID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="name" android:textStyle="bold"
android:gravity="left"
android:layout_weight="1"
android:typeface="monospace"
android:height="40sp"/>
</TableRow>
</TableLayout>
AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
private static String url = "http://54.218.73.244:7000/";
//
//
//
//
/------ CODE -Trying to ADD ------ /
//
//
}
CODE I TRIED FOR AndroidJSONParsingActivity.java
public class AndroidJSONParsingActivity extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7000/";
List<Item> yourData = new ArrayList<Item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
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();
}
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
if(position == 0)
{
//code specific to first list item
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee1.class);
startActivity(myIntent);
}else if(position == 1)
{
Intent myIntent = new Intent(AndroidJSONParsingActivity.this,Employee2.class);
startActivity(myIntent);
}
}
});
}
}
public class AndroidJSONParsingActivity extends ListActivity {
ArrayList <Item> list = new ArraList <Item>();
#Override
public void onStart() {
super.onStart();
new GetHttpData().execute();
}
private class GetHttpData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
private static String url = "http://54.218.73.244:7000/";
JSONArray jArray = getJSONFromUrl(url);
int len = jArray.length();
for(int i = 0; i < len; i++) {
JSONObject restaurant = jArray.getJSONObject(i);
list.add(new Item(restaurant.getString("restaurantNAME"));
}
return null;
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(new ListAdapter(AndroidJSONParsingActivity.this, android.R.layout.simple_list_item_1, list));
}
}
}
This is just one way to parse it, you should also do all HttpRequests and JSON parsing in a separate thread, see http://developer.android.com/reference/android/os/AsyncTask.html
Edited:
You can also check this Example

Categories

Resources