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) {
}
});
Related
I am new in android java world. Now, I'm trying to display data table from MSSQL in ArrayList to ListView in android. I'm trying to make the following code something like this in ScanResult Class;
public class FillList extends AsyncTask<String,String,String>{
String z ="";
List<Map<String,String>> prolist = new ArrayList<Map<String,String>>();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String s) {
Toast t = Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT);
t.show();
}
#Override
protected String doInBackground(String... strings) {
try{
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connectionclass();
if(connect==null){
z ="Connection error";
} else {
String query = "SELECT LabelNo " +
", Qty " +
", Rmrks " +
", ScanDate " +
"FROM dbo.shikakarikensa " +
"WHERE CAST(ScanDate AS DATE) = CAST(GETDATE()-1 AS DATE) " +
"AND Type = 'I' " +
"ORDER BY ScanDate DESC";
PreparedStatement ps = connect.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
CustomListViewValueArr.add(new ScanModel(rs.getString("LabelNo"),rs.getInt("Qty"),rs.getString("Rmrks"),rs.getString("ScanDate")));
}
z="Today's scan result list";
}
} catch (Exception ex){
z = ex.getMessage();
}
return z;
}
}
But I get an error Cannot resolve method 'setText(java.sql.Date)' in the CustomAdapter Class, which is in the line;
holder.txtscandate.setText(scanModel.getScanDate());
scanModel = null;
scanModel=(ScanModel) mList.get(position);
holder.txtlabelno.setText(scanModel.getLabelNo());
holder.txtqty.setText(scanModel.getQty());
holder.txtrmrks.setText(scanModel.getRmrks());
holder.txtscandate.setText(scanModel.getScanDate());
I tried also comment the ScanDate line but the data does not showing in the ListView.
This is Model Class
public class ScanModel {
String LabelNo, Rmrks;
int Qty;
Date ScanDate;
public ScanModel(String labelno, int qty, String rmrks, Date scandate) {
LabelNo = labelno;
Qty = qty;
Rmrks = rmrks;
ScanDate = scandate;
}
public String getLabelNo() { return LabelNo; }
public int getQty() { return Qty; }
public String getRmrks() { return Rmrks; }
public Date getScanDate() { return ScanDate; }
}
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
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.
I have created a custom list view with 6 colomns. Each row is populated.
the first 3 fields are textviews,which are filled from db. Then a spinner and the last two edittexts.
i want to enter values to edittexts and spinner.. this much is ok.
The problem is when i enter values in edittext and after that if i scroll the list, the values entered in edittext changes in position. if i entered in first row, after scrolling it will be in last row or any other.. how i can solve this.. Need help pls..
My adapter class is given below.
public class CustomTransAdapter extends BaseAdapter {
public ArrayList<retrieveTrans> ret_arrArrayList;
private List<retrieveTrans> ret_translist;
private LayoutInflater inflater;
ArrayAdapter<String> adapterspin;
String time, currntdate, status;
String Maxcramnt, balamount;
double Mamount, Bamount, actualamnt;
String idpref, str_agent_id2, accno;
int trcheck;
int d = 0;
String tramnt = "", remarks = "";
Context context;
int count;
public CustomTransAdapter(NewTransactionSheet newTransactionSheet,
int transListPop, List<retrieveTrans> translist) {
// TODO Auto-generated constructor stub
super();
this.ret_translist = translist;
inflater = LayoutInflater.from(newTransactionSheet);
this.ret_arrArrayList = new ArrayList<retrieveTrans>();
this.ret_arrArrayList.addAll(translist);
this.context = newTransactionSheet;
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
newTransactionSheet, android.R.layout.simple_spinner_item,
items);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return ret_translist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return ret_translist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView acc_txt, name_txt, balAmnt_txt;
Spinner trans_spinner;
EditText transAmnt_edittxt, remarks_edittxt;
Button save;
}
#Override
public View getView(final int pos, View cv, ViewGroup arg2) {
// TODO Auto-generated method stub
try {
final ViewHolder holder;
View row = cv;
int p = pos;
Log.e("position of getview:", "" + p);
if (cv == null) {
cv = inflater.inflate(R.layout.trans_pop_list, null);
holder = new ViewHolder();
holder.acc_txt = (TextView) cv
.findViewById(R.id.txtTransAccNo_pop);
holder.name_txt = (TextView) cv
.findViewById(R.id.txtTransName_pop);
holder.balAmnt_txt = (TextView) cv
.findViewById(R.id.txtTransBalAmnt_pop);
holder.trans_spinner = (Spinner) cv
.findViewById(R.id.spinTrans_Type);
holder.transAmnt_edittxt = (EditText) cv
.findViewById(R.id.editTransAmnt_pop);
holder.save = (Button) cv.findViewById(R.id.save);
holder.remarks_edittxt = (EditText) cv
.findViewById(R.id.editRemarks_pop);
cv.setTag(holder);
} else {
holder = (ViewHolder) cv.getTag();
}
holder.acc_txt.setText("" + ret_translist.get(pos).getRetAccNo());
String hari = holder.acc_txt.getText().toString();
holder.name_txt.setText("" + ret_translist.get(pos).getRetName());
holder.balAmnt_txt.setText(""
+ ret_translist.get(pos).getRetBalAmnt());
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, items);
final String haris = holder.name_txt.getText().toString();
holder.trans_spinner.setAdapter(adapterspin);
/* ******************* Save button Click **************** */
holder.save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int position = pos;
final String accno = holder.acc_txt.getText().toString();
final String tramnt = holder.transAmnt_edittxt.getText()
.toString();
String remarks = holder.remarks_edittxt.getText()
.toString();
final String spinner = holder.trans_spinner
.getSelectedItem().toString();
Log.e("accno:", "" + accno);
Log.e("name :", "" + tramnt);
Log.e("position:", "" + position);
Log.e("remark:", "" + remarks);
Log.e("spinner:", "" + spinner);
/****************** time and date **********************/
// ----------Time----------
Calendar c = Calendar.getInstance();
time = (c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE)
+ ":" + c.get(Calendar.SECOND));
Log.e("Current Time", " " + time);
// -----------Date---------
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
currntdate = new SimpleDateFormat("M-d-yyyy").format(now);
Log.e("Date ", " " + currntdate);
status = new String("y");
if (tramnt.equals("")) {
Toast.makeText(arg0.getContext(),
"enter Transaction amount", 5000).show();
Log.e("if cndition", " " + tramnt);
} else if (spinner.equals("type")) {
Toast.makeText(arg0.getContext(),
"enter Transaction type", 5000).show();
Log.e("if cndition", " " + tramnt);
}
else {
if (remarks.equals("")) {
remarks = "null";
}
/************ declaration for dbcall *********************/
AccountDBAdapter db = new AccountDBAdapter(context);
NewTransactionSheet ts = new NewTransactionSheet();
try {
db.open();
String accid = db.getAccID(accno);
String Maxcramnt = db.getMaxCrAmnt(accno);
db.close();
Mamount = Double.parseDouble(Maxcramnt);
Bamount = Double.parseDouble(tramnt);
actualamnt = Mamount - Bamount;
balamount = "" + actualamnt;
db.open();
db.close();
/* Log.e("c value", " " +actualamnt); */
Log.e("tramnt", " " + tramnt);
Log.e("if cndition out", " " + tramnt);
db.open();
db.update_MaxCrAmnt(balamount, accid);
db.close();
actualamnt = 0;
db.open();
String userId = "" + 2;
db.insertTransactionTable(accid.toString(),
currntdate.toString(), spinner.toString(),
tramnt.toString(), userId.toString(),
time.toString(), remarks.toString(),
status.toString());
db.close();
holder.save.setText("SAVED");
holder.save.setBackgroundColor(Color.DKGRAY);
// }
} catch (Exception e) {
Log.e("error", e.getMessage());
}
}
}
});
} catch (Exception c) {
Log.e("adapter error", "" + c.getMessage());
}
return cv;
}
}
Working on this for many days... need help.. Thanks in advance.
I'm obviously missing something in making this custom adapter. Basically, I've got code that grabs JSON from the site, then breaks it down into a ArrayList. I can do a .toString() and spit it all out onto a listview just fine, but everything I find on the net for creating a custom adapter creates the list inside of it. Is there a way to just supply your pre-created list? I've yet to make any headway on getting the custom one to work...but, as I said I can get the string to work just fine, so I'll include that code.
Here's my classes:
public class JSONEvents {
String eid;
String bid;
private String bname;
private String valid;
#Override
public String toString() {
return "Events [eid=" + eid + ", bid=" + bid + ", bname=" + bname
+ ", start=" + start + ", end=" + end + ", points=" + points
+ ", title=" + title + ", description=" + description
+ ", cat=" + cat + ", type=" + type + ", subtype=" + subtype
+ ", valid=" + valid + "]";
}
public String getEventInfo(String field){
if("eid".equals(field)){return eid;}
else if("bid".equals(field)){return bid;}
else if("bname".equals(field)){return bname;}
else if("valid".equals(field)){return valid;}
return "none";
}
}
public class JSONAdventures {
private String aid;
private String bid;
private String start;
private String valid;
#Override
public String toString() {
return "Adventures [aid=" + aid + ", bid=" + bid + ", start=" + start
+ ", end=" + end + ", points=" + points + ", title=" + title
+ ", description=" + description + ", cat=" + cat + ", type="
+ type + ", subtype=" + subtype + ", steps_comp=" + steps_comp
+ ", total_steps=" + total_steps + ", valid=" + valid + "]";
}
public String getEventInfo(String field){
if("aid".equals(field)){return aid;}
else if("bid".equals(field)){return bid;}
else if("start".equals(field)){return start;}
else if("valid".equals(field)){return valid;}
return "none";
}
}
public class JSONEandA {
private ArrayList<JSONEvents> events;
private ArrayList<JSONAdventures> adventures;
#Override
public String toString() {
return "ResponseHolder [events=" + events + ", adventures="
+ adventures + "]";
}
public ArrayList<JSONEvents> getJSONEvents() {
return events;
}
public ArrayList<JSONAdventures> getJSONAdventures() {
return adventures;
}
}
For the code in m activity:
List<JSONEvents> eventlist = new ArrayList<JSONEvents>();
try {
Gson googleJson = new Gson();
JSONEandA rh = googleJson.fromJson(example,
JSONEandA.class);
for (JSONEvents e : rh.getJSONEvents()) {
eventlist.add(e);
//eventlist.addAll(e);
// System.out.println(e.toString());
System.out.println(e.getEventInfo("eid"));
System.out.println(e.toString());
}
final ListView listview = (ListView) findViewById(R.id.eventlistview);
String[] values = new String[eventlist.size()];
eventlist.toArray(values);
// String[] values = new String[] {e.toString()};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(
Events.this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
final View view, int position, long id) {
final String item = (String) parent
.getItemAtPosition(position);
list.remove(item);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
"Item Removed", Toast.LENGTH_LONG).show();
});
I've also pieced together an attempt at an adapter from various tutorials and such, but can't figure out how to tie it all together:
class EventAdapter extends ArrayAdapter<JSONEvents> {
private ArrayList<JSONEvents> items;
public EventAdapter(Context context, int textViewResourceId,
ArrayList<JSONEvents> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_events, null);
}
JSONEvents q = items.get(position);
if (q != null) {
TextView nameText = (TextView) v.findViewById(R.id.firstline);
TextView priceText = (TextView) v.findViewById(R.id.secondLine);
if (nameText != null) {
nameText.setText(q.getEventInfo("eid"));
}
if (priceText != null) {
priceText.setText(q.getEventInfo("bid"));
}
}
return v;
}
}
I would appreciate any help, thanks!
Did you put tha data into your adapter?
adapter.addAll(String[] data);
Or you could do it while creating adapter:
EventAdapter adapter = new EventAdapter(this, R.id.some_id, eventlist);