I've been looking around everywhere in trying to find out why my code was causing an issue. I have a GridView that has an ArrayAdapter which pulls photos down with an AsyncTask. I can see the items being updated but when I try to update the adapter the GridView doesn't seem to update with the new view.
This is the relevant code that does the work...
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
//String id = object.getString("id");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
if(gridViewAdapter != null){
gridViewAdapter.clear();
gridViewAdapter.addAll(list);
gridViewAdapter.notifyDataSetChanged();
gridView.invalidateViews();
} else {
gridViewAdapter = new GridViewAdapter(getActivity(), R.layout.gridview_item, list);
gridView.setAdapter(gridViewAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}
I would really appreciate any help if possible. Trying to get the app out before new years :).
Maybe If you could tell me why this happens so It won't cause an issue again and other will see.
EDIT: Added a bit more code which has it refreshing after I click the button twice.
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private class MyAsyncTask extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private Context context;
public MyAsyncTask (Context context){
this.context = context;
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
pictureAdapter = new PictureAdapter(getActivity(), list);
gridView.setAdapter(pictureAdapter);
}
#Override
protected Void doInBackground(String... strings) {
fetchJsonResponse(strings[0]);
return null;
}
#Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
Toast.makeText(getActivity(), "In Pre Execute", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list);
gridView.invalidate();
progressDialog.dismiss();
}
}
Adapter:
public class PictureAdapter extends BaseAdapter {
private ArrayList<ImageItem> items;
private Context context;
private TextView titleText;
private ImageView itemImage;
public PictureAdapter(Context context, ArrayList<ImageItem> items){
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = LayoutInflater.from(context).inflate(R.layout.gridview_item, parent, false);
titleText = (TextView) v.findViewById(R.id.text);
itemImage = (ImageView)v.findViewById(R.id.image);
titleText.setText(items.get(position).getTitle());
Picasso.with(context).load(items.get(position).getUrl()).fit().into(itemImage);
return v;
}
public void updateItemList(ArrayList<ImageItem> newItemList){
this.items = newItemList;
notifyDataSetChanged();
}
}
Try the below lines in post execute
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pictureAdapter.updateItemList(list,gridView);
progressDialog.dismiss();
}
Now in your updateItemList
public void updateItemList(ArrayList<ImageItem> newItemList,GridView gridView){
this.items = newItemList;
gridView.setAdapter(null);
gridView.invalidateViews();
gridView.deferNotifyDataSetChanged();
gridView.setAdapter(list);
}
Why you are calling Volley request from AsyncTask as Volley perform request on NetworkThread.
Remove AsyncTask and directly call Volley.
Just try this. Hope it helps.
private ProgressDialog progressDialog;
protected void onCreate(Bundle savedInstanceState) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Contacting Rover...");
progressDialog.show();
fetchJsonResponse(url);
}
private void fetchJsonResponse(String url) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
url + "&api_key=" + API_KEY,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.dismiss();
try {
JSONArray photos = response.getJSONArray("photos");
list.clear();
for(int i = 0; i < photos.length(); i++){
JSONObject object = photos.getJSONObject(i);
String url = object.getString("img_src");
list.add(new ImageItem(null, "Picture", url));
Log.i("Debug 2", url);
}
pictureAdapter.notifyDataSetChanged();
Log.i("Debug 2", list.get(0).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
VolleyLog.e("Error: ", error.getMessage());
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
Related
I have created a separate class in which I have defined all about volley and in another activity, I have directly pass URL, CONTEXT and Get Response...
but in my NavDrawerActivity.java how do I call the subCategoryJSON(); method without writing my volley code again as I have done with mainCategoryJSON(); method in which I just simply pass the URL, method type.
Also is this a correct approach I am doing or there need to be some modification in the code, what I want is that wherever I am using API in my project and using volley for it, I don't have to write code again and again just simply pass the URL,method type
VolleyResponseListener.java
public interface VolleyResponseListener {
void onResponse(String response, String tag);
void onError(VolleyError error, String tag);
}
CustomStringRequestVolley.java
public class CustomStringRequestVolley {
private String url;
private String tag;
Context ctx;
private VolleyResponseListener volleyResponseListener;
public CustomStringRequestVolley(String url, String tag,Context ctx,VolleyResponseListener volleyResponseListener){
this.url = url;
this.tag = tag;
this.ctx=ctx;
this.volleyResponseListener = volleyResponseListener;
sendRequest();
}
private void sendRequest() {
final ProgressDialog pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Loading ...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("catresponse", "response " + response);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
volleyResponseListener.onResponse(response, tag);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(ctx).addToRequestQueue(stringRequest);
}
}
NavDrawerActivity.java
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, VolleyResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainCategoryJSON();
subCategoryJSON();
}
private void mainCategoryJSON() {
CustomStringRequestVolley request1 = new CustomStringRequestVolley(URLs.categoryURL, "TAG1", this, this);
}
#Override
public void onResponse(String response, String tag) {
switch (tag) {
case "TAG1":
try {
Log.i("Responseeeeeezaq :", response.toString() + " " + tag);
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
CategoryModelClass categoryModelClass = new CategoryModelClass();
categoryModelClass.setCategoryID(productObject.getInt("Category-Id"));
categoryModelClass.setCategoryName(productObject.getString("Category-Name"));
categoryModelClass.setCategoryImg(productObject.getString("Category-Image"));
categoryArrayList.add(categoryModelClass);
Log.d("zpuyi", String.valueOf(categoryArrayList));
}
categoryAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
VolleyLog.e("Error: ", error.getMessage());
}
private void subCategoryJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.subcategoryURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("subcategoryJsonResponse", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
You have written the answer correctly but you are not implementing the written custom volley class code in the activity class.
First Define the interface class for the Volley as below,
Now implement the volley interface in the java class where you have written the custom volley class as below:
CustomStringRequestVolley.java
public class CustomStringRequestVolley implements volleyCallback {
public Context context;
public CustomStringRequestVolley(Context context) {
this.context = context;
}
public interface volleyCallback {
void onSuccess(String result);
void onError(String error);
}
public void callGetServer(String URL, final
volleyCallback callback){
if (!checkInternetConnection(context)) {
showNoInternetDialogue(context);
return;
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}, error -> {
if (error.networkResponse == null){
if (error.getClass().equals(TimeoutError.class)){
Toast.makeText(context, "Timeout.Please try again",
Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NoConnectionError.class)){
Toast.makeText(context, "Timeout.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NetworkError.class)) {
Toast.makeText(context, "Network Error.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ParseError.class)){
Toast.makeText(context, "Parse error", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ServerError.class)){
Toast.makeText(context, "Server Error.Please try again", Toast.LENGTH_SHORT).show();
}
else {
parseVolleyError(error);
}
}
}
) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
//setting up the retry policy for slower connections
int socketTimeout = 120000;//120000 milli seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Now use this Custom volley class in every activity you required. It reduces you
boilerplate code
NavDrawerActivity.java
CustomStringRequestVolley customStringRequestVolley;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point_navigation);
customStringRequestVolley = new CustomStringRequestVolley(this);
}
private void subCategoryJSON() {
customStringRequestVolley.callGetServer(URLs.subcategoryURL,new volleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String error) {
//show error code
}
});
}
Let me know after you try this #Abhishek
sort ListView Android by float number ...
I have a listview price type float display of a mysql database ,,
I want to sort it (by order) but I have not found a solution ..
how can I do it please !!!
it's the code of my listView with prices done !!
private class GetHttpResponse extends AsyncTask<Void, Void, Void>{
public Context context;
String ResultHolder;
List<subjects> subjectsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpServicesClass httpServiceObject = new
HttpServicesClass(ServerURL);
try
{
httpServiceObject.ExecutePostRequest();
if(httpServiceObject.getResponseCode() == 200)
{
ResultHolder = httpServiceObject.getResponse();
if(ResultHolder != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(ResultHolder);
JSONObject jsonObject;
subjects subjects;
subjectsList = new ArrayList<subjects>();
for(int i=0; i<jsonArray.length(); i++)
{ subjects = new subjects();
jsonObject = jsonArray.getJSONObject(i);
subjects.SubjectName = jsonObject.getString("tarif");
subjectsList.add(subjects);
} }
catch (JSONException e) {
e.printStackTrace();
} } } else
{
Toast.makeText(context, httpServiceObject.getErrorMessage(),
Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{ progressBarSubject.setVisibility(View.GONE);
SubjectListView.setVisibility(View.VISIBLE);
if(subjectsList != null)
{
ListAdapterClass adapter = new ListAdapterClass(subjectsList,
context);
SubjectListView.setAdapter(adapter);
SubjectListView.setOnItemClickListener(new
AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int pos, long id) {
String selectedItem =
parent.getItemAtPosition(pos).toString();
Toast.makeText(TechnicienActivity.this,selectedItem,
Toast.LENGTH_SHORT).show();
Intent intent = new
Intent(getApplicationContext(),Main2Activity.class);
intent.putExtra("Position" , String.valueOf(id));
startActivity(intent);
} }); } } }
You can sort the list by using
Collections.sort(list);
and then set this to the listview.
Example;
subjectsList.add(subjects);
Collections.sort(subjectsList);
This is my Fragment Class - Here i get the JSON array object and call the adapter class for setting it. In the corressponding XML file, i have used a card view and lsit view to display the data. i want to know how to implement a onItemClickListener{} function so that i can go to another activity and display the list in a more detailed manner.
{
String url = "http://www.appplay.in/student_project/public/staff_details";
ProgressDialog mProgressDialog;
ListView lvDetail;
Context context;
ArrayList<staff_model> myList = new ArrayList<>();
ListView lv;
public static ArrayList<staff_model> staff_array;
JSONObject jsonObject;
JSONObject jsonKey;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
context=container.getContext();
View v = inflater.inflate(R.layout.tab_fragment_2, container, false);
lvDetail = (ListView) v.findViewById(R.id.CustomList);
// submit=(Button)v.findViewById(R.id.button) ;
new GetGalleryimage().execute();
v.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
Intent in = new Intent(getActivity(), Staff_Main.class);
startActivity(in);
}
});
return v;
}
public void positionAction(View view) {
int position = (int) view.getTag();
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
private class GetGalleryimage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonarr = jsonObj.getJSONArray("User_Details");
for(int i=0; i<jsonarr.length(); i++)
{
JSONObject jsonObject = jsonarr.getJSONObject(i);
myList.add(new staff_model(jsonObject.getString("name"),jsonObject.getString("dob"),jsonObject.getString("occupation"),jsonObject.getString("emailid"),jsonObject.getString("contact"),jsonObject.getString("timetable"),jsonObject.getString("image")));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
Log.v("result",""+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
staff_BaseAdapter rcAdapter = new staff_BaseAdapter(getActivity(),0, myList);
lvDetail.setAdapter(rcAdapter);
}
}
public class MAP_Detailservice extends
AsyncTask<String, String, String> {
Context mContext;
JSONObject mJsnObj;
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
showProgress();
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
JSONObject json = new JSONObject();
String cricketAllMatchesLink = "http://www.appplay.in/student_project/public/staff_details";
try {
return String.valueOf(HttpUtils.getJson(cricketAllMatchesLink));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.v("POST EXECUTE", "RESULT :" + result);
super.onPostExecute(result);
hideProgress();
// mProgressDialog.dismiss();
// if (HttpUtils.status == 408) {
// Toast.makeText(getActivity(), "Conection Lost ",
// Toast.LENGTH_SHORT).show();
// }
try {
JSONArray array = new JSONArray(result);
JSONObject mJsonObject = array.getJSONObject(0);
// ArrayList<user_agent> GetSearchResults();
ArrayList<staff_model> staff_result = new ArrayList<staff_model>();
/**
* Question Array Parsing
*/
JSONArray jsonQuesstionsArray = mJsonObject
.getJSONArray("User_Details");
for (int i = 0; i < jsonQuesstionsArray.length(); i++) {
// Reading questions
JSONObject jsonQuestionObject = jsonQuesstionsArray
.getJSONObject(i);
String name = jsonQuestionObject.getString("name");
String dob = jsonQuestionObject.getString("dob");
String occupation = jsonQuestionObject.getString("occupation");
String emailid = jsonQuestionObject.getString("emailid");
String contact = jsonQuestionObject.getString("contact");
String timetable = jsonQuestionObject.getString("timetable");
String image = jsonQuestionObject.getString("image");
}
lvDetail.setAdapter(new staff_BaseAdapter(
getActivity(), 0,staff_result));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void showProgress() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Loading please wait");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
public void hideProgress() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onDestroy(){
super.onDestroy();
if ( mProgressDialog!=null && mProgressDialog.isShowing() ){
mProgressDialog.cancel();
}
}
}
This is my Adapter class - Where I have gotten the data and set the code
ArrayList<StaffList> myList = new ArrayList<StaffList>();
LayoutInflater inflater;
Context context;
public StaffBaseAdapter(Context context, ArrayList<StaffList> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public StaffList getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.staff_list_view, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
StaffList currentListData = getItem(position);
mViewHolder.tvTitle.setText(currentListData.getTitle());
return convertView;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
public MyViewHolder(View item) {
tvTitle = (TextView) item.findViewById(R.id.tvTitle);
}
}
}
This is my Model Class
String title;
int imgResId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
first your model class "staff_model" implement parcelable it will help to transfer your single model item pass to other activity.
Then add ItemClickListener in your listview
add this into your getView function
MyViewHolder rowHolder=new MyViewHolder(convertView);
rowHolder.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//do whatever u want
}
});
listView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Here you can convert your json to string
startActivity(new Intent(this, MainActivity.class).putExtra("myList",new Gson().toJson(list)));
}
});
and in your receiving activity
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> list1=new Gson().fromJson(getIntent().getStringExtra("myList"),type);
Here Specify the TypeToken .You will have the exact json that you passed in the intent.
I want pass my String json from fragment to another activity so make interface between fragment and activity but when lunch app get null exception from this line from my fragment :adapterCalljson.MethodCallbackjson(jsonStr);
this is my try so far :
interface class :
public interface AdapterCalljson {
void MethodCallbackjson(String jsonn);
}
fragment :
public class maghalat extends Fragment {
private View myFragmentView;
private RecyclerView recyclerView;
private DataAdapter adapter;
private String TAG = MainActivity.class.getSimpleName();
public ProgressDialog pDialog;
List<jsonContent> listcontent=new ArrayList<>();
public int dog=1;
public String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
public int id;
AdapterCalljson adapterCalljson;
public String json;
public String jsonStr;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
adapterCalljson.MethodCallbackjson(json);
asyncRun();
return myFragmentView;
}
public void asyncRun(){
if(isNetworkConnected()) {
new GetContacts().execute();
} else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
jsonContent.content=c.getString("content");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
jsonContent.curpage=dog;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(), listcontent, new AdapterCallback() {
#Override
public void MethodCallbackgo(String data) {
Integer s=null;
try {
s= Integer.valueOf(data);
}catch (NumberFormatException e)
{
}
if (s!=null && s>=1 && s<=id)
{
dog= Integer.parseInt(data);
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else
{
Toast.makeText(getActivity().getApplicationContext(),"صفحه پیدا نشد",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbacknext() {
if (dog<id)
{
dog += 1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else {
Toast.makeText(getActivity().getApplicationContext(),"این آخرین صفحه است",Toast.LENGTH_SHORT).show();
}
}
#Override
public void MethodCallbackprev() {
if (dog!=1)
{
dog-=1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else{
Toast.makeText(getActivity().getApplicationContext(),"این اولین صفحه است",Toast.LENGTH_SHORT).show();
}
}
});
recyclerView.setAdapter(adapter);
json=jsonStr;
}
}
You haven't assigned an object to adapterCalljson. Assuming you're implementing AdapterCalljson in the host activity, assign it from the context onAttach:
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
#Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
Firstly, your Activity containing the Fragment must implement that interface.
public class MainActivity implements AdapterCalljson {
#Override
void MethodCallbackjson(String jsonn) {
doSomethingWithJson(jsonn);
}
private void doSomethingWithJson(String json) {
}
// onCreate...
}
Next, I would recommend you create the RecyclerView outside the AsyncTask. You don't need to save the myFragmentView variable.
Additionally, you can't call the callback yet. There is no data.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.maghalat, container, false);
// recyclerView = rootView.findViewById
// adapter = ...
// recyclerView.setAdadpter...
asyncRun(); // This happens in the background. There is no JSON yet
return rootView;
}
Then, perhaps you should have doInBackground return the JSON string so you don't have to store it as a class variable.
The last argument is the return type.
public class GetContacts extends AsyncTask<Void, Void, String>
So, then it is public String doInBackground(Void params...) {} and public void onPostExecute(String result) {}.
In other words, don't just return null from doInBackground
#Override
protected String doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
// Parse JSON more...
return jsonStr;
}
And then you should be able to use your callback.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (adapterCalljson != null) {
adapterCalljson.MethodCallbackjson(result);
} else {
Log.w("Callback Error", "callback not assigned");
}
// adapter.notifyDataSetChanged(); // Might want this
}
Hi in the below code I am displaying two spinner one is for displaying brand name and another for displaying model name.
I am getting the response from server like this:
{"RESULT":"SUCCESS","BRANDS":[{"BRANDID":"14","BRANDNAME":"471"},{"BRANDID":"3","BRANDNAME":"ACE"},{"BRANDID":"4","BRANDNAME":"ADLER"},{"BRANDID":"5","BRANDNAME":"ALIEN"},{"BRANDID":"6","BRANDNAME":"ARTISAN-TORO"},{"BRANDID":"7","BRANDNAME":"ASSOCIATED PACIFIC"},{"BRANDID":"8","BRANDNAME":"ASTEX"},{"BRANDID":"9","BRANDNAME":"BERNINA"},{"BRANDID":"10","BRANDNAME":"BONIS"},{"BRANDID":"11","BRANDNAME":"BROTHER"},{"BRANDID":"12","BRANDNAME":"BROTHER "},{"BRANDID":"13","BRANDNAME":"CHANDLER"},{"BRANDID":"15","BRANDNAME":"CINCINNATI"},{"BRANDID":"16","BRANDNAME":"CONSEW"},{"BRANDID":"17","BRANDNAME":"CONSEW\/SEIKO"},{"BRANDID":"18","BRANDNAME":"DENNISON"},{"BRANDID":"19","BRANDNAME":"DURKOPP ADLER"},{"BRANDID":"20","BRANDNAME":"EAGLE"},{"BRANDID":"21","BRANDNAME":"EASTMAN"},{"BRANDID":"22","BRANDNAME":"EASTMAN CARDINAL"},{"BRANDID":"23","BRANDNAME":"ECONOSEW"},{"BRANDID":"1","BRANDNAME":"usha"}]}
Model Response:
{"RESULT":"SUCCESS","MODELS":[{"MODELNAME":"150","MODELID":"2"},{"MODELNAME":"C150WS","MODELID":"3"},{"MODELNAME":"HC720A","MODELID":"4"}
Based on the brand i want to display model names.
java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url","" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.d("Brand_result","" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
spinner_fn();
Log.i("listbrands", " " + listBrands);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}
//ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext()
// ,android.R.layout.simple_spinner_item,listBrands_String);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}