Related
i've received Quiz JSON string from server this string contain 10 Question, i received and stored response in ArrayList. now i want that one Question (and its 4 options)should display on screen then there is next button when i press then next question should be display on screen similarly until control reached all 10 question. my problem is that i cannot do functionality of on press next button show the second one(next) Question. please any one help me i am beginner in android thanks.
Here Is JSON String.
{
"status": 200,
"status_message": "Success",
"response":
[
{
"quizNumber" : "1",
"image" : "",
"question" : "Which car manufacturer was the first to win 100 F1 races?",
"option1" : "Ferrari",
"option2" : "Nissan",
"option3" : "Ford",
"option4" : "",
"answer" : "Ferrari."
},
{
"quizNumber" : "2",
"image" : "",
"question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
"option1" : "Venus",
"option2" : "Hingis",
"option3" : "Martina Navratilova",
"option4" : "Waynetta",
"answer" : "Martina Navratilova"
},
{
"quizNumber" : "3",
"image" : "",
"question" : "How many times have Liverpool been relegated from the top flight of English football?",
"option1" : "Four",
"option2" : "Three",
"option3" : "Two",
"option4" : "Five",
"answer" : "Three"
}]}
And Here Is my MainActivity.java class.
package com.example.quistest;
//import goes here
public class MainActivity extends Activity {
String serviceUrl;
ImageView next;
TextView question,quizno;
CheckBox ans_1,ans_2,ans_3,ans_4;
ArrayList<Quiz_List>data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=new ArrayList<Quiz_List>();
next=(ImageView) findViewById(R.id.imageView_nextID);
quizno=(TextView) findViewById(R.id.question_noID);
question=(TextView) findViewById(R.id.txt_questionID);
ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
}
});
if (isNetworkAvailable()) {
execute();
}
else {
// Error message here if network is unavailable.
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void execute() {
serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please while wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI(serviceUrl);
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array = respObject.getJSONArray("response");
for (int i =0; i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String quizNumber= jsonObject.getString("quizNumber");
String question= jsonObject.getString("question");
String option1 = jsonObject.getString("option1");
String option2 = jsonObject.getString("option2");
String option3 = jsonObject.getString("option3");
String option4 = jsonObject.getString("option4");
data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));
quizno.setText("Question numer:"+quizNumber);
MainActivity.this.question.setText(question);
ans_1.setText(option1);
ans_2.setText(option2);
ans_3.setText(option3);
ans_4.setText(option4);
}
}else {
Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And Here is my AarrayList Quiz_List.java class.
package com.example.quistest;
public class Quiz_List {
private String quiz_no;
private String question;
private String answer_1;
private String answer_2;
private String answer_3;
private String answer_4;
public String getQuiz_no() {
return quiz_no;
}
public void setQuiz_no(String quiz_no) {
this.quiz_no = quiz_no;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer_1() {
return answer_1;
}
public void setAnswer_1(String answer_1) {
this.answer_1 = answer_1;
}
public String getAnswer_2() {
return answer_2;
}
public void setAnswer_2(String answer_2) {
this.answer_2 = answer_2;
}
public String getAnswer_3() {
return answer_3;
}
public void setAnswer_3(String answer_3) {
this.answer_3 = answer_3;
}
public String getAnswer_4() {
return answer_4;
}
public void setAnswer_4(String answer_4) {
this.answer_4 = answer_4;
}
public Quiz_List(String quiz_no, String question, String answer_1,
String answer_2, String answer_3, String answer_4) {
super();
this.quiz_no = quiz_no;
this.question = question;
this.answer_1 = answer_1;
this.answer_2 = answer_2;
this.answer_3 = answer_3;
this.answer_4 = answer_4;
}
}
Please anyone help i want when i want press next then it should display second one question(its 4 options) should display on screen.
And In current situation it displays last question(its 4 options) only.
I write an example as per your requriment
1-we have a json array
{
"status": 200,
"status_message": "Success",
"response":
[
{
"quizNumber" : "1",
"image" : "",
"question" : "Which car manufacturer was the first to win 100 F1 races?",
"option1" : "Ferrari",
"option2" : "Nissan",
"option3" : "Ford",
"option4" : "",
"answer" : "Ferrari."
},
{
"quizNumber" : "2",
"image" : "",
"question" : "In the professional era which woman has won the most titles at Wimbledon [singles, doubles and mixed] ?",
"option1" : "Venus",
"option2" : "Hingis",
"option3" : "Martina Navratilova",
"option4" : "Waynetta",
"answer" : "Martina Navratilova"
},
{
"quizNumber" : "3",
"image" : "",
"question" : "How many times have Liverpool been relegated from the top flight of English football?",
"option1" : "Four",
"option2" : "Three",
"option3" : "Two",
"option4" : "Five",
"answer" : "Three"
}]}
2-Make a pojo class
class Mypojo {
String op1,op2,op3,op4,ans;
Mypojo(String s1,String s2,String s3,String s4,String ss){
op1 = s1;
.......
ans = ss;
}
//add getter / setter method here
}
3- Now in activity take an array list
int i = 0;
ArrayList<Mypojo> mypojo = new AarrayList();
where you parse json
make pojo class object like
Mypojo pojo = new Mypojo(parameters) and pass all parameters
then mypojo.add(pojo);
In this way all json data will be added in pojo type array list.
4-Now in Next button code will be
int arraysize = mypojo.size();
if(i<arraysize){
i++;
get all values from pojo arraylist by using i as a index position like
String op1 = mypojo.get(i).getOp1();
and change your UI.
}
This is for example if you will do all steps correctly your problem will be solved.
Initially set in MainActivity
int count=0;
Add 1 to count and send count to MainActivity.class when next button is clicked.
Intent i=new Intent(MainActivity.this,MainActivity.class);
i.putStringExtra("count",count);
startActivity(i);
and according to received count in post Execute
JSONObject jsonObject = array.getJSONObject(count);
String quizNumber= jsonObject.getString("quizNumber");
String question= jsonObject.getString("question");
String option1 = jsonObject.getString("option1");
String option2 = jsonObject.getString("option2");
String option3 = jsonObject.getString("option3");
String option4 = jsonObject.getString("option4");
Every time next button is clicked count is increased by one
Paste the below in MainActivity
package com.example.quistest;
//import goes here
public class MainActivity extends Activity {
String serviceUrl;
ImageView next;
TextView question,quizno;
CheckBox ans_1,ans_2,ans_3,ans_4;
ArrayList<Quiz_List>data;
String count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=new ArrayList<Quiz_List>();
next=(ImageView) findViewById(R.id.imageView_nextID);
quizno=(TextView) findViewById(R.id.question_noID);
question=(TextView) findViewById(R.id.txt_questionID);
ans_1=(CheckBox) findViewById(R.id.chk_ans1ID);
ans_2=(CheckBox) findViewById(R.id.chk_ans2ID);
ans_3=(CheckBox) findViewById(R.id.chk_ans3ID);
ans_4=(CheckBox) findViewById(R.id.chk_ans4ID);
Intent i=getIntent();
count=i.getStringExtra("count");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int new_count=Integer.parseInt(count)+1;
Intent intent=new Intent(MainActivity.this, MainActivity.class);
intent.putExtra("count",String.valueOf(new_count));
Toast.makeText(getApplicationContext(), "Next...", Toast.LENGTH_SHORT).show();
}
});
if (isNetworkAvailable()) {
execute();
}
else {
// Error message here if network is unavailable.
Toast.makeText(this, "Network is unavailable!", Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void execute() {
serviceUrl ="http://mobile.betfan.com/api/?action=quiz&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP&sporttype=all";
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please while wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI(serviceUrl);
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array = respObject.getJSONArray("response");
JSONObject jsonObject = array.getJSONObject(Integer.parseInt(count));
String quizNumber= jsonObject.getString("quizNumber");
String question= jsonObject.getString("question");
String option1 = jsonObject.getString("option1");
String option2 = jsonObject.getString("option2");
String option3 = jsonObject.getString("option3");
String option4 = jsonObject.getString("option4");
data.add(new Quiz_List(quizNumber,question,option1,option2,option3,option4));
quizno.setText("Question numer:"+quizNumber);
MainActivity.this.question.setText(question);
ans_1.setText(option1);
ans_2.setText(option2);
ans_3.setText(option3);
ans_4.setText(option4);
}else {
Toast.makeText(MainActivity.this, "Quiz received Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
When you need to pass data from one activity to another activity you need to use intent.putExtra() method to send data.
For send data from your main activity ->
Intent intent = new Intent(MainActivity.this,NEXT_ACTIVITY.class); // Change NEXT_ACTIVITY to your option / answer activity.
intent.putExtra("option_1",option1);
intent.putExtra("option_2",option2);
intent.putExtra("option_3",option3);
intent.putExtra("option_4",option4);
intent.putExtra("answer",answer);
startActivity(intent);
To receive data from your next activity ->
Bundle bundle = getIntent().getExtras();
String option1 = bundle.getString("option_1");
String option2 = bundle.getString("option_2");
String option3 = bundle.getString("option_3");
String option4 = bundle.getString("option_4");
String answer = bundle.getString("answer");
Now you can use these data wherever you want in this activity.
If you parse json and add data in array list I suggest you make a pojo class and take all values in pojo type array list. When you press next button find array list size and array list index start from 0 to array list size so take a integer (int i = 0 ) and its initial value must be 0(zero).Now use if (i<array.size()) condition and inside it increase integer value (i++) . By this way you can solve your problem.Do not use Intent , all things do in same activity.
I have a jsonArray which I want to parse in my android app.
The array:-
[
{
"id": 96905,
"category": "topup",
"detail": "Full talktime of Rs.55 + 1 local airtel SMS free for 1 day",
"price": 55,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"validity": "7 days",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 55
},
{
"id": 90397,
"category": "topup",
"price": 510,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 520
},
{
"id": 90399,
"category": "topup",
"price": 1000,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 1020
}]
My android Code:-
Asynctask:-
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
JSONObject jo;
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam");
for (int i = 0; i < ja2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jo = ja2.getJSONObject(i);
map.put("rank", jo.getString("price"));
map.put("country", jo.getString("validity"));
map.put("population", jo.getString("talktime"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
JsonFunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The error I get:-
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:67)
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
The json is hosted here
I was following this tutorial for learning json parsing, but this tutorial uses jsonObject and I am not able to parse the json array.
Not a duplicate to this :-Sending and Parsing JSON Objects or this How to parse this JSON Array in android?
Let me offer an alternate solution (of sorts). A much simpler version of your existing code would be:
Updated code:
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(TestListActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam";
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
okHttpClient.setRetryOnConnectionFailure(true);
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
String strResult = response.body().string();
JSONArray JARoot = new JSONArray(strResult);
for (int i = 0; i < JARoot.length(); i++) {
JSONObject JORoot = JARoot.getJSONObject(i);
HashMap<String, String> map = new HashMap<>();
if (JORoot.has("category") && JORoot.getString("category").equals("topup")) {
if (JORoot.has("id")) {
map.put("id", JORoot.getString("id"));
}
if (JORoot.has("category")) {
map.put("category", JORoot.getString("category"));
}
if (JORoot.has("detail")) {
map.put("detail", JORoot.getString("detail"));
} else {
map.put("detail", null);
}
if (JORoot.has("price")) {
map.put("price", JORoot.getString("price"));
}
/** ADD THE COLLECTED DATA TO THE ARRAY LIST **/
arraylist.add(map); /* THE DATA WILL ONLY BE ADDED IF THE CATEGORY = "topup" */
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListView testList = (ListView) findViewById(R.id.testList);
TestListAdapter adapter = new TestListAdapter(TestListActivity.this, arraylist);
testList.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
private class TestListAdapter extends BaseAdapter {
Activity activity;
// LAYOUTINFLATER TO USE A CUSTOM LAYOUT
LayoutInflater inflater = null;
// ARRAYLIST TO GET DATA FROM THE ACTIVITY
ArrayList<HashMap<String, String>> arrItem;
public TestListAdapter(Activity activity, ArrayList<HashMap<String, String>> arrItem) {
this.activity = activity;
// CAST THE CONTENTS OF THE ARRAYLIST IN THE METHOD TO THE LOCAL INSTANCE
this.arrItem = arrItem;
// INSTANTIATE THE LAYOUTINFLATER
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrItem.size();
}
#Override
public Object getItem(int position) {
return arrItem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// A VIEWHOLDER INSTANCE
ViewHolder holder;
// CAST THE CONVERTVIEW IN A VIEW INSTANCE
View vi = convertView;
// CHECK CONVERTVIEW STATUS
if (convertView == null) {
// CAST THE CONVERTVIEW INTO THE VIEW INSTANCE vi
vi = inflater.inflate(R.layout.test_item, null);
// INSTANTIATE THE VIEWHOLDER INSTANCE
holder = new ViewHolder();
/***** CAST THE LAYOUT ELEMENTS *****/
/* TOP (PRIMARY) ELEMENTS */
holder.txtPrice = (TextView) vi.findViewById(R.id.txtPrice);
holder.txtDetail = (TextView) vi.findViewById(R.id.txtDetail);
// SET THE TAG TO "vi"
vi.setTag(holder);
} else {
// CAST THE VIEWHOLDER INSTANCE
holder = (ViewHolder) vi.getTag();
}
if (arrItem.get(position).get("price") != null) {
String strPrice = arrItem.get(position).get("price");
holder.txtPrice.setText("PRICE: " + strPrice);
}
if (arrItem.get(position).get("detail") != null) {
String strDetail = arrItem.get(position).get("detail");
holder.txtDetail.setText("DETAIL: " + strDetail);
} else {
holder.txtDetail.setText("DETAIL: NA");
}
return vi;
}
private class ViewHolder {
/* TOP (PRIMARY) ELEMENTS */
TextView txtPrice;
TextView txtDetail;
}
}
For the sake of completeness, I am also including the code for the adapter. It is a simple implementation. Do clean it up / optimize it / customize as per your requirement.
This piece of code has been tested prior to being posted (see screenshot of Logs at the bottom)
This uses the OkHttp library. Add this compile statement to the dependencies section of the module's gradle file: compile 'com.squareup.okhttp:okhttp:2.5.0'. Check the link for an updated version.
The example code uses if statements considering that not every record has the same set of nodes.
You BufferReader is not working as expected in your class JSONfunctions , do some changes in your class and it should looks like
JSONfunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
StringBuffer sb = new StringBuffer("");
try {
URL urls = new URL(url);
URLConnection urlConnection;
urlConnection = urls.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
result=sb.toString();
} catch (IOException e) {}
catch (Exception e) {}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
and to avoid Exception check if JSONArray is not null then only it goes to run for loop like this :
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android? service=airtel&circle=assam");
if(ja2!=null)
for (int i = 0; i < ja2.length(); i++) {}
jsonResponse="";
for(int i = 0; i<response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String id = person.getString("id");
String category = person.getString("category");
}
This question already has answers here:
Error parsing data org.json.JSONException: Value String cannot be converted to JSONArray
(2 answers)
Closed 8 years ago.
Here is list activity
ListActivity:
public class ListDataActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_listview);
url = "http://xxx.xx.x.xxx/index.php";
Bundle c = getIntent().getExtras();
blo = c.getString("blood");
new ProgressTask(ListDataActivity.this).execute();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
class ProgressTask extends AsyncTask<String, Void, Boolean> {
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
{
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
} else {
Toast.makeText(getApplicationContext(),
"INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(ListDataActivity.this,
MainActivity.class));
}
}
public ProgressTask(ListActivity activity) {
context = activity;
}
private Context context;
protected void onPreExecute() {}
#Override
protected void onPostExecute(final Boolean success) {
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.row_listitem, new String[] { name, Category },
new int[] { R.id.vehicleType, R.id.vehicleColor }) {
#Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_listitem,
null);
}
// TODO Auto-generated method stub
if (position % 2 == 1)
convertView.setBackgroundColor(Color.rgb(120, 151, 66));
else
convertView.setBackgroundColor(Color.rgb(86, 107, 129));
return super.getView(position, convertView, parent);
}
};
setListAdapter(adapter);
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
protected Boolean doInBackground(final String... args) {
url = url + "?blo_name=" + blo;
Log.d("", url);
baseAdapter jParser = new baseAdapter();
JSONArray json = jParser.getJSONFromUrl(url);
if (json != null) {
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtype = c.getString(name);
String vfuel = c.getString(Category);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(name, vtype);
map.put(Category, vfuel);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
Base Adapter class:
public class baseAdapter {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public baseAdapter() {}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed ");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
PHP:
if (isset($_POST['blo_name'])) {
$str = $_POST['blo_name'];
$sql = "SELECT * FROM blood_group where Category IN ($str)";
$result = mysql_query($sql);
while ($row=mysql_fetch_array($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
}
I am trying to parse bol string, it have value like bol="'B-','O-'"; while I parse this type of value it didn't show results and gives the logcat
logcat:
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
I need to get result against query SELECT * FROM blood_group where Category IN ($str) but I cannot get. When I give hard core value in php like $str = "'A+','B+'"; it give me result while parsing from android it does not give result while in logcat I can see value http://xxx.xx.x.xxx/heart.php?blo_name='A','B' but error as well.
Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
Notice <br - the web service is returning HTML and not a plain JSON string. Basically you need to fix your PHP response so it doesn't return HTML.
I am parsing JSON data into ListView, and successfully parsed first level of JSON in MainActivity.java, where i am showing list of Main Locations, like:
Inner Locations
Outer Locations
Now i want whenever i do tap on Inner Locations then in SecondActivity it should show Delhi and NCR in a List, same goes for Outer Locations as well, in this case whenever user do tap need to show USA
JSON look like:
{
"all": [
{
"title": "Inner Locations",
"maps": [
{
"title": "Delhi",
"markers": [
{
"name": "Connaught Place",
"latitude": 28.632777800000000000,
"longitude": 77.219722199999980000
},
{
"name": "Lajpat Nagar",
"latitude": 28.565617900000000000,
"longitude": 77.243389100000060000
}
]
},
{
"title": "NCR",
"markers": [
{
"name": "Gurgaon",
"latitude": 28.440658300000000000,
"longitude": 76.987347699999990000
},
{
"name": "Noida",
"latitude": 28.570000000000000000,
"longitude": 77.319999999999940000
}
]
}
]
},
{
"title": "Outer Locations",
"maps": [
{
"title": "United States",
"markers": [
{
"name": "Virgin Islands",
"latitude": 18.335765000000000000,
"longitude": -64.896335000000020000
},
{
"name": "Vegas",
"latitude": 36.114646000000000000,
"longitude": -115.172816000000010000
}
]
}
]
}
]
}
Note: But whenever i do tap on any of the ListItem in first activity, not getting any list in SecondActivity, why ?
MainActivity.java:-
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
Intent sendtosecond = new Intent(MainActivity.this, SecondActivity.class);
// Pass all data rank
sendtosecond.putExtra("title", arraylist.get(position).get(MainActivity.TITLE));
Log.d("Tapped Item::", arraylist.get(position).get(MainActivity.TITLE));
startActivity(sendtosecond);
}
});
}
}
}
SecondActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
Intent in = getIntent();
strReceived = in.getStringExtra("title");
Log.d("Received Data::", strReceived);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("maps");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
try below method:-
try
{
JSONObject j = new JSONObject("your json response");
JSONArray all = j.getJSONArray("all");
for (int i = 0; i < all.length(); i++)
{
JSONObject data = all.getJSONObject(i);
System.out.println("title =>"+data.getString("title"));
JSONArray maps = data.getJSONArray("maps");
for (int k = 0; k < maps.length(); k++)
{
JSONObject data_sec = maps.getJSONObject(k);
System.out.println("name => "+data_sec.getString("name"));
System.out.println("latitude => "+data_sec.getString("latitude"));
System.out.println("longitude => "+data_sec.getString("longitude"));
}
}
}
catch (Exception e)
{
// TODO: handle exception
}
// Try this way,hope this will help you to solve your problem.
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("index", i);
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, String.valueOf(position), Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
Intent sendtosecond = new Intent(MainActivity.this, SecondActivity.class);
// Pass all data rank
sendtosecond.putExtra("title", arraylist.get(position).get(MainActivity.TITLE));
sendtosecond.putExtra("index", arraylist.get(position).get(MainActivity.INDEX));
Log.d("Tapped Item::", arraylist.get(position).get(MainActivity.TITLE));
Log.d("Tapped Item Index::", arraylist.get(position).get(MainActivity.INDEX));
startActivity(sendtosecond);
}
});
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
Intent in = getIntent();
strReceived = in.getStringExtra("title");
strReceivedIndex = in.getStringExtra("index");
Log.d("Received Data::", strReceived);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://10.0.2.2/locations.json");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("all").getJSONObject(Integer.parseInt(strReceivedIndex)).getgetJSONArray("maps");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
The Class:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Read().execute("masjids");
}
public JSONObject retrieveInfo(String radius) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(
"http://iqamah.org/api/index.php?lat=43&long=-79&radius=");
url.append(radius);
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
HttpResponse r = httpclient.execute(get);
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject timeline = new JSONObject(data);
return timeline.getJSONObject("1");
}
private class Read extends AsyncTask<String, Integer, String> {
ProgressDialog pd = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading...");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
JSONObject json = retrieveInfo("200");
return json.getString(arg0[0]);
} 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();
}
return null;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
pd.dismiss();
TextView day = (TextView) findViewById(R.id.displayDay);
day.setText("Masjid: " + status);
}
}
}
The JSON:
{
"status": "ok",
"masjids": [
{
"id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99"
},
{
"id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59"
},
{
"id": "43|Darul Khair|25 St Dennis, Toronto|52.12"
}
]
}
I am trying to access the masjids->id[0] array, how can I do this with the above code?
String data = "{ "status": "ok", "masjids": [ { "id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99" }, { "id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59" }, { "id": "43|Darul Khair|25 St Dennis, Toronto|52.12" } ] }";
JSONObject jObj = new JSONObject(data);
JSONArray jArray_masjids = jObj.getJSONArray("masjids");
String address = jArray_masjids.getJSONObject(0).getString("id");
JSONObject timeline = new JSONObject(data);
JasonArry jarry=timeline.getJsonArray("masjids");
for (int i = 0; i < jarry.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
String newStr = explrObject.getString("id");
}
Try this,
String data = "{ "status": "ok", "masjids": [ { "id": "44|Madina Masjid|1200 Danforth Ave, Toronto|49.99" }, { "id": "39|Darul Taqwa|1 Thorncliffe Park Drive, Toronto|51.59" }, { "id": "43|Darul Khair|25 St Dennis, Toronto|52.12" } ] }";
JSONObject jObj = new JSONObject(data);
JSONArray jArray_masjids = jObj.getJSONArray("masjids");
for(int i = 0 ;i<jArray_masjids;i++){
String address = jsonArray.getJSONObject(i).getString("id");
}