Listview not updated in android after spinner selection - android

hello guys i am working an app where i want to update my listview but everything is working perfect only list view is not updated i don't understand where i am doing wrong help me
code is
public class MainActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
private Spinner spinner;
private ArrayList<String> students;
private JSONArray result;
CallbackManager callbackManager;
ShareDialog shareDialog;
// listveiw data
private static final String TAG = MainActivity.class.getSimpleName();
String url = "http://www.example.com/json/json.php";
private ProgressDialog pDialog;
private List<Model> movieList = new ArrayList<Model>();
private ListView listView;
private CustomListAdapter adapter;
final Model model = new Model();
final Json_Data j_data = new Json_Data();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
students = new ArrayList<String>();
spinner = (Spinner) findViewById(R.id.txtSpinner);
listView = (ListView) findViewById(R.id.list);
spinner.setOnItemSelectedListener(this);
getData();
listdata();
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final TextView tv_id = (TextView) view.findViewById(R.id.title);
String txt = tv_id.getText().toString();
model.setItemText(txt);
Log.e(TAG, "====>" + txt);
_Dialog_Custom();
}
});
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void listdata(){
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hidePDialog();
Log.e(TAG, response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Model model = new Model();
String status = obj.getString("txt");
String cate = obj.getString("category");
model.setList_category(cate);
model.setTitle(status);
movieList.add(model);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
private void getData() {
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j_obj = null;
try {
j_obj = new JSONObject(response);
result = j_obj.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(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 getStudents(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text_spinner = spinner.getSelectedItem().toString();
//Log.e("Selected value in","==>"+text_spinner);
j_data.setSpintext(text_spinner);
makeJsonArrayRequest();
Toast.makeText(MainActivity.this, "Get Value from spinner" +text_spinner, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private void _Dialog_Custom() {
final Dialog dialog = new Dialog(this);
final String txt1 = model.getItemText().toString();
Log.e("Hello Dialog", ":=>" + txt1);
dialog.setContentView(R.layout.dialogbox);
dialog.setTitle("Share via");
dialog.setCanceledOnTouchOutside(true);
ImageButton _Fb_Sharebtn = (ImageButton) dialog.findViewById(R.id.share_facebook);
_Fb_Sharebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
// https://developers.facebook.com/docs/sharing/android
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription(
"The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
}
});
ImageButton _Sharebtn_google = (ImageButton) dialog.findViewById(R.id.share_btn_google);
_Sharebtn_google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new PlusShare.Builder(MainActivity.this)
.setType("text/plain")
.setText(txt1)
.getIntent();
try {
startActivity(shareIntent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.plus&hl=en")));
}
}
});
ImageButton whtsapp_sahre = (ImageButton) dialog.findViewById(R.id.whatsapp_btn);
whtsapp_sahre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
String result = txt1;
whatsappIntent.putExtra(Intent.EXTRA_TEXT, result);
try {
startActivity(whatsappIntent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.whatsapp")));
}
}
});
ImageButton _Twwiterbtn = (ImageButton) dialog.findViewById(R.id.twwiter_btn);
_Twwiterbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
String result = txt1;
intent.setType("text/plain")
.setPackage("com.twitter.android");
intent.putExtra(Intent.EXTRA_TEXT, result);
try {
startActivity(intent);
} catch (ActivityNotFoundException ex) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.twitter.android&hl=en")));
}
}
});
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
dialog.show();
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent backintent = new Intent(getApplicationContext(), Main_Selected_Activity.class);
startActivity(backintent);
finish();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
private void makeJsonArrayRequest() {
String spinner_data =j_data.getSpintext().toString().trim();
Log.e(TAG, spinner_data.toString());
String arrayurl = "http://www.example.com/jsoncategory.php?category="+spinner_data;
Log.e("Link is here","==>"+arrayurl);
ArrayList<String> newdata = new ArrayList<String>();
movieList = new ArrayList<Model>();
JsonArrayRequest movieReq = new JsonArrayRequest(arrayurl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "link response=>" + response);
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
String name = obj.getString("txt");
model.setList_category(name);
movieList.add(model);
}catch (JSONException e) {
e.printStackTrace();
Log.e("Hello error","==>"+e);
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
}
please help me

Follow The Below approach
Create a public method in your adapter class:
private List<Model> adapterInitialMovieList = null;
public void setDataOnSpinnerSelected(List<Model> movieList){
adapterInitialMovieList = movieList;
notifyDataSetChanged();
}
In Your Activity Class Inside Spinner onClick method:
if(adapter != null){
adapter.setDataOnSpinnerSelected(yourChangedArrayListOfModelClass);
}

use
movieList.clear();
instead of
movieList = new ArrayList<Model>();
The problem is about the creation of a new arraylist. So, the ArrayAdapter do not 'know' you when you want to create a new one ArrayList (with the different address).
In line
adapter = new CustomListAdapter(this, movieList);
you push a some address of arraylist. In a new line later you generates a new arraylist with the different one and work with it. But the adapter works with the 'old variant' of arraylist.

Remove this line from makeJsonArrayRequest() :
movieList = new ArrayList<Model>();
You are assigning a new object(ArrayList) to the movieList and adding values in the new object instead of the one which you passed to the list adapter. Hence the reference of the object which is being used by the list adapter is lost and when you call adapter.notifyDataSetChanged(); there is no updation as the object which is used by the list adapter is unchanged.

Related

RecyclerView does not show anything immediately

I'm trying to fix a problem related to RecyclerView. When I try to show the list of objects for the first time I don't see anything. The data are passed thanks to a volley request that is known to be async. So, I've tried various solutions like onDataSetChanged() but nothing happens. I want to remark that the solution works, the second time I watch the list I can see it without any problems.
Here's my code:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
private static MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
recyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
adapter = new MyAdapter(this,initData());
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
private List<ParentObject> initData() {
TitleCreator titleCreator = TitleCreator.get(this);
List<TitleParent> titles = titleCreator.getAll();
List<ParentObject> parentObject = new ArrayList<>();
for(TitleParent title:titles)
{
List<Object> childList = getList(title);
title.setChildObjectList(childList);
parentObject.add(title);
}
return parentObject;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
((MyAdapter)recyclerView.getAdapter()).onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_enter, R.anim.right_out);
}
private List<Object> getList(final TitleParent title){
final List<Object> childList = new ArrayList<>();
// Tag used to cancel the request
String tag_string_req = "request";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_DASHBOARD, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("POL", "Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
for (int i = 0; i < jObj.getJSONArray("polizze").length(); i++) {
JSONObject user = jObj.getJSONArray("polizze").getJSONObject(i);
String certificate = user.getString("numero_contratto");
if(title.getTitle().contains(certificate)){
String scadenza = user.getString("scadenza");
String totale = user.getString("totale");
childList.add(new TitleChild(scadenza,totale));
}
}
Log.d("TRY", "Response: " + response.toString());
adapter.notifyDataSetChanged();
} 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) {
Log.e("DASH", "Login Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(),
// error.getMessage(), Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return childList;
}
Thank you for your help!
well there are couple of points
get list method returning empty list after made volley request.
make sure list filled data from the server then call the set data.
you have to try something like below.
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
private static MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
recyclerView = (RecyclerView) findViewById(R.id.myRecyclerView);
// show some loading bar
initData();
}
private void initData() {
TitleCreator titleCreator = TitleCreator.get(this);
List<TitleParent> titles = titleCreator.getAll();
List<ParentObject> parentObject = new ArrayList<>();
for(TitleParent title:titles)
{
List<Object> childList = getList(title);
title.setChildObjectList(childList);
parentObject.add(title);
}
}
private void setData(List<ParentObject> parentObject) {
// load the data here
adapter = new MyAdapter(this,parentObject);
adapter.setParentClickableViewAnimationDefaultDuration();
adapter.setParentAndIconExpandOnClick(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
((MyAdapter)recyclerView.getAdapter()).onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.left_enter, R.anim.right_out);
}
private List<Object> getList(final TitleParent title){
final List<Object> childList = new ArrayList<>();
// Tag used to cancel the request
String tag_string_req = "request";
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_DASHBOARD, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("POL", "Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
for (int i = 0; i < jObj.getJSONArray("polizze").length(); i++) {
JSONObject user = jObj.getJSONArray("polizze").getJSONObject(i);
String certificate = user.getString("numero_contratto");
if(title.getTitle().contains(certificate)){
String scadenza = user.getString("scadenza");
String totale = user.getString("totale");
childList.add(new TitleChild(scadenza,totale));
}
setData(childList);
}
Log.d("TRY", "Response: " + response.toString());
} 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) {
Log.e("DASH", "Login Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(),
// error.getMessage(), Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return childList;
}

when i am pressing back button(up button) it is showing "app stopped unfortunately" after using volley

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
but1=(Button)findViewById(R.id.btnlogin);
//
final String Token=getIntent().getExtras().getString("token");
// Toast.makeText(getApplicationContext(),Token, Toast.LENGTH_SHORT).show();
final String firstName=getIntent().getExtras().getString("firstname");
//getting cardview data's
String url =
com.android.volley.toolbox.JsonObjectRequest jsonRequest = new com.android.volley.toolbox.JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
JSONArray obj = response.getJSONArray("result");
int o = obj.length();
Log.v("Length", String.valueOf(o));
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
//listname.add(jsonObject.getString("templateId"));
listehr.add(jsonObject.getString("templateId"));
listdate.add(jsonObject.getString("startTime"));
listtime.add(jsonObject.getString("category"));
// ehrUid.add(jsonObject.getString("ehrUid"));
List<String> compositionUid = new ArrayList<>();
// String startTime = jsonObject.getString("startTime");
// Log.v("startTime",startTime);
}
Log.v("listtime", String.valueOf(listtime.size()));
Log.v("Response", response.toString());
String total = response.getString("total");
Log.v("Total",total);
String result = response.getString("result");
Log.v("Result",result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization",Token);
return headers;
}
};
com.android.volley.toolbox.Volley.newRequestQueue(NavigationActivity.this).add(jsonRequest);
//
You have to send String Values for these two Keys "token","firstname".
final String Token=getIntent().getExtras().getString("token");
final String firstName=getIntent().getExtras().getString("firstname");
If you cant find it send the code snippet of intent in another class.
Punithapriya this is the code for main activity
public class MainActivity extends AppCompatActivity {
TextView t;
private EditText username;
private EditText password;
EditText showPsd;
CheckBox mCbShowPwd;
public Button but1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//login page using json
but1=(Button)findViewById(R.id.btnlogin);
username=(EditText)findViewById(R.id.editText2);
password=(EditText)findViewById(R.id.btnpass);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//validation for login
if(username.getText().toString().length()==0){
username.setError("Username not entered");
username.requestFocus();
}
else if(password.getText().toString().length()==0){
password.setError("Password not entered");
password.requestFocus();
}
//
String url = ;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
Log.v("Hai", response.toString());
String firstName = response.getString("firstName");
Log.v("firstName", firstName);
String organizationList = response.getString("organizationList");
Log.v("organizationList",organizationList);
String token = response.getString("token");
Log.v("token",token);
Toast.makeText(getApplicationContext(),"Logged in Suceessfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,NavigationActivity.class);
i.putExtra("token",token);
i.putExtra("firstname",firstName);
startActivity(i);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
Toast.makeText(getApplicationContext(),"Login Error", Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(MainActivity.this).add(jsonRequest);
}
});
//password
showPsd = (EditText) findViewById(R.id.btnpass);
// get the show/hide password Checkbox
mCbShowPwd = (CheckBox) findViewById(R.id.btnshow);
// add onCheckedListener on checkbox
// when user clicks on this checkbox, this is the handler.
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
showPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
} else {
// hide password
showPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
}
}
});
//
//Textview calling
final TextView regLink=(TextView)findViewById(R.id.register1);
final TextView forLink=(TextView)findViewById(R.id.forgot);
//register
regLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regIntent=new Intent(MainActivity.this,RegisterActivity.class);
MainActivity.this.startActivity(regIntent);
}
});
//forgot
forLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forIntent=new Intent(MainActivity.this,ForgotActivity.class);
MainActivity.this.startActivity(forIntent);
}
});
}
//exit dialog box
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("EHR Store");
builder.setIcon(R.drawable.sd);
builder.setMessage("Do you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

refresh current page without blinking android

My app has a list and a button to add element to the list and reload it in the same activity, when pressing the button I need to reload the activity without blinking or time of reloading Like when you send message in messenger.I try the following code:
recreate()
tvSender.setText("");
And this code :
Intent intent = getIntent();
finish();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
This works but it's still not what i want exact any help pls
the full code :
public class ChatRoom extends AppCompatActivity {
String username;
String username1;
TextView userroom;
String image1;
Message_adapter adapter;
ListView L_MESSAGES;
ArrayList<Messages> messages= new ArrayList<Messages>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_room);
Intent intent = getIntent();
username = intent.getStringExtra("username");
username1 = intent.getStringExtra("username1");
userroom =(TextView) findViewById(R.id.userroom);
final EditText tvSender =(EditText) findViewById(R.id.Sender);
final ImageButton btSender=(ImageButton)findViewById(R.id.btSender);
final ImageButton btBack=(ImageButton)findViewById(R.id.back);
btBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatRoom.this, ChatActivity.class);
intent.putExtra("username", username);
intent.putExtra("username1", username1);
ChatRoom.this.startActivity(intent);
}
});
btSender.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
getsendMessages();
}
private void getsendMessages(){
String url =config_message.DATA_URL1+username+"&username1="+username1;
userroom.setText(username1);
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJsonFriend(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(ChatRoom.this,volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJsonFriend(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config_message.JSON_ARRAY);
JSONObject collegeData =null;
messages.clear();
for(int i=0;i<result.length();i++) {
collegeData = result.getJSONObject(i);
String friend = collegeData.getString(config_message.KEY_SENDER);
image1 = collegeData.getString(config_message.KEY_IMAGE);
String time = collegeData.getString(config_message.KEY_Time);
String sender = collegeData.getString(config_message.KEY_Sender);
messages.add(new Messages(friend,image1,time,sender));
}
} catch (JSONException e) {
e.printStackTrace();
}
L_MESSAGES=(ListView) findViewById(R.id.chatRoomsList);
adapter = new Message_adapter(this,messages);
L_MESSAGES.setAdapter(adapter);
L_MESSAGES.setSelection(L_MESSAGES.getAdapter().getCount()-1);
}
}
this the button to refresh list:
public void onClick(View v) {
final String message=tvSender.getText().toString();
Response.Listener<String> responselistener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if (success) {
recreate();
tvSender.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
MessageSender loginrequest = new MessageSender(message, username,username1, responselistener);
RequestQueue queue = Volley.newRequestQueue(ChatRoom.this);
queue.add(loginrequest);
}
});
There is no need to restart whole Activity. Instead you can insert an element in your list dataset(ArrayList<> or something) and call adapter.notifyDataSetChanged() to make the changes in listview.

Why is Volley's onResponse not called

I am fetching json data through Volley. The problem I am having
is that Volley's onResponse is never called, and hence the data are not parsed and displayed.
Sample JSON data
{
"title": "This is a sample text title title",
"cat": {
"origin" : "United states",
"target" : "Asia",
},
"content": "Lorem ipsum ipsum trxt hag jlak jshss jsyts pjqgq uuqtyq usiuqjo uwywh",
}
NewsActivity
public class NewsDetails extends AppCompatActivity {
private final String TAG = "NewsDetails";
private ProgressDialog mProgresscircle;
TextView newsTitle, newsOrigin, newsContent;
//private int news_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
newsTitle = (TextView) findViewById(R.id.dnews_title);
newsOrigin = (TextView) findViewById(R.id.dnews_origin);
newsContent = (TextView) findViewById(R.id.dnews_content);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Calling method to load newss
loadNews();
} else {
final Context context;
context = this;
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle(R.string.alert_titl);
alertDialog.setCancelable(false);
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setMessage(R.string.failed_news);
alertDialog.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialog.show();
} else {
loadNews();
}
}
});
alertDialog.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
}
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(DetailConfig.GET_DURL + news_id,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called NewsDetails");
//Dismissing progressbar;
if (mProgresscircle != null) {
mProgresscircle.dismiss();
}
//Calling method to parse json array
parseNews(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
//This method will parse json data of news
private void parseNews(JSONArray jsonArray) {
Log.d(TAG, "Parsing news array");
for (int i = 0; i<jsonArray.length(); i++) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString(DetailConfig.TAG_DPOST_TITLE);
newsTitle.setText(title);
JSONObject pOrigin = jsonObject.getJSONObject("cat");
String origin = pOrigin.getString("origin");
newsOrigin.setText(origin);
String content = jsonObject.getString(DetailConfig.TAG_DPOST_CONTENT);
newsContent.setText(content);
} catch (JSONException w) {
w.printStackTrace();
}
}
}
}
The things I know
In logcat, loadNews method is called.
I'm logging Volley, and from logcat volley is not complaining in anyway
I can't see "onResponse called NewsDetails" in logcat, meaning that for some reason not known to me, it's not called
So, my question is why is onResponse not called and how should I fix it?
You should use JsonObjectRequest instead of JsonArrayRequest because you are getting jsonobject in the response.
For getting more knowledge you may go through Volley tutorial
/* you are getting json in response but your response listener method is get Json Array replace your code with below code and also add an debug point in your error listener method */
private void loadNews() {
Log.d(TAG, "loadNews called");
mProgresscircle = new ProgressDialog(NewsDetails.this);
mProgresscircle.setCancelable(false);
mProgresscircle.setMessage(null);
mProgresscircle.show();
int news_id = getIntent().getIntExtra("NewsId", -1);
Toast.makeText(NewsDetails.this, "News id is" + news_id, Toast.LENGTH_SHORT).show();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to queue
requestQueue.add(djsonArrayRequest);
}
// or replace this code into your into your loadNews method
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
DetailConfig.GET_DURL, requestParam,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Debug", response.toString());
//TODO parsing code
parseNews(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("", "Error: " + error.getMessage());
}
});
**
You can also refer below link for complete tutorial http://www.hackpundit.com/android-turorial-json-parse-volley/
**

Refresh ListView after adding an item in dialog box

Hello I populated a listview by following this Tutorial
And I want the listview to automatically refreshed after I add an item in a dialog form (consist of EditText etc.) There are suggestion I already followed but unfortunately still cant achieved it.
Here is My Code
public class Attendance extends AppCompatActivity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
//Attendance List json url
private static final String url = "http://10.0.2.2/MobileClassRecord/getAttendanceList.php";
private ProgressDialog pDialog;
private List<AttendanceList> attList = new ArrayList<>();
private ListView mylistView;
private CustomAttendanceListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mylistView = (ListView) findViewById(R.id.list);
adapter = new CustomAttendanceListAdapter(this, attList);
mylistView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
JsonArrayRequest attReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
AttendanceList alist = new AttendanceList();
alist.setDate(jsonObject.getString("att_date"));
alist.setName(jsonObject.getString("att_name"));
attList.add(alist);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG, "Error: " + volleyError.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(attReq);
}
#Override
protected void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
Any help would be much appreciated :)
I simply use this technique : in the Attendance activity put this
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
refreshData();
}
as soon the AlertDialog is dismissed, it calls therefreshData() method that refreshs the ListView

Categories

Resources