This code will get only first value from json string - java

please help me out from this i need to display the json array data but it will only show the first value from json .i tried to change the values but one value is shown not an array
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnadd=(Button)findViewById(R.id.btnhit);
tvdata = (TextView)findViewById(R.id.tvJsonitem);
btnadd.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("https://api.myjson.com/bins/106o37");
}
}
);
}
public class JSONTask extends AsyncTask{
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
StringBuffer finalBufferedData=new StringBuffer();
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String description = obj.getString("description");
finalBufferedData.append(description + "\t\n"
);
return finalBufferedData.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

Your return statement should be outside of your for loop. Now it is inside so the method returns the first value.

use this
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
StringBuffer finalBufferedData=new StringBuffer();
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String description = obj.getString("description");
finalBufferedData.append(description + "\t\n"
);
}
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

Related

JSONException: No value for courseDivide

Just tried to run and I receive this error:
JSONException: No value for courseDivide
StatisticsFragment$ByEntire.onPostExecute(StatisticsFragment.java:225)
StatisticsFragment$ByEntire.onPostExecute(StatisticsFragment.java:153)
I'm a beginner with Java and I can't seem to figure out why JSONException has No value.
The code:
class ByEntire extends AsyncTask<Void, Void, String> {
String target;
ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute(){
try{
target = "http://wook1150.cafe24.com/ByEntire.php";
dialog.setMessage("로딩중");
dialog.show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(target);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp;
StringBuilder stringBuilder = new StringBuilder();
while ((temp = bufferedReader.readLine()) !=null)
{
stringBuilder.append(temp + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
public void onProgressUpdate(Void... values){
super.onProgressUpdate();
}
#Override
public void onPostExecute(String result){
try{
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("response");
int count = 0;
int courseID;
String courseGrade;
String courseTitle;
String courseProfessor;
int courseCredit;
int courseDivide; //////Error here//////
int coursePersonnel;
String courseTime;
while(count < jsonArray.length()){
JSONObject object = jsonArray.getJSONObject(count);
courseID = object.getInt("courseID");
courseGrade = object.getString("courseGrade");
courseTitle = object.getString("courseTitle");
courseProfessor = object.getString("courseProfessor");
courseCredit = object.getInt("courseCredit");
courseDivide = object.getInt("courseDivide)");
coursePersonnel = object.getInt("coursePersonnel)");
courseTime = object.getString("courseTime)");
rankList.add(new Course(courseID, courseGrade, courseTitle, courseCredit, courseDivide, coursePersonnel,courseTime, courseProfessor));
count++;
dialog.dismiss();
}
rankListAdapter.notifyDataSetChanged();
}catch (Exception e){
e.printStackTrace();
}
}
}
Might be your JSON doesnt have courseDivide or mistyping, remove the ')'
courseDivide = object.getInt("courseDivide");
coursePersonnel = object.getInt("coursePersonnel");
courseTime = object.getString("courseTime");

Making Attendance App in Android

I have to make attendance app for college.The app will take data from colleges website and display it on app according to user login and password.
When we login into college's website we have to put id and password, same thing I want on my app so that user can see it on an app itself.
I have searched httpurlconnection, httpget, httppost, jsoup.
Up till now, I have understood that I have to make httprequest for loading the college's attendance site and then httppost to post username and password and after that jsoup to grab the data from HTML page.
But I have seen tutorials only to request JSON pages, but how to request for HTML pages?and post login to it?
Here is what I tried and collected data from JSON
private TextView textresponse1;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Get= (Button) findViewById(R.id.httprequest);
textresponse1= (TextView)findViewById(R.id.textresponse);
progressDialog=new ProgressDialog(this);
Get.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
progressDialog.setMessage("Collecting Data");
progressDialog.show();
}
public class JSONTask extends AsyncTask<String,String,String >{
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url=new URL(params[0]);
connection=(HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
String line="";
StringBuffer buffer=new StringBuffer();
while ((line = reader.readLine())!=null) {
buffer.append(line);
}
String finaljosn=buffer.toString();
StringBuffer add =new StringBuffer();
JSONObject parentobject=new JSONObject(finaljosn);
JSONArray parentarray=parentobject.getJSONArray("movies");
for(int i=0;i<parentarray.length();i++) {
JSONObject moviename = parentarray.getJSONObject(i);
String finalmovie = moviename.getString("movie");
int finalyear = moviename.getInt("year");
add.append(finalmovie +"- "+finalyear + "\n");
}
return add.toString();
// return finalmovie +" -Rushabh- " +finalyear;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection!=null) {
connection.disconnect();
}
try {
if (reader!=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
textresponse1.setText(result);
}
}
String mLoadURL="http://www.google.com";
public class LoadHtml extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(mLoadURL);
StringBuilder stringBuilder = new StringBuilder();
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (!s.trim().isEmpty()) {
//load html to webview
}
}
}
Call Above AsyncTask using:
LoadHtml loadHtml= new LoadHtml();
load.execute();

Trying to troubleshoot a JSON with an array within an array

I'm trying to troubleshoot my code, which has a array within an array, and then I want to retrieve all of the ID values inside it
private TextView tvData;
private ImageView imgtest;
String ChampionName;
String ChampionNameInLowerCase;
String item2;
String item3;
String Booked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
imgtest = (ImageView) findViewById(R.id.imageView);
// http://api.champion.gg/champion/Ekko/
new JSONTask().execute("http://api.champion.gg/champion/Ekko/");
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray jsonarray = new JSONArray(finalJson);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject finalObject = jsonarray.getJSONObject(i);
ChampionName = finalObject.getString("key");
String role = finalObject.getString("role");
String items = finalObject.getString("items");
JSONObject ItemArray = new JSONObject(items);
item2 = ItemArray.getString("mostGames");
JSONObject ItemArray2 = new JSONObject(item2);
item3 = ItemArray2.getString("items");
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tvData.setText(result);
ChampionNameInLowerCase = ChampionName.toLowerCase().replaceAll("'", "");;
int id = getResources().getIdentifier("com.example.kripzy.url:drawable/" + ChampionNameInLowerCase+"_square_0", null ,null);
imgtest.setImageResource(id);
}
}
}
And then more closely the code up for question is this section;
JSONArray jsonarray2 = new JSONArray(item3);
for (int j=0;j<jsonarray2.length();j++) {
JSONObject finalObject2 = jsonarray.getJSONObject(j);
Booked = finalObject2.getString("id");
}
return ChampionName + role + item3 + Booked;
}
When the code directly above is added, it gives an error
org.json.JSONException: No value for id
When I delete that small snippet of code, the code produces
The problem is here Booked = finalObject2.getString("id"); use Booked = finalObject2.getInt("id");
and by the way you can use
JSONObject finalObject2 = jsonarray.getJSONObject(jsonarray2.length()-1); instead the the for (int j=0;j<jsonarray2.length();j++)
In the for-loop where you iterate over jsonarray2 you access jsonarray instead of jsonarray2 to get your JSONObject.

Android JSON data retrieval

I am new to android and I am unable to retrieve data from this JSON code below. Please reply with suggestions.
Json Code:-
{"category":{"name":["Spa","Salon","Makeup"],"brand_title":["Aura Thai Spa- Greater Kailash 1",.....]}}
Android code:
public class Salon extends AppCompatActivity {
String url="my_url";
String catname,brandname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_salon);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
sname=(TextView)findViewById(R.id.person_name);
bname=(TextView)findViewById(R.id.person_age);
new MyAsyncTask().execute(url);
}
class MyAsyncTask extends AsyncTask<String, String, JSONObject> {
URLConnection urlConnection;
String result = "";
JSONObject jsonRootObject;
#Override
protected JSONObject doInBackground(String... params) {
try {
URL url_data = new URL(url);
urlConnection = url_data.openConnection();
urlConnection.connect();
// Convert response to string using String Builder
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
//Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
try{
jsonRootObject = new JSONObject(result);
}catch(JSONException e){
e.printStackTrace();
}
return jsonRootObject;
}
protected void onPostExecute(JSONObject result){
try {
//Iterate the jsonArray and print the info of JSONObjects
JSONArray jsonArray = jsonRootObject.getJSONArray("name");
for(int i=0; i < jsonArray.length(); i++) {
JSONObject name_0 = jsonArray.getJSONObject(i);
catname = name_0.getString("").toString();
}
/* JSONArray jsonArray2 = jsonRootObject.getJSONArray("brand_name");
JSONObject brand = jsonArray2.getJSONObject(0);
brandname = brand.getString("brand_title[0]");*/
//loat salary = Float.parseFloat(jsonObject.optString("salary").toString());
sname.setText(catname);
//bname.setText(brandname);
} catch (JSONException e) {e.printStackTrace();}
}
}
}
try replacing:
JSONArray jsonArray = jsonRootObject.getJSONArray("name");
with:
JSONArray jsonArray = jsonRootObject.getJSONObject("category").getJSONArray("name");
When you do:
jsonRootObject = new JSONObject(result);
You are getting the whole JSONobject string as itself, so you need to get just the category object:
jsonRootObject = jsonRootObject.getJSONObject("category")
and then you can get the array from the category:
JSONArray jsonArray = jsonRootObject.getJSONArray("name");
Try parsing like this. This will give you your required name and brand_title
// Declare outside onCreate
JSONObject topObject;
JSONObject category;
JSONArray name;
String json;
JSONArray brand_title;
// the parsing
json = "{\"category\":{\"name\":[\"Spa\",\"Salon\",\"Makeup\"],\"brand_title\":[\"Aura Thai Spa- Greater Kailash 1\"]}}";
try {
topObject = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
try {
category = topObject.getJSONObject("category");
} catch (JSONException e) {
e.printStackTrace();
}
try {
name = category.getJSONArray("name");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i<name.length(); i++){
try {
String parsedNanes = name.getString(i);
Log.i("parsedNames", parsedNanes);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
brand_title = category.getJSONArray("brand_title");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i<brand_title.length(); i++){
try {
String parsedBrandTitles = brand_title.getString(i);
Log.i("parsedBrandTitles", parsedBrandTitles);
} catch (JSONException e) {
e.printStackTrace();
}
}

Cannot convert to JSON Array

I tried to convert JSON from PHP server side to string in Android.
It force closes with (java.lang.String cannot be converted to JSONObject ) Error.
This is my Web class for HTTP connecting:
public class Web {
public static String readUrl(String url) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String result = convertInputstreamToString(inputStream);
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static String convertInputstreamToString(InputStream inputStream){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line ="";
while ((line = reader.readLine())!=null) {
builder.append(line);
}
return String.valueOf(builder);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
String result = Web.readUrl("http://192.168.1.53/mana/mana%20records.php");
if (result != null) {
try {
JSONArray records = new JSONArray(result);
for (int i = 0; i < records.length(); i++) {
JSONObject record = records.getJSONObject(i);
Log.d("Records", record.getString("date"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
And this is my JSON:
[{"date":"2015-12-01","Shift Day":"on","Shift Night":"",
"Shift Person":"a","Code":"1","1st":"1000","Size 8":null,
"2nd":"1","3rd":"10","logo":"1000","Storage":"10000"},
{"date":"2015-12-02","Shift Day":"",
"Shift Night":"on","Shift Person":"b","Code":"2","1st":"2000",
"Size 8":null,"2nd":"2","3rd":"20","logo":"2000",
"Storage":"20000"}]

Categories

Resources