In my application I'm working with two spinners first spinner contains data like Department and id and second spinner contains deficiency and id, here I am working with some URL as below.
http://182.18.163.39/m/def.php?issue=1
This URL gives me first spinner values. On selecting a value from the first spinner the data related to that value will come in second spinner.
Here is my second URL which gives second spinner values.
"http://182.18.163.39/m/def.php?issue=2&dept="+dept_id
In this URL I want to pass the id from the first URL, here is my problem I am able to get all values from first spinner. When I select one value from first spinner it doesn't give me related values in the second spinner.
Anyone give me an example code for solving this.
Here is the code:
//Department spinner
Spinner spinner;
String URL="http://182.18.163.39/train/m/def.php?issue=1";
ArrayList<String> Department;
String uid;
//Deficiency category spinner
Spinner spinner2;
String URL2 = "http://182.18.163.39/train/m/def.php?issue=2&dept="+dept_id;
ArrayList<String>Deficiency;
String defid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_deficiency);
//spinner for department
Department = new ArrayList<>();
spinner=(Spinner)findViewById(R.id.select_department);
loadSpinnerData(URL);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String department = spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),department,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
//spinner for deficiency
Deficiency = new ArrayList<>();
spinner2 = (Spinner)findViewById(R.id.deficiency_category);
loadSpinnerDeficiency(URL2);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String deficiency = spinner2.getItemAtPosition(spinner2.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),deficiency,Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
// DO Nothing here
}
});
}
private void loadSpinnerData(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String department = jsonobject.getString("Department");
dept_id = jsonobject.getString("ID");
Department.add(department);
}
spinner.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Department));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadSpinnerDeficiency(String url2) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/def.php?issue=2&dept="+dept_id);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String defcat = jsonobject.getString("Deficiency");
defid = jsonobject.getString("ID");
Deficiency.add(defcat);
}
spinner2.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Deficiency));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
here is my json response of first URL:
[{
"Department": "Select Department",
"ID": ""
}, {
"Department": "Engg North",
"ID": "1"
}, {
"Department": "DIESEL SHED",
"ID": "2"
}, {
"Department": "S & T",
"ID": "3"
}, {
"Department": "SAFETY",
"ID": "4"
}, {
"Department": "Srdenwest",
"ID": "5"
}, {
"Department": "enggwest",
"ID": "6"
}, {
"Department": "Engg central",
"ID": "7"
}, {
"Department": "electmaint",
"ID": "8"
}, {
"Department": "Operating",
"ID": "9"
}, {
"Department": "Security",
"ID": "10"
}, {
"Department": "Diesel Shed",
"ID": "11"
}, {
"Department": "Electric Loco shed",
"ID": "12"
}, {
"Department": "C & W",
"ID": "13"
}, {
"Department": "trso",
"ID": "14"
}, {
"Department": "trdohe",
"ID": "15"
}, {
"Department": "engg",
"ID": "16"
}, {
"Department": "commercial",
"ID": "17"
}, {
"Department": "engg South",
"ID": "18"
}, {
"Department": "Mechanical",
"ID": "19"
}]
And here is my json response of second URL:
[{
"Deficiency": "Select Deficiency",
"ID": ""
}, {
"Deficiency": "Engg",
"ID": "1"
}, {
"Deficiency": "Track",
"ID": "25"
}, {
"Deficiency": "LCs",
"ID": "26"
}, {
"Deficiency": "Misc",
"ID": "43"
}, {
"Deficiency": "",
"ID": "NULL"
}]
you shuold create a custom object like
private HashMap<String,String>departmentMap=new HashMap<>();
private void loadSpinnerData(String url) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String department = jsonobject.getString("Department");
uid = jsonobject.getString("ID");
Department.add(department);
departmentMap.put(department,uid);
}
spinner.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Department));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and modify your firstSpinner onclick like
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l){
String department=spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
Toast.makeText(getApplicationContext(),department,Toast.LENGTH_LONG).show();
String id=departmentMap.get(department);
loadSpinnerDeficiency(URL2,id);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView){
// DO Nothing here
}
});
now you can use id in loadSpinnerDeficiency method to get proper response
private void loadSpinnerDeficiency(String url2,String uid) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://182.18.163.39/train/m/def.php?issue=2&dept="+uid);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(responseString);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String defcat = jsonobject.getString("Deficiency");
defid = jsonobject.getString("ID");
Deficiency.add(defcat);
}
spinner2.setAdapter(new ArrayAdapter<String>(NewDeficiency.this, android.R.layout.simple_spinner_dropdown_item, Deficiency));
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I have two fragments, one shows a program list and one shows a course list. How do I get the selected program from the mainactivity to only show the corresponding course description? They match by ID. Currently, when I click on a program, the whole course list shows up instead of the corresponding course.
MainActivity Fragment (shows all data in JSON file):
ProgramAdapter programAdapter;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ProgramDetail item = (ProgramDetail) getListAdapter().getItem(position);
Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
intent.putExtra(ProgramDetailActivity.EXTRA_ID, item.getId());
startActivity(intent);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
programAdapter = new ProgramAdapter(getActivity());
setListAdapter(programAdapter);
setListShown(false);
new HttpAsyncTask().execute("https://gist.githubusercontent.com/kdotzenrod517/39bc7372759c762e33188fb1a6cbce5d/raw/a2baa28d19fd597be999c8fddb6b48c888cd33f4/gistfile1.txt");
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.e("HttpAsyncTask", "doInBackground");
String result = "";
HttpURLConnection urlConnection = null;
try{
URL url = new URL(params[0]);
Log.e("HttpAsyncTask", params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.e("HttpAsyncTask", "getInputStream");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String s = "";
while ((s = reader.readLine()) != null){
result += s;
Log.e("HttpAsyncTask", result);
}
} catch (Exception e){
Log.e("HttpAsyncTask", "EXCEPTION: " + e.getMessage());
} finally {
if (urlConnection != null){
urlConnection.disconnect();
}
}
return result;
}
#Override
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> items = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(new ProgramDetail(jsonObject.getString("name"),null,jsonObject.getLong("id")));
}
programAdapter.addAll(items);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
}
}
}
CourseList Fragment (should only show matching JSON data by ID)
`
protected void onPostExecute(String s) {
Log.e("HttpAsyncTask", "entering onPostExecute");
try {
JSONArray jsonArray = new JSONArray(s);
final int length = jsonArray.length();
Log.i("HttpAsyncTask", "Number" + length);
List<ProgramDetail> item = new ArrayList<>();
for (int i=0; i < length; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
item.add(new ProgramDetail(jsonObject.getString("name"), null, jsonObject.getLong("id")));
}
programAdapter.addAll(item);
programAdapter.notifyDataSetChanged();
setListShown(true);
} catch (JSONException e) {
}
Program List
[
{
"id": "0",
"name": "Intro to Android"
},
{
"id": "1",
"name": "Advanced Android"
},
{
"id": "2",
"name": "Intro to Java"
},
{
"id": "3",
"name": "Advanced Java"
},
{
"id": "4",
"name": "Intro to Data Science"
}
]
Course List JSON
{
"id": "0",
"name": "Welcome to Android!"
},
{
"id": "1",
"name": "Enterprise level Android Dev"
},
{
"id": "2",
"name": "Welcome to Java!"
},
{
"id": "3",
"name": "Enterprise Level Java"
},
{
"id": "4",
"name": "Welcome to Data Science!"
}
I am new in android dev i am fetch data from URL and want to set name in spinner and send their id to server
MY JSON
{
"data": [{
"name": "RELIANCE CDMA",
"ID": "1"
}, {
"name": "IDEA",
"ID": "5"
}, {
"name": "AIRTEL",
"ID": "7"
}, {
"name": "MTNL DELHI",
"ID": "8"
}, {
"name": "MTNL MUMBAI",
"ID": "8"
}, {
"name": "VODAFONE",
"ID": "12"
}, {
"name": "LOOP",
"ID": "13"
}, {
"name": "BSNL",
"ID": "14"
}, {
"name": "AIRCEL",
"ID": "19"
}, {
"name": "TATA INDICOM",
"ID": "23"
}, {
"name": "VIRGIN CDMA",
"ID": "27"
}, {
"name": "RELIANCE GSM",
"ID": "32"
}, {
"name": "TATA DOCOMO",
"ID": "35"
}, {
"name": "VIRGIN GSM",
"ID": "36"
}, {
"name": "MTS",
"ID": "38"
}, {
"name": "UNINOR",
"ID": "41"
}, {
"name": "VIDEOCON",
"ID": "43"
}, {
"name": "T24",
"ID": "52"
}]
}
and i am using this code
in android
CODE
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL("http://www.myurl.com/index.php"); // example only
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data worldpop = new Json_Data();
worldpop.setName(jsonobject.optString("name"));
worldpop.setId(jsonobject.optString("ID"));
json_data.add(worldpop);
datalist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner mySpinner = (Spinner)getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = datalist.get(position);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
but this code only show name in spinner but not select any id form my json
It should be:
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<Pair<String, String>>();
jsonobject = JSONfunctions
.getJSONfromURL("http://www.myurl.com/index.php"); // example only
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data worldpop = new Json_Data();
worldpop.setName(jsonobject.optString("name"));
worldpop.setId(jsonobject.optString("ID"));
json_data.add(worldpop);
datalist.add(new Pair<String, String>(jsonobject.optString("ID"), jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = datalist.get(position).first;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
But it seems to me that you don't understand what's going on in that code, so highly suggest to sort out in that.
And one more advice - don'y use AsyncTask, and take a look on Retrofit.
I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}
My app is crashing when trying to parse Instagram JSON. What am I doing wrong here?
public class InstagramActivity extends BaseActivity {
static String url;
static ArrayList<String> thumbnailURLS;
static ArrayList<String> standardURLS;
static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
context = getApplicationContext();
getActionBar().setTitle("Instagram");
url = "https://api.instagram.com/v1/users/1373666362/media/recent/?client_id=a2b04732b52d43c99fe453a8ca2a5512&count=50";
thumbnailURLS = new ArrayList<String>();
standardURLS = new ArrayList<String>();
new ParseJSON().execute();
}
public static class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser()
{
}
public JSONObject getJSONFromUrl(String jsonUrl)
{
// Making HTTP request
try
{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(jsonUrl);
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 to parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
public static class ParseJSON extends AsyncTask<Void,Void,ArrayList> {
#Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected ArrayList doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// get json from url here
JSONObject json = jParser.getJSONFromUrl(url);
try {
JSONArray dataArray = json.getJSONArray("data");
int thumbnailsCount = dataArray.length();
for (int i = 0; i < thumbnailsCount; i++) {
JSONObject imagesObject = dataArray.getJSONObject(i).getJSONObject("images");
String thumbURL = imagesObject.getJSONObject("thumbnail").getString("url");
thumbnailURLS.add(thumbURL);
}
}
catch (Exception e) {
e.getMessage().toString();
}
return thumbnailURLS;
}
#Override
protected void onPostExecute(ArrayList result) {
super.onPostExecute(result);
for (String thumb : thumbnailURLS) {
System.out.println(thumb);
}
}
}
}
It catches a JSONException
E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
and
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
This is NULL. JSONObject json = jParser.getJSONFromUrl(url);
Here is some of the expected JSON.
{
"pagination": {
"next_url": "https://api.instagram.com/v1/users/1373666362/media/recent?access_token=25320296.1fb234f.b797e861c2494059b6584ac9749208fe&count=2&max_id=791341826737262101_1373666362",
"next_max_id": "791341826737262101_1373666362"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"kystatefair"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Amaro",
"created_time": "1408648864",
"link": "http://instagram.com/p/r-MuYWFU96/",
"likes": {
"count": 5,
"data": [
{
"username": "tayworthington_",
"profile_picture": "http://photos-g.ak.instagram.com/hphotos-ak-xaf1/10632550_835588266460870_765781001_a.jpg",
"id": "24471760",
"full_name": "τᎯϓιΘર"
},
{
"username": "renee_laurent",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_407687505_75sq_1397913189.jpg",
"id": "407687505",
"full_name": "Renee Laurent"
},
{
"username": "kystatefair",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_381460857_75sq_1396983015.jpg",
"id": "381460857",
"full_name": "kystatefair"
},
{
"username": "jennaharrod1",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xfa1/10665605_1495839117327497_809128971_a.jpg",
"id": "18591399",
"full_name": "Jenna Harrod"
}
]
},
"images": {
"low_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_a.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_s.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598650_352432021574566_306460147_n.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1408648864",
"text": "Congratulations to The Lindsey Family for winning the Gospel Quartet competition! #kystatefair",
"from": {
"username": "kyfarmbureau",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"id": "1373666362",
"full_name": "Kentucky Farm Bureau"
},
"id": "792126548887293629"
},
"user_has_liked": false,
"id": "792126548258148218_1373666362",
"user": {
"username": "kyfarmbureau",
"website": "",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"full_name": "Kentucky Farm Bureau",
"bio": "",
"id": "1373666362"
}
},
{
"attribution": null,
"tags": [
"kfbmtc"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1408555318",
"link": "http://instagram.com/p/r7aTLelU4V/",
"likes": {
"count": 4,
"data": [
{
"username": "corkey_cole",
"profile_picture": "http://photos-e.ak.instagram.com/hphotos-ak-xaf1/10598220_490230854445140_2139881142_a.jpg",
"id": "324166968",
"full_name": "corkey_cole"
},
{
"username": "renee_laurent",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_407687505_75sq_1397913189.jpg",
"id": "407687505",
"full_name": "Renee Laurent"
},
{
"username": "silveradomafia04",
"profile_picture": "http://photos-e.ak.instagram.com/hphotos-ak-xfa1/914483_1500860143488988_1771984176_a.jpg",
"id": "1006562558",
"full_name": "Gideon Bailey"
},
{
"username": "sharelouisville",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_1302605134_75sq_1399019203.jpg",
"id": "1302605134",
"full_name": "Share Louisville"
}
]
},
"images": {
"low_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_a.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_s.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://scontent-a.cdninstagram.com/hphotos-xaf1/t51.2885-15/10598436_1456586981280578_133918080_n.jpg",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1408555318",
"text": "Media is starting to crowd around for #kfbmtc",
"from": {
"username": "kyfarmbureau",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"id": "1373666362",
"full_name": "Kentucky Farm Bureau"
},
"id": "791341827391573199"
},
"user_has_liked": false,
"id": "791341826737262101_1373666362",
"user": {
"username": "kyfarmbureau",
"website": "",
"profile_picture": "http://photos-b.ak.instagram.com/hphotos-ak-xpf1/10349740_650479825030913_1755233568_a.jpg",
"full_name": "Kentucky Farm Bureau",
"bio": "",
"id": "1373666362"
}
}
]
}
UPDATE: The problem appears to be with the Instagram api url I'm using isn't giving me the JSON. I think it may be because I'm using my client_id instead of getting an access token. Does anyone know if that is the case? I used a JSON URL from something else that I know doesn't require an access token and it returned the JSON just fine.
I have updated your method getJSONFromUrl, which can be seen below:
The problem is that, the server is returning 405 means method not allowed. You was using POST to access the data, which this server does not allow. You have to use GET here for a successful request.
Rest of your code is working fine.
You can update the code below to add a default case where you can return a valid constant json string with a message that can avoid app crash, as well you can add other cases like 404 and 405 and return a valid json with an appropriate message that is suitable to the user to understand.
public JSONObject getJSONFromUrl(String jsonUrl)
{
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(jsonUrl);
String responseBody = "DEFAULT_MSG_TEXT";
int resCode = 0;
try{
HttpResponse response = client.execute(get);
int responseCode = response.getStatusLine().getStatusCode();
resCode = responseCode;
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
break;
}
}
catch(Exception ex){
Log.e("Post Error",resCode + "\n Exception" + ex);
responseBody = "DEFAULT_MSG_TEXT";
}
json = responseBody;
// try to parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Try this and let me know !!!
Im trying to create an app that shows images from an tumblr account, using JSON. Im doing this by altering some code i had for an twitter app that did almost the same thing.
Unfortunately i find the tumblr api mush harder to use, and all the examples i can find are made for php and does therefore not help.
nullPointerException at this line:
for (int i = 0; i < arr.length(); i++) {
The JSON is validated with jsonlint.com and looks like this:
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "Facts and Chicks",
"posts": 789,
"name": "factsandchicks",
"url": "http://factsandchicks.com/",
"updated": 1347565227,
"description": "Random facts and hot chicks, the best way to learn.\nWebsite and Concept by: GustoNYC",
"ask": false
},
"posts": [
{
"blog_name": "factsandchicks",
"id": 31474135003,
"post_url": "http://factsandchicks.com/post/31474135003/ups-was-founded-by-two-teenagers-with-one-bicycle",
"slug": "ups-was-founded-by-two-teenagers-with-one-bicycle",
"type": "photo",
"date": "2012-09-13 19:37:59 GMT",
"timestamp": 1347565079,
"state": "published",
"format": "html",
"reblog_key": "iWEenkAh",
"tags": [
"facts",
"factsandchicks",
"chicks",
"UPS",
"teenagers",
"friends",
"business",
"America",
"WTF",
"money",
"inspiration",
"history"
],
"highlighted": [],
"note_count": 241,
"source_url": "http://factsandchicks.com",
"source_title": "factsandchicks.com",
"caption": "<p>UPS was founded by two teenagers with one bicycle and $100 Borrowed from a Friend.</p>\n<p>source</p>",
"link_url": "http://factsandchicks.com",
"photos": [
{
"caption": "",
"alt_sizes": [
{
"width": 640,
"height": 960,
"url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_1280.jpg"
},
{
"width": 500,
"height": 750,
"url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_500.jpg"
},
{
"width": 400,
"height": 600,
"url": "http://24.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_400.jpg"
},
{
"width": 250,
"height": 375,
"url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_250.jpg"
},
{
"width": 100,
"height": 150,
"url": "http://24.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_100.jpg"
},
{
"width": 75,
"height": 75,
"url": "http://24.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_75sq.jpg"
}
],
"original_size": {
"width": 640,
"height": 960,
"url": "http://25.media.tumblr.com/tumblr_m8fz0bLjJU1r3tp7bo1_1280.jpg"
}
}
]
},
and my code looks like this:
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Tweet> tweets;
try {
tweets = getTweets();
ListView listView = (ListView) findViewById(R.id.ListViewId);
listView.setAdapter(new UserItemAdapter(this, R.layout.listitem,
tweets));
} catch (ClientProtocolException 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();
}
}
public class UserItemAdapter extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public UserItemAdapter(Context context, int imageViewResourceId,
ArrayList<Tweet> tweets) {
super(context, imageViewResourceId, tweets);
this.tweets = tweets;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listitem, null);
}
Tweet tweet = tweets.get(position);
if (tweet != null) {
ImageView image = (ImageView) v.findViewById(R.id.avatar);
if (image != null) {
image.setImageBitmap(getBitmap(tweet.image_url));
}
}
return v;
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
} catch (Exception ex) {
return null;
}
}
public ArrayList<Tweet> getTweets() throws ClientProtocolException,
IOException, JSONException {
String searchUrl = "http://api.tumblr.com/v2/blog/factsandchicks.com/posts?api_key=API_KEY";
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(searchUrl);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try {
responseBody = client.execute(get, responseHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray posts = JSONObject.getJSONObject("response").getJSONArray(
"posts");
for (int i = 0; i < posts.length(); i++) {
JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
for (int j = 0; j < photos.length(); j++) {
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes").getJSONObject(0)
.getString("url");
Tweet tweet = new Tweet(url);
tweets.add(tweet);
}
return tweets;
}
public class Tweet {
public String image_url;
public Tweet(String url) {
this.image_url = url;
}
}
}
I don't know why this isn't working, because i can make it work for twitter.
Any help is appriciated!
You read "response" from the JSON as Array, but it's not an array, just a object. Seems like that's one problem. You're not reading out the objects like how they're in the JSON, pay more attention!
Try doing something like this:
JSONArray posts = jsonObject.getJSONObject("response").getJSONArray("posts");
for(int i = 0; i < posts.length(); i++){
JSONArray photos = posts.getJSONObject(i).getJSONArray("photos");
for(int j = 0; j < photos.length(); j++){
JSONObject photo = photos.getJSONObject(j);
String url = photo.getJSONArray("alt_sizes").getJSONObject(0).getString("url");
Tweet tweet = new Tweet(url);
tweets.add(tweet);
}
}
I can't test this at the moment, hope I didn't do any mistakes.