Populate Android spinner from PHP MySql - java

I have populate spinner from PHP MySql.While i select 1st item then populate another spinner from item click.But the problem is in second spinner populate the data doubly.Whenever i select the item of 1st Spinner.Can someone help me for only once add the data in Second spinner.
Here is my Screen Shot
Here is my Activity Code
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "On Item Select : \n" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
strSelected_Category=parent.getItemAtPosition(pos).toString();
System.out.println("strSelected_Category = " + strSelected_Category);
spinnerSubCategory.setEnabled(true);
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_SUB_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", " > " + json);
if (json != null)
{
try {
JSONArray array=new JSONArray(json);
JSONArray sortedArray = new JSONArray();
for(int i=0;i<array.length();i++)
{
JSONObject obj=array.getJSONObject(i);
if(obj.getString("cat_name").equalsIgnoreCase(strSelected_Category))
{
sortedArray.put(obj);
Log.e("sortedArray"," = " +sortedArray);
}
}
if (sortedArray != null)
{
for (int i = 0; i < sortedArray.length(); i++)
{
JSONObject catObj = (JSONObject) sortedArray.get(i);
Category cat = new Category(catObj.getInt("subcat_id"),catObj.getString("subcat_name"));
sub_categoriesList.add(cat);
Log.e("cat "," = " + cat);
}
populateSubCategory();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.e("JSON Data", "Didn't receive any data from server!");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* Adding Category spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++)
{
lables.add(categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(spinnerAdapter);
}
private void populateSubCategory() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < sub_categoriesList.size(); i++)
{
lables.add(sub_categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSubCategory.setAdapter(spinnerAdapter);
}

spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "On Item Select : \n" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
strSelected_Category=parent.getItemAtPosition(pos).toString();
System.out.println("strSelected_Category = " + strSelected_Category);
spinnerSubCategory.setEnabled(true);
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_SUB_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", " > " + json);
if (json != null)
{
try {
JSONArray array=new JSONArray(json);
JSONArray sortedArray = new JSONArray();
for(int i=0;i<array.length();i++)
{
JSONObject obj=array.getJSONObject(i);
if(obj.getString("cat_name").equalsIgnoreCase(strSelected_Category))
{
sortedArray.put(obj);
Log.e("sortedArray"," = " +sortedArray);
}
}
sub_categoriesList.clear();
if (sortedArray != null)
{
for (int i = 0; i < sortedArray.length(); i++)
{
JSONObject catObj = (JSONObject) sortedArray.get(i);
Category cat = new Category(catObj.getInt("subcat_id"),catObj.getString("subcat_name"));
sub_categoriesList.add(cat);
Log.e("cat "," = " + cat);
}
populateSubCategory();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.e("JSON Data", "Didn't receive any data from server!");
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
/**
* Adding Category spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < categoriesList.size(); i++)
{
lables.add(categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(spinnerAdapter);
}
private void populateSubCategory() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < sub_categoriesList.size(); i++)
{
lables.add(sub_categoriesList.get(i).getName());
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSubCategory.setAdapter(spinnerAdapter);
}
TRY THIS , HAPPY CODING :)

Related

ScrollView should scroll to a particular TextView While selecting the same name in Spinner

In my app I want to scroll my ScrollView when I am selecting a text in Spinner upto one particular TextView which contains the text same as selected Spinner text in Android Studio using Java. (you can check image also). Here my spinner is dynamic and my textviews are also dynamic.
My Code - For Spinner
private void spinnerbind() {
JSONObject request = new JSONObject();
try {
request.put("action", "get_spinner");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, url,request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("data");
if(response.optString("status").equals("1")){
goodModelArrayList = new ArrayList<>();
//JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PlayerModel playerModel = new PlayerModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setid(dataobj.getString("id"));
playerModel.setTitle(dataobj.getString("specialist"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size(); i++){
names.add(goodModelArrayList.get(i).getTitle().toString());
}
spinnerArrayAdapter = new ArrayAdapter<String>(DoctorsActivity.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
mySpinner.setAdapter(spinnerArrayAdapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
PlayerModel playerModel = goodModelArrayList.get(position);
myid=playerModel.getId();
scrollView.scrollTo(0, 200);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
My Code - For Text Binding
public void detailsbind(){
JSONObject docrequest = new JSONObject();
try {
myrequest.put("action", "get_doctors");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, url,myrequest, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.optString("status").equals("1")){
// Toast.makeText(getApplicationContext(),response.getString("data"), Toast.LENGTH_SHORT).show();
JSONArray dataSpecArray = response.getJSONArray("data");
LayoutInflater inflater = getLayoutInflater();
for (int k = 0; k < dataSpecArray.length(); k++) {
PlayerModel Specialist = new PlayerModel();
JSONObject specJSONobj = dataSpecArray.getJSONObject(k);
TextView text1 = new TextView(MyActivity.this);
text1.setText(specJSONobj.getString("specialist"));
mainlayout.addView(text1);
}
}else{
Toast.makeText(DoctorsActivity.this, response.optString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
scrollview.scrollTo(0, getRelativeTop(textView))
private int getRelativeTop(View textView) {
if (textView.getParent() == textView.getRootView())
return textView.getTop();
else
return textView.getTop() + getRelativeTop((View) textView.getParent());
}

Error on Using Comparator for Sort ArrayList inside doInBackground Method

i am working on an Android Apps that need to show sorted data by double value. The data is fetched from online database server. So far is going well until i want to sort the data, i read some thread and using Comparator method to sort my arraylist. But, it didn't work. I don't know what happen but there's no error log on my log cat and the data doesn't appear on the screen.
Please help me what i need to do sir?
Thanks.
NB. this the code for my doInBackground method where i doing the process of fetching and sorting the data.
public class getCarRent extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
URL hp = null;
try {
hp = new URL(getString(R.string.liveurl)
+ "getCarRent.php?value=" + catId);
// hp = new URL(
// "http://192.168.1.106/restourant/foodtype.php?value="
// + id);
//Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
Log.d("input", "" + input);
BufferedReader r = new BufferedReader(new InputStreamReader(
input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
// Log.d("URL", "" + total);
JSONArray j = new JSONArray(total);
// Log.d("URL1", "" + j.length());
Item[] itemList = new Item[j.length()];
resultList = new ArrayList<Item>();
for (int i = 0; i < j.length(); i++) {
Item item = new Item();// buat variabel category
//JSONObject Obj;
JSONObject Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
item.setId(Obj.getString(JF_ID));
//item.setTitle(Obj.getString(JF_TITLE));
item.setAddress(Obj.getString(JF_ADDRESS));
item.setTelephoneNumber(Obj.optString(JF_TELEPHONE, NO_DATA_FOUND));
item.setEmailAddress(Obj.optString(JF_EMAIL, NO_DATA_FOUND));
item.setWebUrl(Obj.optString(JF_WEB, NO_DATA_FOUND));
item.setFacebookUrl(Obj.optString(JF_FACEBOOK, NO_DATA_FOUND));
item.setLatitude(Obj.optDouble(JF_LATITUDE, NULL_LOCATION));
item.setLongitude(Obj.optDouble(JF_LONGITUDE, NULL_LOCATION));
try {
item.setRating(Float.parseFloat(Obj.optString(JF_RATING, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRating(0.0f);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATING_COUNT, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
try {
item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATINGSCORE, NO_DATA_FOUND)));
} catch (NumberFormatException e) {
item.setRatingCount(0);
}
item.setTagLine(Obj.optString(JF_TAG_LINE, NO_DATA_FOUND));
item.setDescription(Obj.optString(JF_DESCRIPTION, NO_DATA_FOUND));
item.setVerification(Obj.optString(JF_VERIFICATION, NO_DATA_FOUND).equals("1") ? true : false);
item.setCarId(Obj.optString(JF_CARID, NO_DATA_FOUND));
item.setTitle(Obj.optString(JF_CARTITLE, NO_DATA_FOUND));
item.setCarRentalId(Obj.optString(JF_CARRENTALID, NO_DATA_FOUND));
item.setCarPrice(Obj.optString(JF_CARPRICE, NO_DATA_FOUND));
item.setCarYear(Obj.optString(JF_CARYEAR, NO_DATA_FOUND));
JSONArray imgArr = Obj.getJSONArray("thumbImage");
String[] imageThumb = new String[imgArr.length()];
// String[] imageLarge = new String[imgArr.length()];
for (int k = 0; k < imgArr.length(); k++) {
imageThumb[k] = imgArr.getString(k);
// imageLarge[k] = imgArr.getJSONObject(k).getString(JF_TITLE);
}
for(int l = 0; l <imgArr.length(); l++) {
item.setImageLargeUrls(imageThumb);
}
item.setImageThumbUrls(imageThumb);
// item.setImageLargeUrls(imageLarge);
// JSONArray imgArr = Obj.getJSONArray("thumbImage");
/*String[] imgCount = new String[imgArr.length()];
for(int k = 0 ; k < imgCount.length; k++) {
imgCount[k] = imgArr.getString(k);
item.setImageThumbUrls(imgCount);
}*/
Location trgtLocation = new Location("trgtLocation");
trgtLocation.setLatitude(item.getLatitude());
trgtLocation.setLongitude(item.getLongitude());
Log.d("LatLong", "Latitude "+String.valueOf(trgtLocation.getLatitude())+"Longitude "+ String.valueOf(trgtLocation.getLongitude()));
Location crntLocation = gTrack.getLocation(getActivity());
Log.d("crntLocation", String.valueOf(gTrack.getLocation(getActivity())));
item.setDistance(crntLocation.distanceTo(trgtLocation) / 1000);
Log.d("distance", String.valueOf(item.getDistance()));
Log.d("URL1", "" + Obj.getString(JF_TITLE));
resultList.add(item);
}
// itemList;//kayaknya bukan Item atau item
Arrays.sort(itemList, new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
return lhs.getDistance().compareTo(rhs.getDistance());//mungkin valuenya null
}
});
itemList.notify();
for (int i = 0; i < j.length(); i++) {
Log.d("itemList", String.valueOf(itemList[i]));
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
resultListView.setAdapter(new ResultListAdapterRental(getActivity(), mCallbacks, resultList));
}
});
} 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();
} catch (NullPointerException e) {
// TODO: handle exception
}
return null;
}
}
Use this:
Collections.sort(resultList, new Comparator<Item>() {
#Override
public int compare(Item lhs, Item rhs) {
return lhs.getDistance().compareTo(rhs.getDistance());//mungkin valuenya null
}
});

Json to hashMap listview

I'm new to android development. Can you please help me to put my code to the hashmap-listview? Here I am loading bank images to the ListView. in my new JSON there is a key and value. ie (BankName , logo)
public void ListDrwaer() {
List<String> listImg = new ArrayList<String>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
listImg.add(test1);
Log.d("URL", test1);
}
ItemsAdapter adapter = new ItemsAdapter(getActivity(), listImg);
menu.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
}
You can use Pairs instead of HashMap
Try this
public void ListDrwaer() {
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
img_url = jsonChildNode.optString("logo");
String test1 = img_test_url + img_url;
String BankName = jsonChildNode.optString("id");
listData.add(new Pair<String,String>(BankName,test1 ));
}
ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
list.setAdapter(adapter);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Connection Error...",
Toast.LENGTH_LONG).show();
}
}

Remove Selected Spinner Item In Android

I have spinner in my Activity which is set the item from JSON data and when i select any item from spinner and set into the spinner, and i have done all this things properly.But when i want to remove selected item from spinner i got exception:
E/AndroidRuntime(1022): java.lang.UnsupportedOperationException"
and
E/AndroidRuntime(1022):atandroid.widget.ArrayAdapter.remove(ArrayAdapter.java:212)
at the code line of
E/AndroidRuntime(1022):at com.spinnerdemo.SpinDemo$1.onItemSelected(SpinDemo.java:102)
Here is my code:
public class SpinDemo extends Activity {
private static String strUrl = "http://192.168.1.61/jyoti/android_app/all_questions.php";
private static String TAG_ID = "id";
private static String TAG_CODE = "q_prefix";
private static String TAG_CODE_ARR = "Questions";
JSONArray jsonArray = null;
Spinner codeSpinner, spinner2;
EditText edTextSpinnerItem;
String[] items;
String strEdtext;
String strid , strcode ;
ArrayList<String> codeList;
public ArrayAdapter<String> adapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeList = new ArrayList<String>();
codeSpinner = (Spinner) findViewById(R.id.spinner2);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(strUrl);
try
{
jsonArray = json.getJSONArray(TAG_CODE_ARR);
// looping through All Contacts
final String[] items = new String[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
strid = c.getString(TAG_ID);
strcode = c.getString(TAG_CODE);
items[i] = c.getString(TAG_CODE);
System.out.println("Hello events " + items);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
codeSpinner.setAdapter(adapter);
}
}
catch (JSONException e) {
e.printStackTrace();
}
codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3)
{
// TODO Auto-generated method stub
String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
System.out.println("anyvariable = " + anyvariable);
edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
edTextSpinnerItem.setText(anyvariable);
System.out.println("edTextSpinnerItem " + edTextSpinnerItem);
String t = adapter.getItem(pos);
System.out.println("Get The Item Position From Adapter = " + t);
adapter.remove(t);
adapter.notifyDataSetChanged();
codeSpinner.setAdapter(adapter);
//mySpinner.setAdapter(m_adapterForSpinner);
//adapter.remove((String)codeSpinner.getSelectedItem());
//adapter.notifyDataSetChanged();
//System.out.println("Item is Removed From The Spinner Drop Dwon List");
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
}
I think that the problem is caused from the deleting an element that is actual selected
Try to use a list instead of an Array for the items:
http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context,%20int,%20int,%20java.util.List)
Then in the on item selected use
items.remove(t);
Instead of:
adapter.remove(t);
With this change you remove the item from the ArrayList(List) and not from the adapter.
The adapter notifyDataSetChanged capture the change on the List and refresh the spinner
Try this..
1) Give spinner setadapter after for loop
2) If you need to remove any item. You need to use ArrayList it is the easy way.
I Posted code after some changes.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
codeList = new ArrayList<String>();
codeSpinner = (Spinner) findViewById(R.id.spinner2);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(strUrl);
try
{
jsonArray = json.getJSONArray(TAG_CODE_ARR);
// looping through All Contacts
final String[] items = new String[jsonArray.length()];
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
strid = c.getString(TAG_ID);
strcode = c.getString(TAG_CODE);
items[i] = c.getString(TAG_CODE);
System.out.println("Hello events " + items);
codeList.add(strcode);
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,codeList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
codeSpinner.setAdapter(adapter);
}
catch (JSONException e) {
e.printStackTrace();
}
codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3)
{
// TODO Auto-generated method stub
String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
System.out.println("anyvariable = " + anyvariable);
edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
edTextSpinnerItem.setText(anyvariable);
System.out.println("edTextSpinnerItem " + edTextSpinnerItem);
String t = adapter.getItem(pos);
System.out.println("Get The Item Position From Adapter = " + t);
Object t2 = adapter.getItem(pos);
Log.v("t2", ""+t2);
codeList.remove(t2);
adapter.notifyDataSetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}

Android Java programming: need help creating an object variable

I'm trying to make an Android application that access RottenTomatoes.com and loads the API data of upcoming movies.
I can successfully obtain the API data, but when I try to parse the data I run into trouble.
Here's the block of code that isn't working:
public class MovieJSONParser {
static public class MovieParser{
static ArrayList<Movie> parseMovie(String jsonString) throws JSONException {
ArrayList<Movie> movies = new ArrayList<Movie>();
JSONObject moviesJSON = new JSONObject(jsonString);
JSONArray moviesArray = moviesJSON.getJSONArray("movies");
Log.d("app", "in MovieJSONParser");
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject o = moviesArray.getJSONObject(i);
Log.d("app", o.toString());
Log.d("app", "Created a JSON object to put in Movies");
// THIS LINE ISN'T WORKING
Movie movie = new Movie(o);
Log.d("app", "after Movie declaration");
movies.add(movie);
}
Log.d("app", "end of MovieJSONParser");
return movies;
}
}
}
I know the line of code that I labeled as not working isn't working because the log comments are all appearing correctly up until the statement:
Movie movie = new Movie(o);
This line of code is trivial... a simple class object declaration... I have no idea why it's making the program crash... There is no actual error. The program runs.
Here is my Movie.class:
public class Movie extends Activity {
String url_posterThumbnail, title, year, mpaa_rating;
int critics_score;
public Movie(JSONObject o) throws JSONException {
Log.d("app", "in Movie");
this.title = o.getString("title");
this.year = o.getString("year");
this.mpaa_rating = o.getString("mpaa_rating");
this.critics_score = o.getInt("critics_score");
this.url_posterThumbnail = o.getString("thumbnail");
}
public String returnUrl_posterThumbnail() {
return url_posterThumbnail;
}
public void setUrl_posterThumbnail(String url_posterThumbnail) {
this.url_posterThumbnail = url_posterThumbnail;
}
public String returnTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String returnYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String returnMpaa_rating() {
return mpaa_rating;
}
public void setMpaa_rating(String mpaa_rating) {
this.mpaa_rating = mpaa_rating;
}
public int returnCritics_score() {
return critics_score;
}
public void setCritics_score(int critics_score) {
this.critics_score = critics_score;
}
#Override
public String toString() {
return "Movie [url_posterThumbnail=" + url_posterThumbnail + ", title="
+ title + ", year=" + year + ", mpaa_rating=" + mpaa_rating
+ ", critics_score=" + critics_score + "]";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.movies, menu);
return true;
}
}
Here's my MainActivity.class in case you need it:
public class MainActivity extends Activity {
String APIKEY = "vs6hcrs57h4wy74u3zgxhmrm";
String url_MY_FAVORITE_MOVIES = "";
String url_BOX_OFFICE_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=3&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
String url_IN_THEATRES_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json?page_limit=3&page=1&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
String url_OPENING_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/opening.json?limit=3&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
String url_UPCOMING_MOVIES = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/upcoming.json?page_limit=3&page=1&country=us&apikey=p53b5bybwxpg7nfykwzezkzr";
ListView listview;
ArrayList<Movie> movies = new ArrayList<Movie>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("app", "Hi! In onCreate");
listview = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1);
listview.setAdapter(arrayAdapter);
arrayAdapter.add("My Favorite Movies");
arrayAdapter.add("Box Office Movies");
arrayAdapter.add("In Theatres Movies");
arrayAdapter.add("Opening Movies");
arrayAdapter.add("Upcoming Movies");
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int listViewPosition,
long arg3) {
Intent i = new Intent(getBaseContext(), MoviesDetails.class);
switch (listViewPosition) {
case 0:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_MY_FAVORITE_MOVIES).get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 1:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_BOX_OFFICE_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 2:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_IN_THEATRES_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 3:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_OPENING_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
case 4:
try {
movies = new GetMoviesASYNCTASK(MainActivity.this).execute(url_UPCOMING_MOVIES).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("app", "right before starting MoviesDetails activity");
i.putExtra("movies", movies);
startActivity(i);
break;
default:
break;
}
Log.d("app", "end of file?");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Lastly, here's my GetMoviesASYNCTASK.class if you need it:
public class GetMoviesASYNCTASK extends AsyncTask<String, Void, ArrayList<Movie>> {
String url_string;
ProgressDialog pd;
MainActivity main;
public GetMoviesASYNCTASK(MainActivity main){
this.main = main;
}
#Override
protected ArrayList<Movie> doInBackground(String... params) {
url_string = params[0];
// pd = new ProgressDialog(main);
// pd.setCancelable(false);
// pd.setMessage("Loading Movies...!");
// pd.show();
Log.d("app", "begin asynctask");
try {
URL url = new URL(url_string);//Parse the string as an url
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//create a http connection using that url
con.setRequestMethod("GET");//Use the get method
con.connect(); //Connect to http
int statusCode = con.getResponseCode();//Get the server's response
if (statusCode == HttpURLConnection.HTTP_OK) { //If server returns 200
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line);
line = reader.readLine();
}
Log.d("app", "String value of API stored");
ArrayList<Movie> movies = MovieJSONParser.MovieParser.parseMovie(sb.toString());
Log.d("app", "movies in ASYNCTASK initialized :)");
return movies;
}
} 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();
}
Log.d("app", "asynctask didn't work");
return null;
}
// Override
protected void onPostExecute(ArrayList<Movie> result) {
//ArrayList<String> movieTitles = new ArrayList<String>();
super.onPostExecute(result);
Log.d("app", "exiting asynctask");
//pd.dismiss();
}
}
Am I missing something obvious?
Any help will be greatly appreciated!
critics_score is in ratings object but here you are trying to access that key directly. so it is throwing exception.
Better use optString() with some default value instead of getString(), as even if the key doesn't exist, will not end with exceptions..
Here is the working code :
JSONObject object = new JSONObject(result);
JSONArray records = object.getJSONArray("movies");
Log.d(LOG_TAG, "records" + records);
int len = records.length();
String albumart[] = new String[len];
for (int i = 0; i < len; i++) {
JSONObject record = (JSONObject) records.getJSONObject(i);
String extid = record.getString("id");
String accountName = record.optString("title", "No title");
JSONObject posters = record.getJSONObject("posters");
String albuart = posters.optString("detailed", null);
String critics = record.optString("critics_consensus", "No Critics");
String year = record.getString("year");
String rating = record.optString("mpaa_rating", "No rating");
JSONObject ratings = record.getJSONObject("ratings");
String rating = ratings.optString("critics_score", "");
if(rating.length() <= 0 ) {
rating = "0";
}
String audience_rating = ratings.optString("audience_rating", "");
if(audience_rating.length() <= 0 ) {
audience_rating = "0";
}
String duration = record.optString("runtime", "");
if(duration.length() <= 0 ) {
duration = "0"
}
}

Categories