Not fetching all images from json - android

I have two images in JSONArray. First is an image and other is thumbnail of a video. The thumbnail is showing but the image does not appears. I'm unable to understand what's the problem. I would be pleased to have any help to properly fetch the json.
public class MainActivity extends AppCompatActivity {
private GridView mGridView;
private GridItem newItem;
private GridViewAdapter mGridAdapter;
private ArrayList<GridItem> mGridData;
public static final String KEY_USERID = "user_id";
private static final String REGISTER_URL = "http://xxx.xxx.xxx.xxx:8001/api/userlog/fetch/";
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = (GridView)findViewById(R.id.gridView);
registerUser();
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter(this, R.layout.profile_gridview_item, mGridData);
mGridView.setAdapter(mGridAdapter);
}
///////////////////////////////////////// Volley Method Starts //////////////////////////////////////////////////////////////////
private void registerUser(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
System.out.println(jObj);
String status = jObj.getString("status");
// Now check status value
if (status.equals("0")) {
Toast.makeText(getApplicationContext(), "There was some error! Please try again.", Toast.LENGTH_LONG).show();
}else if(status.equals("1")){
JSONArray result = jObj.getJSONArray("results");
for(int i = 0 ; i <result.length() ; i++){
JSONObject json_data = result.getJSONObject(i);
newItem = new GridItem();
String image = json_data.getString("log_file");
String date = json_data.getString("create_day");
String month = json_data.getString("create_month");
newItem.setImage(image);
newItem.setDate(date);
newItem.setMonth(month);
mGridData.add(newItem);
}
mGridAdapter.setGridData(mGridData);
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERID, "1");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
///////////////////////////////////////// Volley Method Ends ////////////////////////////////////////////////////////////////////
}

Related

while sending array from android to server 1st element sets at server side 0 value but in android it sets correct value what is the solution

server data
android data
I am passing arraylist of srid of all element and post to server using volley request.enter image description here
here is the code
public class AttendenceShowStdList extends AppCompatActivity {
ActivityAttendenceShowStdListBinding AttendenceShowStdList;
ArrayList<AttStdListModel> userlist = new ArrayList<>();
ArrayList<AllStdListsrIdAdmIdModel> list= new ArrayList<>();
ArrayList<AllStdListModel> stdlist = new ArrayList<>();
AttStdListAdapter adapter;
private DatePickerDialog datePickerDialog;
private String date,clid,sectionId,yrId,instId,usid,usType,attdate;
SharedPreferences sharedPreferences_teach;//staff shareprefferece for profile fetch
private static final String SHARED_PREF_NAME_TEACH="myprefteach";
private static final String Key_USID_TEACH = "techusid";
private static final String Key_INSTID_TEACH = "techinstid";
private static final String Key_USTYPE_TEACH = "techustype";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AttendenceShowStdList= ActivityAttendenceShowStdListBinding.inflate(getLayoutInflater());
setContentView(AttendenceShowStdList.getRoot());
sharedPreferences_teach =getSharedPreferences(SHARED_PREF_NAME_TEACH, Context.MODE_PRIVATE);
instId=sharedPreferences_teach.getString(Key_INSTID_TEACH,null);
usid=sharedPreferences_teach.getString(Key_USID_TEACH,null);
usType=sharedPreferences_teach.getString(Key_USTYPE_TEACH,null);
//getting data from TakeAttendenceAdapter cardview
clid=getIntent().getExtras().getString("ClassId");
sectionId=getIntent().getExtras().getString("sectionId");
Log.d("cliddd",clid);
yrId=getIntent().getExtras().getString("YearId");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
date = sdf.format(new Date());
Log.d("dttt",date);
userlist = (ArrayList<AttStdListModel>) getModel(false);
adapter = new AttStdListAdapter(this,userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
AttendenceShowStdList.rvstdlist.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
// recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
// recyclerView.setHasFixedSize(true);
getData();
//toolbar
setSupportActionBar(AttendenceShowStdList.toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
AttendenceShowStdList.submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitAttendence();
// Intent intent = new Intent(AttendenceShowStdList.this,SubmitAttendenceActivity.class);
// startActivity(intent);
}
});
}
private List<AttStdListModel> getModel(boolean isSelect){
List<AttStdListModel> list = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
AttStdListModel model = new AttStdListModel();
model.setSelected(isSelect);
// model.setStud_name(String.valueOf(list.get(i)));
model.setAdmi_id(String.valueOf(list.get(i)));
list.add(model);
}
return list;
}
private void getData() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/get_studteachers_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
JSONArray jsonArray5=respObj.getJSONArray("studatt_details");
Log.d("std details",jsonArray5.toString());
for(int i=0;i<jsonArray5.length();i++){
JSONObject jsonObject=jsonArray5.getJSONObject(i);
String sr_id=jsonObject.optString("sr_id");
String admi_id=jsonObject.optString("admi_id");
String stud_name=jsonObject.optString("stud_name");
String stud_phone=jsonObject.optString("stud_phone");
String stud_email=jsonObject.optString("stud_email");
String attd_status=jsonObject.optString("attd_status");
String attd_reason=jsonObject.optString("attd_reason");
userlist.add(new AttStdListModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
Log.d("s", String.valueOf(userlist));
list.add(new AllStdListsrIdAdmIdModel(sr_id,admi_id,stud_name,stud_phone,stud_email,
attd_status,attd_reason));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new AttStdListAdapter(getApplicationContext(),userlist);
AttendenceShowStdList.rvstdlist.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("get_studattd","1");
params.put("us_id",usid);
params.put("inst_id",instId);
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("stud_attend_date",date);
return params;
}
};
queue.add(request);
}
//submit attendence
private void submitAttendence() {
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String url1="https://comzent.in/wonderschoolerp/apis/teacher/take_studteacher_att.php";
StringRequest request = new StringRequest(Request.Method.POST, url1, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Toast.makeText(getContext(), "Data added to API", Toast.LENGTH_SHORT).show();
try {
JSONObject respObj = new JSONObject(response);
String msg=respObj.getString("message");
Toast.makeText(AttendenceShowStdList.this, msg, Toast.LENGTH_LONG).show();
Log.d("response msg",msg);
if(msg.equals("Attendance Generated Successfully..!")){
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Fail to get response = " + error, Toast.LENGTH_LONG).show();
Log.d("error msg", String.valueOf(error));
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
ArrayList<String> allstdsrid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdsrid.add(String.valueOf(list.get(i).getSr_id()));
}
params.put("sr_id", String.valueOf(allstdsrid));
Log.d("params", String.valueOf(params));
Log.d("allstudentsrid", String.valueOf(allstdsrid));
ArrayList<String> allstdadmid = new ArrayList<String>();
for(int i=0; i < list.size(); i++) {
allstdadmid.add(list.get(i).getAdmi_id());
params.put("admission_id", String.valueOf(allstdadmid));
}
Log.d("allstudentsadmid", String.valueOf(allstdadmid));
///selected student list
ArrayList<String> attstd = new ArrayList<String>();
for (int i = 0; i < AttStdListAdapter.userlist.size(); i++) {
if (AttStdListAdapter.userlist.get(i).getSelected()) {
attstd.add(AttStdListAdapter.userlist.get(i).getAdmi_id());
}
}
params.put("student_attend_submit","1");
params.put("class_id",clid);
params.put("sec_id",sectionId);
params.put("ay_id",yrId);
params.put("att_status", String.valueOf(attstd));
Log.d("params", String.valueOf(params));
params.put("stud_attend_date",date);
params.put("inst_id",instId);
params.put("us_id",usid);
params.put("us_type",usType);
return params;
}
};
queue.add(request);
}
//toolbar back to home
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
After submitting attendance, values of array of srid and admid retrive at server correctly ,problem is that only first record's srid and admid sets to '0' value.There is no problem when same Api is fetch on postman.

android org.json.JSONArray cannot be converted to JSONObject (can not display the url)

I am new in android I work on a webservice application and the backend in laravel ,I want to read the trades and according to the job I find the tasks but I can not display the data it shows me this error msg ..
"org.json.JSONArray cannot be converted to JSONObject"
public static final String TacheNamearray = "libelle_tache";
public static final String TacheName = "libelle_tache";
public static final String JSON_ARRAY_TACHE = "result";
public static final String MetierNamearray = "libelle_metier";
public static final String MetierName = "libelle_metier";
public static final String JSON_ARRAY = "result";
private JSONArray result;
private ArrayList<String> arrayListTache;
TextView tacheename;
Spinner spinner_tache;
Spinner spinner;
Button button;
private GpsTracker gpsTracker;
private TextView tvLatitude,tvLongitude;
String URL_Post = "http://192.168.1.233/projet/public/api/getmetier";
private ArrayList<String> arrayList;
TextView employeename;
private TextView tvUsername, tvEmail;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recherche);
spinner= (Spinner) findViewById(R.id.spnrEmployee);
spinner_tache= (Spinner) findViewById(R.id.spnrTache);
tacheename= (TextView) findViewById(R.id.tvTache);
employeename= (TextView) findViewById(R.id.tvName);
button = (Button) findViewById(R.id.button);
tvLatitude = (TextView)findViewById(R.id.latitude);
tvLongitude = (TextView)findViewById(R.id.longitude);
arrayListTache = new ArrayList<String>();
userInfo = new UserInfo(this);
tvEmail = (TextView)findViewById(R.id.key_email);
String email = userInfo.getKeyEmail();
tvEmail.setText(email);
arrayList = new ArrayList<String>();
getMetiers();
spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
//Setting the values to textviews for a selected item
String metier= arrayList.get(position);
getTaches(metier);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
employeename.setText("");
}
});
}
private void getMetiers() {
StringRequest stringRequest = new
StringRequest("http://192.168.1.233/projet/public/api/getmetier",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
empdetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void empdetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList.add(json.getString(MetierNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
}
// arrayList.add(0,"Select Employee");
spinner.setAdapter(new ArrayAdapter<String>(RechercheActivity.this,
android.R.layout.simple_spinner_dropdown_item, arrayList));
}
//Method to get student name of a particular position
private String getemployeeName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(MetierName);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
public void getLocation(View view){
gpsTracker = new GpsTracker(RechercheActivity.this);
insert();
if(gpsTracker.canGetLocation()){
double latitude = gpsTracker.getLatitude();
double longitude = gpsTracker.getLongitude();
tvLatitude.setText(String.valueOf(latitude));
tvLongitude.setText(String.valueOf(longitude));
}else{
gpsTracker.showSettingsAlert();
}
Intent intent = new Intent(RechercheActivity.this,
TechnicienActivity.class);
startActivity(intent);
}
public void insert(){
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_Post, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplication(),response,Toast.LENGTH_LONG).show();
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RechercheActivity.this,error+"",Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String,String>getParams()throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
String text1 = spinner.getSelectedItem().toString();
String lon = tvLongitude.getText().toString().trim();
String lat = tvLatitude.getText().toString().trim();
params.put("libelle_metier",text1);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getTaches(String metier) {
StringRequest stringRequest = new
StringRequest("http://192.168.1.233/projet/public/api/gettaches",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result= j.getJSONArray(JSON_ARRAY_TACHE);
tachedetails(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void tachedetails(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayListTache.add(json.getString(TacheNamearray));
} catch (JSONException e) {
e.printStackTrace();
}
// arrayListTache.add(0,"Select Employee");
spinner_tache.setAdapter(new ArrayAdapter<String>
(RechercheActivity.this,
android.R.layout.simple_spinner_dropdown_item, arrayListTache));
}
//Method to get student name of a particular position
private String gettacheName(int position){
String libelle_tache="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
libelle_tache = json.getString(TacheName);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return libelle_tache;
}
and the JSON part gives me that ..
[{"id":1,"libelle_metier":"metier 1","deleted_at":null,"created_at":"2018-04-03 09:12:37","updated_at":"2018-04-03 09:12:37"},{"id":2,"libelle_metier":"metier 2","deleted_at":null,"created_at":"2018-04-03 09:12:44","updated_at":"2018-04-03 09:12:44"},{"id":3,"libelle_metier":"metier 4","deleted_at":null,"created_at":"2018-04-03 09:46:36","updated_at":"2018-04-04 14:15:06"}]
and my PHP code and
class TechniciensController extends Controller
{
public function GetTechniciens()
{
return Technicien::all();
}
return json_encode(Technicien::all());
then you can use json_decode.
this line :
j = new JSONObject(response);
update it:
JSONArray jsonarray = new JSONArray(response);
i think it's works.

how can i display google nearbyplace api images response in listview?

I am using json volley to for getting information from google api.I know how to display text in listview but dont know how to display images because they are in string form i really dont know how to convert that string into image and display in listview . here is my code
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView lst_1;
Button btn_one;
String url;
ArrayList<CostumAdapter> contactList;
private ProgressDialog progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
contactList = new ArrayList<>();
lst_1 = (ListView) findViewById(R.id.lst_1);
btn_one = (Button) findViewById(R.id.btn_1);
btn_one.setOnClickListener(this);
}
public void Progress() {
progress = new ProgressDialog(this);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setMessage("Loading");
progress.show();
}
private void jsonfunction() {
Progress();
url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?" +
"location=-33.8670522,151.1957362&" +
"radius=500&" +
"type=restaurant&" +
"key=AIzaSyAG5Fndg4wPzs81FNv5-Ycl7GDlAdqeIaI" +
"&sensor=true";
Log.e("url", url);
final StringRequest stringrequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
try {
JSONObject jsonobj = new JSONObject(response);
JSONArray jsonArray = jsonobj.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONArray jsonArray2 = object.getJSONArray("photos");
for (int a = 0; a < jsonArray2.length(); a++) {
JSONObject object2 = jsonArray2.getJSONObject(a);
contactList.add(new CostumAdapter(
jsonArray.getJSONObject(i).getString("name"),
object2.getString("photo_reference")
));
}
}
Log.e("response in a", String.valueOf(contactList));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, "error in jason", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
function();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "error in ErrorListener", Toast.LENGTH_LONG).show();
}
});
singalton.getinstance(MainActivity.this).addtorequestque(stringrequest);
}
public void function() {
CustomListAdapter adapter = new CustomListAdapter(getApplicationContext(), R.layout.custumlistview, contactList);
lst_1.setAdapter(adapter);
}
#Override
public void onClick(View v) {
jsonfunction();
}
}

cannot find symbol method getJSONArray(String) Volley

hi everyone i am working on a android project where i have to retrive the data form JSON. here is my link
I am trying to get the data using the below code
public class DisplayUser extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_user);
textViewResult = (TextView) findViewById(R.id.check_data_id); // in this text view i will display the text
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = statics_demo.USER_URL+"7";// this is fixed url where i am getting the data
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayUser.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
JSONObject result;
private void showJSON(String response) {
try {
JSONArray obj = response.getJSONArray("responseMs");
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
String name = jsonObject.getString("name");
System.out.println("luckyyyyyy"+name);
// String type = jsonObject.getString("type");
// retrieve the values like this so on..
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
When i run the code i am getting a erorr saying
"Error:(60, 37) error: cannot find symbol method getJSONArray(String)"
String s = "[]"; JsonParser parser = new JsonParser(); JsonElement tradeElement = parser.parse(s); JsonArray trade = tradeElement.getAsJsonArray();
you need to convert string to jsonarray first

ListView not getting updated , where should I call notifyDataSetChanged() and where should i set the adapter?

I have written a program to post some json data and get the same json data so that i can show the data in a ListView in the same activity.
Posting the data and getting the data is done with the help of volley library.
So my problem is when I type something inside my EditText and click on the button to post some data , the data gets posted but I am not able to view it instantly inside my ListView , in short data is not getting refreshed instantly inside my ListView.I have also tried using notifyDataSetChanged() but all in vain.
I am posting my whole activity here , please tell me where exactly i have to set my adapter , my ArrayList and the notifyDataSetChanged()
public class Write_Answers extends ListActivity{
Boolean isInternetPresent = false;
ConnectionDetector cd;
TextView txtQuestions;
String questions;
EditText editAnswers;
Button btnAnswer;
String postAnswerUrl = "";
String getAnswerUrl = "";
public String answers;
SessionManager session;
String userType,deviceId,questionId;
ListView lvAnswers;
public static final String TAG_QUESTION_ID = "QId";
public static final String TAG_TRANSACTION_ID = "TransactionId";
public static final String TAG_ANSWERS = "Answer";
public static final String TAG_DATE= "Date";
public static final String TAG_TIME = "Time";
public static final String TAG_DEVICE_ID = "DeviceId";
public static final String TAG_USER_TYPE = "UserType";
ArrayList<HashMap<String, String>> answersList;
CustomAnswerAdapter customAnswerAdapter;
HashMap<String,String> ans_details_map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.write_answers);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
txtQuestions = (TextView) findViewById(R.id.textQuestions);
editAnswers = (EditText) findViewById(R.id.edtAnswer);
btnAnswer = (Button) findViewById(R.id.btnAnswer);
questions = getIntent().getStringExtra("questions");
txtQuestions.setText(questions);
answersList = new ArrayList<HashMap<String, String>>();
customAnswerAdapter = new
CustomAnswerAdapter(Write_Answers.this,answersList);
lvAnswers = getListView();
lvAnswers.setAdapter(customAnswerAdapter);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
questionId = getIntent().getStringExtra("questionsId");
postAnswerUrl = "http://gps.traxistar.net/PostAnswers.svc/PostAnswers";
getAnswerUrl = "http://gps.traxistar.net/GetAnswers.svc/GetAnswers;
////////////////////////// get the data from the server the ones which i have to set to the adapter and show in the Listview ///////////////////////
if (isInternetPresent) {
JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(getAnswerUrl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Json Array", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject json = response.getJSONObject(i);
String ques_id =
json.getString(TAG_QUESTION_ID);
String trans_id =
json.getString(TAG_TRANSACTION_ID);
String device_id =
json.getString(TAG_DEVICE_ID);
String ans = json.getString(TAG_ANSWERS);
String answerDate =
json.getString(TAG_DATE);
String answerTime =
json.getString(TAG_TIME);
String userType =
json.getString(TAG_USER_TYPE);
ans_details_map = new HashMap<String,
String>();
ans_details_map.put(TAG_ANSWERS, ans);
ans_details_map.put(TAG_DATE, answerDate);
ans_details_map.put(TAG_TIME, answerTime);
answersList.add(ans_details_map);
}
} catch (Exception e) {
e.printStackTrace();
}
customAnswerAdapter.notifyDataSetChanged();
lvAnswers.setSelection(answersList.size() - 1);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley Error", "Error: " + error.getMessage());
Log.d("Error", "Error: " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
} else {
showAlertDialog(getApplicationContext(), "No Internet Connection",
"You don't have internet connection.",
false);
}
btnAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
answers = editAnswers.getText().toString();
if (answers.equals("")) {
Toast.makeText(getBaseContext(), "Please write an answer",
Toast.LENGTH_LONG).show();
} else {
if (isInternetPresent) {
postAnswers();
editAnswers.setText("");
} else {
showAlertDialog(getApplicationContext(), "No Internet
Connection", "You don't have internet connection.",
false);
}
}
}
});
}
////////////////////////////// posting the data to the server on button click ////////////////////////////
private void postAnswers() {
Calendar in = Calendar.getInstance();
Date dt1 = new Date();
in.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
SimpleDateFormat sdf1 = new SimpleDateFormat("E, MMM d, yyyy");
String dateval = sdf1.format(dt1);
SimpleDateFormat stf1 = new SimpleDateFormat("h:mm a");
String timeval = stf1.format(dt1);
final String date1 = dateval.toString();
final String time1 = timeval.toString();
final String datetime = dateval.toString() + "T"
+ timeval.toString();
final String transId = deviceId + "" + datetime;
answers = editAnswers.getText().toString();
List<Map<String, String>> listMap =
new ArrayList<Map<String, String>>();
Map<String, String> answersMap = new HashMap<String, String>();
answersMap.put("TransactionId", transId);
answersMap.put("DeviceId", deviceId);
answersMap.put("Answer", answers);
answersMap.put("QId", questionId);
answersMap.put("Date", date1);
answersMap.put("Time", time1);
answersMap.put("UserType", userType);
listMap.add(answersMap);
JsonObjectRequest jsObjRequest = new
JsonObjectRequest(Request.Method.POST, postAnswerUrl,
String.valueOf(new JSONArray(listMap)), new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Write_Answers.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Answer
posted", Toast.LENGTH_LONG).show();
}
});
Log.d("Json Response ",response.toString());
}catch(Exception e){
//Log.d("JSON Array", response.toString());
e.printStackTrace();
}
//editAnswers.setText("");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley Error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-type", "application/json; charset=utf-8");
return headers;
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse
response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
if (response.data == null || response.data.length == 0) {
return Response.success(new JSONObject(),
HttpHeaderParser.parseCacheHeaders(response));
} else {
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
}
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
};
AppController.getInstance().addToRequestQueue(jsObjRequest);
}
An ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.
When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.
I recommend using the the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Any type of update (remove/edit/add) you want to do
(on Post Button click do your posting after that these steps)
1. update your ArrayList first
2. remove all views from ListView with previous ArrayList data
3. call the adapter again with the updated ArrayList again
hope this helps you.
Try calling notifyDatasetChanged() like this:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
customAnswerAdapter.notifyDataSetChanged();
}
}, 3000);
and check whether this is working

Categories

Resources