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.
Related
Hi in the below code how to get names of the below JSON responses from users object.want to display the names and setting to the spinner adapter.
can anyone help me
expected output:
Admin Administrator
Ganeshprasad S etc
response:
{
"name": "assigned_user_id",
"label": "Assigned To",
"mandatory": true,
"type": {
"name": "owner",
"users": {
"19x1": "Admin Administrator",
"19x5": "Ganeshprasad S",
"19x6": "Balaji RR",
"19x7": "Kiran Thadimarri",
"19x8": "Sridhar Balakrishnan",
"19x9": "Shilpa MK",
"19x10": "Velmurugan N",
"19x11": "Aamir Khanna",
"19x12": "Jamir Abbas Pinjari",
"19x13": "Syed Shadab Ashraf",
"19x14": "Shahul Hameed",
"19x15": "Manjula C",
"19x16": "Keerthi Vasan L",
"19x17": "Lochan Jyoti Borgohain",
"19x18": "Rajkumar Sanatomba Singh",
"19x19": "Krishna Pandey",
"19x20": "Nabajit Pathak",
"19x21": "Manoranjan Ningthoujam",
"19x22": "Pravin Karbhari Ahire",
"19x23": "Pratap Kumar Choudhary"
}
}
}
below is code .nothing was displaying for the spinner
java:
if (name.equals("assigned_user_id")) {
String jsondata ="";
try {
JSONObject jsonobj = new JSONObject(jsondata);
JSONObject type = jsonobj.getJSONObject("type");
JSONObject usr = type.getJSONObject("users");
Iterator<String> keys = usr.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonobj.get(key) instanceof JSONObject) {
String v = usr.getString("19x1");
account_manger.add(v);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item, account_manger);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinneraccountManager.setAdapter(dataAdapter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Lets say your JSON data is in String
String jsondata ;
JSONObject jsonobj = new JSONObject(jsondata);
Since this json object has many properties so we will get the property "type" which is of type Object, So we will create another object of JSONObject
JSONObject type = jsonobj.getJSONObject("type");
Inside this type json object we have two properties name and users and in which user is another object, so we will get users object from type object
JSONObject usr = jsonobj.getJSONObject("users");
Iterator<String> keys = usr.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
//print here
}
}
// String n1 = usr.getString("19x1");
// String n2 = usr.getString("19x5");
// String n3 = usr.getString("19x6");
//and So on......
Create XML for Spinner Android
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Spinner
android:id="#+id/spinner"
android:layout_width="149dp"
android:layout_height="40dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.498" />
And the MainActivity code is
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemSelectedListener {
String[] names = { n1,n2,n3};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
Toast.makeText(getApplicationContext(),names[position] , Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
String response = "{\n" +
" \"name\": \"assigned_user_id\",\n" +
" \"label\": \"Assigned To\",\n" +
" \"mandatory\": true,\n" +
" \"type\": {\n" +
" \"name\": \"owner\",\n" +
" \"users\": {\n" +
" \"19x1\": \"Admin Administrator\",\n" +
" \"19x5\": \"Ganeshprasad S\",\n" +
" \"19x6\": \"Balaji RR\",\n" +
" \"19x7\": \"Kiran Thadimarri\",\n" +
" \"19x8\": \"Sridhar Balakrishnan\",\n" +
" \"19x9\": \"Shilpa MK\",\n" +
" \"19x10\": \"Velmurugan N\",\n" +
" \"19x11\": \"Aamir Khanna\",\n" +
" \"19x12\": \"Jamir Abbas Pinjari\",\n" +
" \"19x13\": \"Syed Shadab Ashraf\",\n" +
" \"19x14\": \"Shahul Hameed\",\n" +
" \"19x15\": \"Manjula C\",\n" +
" \"19x16\": \"Keerthi Vasan L\",\n" +
" \"19x17\": \"Lochan Jyoti Borgohain\",\n" +
" \"19x18\": \"Rajkumar Sanatomba Singh\",\n" +
" \"19x19\": \"Krishna Pandey\",\n" +
" \"19x20\": \"Nabajit Pathak\",\n" +
" \"19x21\": \"Manoranjan Ningthoujam\",\n" +
" \"19x22\": \"Pravin Karbhari Ahire\",\n" +
" \"19x23\": \"Pratap Kumar Choudhary\"\n" +
" }\n" +
" }\n" +
"}";
This the data class
public class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof User){
User user = (User )obj;
if(user.getName().equals(name) && user.getId()==id ) return true;
}
return false;
}
}
UserArrayList
This is how you can get the data
ArrayList<User> userList = new ArrayList<>();
try {
JSONObject jsonobj = new JSONObject(response);
JSONObject type = jsonobj.getJSONObject("type");
JSONObject usr = type.getJSONObject("users");
Iterator<String> keys = usr.keys();
while(keys.hasNext()) {
String key = keys.next();
String value = usr.getString(key);
User user = new User(key,value);
userList.add(user);
}
Log.e("value","value----"+userList);
} catch (JSONException e) {
e.printStackTrace();
}
This is the spinner Adapter
ArrayAdapter<User> adapter = new ArrayAdapter<User>(context, android.R.layout.simple_spinner_dropdown_item, userList );
spinneraccountManager.setAdapter(adapter);
spinneraccountManager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
User user = (User) parent.getSelectedItem();
Toast.makeText(view.getContext(), "User ID: "+user.getId()+", User Name : "+user.getName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
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;
}
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
My ListView is not showing anything.
I'm downloading the top stories API from Hacker-News and putting them in my app. I want to put the titles of those stories in my list view (they are over 100).
I download them and store them in a database for permanent storage and then add them to my list view, but NOTHING is showing up in my app. Can anyone explain to me why?
UPDATE: I get a CursorIndexOutOfBoundException problem. ( index 350 out of 350)
public class MainActivity extends AppCompatActivity {
ListView listView;
private SQLiteDatabase myDatabase;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
DownloadIDs ids = new DownloadIDs();
String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
ids.execute(URL);
try {
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);
Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor1.getColumnIndex("urlID");
cursor1.moveToFirst();
while (cursor1 != null) {
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty";
new DownloadContent().execute(newUrl);
cursor1.moveToNext();
}
Cursor cursor2 = myDatabase.rawQuery("SELECT * FROM content", null);
int titleIndex = cursor2.getColumnIndex("title");
cursor2.moveToFirst();
titles.add("Hello");
while(cursor2 != null){
titles.add(cursor2.getString(titleIndex));
arrayAdapter.notifyDataSetChanged();
cursor2.moveToNext();
}
}catch (Exception e){
e.printStackTrace();
}
}
public class DownloadIDs extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM ids", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
JSONArray ids = new JSONArray(s);
for (int i = 0; i < ids.length(); i++) {
myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public class DownloadContent extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content(id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
cursor = myDatabase.rawQuery("SELECT COUNT(*) FROM content", null);
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!(count > 0)) {
JSONObject jsonObject = new JSONObject(s);
String title = jsonObject.getString("title");
Log.i("title", title);
String url = jsonObject.getString("url");
Log.i("url", url);
myDatabase.execSQL("INSERT INTO content (title, url) VALUES('" + title + "','" + url + "')");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Got it! I fixed it. I just had to reduce the amount of news (I decided to choose the top 20 ones), and I decided to run only one ASyncTask on my app.
Here is the edited code:
PD: Thanks to #cafebabe1991 as he gave me tips on how to fix it. Thanks!
public class MainActivity extends AppCompatActivity {
ListView listView;
private SQLiteDatabase myDatabase;
ArrayList<String> titles;
ArrayList<String> urls;
ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
titles = new ArrayList<>();
urls = new ArrayList<>();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, titles);
listView.setAdapter(arrayAdapter);
try {
myDatabase = this.openOrCreateDatabase("HackerNews", MODE_PRIVATE, null);
DownloadTask downloadTask = new DownloadTask();
String URL = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
downloadTask.execute(URL);
Cursor cursor = myDatabase.rawQuery("SELECT * FROM content", null);
int titleIndex = cursor.getColumnIndex("title");
int urlIndex = cursor.getColumnIndex("url");
cursor.moveToFirst();
while(cursor!=null){
titles.add(cursor.getString(titleIndex));
urls.add(cursor.getString(urlIndex));
cursor.moveToNext();
}
arrayAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
MainActivity2.url = urls.get(position);
startActivity(intent);
}
});
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String articleInfo = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data >= 0) {
char current = (char) data;
articleInfo += current;
data = reader.read();
}
//myDatabase.execSQL("CREATE TABLE IF NOT EXISTS ids (id INTEGER PRIMARY KEY, urlID VARCHAR)");
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS content (id INTEGER PRIMARY KEY, title VARCHAR, url VARCHAR)");
myDatabase.delete("content", null, null);
JSONArray ids = new JSONArray(articleInfo);
for (int i = 0; i < 20; i++) {
//myDatabase.execSQL("INSERT INTO ids (urlID) VALUES ('" + ids.getString(i) + "')");
String articleInfo2 = "";
URL url2 = new URL("https://hacker-news.firebaseio.com/v0/item/" + ids.getString(i) + ".json?print=pretty");
HttpURLConnection urlConnection2 = (HttpURLConnection) url2.openConnection();
InputStream inputStream2 = urlConnection2.getInputStream();
InputStreamReader reader2 = new InputStreamReader(inputStream2);
int data2 = reader2.read();
while (data2 >= 0) {
char current2 = (char) data2;
articleInfo2 += current2;
data2 = reader2.read();
}
JSONObject jsonObject = new JSONObject(articleInfo2);
String title = "'" + jsonObject.getString("title").replaceAll("'", "") + "'";
String articleURL = "'" + jsonObject.getString("url") + "'";
myDatabase.execSQL("INSERT INTO content (title, url) VALUES (" + title + "," + articleURL + ")");
}
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
The problem lies in this code
1.)
Cursor cursor1 = myDatabase.rawQuery("SELECT * FROM ids", null);
int index = cursor1.getColumnIndex("urlID");
cursor1.moveToFirst();
while (cursor1 != null) {
String newUrl = "https://hacker-news.firebaseio.com/v0/item/" + cursor1.getString(index) + ".json?print=pretty";
new DownloadContent().execute(newUrl);
cursor1.moveToNext();
}
How ?
You say to to cursor to get you the column index and from that you fetch the item id, but when database is empty the value will be null. Hence the api will not return a response. Additionally you do the same mistake with the cursor as mentioned in the point below.
2.)
int titleIndex = cursor2.getColumnIndex("title");
cursor2.moveToFirst();
titles.add("Hello");
while(cursor2 != null){
titles.add(cursor2.getString(titleIndex));
arrayAdapter.notifyDataSetChanged();
cursor2.moveToNext();
}
How ?
You said to the cursor to move to the first record (moveToFirst()) , what if the currently no record exist. This method returns false if the cursor is empty. So make sure that this method returns true and then proceed.
OR
Do this(Better approach)...
while(cursor.moveToNext()) {
//If inside , that means you are on the next record.Fetch the column values here
}
References :
Cursor methods
Discussion about best ways to iterate a cursor
For loading data into the listview from the database
Am working for first time with SQLite on android and i have some trouble , so what i want to do is insert a date into my DB,
then onCLickLinsten to insert then retrieve the data to sent them to another activity, just tryed this to understand and practice it, here is the second part of my code:
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue;
private static final String URL = "http://192.168.1.104/sync_adapter.php";
private StringRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase myDB= null;
final String TableName = "Personne";
final String[] name1 = new String[1];
final EditText edi1 = (EditText) findViewById(R.id.edittext1);
final TextView text1 = (TextView) findViewById(R.id.textview1);
Button btn = (Button) findViewById(R.id.button);
Button btn2 = (Button) findViewById(R.id.button2);
myDB = this.openOrCreateDatabase("namesDB", MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (id INT(3),name VARCHAR );");
final SQLiteDatabase finalMyDB = myDB;
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String text2 = edi1.getText().toString();
requestQueue = Volley.newRequestQueue(MainActivity.this);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray contacts = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
contacts = jsonObject.getJSONArray("result");
JSONObject c = contacts.getJSONObject(0);
final String name = c.getString("nom");
Toast.makeText(MainActivity.this, "Mr "+name+" ID: "+text2, Toast.LENGTH_SHORT).show();
text1.setText(""+name);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
}){
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<String, String>();
hashMap.put("text2",text2);
return hashMap;
}
};
requestQueue.add(request);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalMyDB.execSQL("INSERT INTO "
+ TableName
+ " (id, name)"
+ " VALUES ('text2' ,'name');");
Cursor c = finalMyDB.rawQuery("SELECT name FROM " + TableName , null);
int Column1 = c.getColumnIndex("name");
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
name1[0] = c.getString(Column1);
}
while(c.moveToNext());
}
Intent i = new Intent(MainActivity.this,ResultActivity.class);
i.putExtra("name1", name1[0]);
startActivity(i);
}
});
}
am i doing it right ? thank's for help