How to display data? - android

I am using this method to call my service in my application.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
String url = "url";
AQuery mAQuery = new AQuery(Next.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
#Override
public void callback(String url, String data, AjaxStatus status) {
super.callback(url, data, status);
if (BuildConfig.DEBUG) {
Log.d("###$Request URL", url + "");
Log.d("###$Response ", data + "");
Log.d("###$Status Message : ", status.getMessage() + "");
Log.d("###$Status Code : ", status.getCode() + "");
}
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONObject json = new JSONObject(StringData);
String COMP_REQ_ID = json.getString("COMP_REQ_ID");
String CompanyName = json.getString("CompanyName");
String COMP_REQ_TYPE = json.getString("COMP_REQ_TYPE");
String Name = json.getString("Name ");
myAwesomeTextview.setText("COMP_REQ_ID: " + COMP_REQ_ID + "\n" + "CompanyName:" + CompanyName + "\n" + "COMP_REQ_TYPE: " + COMP_REQ_TYPE + "\n" + "Name : " + Name);
} catch (JSONException e) {
myAwesomeTextview.setText("" + e);
}
But the data coming from server is not getting display on my phone screen.
The data i got from my service is given below:
[{"Name":null,"PositionName":null,"DateOfEvent":null,"EvetnId":0,"HetId":0,"EventDate":null,"COMP_REQ_ID":9714,"COMP_REQ_TYPE":"Intership","JobTitle":"Administrator","CompanyName":"Jensor's International (Ltd).","ReqQualification":"","DegreeName":"B.E/B.Tech,M.C.A,M.B.A,B.A,B.A.M.S,B.Com,B.S.W","Post_Status":1,"Eventdate":"21/06/2016","JobsOrInternships":null},{"Name":null,"PositionName":null,"DateOfEvent":null,"EvetnId":0,"HetId":0,"EventDate":null,"COMP_REQ_ID":9713,"COMP_REQ_TYPE":"Intership","JobTitle":"junior counselor","CompanyName":"Jensor's International (Ltd).","ReqQualification":"","DegreeName":"B.E/B.Tech,M.C.A,M.B.A,B.B.M,B.Com,B.F.A","Post_Status":1,"Eventdate":"21/06/2016","JobsOrInternships":null}
How to display it.

You should use JSONArray to parse your result
JSONArray rootArray = new JSONArray(jsonString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject json = rootArray.getJSONObject(i);
String COMP_REQ_ID = json.getString("COMP_REQ_ID");
}
Or you can use GSon library to parse the result for you. I recommend this post as example how to query data from ASP.NET Web API.
I think you should make your question clear because I'm not sure if you have problem with getting data or showing data to ui.

public class ArrayBean {
public String Name;
public String PositionName;
public String DateOfEvent;
public String EvetnId;
public String HetId;
public String EventDate;
public String COMP_REQ_ID;
public String COMP_REQ_TYPE;
public String JobTitle;
public String CompanyName;
public String ReqQualification;
public String DegreeName;
public String Eventdate;
public String JobsOrInternships;
}
ArrayBean bean;
JSONArray array=new JSONArray("StringData ");
JSONObject json;
for(int i=0;i<array.length();i++){
bean=new ArrayBean();
json=new JSONObject();
json=array.getJSONObject(i);
bean.COMP_REQ_ID=json.getString("COMP_REQ_ID");
bean.COMP_REQ_TYPE=json.getString("COMP_REQ_TYPE");
bean.CompanyName=json.getString("CompanyName");
bean.DateOfEvent=json.getString("DateOfEvent");
bean.EventDate=json.getString("EventDate");
bean.EvetnId=json.getString("EvetnId");
bean.HetId=json.getString("HetId");
bean.JobsOrInternships=json.getString("JobsOrInternships");
bean.JobTitle=json.getString("JobTitle");
bean.Name=json.getString("Name");
bean.PositionName=json.getString("PositionName");
bean.ReqQualification=json.getString("ReqQualification");
}

Note, care about data-types in JSON e.g key COMP_REQ_ID has value data-type is int. You should use optString or optInt instead of getString or getInt to parse your result
JSONArray rootArray = new JSONArray(jsonString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
int COMP_REQ_ID = json.optInt("COMP_REQ_ID");
String COMP_REQ_TYPE = json.optString("COMP_REQ_TYPE");
...
}

i used this code
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
int COMP_REQ_ID = json.optInt("COMP_REQ_ID");
String COMP_REQ_TYPE = json.optString("COMP_REQ_TYPE");
String CompanyName = json.getString("CompanyName ");
String Name = json.getString("Name");
String PositionName = json.getString("PositionName");
myAwesomeTextview.setText("COMP_REQ_ID:" + COMP_REQ_ID + "\n" + "COMP_REQ_TYPE" + COMP_REQ_TYPE + "\n" + "CompanyName" + CompanyName + "\n" + "Name" + Name + "\n" + "PostionNmae" + PositionName);
}
But then also the result is not diplayed on my phone And in android studio logcat it showing me this:
reporting:java.lang.NullPointerException at com.example.anand.Next$1.callback(Next.java:55)
at com.example.anand.Next$1.callback(Next.java:24)
at

Related

Unsorted saving of data from php to sqlite

I am saving receiving data from external server. Now, this is the sample data that I am receiving:
Now what happens is that when I save them to mysqlite db, it doesn't the follow the order of id, Here's the sample of it:
Here's my code for fetching data:
private class getData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Http sh = new Http();
try {
String URLS = "http://localhost/sample.php?date="+datePHP+"&gametype="+gamePHP+"&time="+timePHP+"&bettype="+typePHP;
String jsonStr = sh.makeServiceCall(URLS);
if(jsonStr != null){
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray sims = (JSONArray)jsonObj.get("mmi");
for (int i = 0; i < sims.length(); i++) {
JSONObject c = sims.getJSONObject(i);
String betid = c.getString("id");
String betnumber = c.getString("betnumber");
String betamount = c.getString("betamount");
boolean insertBets = databaseHelper.addBets(betid, betnumber, betamount, timePHP, datePHP,gamePHP,typePHP);
if (insertBets){
System.out.println("SAVED");
}else{
System.out.println("UPDATED");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
runOnUiThread(() -> {
populatelistview();
});
}
}
Code for saving to sqlite:
public boolean addBets(String betid, String betnum, String betAmt, String betTime, String betDate, String gameType, String betType) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("betid", betid);
contentValues.put("betNum", betnum);
contentValues.put("betAmt", betAmt);
contentValues.put("betTime", betTime);
contentValues.put("betDate", betDate);
contentValues.put("gameType", gameType);
contentValues.put("betType", betType);
String sql = "SELECT * FROM betsx WHERE betNum ='" + betnum + "' AND betTime ='" + betTime + "' AND betDate = '" + betDate + "' AND gameType ='" + gameType + "' AND betType ='" + betType + "'";
Cursor cursor = db.rawQuery(sql, null);
db.insert("betsx", null, contentValues);
System.out.println(betnum + "//" + betAmt);
return true;
}

How to get data from key of a JSON [duplicate]

This question already has answers here:
How to iterate over a JSONObject?
(15 answers)
Closed 5 years ago.
I am creating an app in which i need to parse a list of contacts which is in JSONObject format, with key before each object, i don't know how to parse this format.
{
"1": {
"mobileContact": "98562325",
"systemContact": "9198562325"
},
"3": {
"mobileContact": "987563656",
"systemContact": "91987563656"
},
"4": {
"mobileContact": "965632525",
"systemContact": "91965632525"
},
"6": {
"mobileContact": "965436222",
"systemContact": "91965436222"
}
}
Use the keys() iterator to iterate over all the properties, and call get() for each.
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
try{
JSONObject json = new JSONObject(jsonRespondeString);
Iterator<String> iterator = json.keys();
while (iterator.hasNext()){
String key = iterator.next();
JSONObject object = json.getJSONObject(key);
String value1 = object.getString("key1");
String value2 = object.getString("key2");
}
}
catch (JSONException e){
e.printStackTrace();
}
please try this it helps
You can use GSON library to parse it.
String data = "{\n" +
" \"1\": {\n" +
" \"mobileContact\": \"98562325\",\n" +
" \"systemContact\": \"9198562325\"\n" +
" },\n" +
" \"3\": {\n" +
" \"mobileContact\": \"987563656\",\n" +
" \"systemContact\": \"91987563656\"\n" +
" },\n" +
" \"4\": {\n" +
" \"mobileContact\": \"965632525\",\n" +
" \"systemContact\": \"91965632525\"\n" +
" },\n" +
" \"6\": {\n" +
" \"mobileContact\": \"965436222\",\n" +
" \"systemContact\": \"91965436222\"\n" +
" }\n" +
"}";
Map<String, Item> itemMap = new HashMap<>();
itemMap = new Gson().fromJson(data, itemMap.getClass());
Log.i("data", itemMap);
Item Class
private class Item {
String mobileContact;
String systemContact;
// getters and setters
public String getMobileContact() {
return mobileContact;
}
public void setMobileContact(String mobileContact) {
this.mobileContact = mobileContact;
}
public String getSystemContact() {
return systemContact;
}
public void setSystemContact(String systemContact) {
this.systemContact = systemContact;
}
}
You need to add the following to the build.gradle file,
compile 'com.google.code.gson:gson:2.8.0'

how should i make JSONObject and JSONArray from json url or json

My JSON:
{
"response_code": 200,
"error": false,
"train_name": "KCG YPR EXP",
"train_num": "17603",
"pnr": "1234567890",
"failure_rate": 19.346153846153847,
"doj": "20-8-2015",
"chart_prepared": "Y",
"class": "SL",
"total_passengers": 2,
"train_start_date": {
"month": 8,
"year": 2015,
"day": 20
},
"from_station": {
"code": "KCG",
"name": "KACHEGUDA"
},
"boarding_point": {
"code": "KCG",
"name": "KACHEGUDA"
},
"to_station": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"reservation_upto": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"passengers": [
{
"no": 1,
"booking_status": "S7,58,GN",
"current_status": "S7,58",
"coach_position": 9
},
{
"no": 2,
"booking_status": "S7,59,GN",
"current_status": "S7,59",
"coach_position": 9
}
]
}
What I did so far:
if(jsonStr!=null)
{
try
{
JSONObject object=new JSONObject(jsonStr);
JSONArray jsonArray=object.getJSONArray("passengers");
for (int i=0;i<=jsonArray.length();i++)
{
JSONObject o=jsonArray.getJSONObject(i);
int no= Integer.parseInt(o.optString("no").toString());
String booking_status=o.getString("Booking Status");
String current_status=o.getString("Current Status");
String coach_position=o.getString("Coach Position");
JSONObject data=o.getJSONObject("details");
String train_name = data.getString("Train Name");
int train_num = Integer.parseInt(data.optString("train number").toString());
int pnr = Integer.parseInt(data.optString("pnr").toString());
String chart_prepared = data.getString("Chart Prepared");
int total_passengers=Integer.parseInt(data.optString("total passengers").toString());
JSONObject date=data.getJSONObject("tarin_start_date");
int month=Integer.parseInt(data.optString("month").toString());
int year=Integer.parseInt(data.optString("year").toString());
int day=Integer.parseInt(data.optString("day").toString());
JSONObject co=date.getJSONObject("from_station");
String code=co.getString("code");
String name=co.getString("name");
JSONObject co1=co.getJSONObject("boarding_point");
String code1=co1.getString("code");
String name1=co1.getString("name");
JSONObject co2=co1.getJSONObject("to_station");
String code2=co2.getString("code");
String name2=co2.getString("name");
JSONObject co3=co2.getJSONObject("from_station");
String code3=co3.getString("code");
String name3=co3.getString("name");
HashMap<String,String> dtail=new HashMap<>();
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus",booking_status);
dtail.put("Current Staus",current_status);
dtail.put("Coach Positon",coach_position);
dtail.put("Train Name",train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared",chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code",code);
dtail.put("name",name);
dtail.put("code",code1);
dtail.put("name",name1);
dtail.put("code",code2);
dtail.put("name",name2);
dtail.put("code",code3);
dtail.put("name",name3);
dataList.add(dtail);
}
}
catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
else
{
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
Here is your solution.
Hope this will help you. Whenever you work with JSON check all key name. It should always same as response key name
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
HashMap<String, String> dtail = new HashMap<>();
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject o = jsonArray.getJSONObject(i);
int no = Integer.parseInt(o.optString("no").toString());
String booking_status = o.getString("booking_status");
String current_status = o.getString("current_status");
String coach_position = o.getString("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus", booking_status);
dtail.put("Current Staus", current_status);
dtail.put("Coach Positon", coach_position);
}
String train_name = object.getString("train_name");
int train_num = Integer.parseInt(object.optString("train_num").toString());
int pnr = Integer.parseInt(object.optString("pnr").toString());
String chart_prepared = object.getString("chart_prepared");
int total_passengers = Integer.parseInt(object.optString("total_passengers").toString());
JSONObject date = object.getJSONObject("train_start_date");
int month = Integer.parseInt(date.optString("month").toString());
int year = Integer.parseInt(date.optString("year").toString());
int day = Integer.parseInt(date.optString("day").toString());
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("reservation_upto");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
dtail.put("Train Name", train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared", chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
dataList.add(dtail);
} catch (final JSONException e) {
Log.e("Json", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
Hope this will help :-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy);
String str = "{\n" +
" \"response_code\": 200,\n" +
" \"error\": false,\n" +
" \"train_name\": \"KCG YPR EXP\",\n" +
" \"train_num\": \"17603\",\n" +
" \"pnr\": \"1234567890\",\n" +
" \"failure_rate\": 19.346153846153847,\n" +
" \"doj\": \"20-8-2015\",\n" +
" \"chart_prepared\": \"Y\",\n" +
" \"class\": \"SL\",\n" +
" \"total_passengers\": 2,\n" +
" \"train_start_date\": {\n" +
" \"month\": 8,\n" +
" \"year\": 2015,\n" +
" \"day\": 20\n" +
" },\n" +
" \"from_station\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"boarding_point\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"to_station\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"reservation_upto\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"passengers\": [\n" +
" {\n" +
" \"no\": 1,\n" +
" \"booking_status\": \"S7,58,GN\",\n" +
" \"current_status\": \"S7,58\",\n" +
" \"coach_position\": 9\n" +
" },\n" +
" {\n" +
" \"no\": 2,\n" +
" \"booking_status\": \"S7,59,GN\",\n" +
" \"current_status\": \"S7,59\",\n" +
" \"coach_position\": 9\n" +
" }\n" +
" ]\n" +
"}";
parseJson(str);
}
private void parseJson(String jsonStr) {
HashMap<String, String> dtail = new HashMap<>();
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
int responseCode = object.getInt("response_code");
boolean error = object.getBoolean("error");
String train_name = object.getString("train_name");
int train_num = object.getInt("train_num");
int pnr = object.getInt("pnr");
double failurerate = object.getDouble("failure_rate");
String dateofJoin = object.getString("doj");
String chart = object.getString("chart_prepared");
String Class = object.getString("class");
int total_passengers = object.getInt("total_passengers");
JSONObject date = object.getJSONObject("train_start_date");
int month = date.getInt("month");
int year = date.getInt("year");
int day = date.getInt("day");
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("from_station");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int no = jsonObject.getInt("no");
String booking_status = jsonObject.getString("booking_status");
String current_status = jsonObject.getString("current_status");
int coach_position = jsonObject.getInt("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("booking_status", booking_status);
dtail.put("current_status", current_status);
dtail.put("coach_position", String.valueOf(coach_position));
}
dtail.put("responseCode", String.valueOf(responseCode));
dtail.put("error", "" + error);
dtail.put("Train Name", train_name);
dtail.put("dateofJoin", dateofJoin);
dtail.put("chart", chart);
dtail.put("Class", Class);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("FAILURE_RATE", String.valueOf(failurerate));
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
Log.e("Result------", "" + dtail);
} catch (final JSONException e) {
Log.e("tag", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
}

Parsing json content and viewing it on text View

I am newbie to android and it designing a an app that will read questions and options from a json file and will set text on the text view , and next question will be displayed only if correct option is clicked, but I am not able to figure out how I should be doing this.
{
"questions": [
{
"question": "Question....",
"opt1": "ravi#gmail.com",
"opt2": "country",
"opt3" : "male",
"opt4": "option 4",
"coropt": "b"
},
{
"question": "Question....",
"opt1": "johnny_depp#gmail.com",
"opt2": "country",
"opt3" : "male",
"opt4": "option 4",
"coropt": "a"
},
{
"question": "Question....",
"opt1": "leonardo_dicaprio#gmail.com",
"opt2": "country",
"opt3" : "male",
"opt4": "option 4",
"coropt": "d"
},
{
"question": "Question....",
"opt1": "john_wayne#gmail.com",
"opt2": "country",
"opt3" : "male",
"opt4": "option 4",
"coropt": "c"
}
]
}
here is the view in which json array data needs to be placed one by one
this is the code I am working on but I am stuck how and where to parse json data.
public class JavaQuiz extends AppCompatActivity {
TextView ltv, tv1, tv2, tv3, tv4;
// JSON Node names
private static final String TAG_QUESTIONS = "questions";
private static final String TAG_QUESTION = "question";
private static final String TAG_OPTION1 = "opt1";
private static final String TAG_OPTION2 = "opt2";
private static final String TAG_OPTION3 = "opt3";
private static final String TAG_OPTION4 = "opt4";
private static final String TAG_CORRECTOPTION = "coropt";
// contacts JSONArray
JSONArray questions = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> questionList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_quiz);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ltv = (TextView) findViewById(R.id.textView7);
tv1 = (TextView) findViewById(R.id.textView8);
tv2 = (TextView) findViewById(R.id.textView9);
tv3 = (TextView) findViewById(R.id.textView10);
tv4 = (TextView) findViewById(R.id.textView11);
}
class QuestionShow extends AsyncTask<String, Void, Void> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JavaQuiz.this);
progressDialog.setTitle("Fetching");
progressDialog.setMessage("Setting question");
progressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
/* HttpPost post=new HttpPost("http://192.168.1.5/questions.json");
post.setEntity(new UrlEncodedFormEntity(params[0]));
HttpResponse response = client.execute(post);
*/
String jsonStr = "http://192.168.1.5/questions.json";
/* if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_QUESTIONS);
// looping through All questions
for (int i = 0; i < questions.length(); i++) {
JSONObject q = questions.getJSONObject(i);
String question = q.getString(TAG_QUESTION);
String op1 = q.getString(TAG_OPTION1);
String op2 = q.getString(TAG_OPTION2);
String op3 = q.getString(TAG_OPTION3);
String op4 = q.getString(TAG_OPTION4);
String coropt = q.getString(TAG_CORRECTOPTION);
/* // tmp hashmap for single question
HashMap<String, String> ques = new HashMap<String, String>();
// adding each child node to HashMap key => value
ques.put(TAG_QUESTION, question);
ques.put(TAG_OPTION1, op1);
ques.put(TAG_OPTION2, op2);
ques.put(TAG_OPTION3, op3);
ques.put(TAG_OPTION4, op4);
ques.put(TAG_CORRECTOPTION, coropt);
// adding contact to contact list
questionList.add(ques);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
*/
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
String jsonStr = "http://192.168.1.5/questions.json";
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_QUESTIONS);
// looping through All questions
for (int i = 0; i < questions.length(); ) {
JSONObject q = questions.getJSONObject(i);
String question = q.getString(TAG_QUESTION);
String op1 = q.getString(TAG_OPTION1);
String op2 = q.getString(TAG_OPTION2);
String op3 = q.getString(TAG_OPTION3);
String op4 = q.getString(TAG_OPTION4);
String coropt = q.getString(TAG_CORRECTOPTION);
ltv.setText(question);
tv1.setText(op1);
tv2.setText(op1);
tv3.setText(op1);
tv4.setText(op1);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
public void answer(View view)
{
String
if (view==tv1)
{
if(tv1.getText().toString()==)
}
}
}
Firstly to run the AsyncTask you need to call the AsyncTask from your onCreate method as shown below
public class JavaQuiz extends AppCompatActivity {
TextView ltv, tv1, tv2, tv3, tv4;
// contacts JSONArray
JSONArray questions = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> questionList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_quiz);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ltv = (TextView) findViewById(R.id.textView7);
tv1 = (TextView) findViewById(R.id.textView8);
tv2 = (TextView) findViewById(R.id.textView9);
tv3 = (TextView) findViewById(R.id.textView10);
tv4 = (TextView) findViewById(R.id.textView11);
String jsondata = "{\n" +
"\"questions\": [\n" +
" {\n" +
" \"question\": \"Question....\",\n" +
" \"opt1\": \"ravi#gmail.com\",\n" +
" \"opt2\": \"country\",\n" +
" \"opt3\" : \"male\",\n" +
" \"opt4\": \"option 4\",\n" +
" \"coropt\": \"b\"\n" +
" },\n" +
" {\n" +
" \"question\": \"Question....\",\n" +
" \"opt1\": \"johnny_depp#gmail.com\",\n" +
" \"opt2\": \"country\",\n" +
" \"opt3\" : \"male\",\n" +
" \"opt4\": \"option 4\",\n" +
" \"coropt\": \"a\"\n" +
" },\n" +
" {\n" +
" \"question\": \"Question....\",\n" +
" \"opt1\": \"leonardo_dicaprio#gmail.com\",\n" +
" \"opt2\": \"country\",\n" +
" \"opt3\" : \"male\",\n" +
" \"opt4\": \"option 4\",\n" +
" \"coropt\": \"d\"\n" +
" },\n" +
" {\n" +
" \"question\": \"Question....\",\n" +
" \"opt1\": \"john_wayne#gmail.com\",\n" +
" \"opt2\": \"country\",\n" +
" \"opt3\" : \"male\",\n" +
" \"opt4\": \"option 4\",\n" +
" \"coropt\": \"c\"\n" +
" }\n" +
"]\n" +
"}";
new QuestionShow(JavaQuiz.this).execute(jsondata);
//If using URL use this below
// new QuestionShow(JavaQuiz.this).execute("http://192.168.1.5/questions.json");
}
public class QuestionShow extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
ProgressDialog progressDialog;
Context context;
public QuestionShow(Context context) {
this.context = context;
}
// JSON Node names
public String TAG_QUESTIONS = "questions";
public String TAG_QUESTION = "question";
public String TAG_OPTION1 = "opt1";
public String TAG_OPTION2 = "opt2";
public String TAG_OPTION3 = "opt3";
public String TAG_OPTION4 = "opt4";
public String TAG_CORRECTOPTION = "coropt";
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetching");
progressDialog.setMessage("Setting question");
progressDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
/*Your networking activities can be done here and the params[0] URL can be passed to it*/
// HttpClient client = new DefaultHttpClient();
// HttpPost post = new HttpPost("http://192.168.1.5/questions.json");
// try {
// post.setEntity(new UrlEncodedFormEntity(params[0]));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
// HttpResponse response = client.execute(post);
//
String jsonStr = params[0];
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
questions = jsonObj.getJSONArray(TAG_QUESTIONS);
questionList = new ArrayList<>();
// looping through All questions
for (int i = 0; i < questions.length(); i++) {
JSONObject q = questions.getJSONObject(i);
String question = q.getString(TAG_QUESTION);
String op1 = q.getString(TAG_OPTION1);
String op2 = q.getString(TAG_OPTION2);
String op3 = q.getString(TAG_OPTION3);
String op4 = q.getString(TAG_OPTION4);
String coropt = q.getString(TAG_CORRECTOPTION);
// tmp hashmap for single question
HashMap<String, String> ques = new HashMap<String, String>();
// adding each child node to HashMap key => value
ques.put(TAG_QUESTION, question);
ques.put(TAG_OPTION1, op1);
ques.put(TAG_OPTION2, op2);
ques.put(TAG_OPTION3, op3);
ques.put(TAG_OPTION4, op4);
ques.put(TAG_CORRECTOPTION, coropt);
// adding contact to contact list
questionList.add(ques);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// }
return questionList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> hashMapArrayList) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (hashMapArrayList.size() > 0) {
ltv.setText(hashMapArrayList.get(2).get(TAG_QUESTION));
tv1.setText(hashMapArrayList.get(2).get(TAG_OPTION1));
tv2.setText(hashMapArrayList.get(2).get(TAG_OPTION2));
tv3.setText(hashMapArrayList.get(2).get(TAG_OPTION3));
tv4.setText(hashMapArrayList.get(2).get(TAG_OPTION4));
} else {
Toast.makeText(getApplicationContext(), "No data found", Toast.LENGTH_SHORT).show();
}
}
}
// public void answer(View view)
// {
// String
// if (view==tv1)
// {
// if(tv1.getText().toString()==)
// }
// }
}
Since you have a webservice running to get the data, you will need to call the webservice inside the AsyncTask in your doInBackground() method.
Then you need to pass on the received result to the onPostExecute() method.
Receive the data in the onPostExecute and then setText them in your layouts.
I have selected first question only you can iterate or select your preferred question to display or even change the json output to be parsed.
The result is procured successfully as shown below in the screenshot.

how to get value from nameless array of Json

String Result=GET(url);
Log.e("result", "data" + Result);
try{
//JSONObject jsonResponse = new JSONObject(Result);
// JSONArray jsonMainNode = jsonResponse.optJSONArray();
//int len= jsonMainNode.length();
JSONArray jsonarray = new JSONArray(Result);
for (int i = 0; i < 3; i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
System.out.println("categoryId : " + i + " = " + jsonobj.getString("FirstName"));
System.out.println("Title : " + i + " = " + jsonobj.getString("LastName"));
//System.out.println("songs : " + i + " = " + jsonobj.getString("songs"));
}
Note: I am trying this to get object of nameless array. I am not getting how to store the response as a form of Json object
Try this it works for me.
try {
JSONArray jarr = new JSONArray(Result);
for (int i = 0; i < jarr.length(); i++) {
JSONObject jsonobj= jarr.getJSONObject(i);
System.out.println("categoryId : " + i + " = " + jsonobj.getString("FirstName"));
System.out.println("Title : " + i + " = " + jsonobj.getString("LastName"));
}
}

Categories

Resources