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
Related
I have defined the separate adapter Class and getter and setters.
Can anyone help to clear the error?
Thanks in Advance.
this is the class which using the recycler view. the separate card view has attached to the Recycler
public class boxInService extends AppCompatActivity {
RecyclerView recyclerView;
inserviceAdapter inadapter;
List<serviceData> serviceDataList;
ProgressDialog progressDialog;
private SharedPreferences pref;
private static final String PREF_NAME="share_pref";
String op;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_box_in_service);
getSupportActionBar().setTitle("Boxes in Service");
serviceDataList=new ArrayList<>();
recyclerView=findViewById(R.id.in_service_recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
pref=getSharedPreferences(PREF_NAME,MODE_PRIVATE);
op=pref.getString("operator_stored","");
progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.show();
loadData();
}
private void loadData() {
StringRequest request=new StringRequest(
Request.Method.GET,
ROOT_URL + boxinService + op,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONArray jsonArray=new JSONArray(response);
for (int i=0;i<=jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String chip=object.getString("chip_id");
String ua=object.getString("ua_key");
String cas=object.getString("cas");
String model=object.getString("stb_type");
serviceData s_Data=new serviceData(chip,ua,cas,model);
serviceDataList.add(s_Data);
}
inadapter=new inserviceAdapter(boxInService.this,serviceDataList);
recyclerView.setAdapter(inadapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_SHORT).show();
}
}
);
VolleyRequest.getInstance(this).addToRequest(request);
}
}
Is anything Missing?
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;
}
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.
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/
**
I code to send some message and email using HTTP post using Volley.
when i run the emulator using Genymotion.Everything luking fine but i click the click button it show HTTP has been stopped. I am giving logcat picture Please click this Logcat picture to see Please help me what is wrong and how to resolve this problem
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String URL_CLICK = "http://www.careoservice.goyalsoftwares.com/feedback/add.php";
public static final String KEY_MESSAGE = "message";
public static final String KEY_EMAIL = "email";
private EditText editTextMessages;
private EditText editTextEmail;
private Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextEmail = (EditText) findViewById(R.id.editmsg);
editTextEmail = (EditText) findViewById(R.id.editmail);
buttonSend = (Button) findViewById(R.id.btnclk);
buttonSend.setOnClickListener(this);
}
public void sendView() throws JSONException {
final String message = editTextMessages.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_CLICK, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_MESSAGE, message);
params.put(KEY_EMAIL, email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
if (v == buttonSend) {
try {
sendView();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
You are not initialazing the "editTextMessages", this is your null pointer exception.