I've tried in some way but the response is always null,
But the data will be sent I checked with toast and as expected
I also have used postman to check when the data sent in accordance with the key value then the results are appropriate.
this my code to send data
public class FragmentPetaniTerdekat extends Fragment {
Context context;
View view;
Dialog dialog;
RecyclerView recyclerView;
ArrayList<String> jenis = new ArrayList<>();
ArrayList<String> jarak = new ArrayList<>();
ArrayList<String> durasi = new ArrayList<>();
String my_location;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
dialog = new Dialog(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_fragment_petani, container, false);
location();
return view;
}
// get adddres name current location
private void location() {
dialog.showDialog("Pesan","memuat data...");
LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// get lat and lng
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
my_location = String.valueOf(lat+","+lng);
getApi(my_location);
Toast.makeText(context,String.valueOf(lat+","+lng),Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context,"lokasi tidak ditemukan",Toast.LENGTH_LONG).show();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
LocationManager mLocationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return ;
}
// check alternative get location
boolean GPS_ENABLE, NETWORK_ENABLE;
GPS_ENABLE = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
NETWORK_ENABLE = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (GPS_ENABLE){
Toast.makeText(getActivity(),"GPS state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60 * 1 , 1, mLocationListener);
}else if(NETWORK_ENABLE){
Toast.makeText(getActivity(),"network state",Toast.LENGTH_LONG).show();
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1,mLocationListener);
}else{
Toast.makeText(getActivity(),"ganok seng kepilih cak",Toast.LENGTH_LONG).show();
showSettingsAlert();
}
}
// show alert setting if gps non aktif
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
getActivity().startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public void initRecylerView(View v){
recyclerView = (RecyclerView)v.findViewById(R.id.recylerview_petani_terdekat);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
RecyclerView.Adapter adapter = new AdapterPetaniTerdekat(context,jenis,jarak,durasi);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void getApi(final String my_location){
Log.e("my_location", my_location);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL_PETANI_TERDEKAT, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.message(response.toString());
if (response != null) {
try {
JSONArray get_respone = response.getJSONArray("result_petani_terdekat");
for (int i=0; i<get_respone.length(); i++){
JSONObject result = get_respone.getJSONObject(i);
ModelPetaniTerdekat petaniTerdekat = new ModelPetaniTerdekat();
petaniTerdekat.setJenis(result.getString("jenis"));
JSONObject kriteria = result.getJSONObject("jarak");
for (int z=0; z<kriteria.length(); z++){
petaniTerdekat.setJarak(kriteria.getString("distance"));
petaniTerdekat.setDurasi(kriteria.getString("duration"));
}
jenis.add(petaniTerdekat.getJenis());
jarak.add(petaniTerdekat.getJarak());
durasi.add(petaniTerdekat.getDurasi());
dialog.closeDialog();
}
initRecylerView(view);
} catch (JSONException e) {
dialog.message("Error : "+e.toString());
e.printStackTrace();
}
}else{
dialog.message("Error : Tidak ada data !");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
dialog.message("Error : TimeoutError");
} else if (error instanceof AuthFailureError) {
dialog.message("Error : AuthFailureError");
} else if (error instanceof ServerError) {
dialog.message("Error : ServerError");
} else if (error instanceof NetworkError) {
dialog.message("Error : NetworkError");
} else if (error instanceof ParseError) {
error.printStackTrace();
dialog.message("Error : ParseError");
}
dialog.closeDialog();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> stringMap = new HashMap<>();
stringMap.put("lokasi_saya",my_location);
return stringMap;
}
};
AppSingleton.getInstance(context).addToRequestQueue(request);
request.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}
this my web service
header('Content-Type: application/json');
include_once 'helper_api.php';
include_once '../crud.php';
if ($_SERVER['REQUEST_METHOD']=='POST') {
$origins = isset($_POST['lokasi_saya'])?$_POST['lokasi_saya']:"";
$crud = new Crud();
$sql = "SELECT tb_petani.id_petani, tb_petani.nama, tb_petani.no_telp, tb_petani.alamat, tb_jenis.nama_jenis
FROM tb_petani, tb_master_cabe, tb_jenis
WHERE tb_jenis.id_jenis = tb_master_cabe.id_jenis
AND tb_petani.id_petani = tb_master_cabe.id_petani
AND tb_petani.status ='2'";
$result = $crud->fetchData($sql);
$helper = new Helper_api();
$data_petani = array();
foreach ($result as $value) {
$destinatios = $value['alamat'];
$distance_duration = $helper->getDistanceDuration($origins, $destinatios);
$data_petani[] = array(
"nama"=>$value['nama'],
"no_telp"=>$value['no_telp'],
"alamat"=>$value['alamat'],
"jenis"=>$value['nama_jenis'],
"jarak"=>$distance_duration
);
}
// sort ascending array multidimensi (distance)
usort($data_petani, function($a, $b) {
return $a['jarak']['distance'] - $b['jarak']['distance'];
});
echo json_encode(array("result_petani_terdekat"=>$data_petani));
}
try with sending data in key-value pair, try this code :
HashMap<String, String> inputs = new HashMap<String, String>();
inputs.put("your key1", "value");
inputs.put("your key2", "value2");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
URL_PETANI_TERDEKAT, new JSONObject(inputs),
new com.android.volley.Response.Listener<JSONObject>() {
......
}
Try to add this code with getparams()
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
problem solved
I replaced the objectRequest into the stringRequest parameter successfully sent
Thank you very much guys
Related
I've an activity whuich load some data from mySql db to populate a Recyclerview.
PollActivity.java (relevant code)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll);
rv = findViewById(R.id.rv);
// *** Rv Init ***
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(false);
polls = new ArrayList<>();
// SqLite data management
db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
final String userid = user.get("uid");
// Local data
String localBefore = Locale.getDefault().getLanguage().toUpperCase();
final String local;
switch (localBefore){
case "IT":
local = "IT";
break;
case "FR":
local = "FR";
break;
case "DE":
local = "DE";
break;
case "ES":
local = "ES";
break;
default:
local = "EN";
break;
}
// ************
// *** MAIN ***
// ************
// Tag used to cancel the request
String tag_string_req = "req_login";
MaterialDialog.Builder builder = new MaterialDialog.Builder(this)
.title(R.string.strDialogProgressLoading_title)
.content(R.string.strDialogProgressReg_desc)
.progress(true, 0);
final MaterialDialog myDialog = builder.build();
myDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_LOADING, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
for(int i=0; i<jObj.length()-2; i++){
int j = i + 1;
JSONObject pollObject = jObj.getJSONObject("poll" + i);
JSONObject pollObjectNext = jObj.getJSONObject("poll" + j);
i++;
//Id to String Translate
int idInterests = getResources().getIdentifier("strInterestsItem" + pollObject.getString("id_interests"), "string", getPackageName());
String strInterests = getString(idInterests);
String strPoint;
if(pollObject.getString("sponsor").equals("UUABA")){
strPoint = "+200";
}else{
strPoint = "+150";
}
//String concatenation
String idPoll = "#" + pollObject.getString("id_poll");
String strQuestion = "#" + pollObject.getString("poll_question");
String IdUser = userid;
polls.add(new Poll(idPoll
, pollObject.getString("sponsor")
, pollObject.getString("poll_user_state")
, IdUser
, strInterests
, strQuestion
, pollObject.getString("poll_answer")
, pollObject.getString("id_poll_answer")
, pollObjectNext.getString("poll_answer")
, pollObjectNext.getString("id_poll_answer")
, strPoint));
}
initializeAdapter();
myDialog.dismiss();
} else {
myDialog.dismiss();
// Error in loading. Get the error message
String errorMsg = jObj.getString("error_msg");
int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
String strErrorRes = getString(idErrorRes);
//POPUP ERRORE
new MaterialDialog.Builder(PollActivity.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(strErrorRes)
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
myDialog.dismiss();
//POPUP ERRORE
new MaterialDialog.Builder(PollActivity.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to loading url
Map<String, String> params = new HashMap<String, String>();
params.put("userid", userid);
params.put("local", local);
//Log.d("NINJA", "UserID: " + userid);
//Log.d("NINJA", "Local: " + local);
return params;
}
};
// Adding request to request queue
AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);
// ************
// ************
// ************
private void initializeAdapter(){
RVAdapter adapter = new RVAdapter(polls);
rv.setAdapter(adapter);
}
public void reloadActivity(){
startActivity(getIntent());
finish();
}
}
RVAdapter.java(my Recycler View Adapter)
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PollViewHolder> {
public static class PollViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView txtIdPoll;
ImageView imgSponsor;
ImageView imgNew;
TextView txtIdInterests;
TextView txtQuestion;
RadioGroup radioGroupAnswers;
RadioButton radioAnswer1;
RadioButton radioAnswer2;
Button btnPoint;
PollViewHolder(View itemView) {
super(itemView);
cv = itemView.findViewById(R.id.cv);
txtIdPoll = itemView.findViewById(R.id.txtIdPoll);
imgSponsor = itemView.findViewById(R.id.imgSponsor);
imgNew = itemView.findViewById(R.id.imgNew);
txtIdInterests = itemView.findViewById(R.id.txtIdInterests);
txtQuestion = itemView.findViewById(R.id.txtQuestion);
radioGroupAnswers = itemView.findViewById(R.id.radioGroupAnswers);
radioAnswer1 = itemView.findViewById(R.id.radioAnswer1);
radioAnswer2 = itemView.findViewById(R.id.radioAnswer2);
btnPoint = itemView.findViewById(R.id.btnPoint);
}
}
List<Poll> polls;
//Context context;
public RVAdapter(List<Poll> polls){
this.polls = polls;
//this.context = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PollViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.poll_item, viewGroup, false);
PollViewHolder pvh = new PollViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(final PollViewHolder pollViewHolder, final int i) {
final int rb1id = 1000;
final int rb2id = 2000;
//Setting RadioButton ID
pollViewHolder.radioAnswer1.setId(rb1id);
pollViewHolder.radioAnswer2.setId(rb2id);
pollViewHolder.txtIdPoll.setText(polls.get(i).txtIdPoll);
if(polls.get(i).txtSponsor.equals("UUABA")){
pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_logo_red_bg);
}else{
pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_sponsor_green_bg);
}
if(polls.get(i).txtNew.equals("0")){
pollViewHolder.imgNew.setImageResource(R.drawable.ic_new);
}else{
pollViewHolder.btnPoint.setEnabled(false);
pollViewHolder.btnPoint.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);
}
pollViewHolder.txtIdInterests.setText(polls.get(i).txtIdInterests);
pollViewHolder.txtQuestion.setText(polls.get(i).txtQuestion);
pollViewHolder.radioAnswer1.setText(polls.get(i).txtAnswer1);
pollViewHolder.radioAnswer2.setText(polls.get(i).txtAnswer2);
pollViewHolder.btnPoint.setText(polls.get(i).txtPoint);
pollViewHolder.btnPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId() == -1){
Snackbar snackbar = Snackbar.make(v, R.string.strSnackPoll, Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
TextView textView =snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}else{
QueryUtils queryUtils = new QueryUtils();
String IdPoll = String.valueOf((polls.get(i).txtIdPoll)).replace("#", "");
switch (pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId()){
case 1000:
queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer1)));
break;
case 2000:
queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer2)));
break;
}
}
}
});
}
#Override
public int getItemCount() {
return polls.size();
}
}
At this point, I would like to update a db field at button click and reload PollActivity.java to force the RecyclerView update (I'd like that the NEW image disappear from the updated CardView). I guess to do this calling a method of my QueryUtils.java (one of the method it will contain), avoiding to write too mutch code inside adapter.
QueryUtils.java
#SuppressLint("Registered")
public class QueryUtils extends Application {
private String tag_string_req = "req_poll_answer_upg";
public void upgPollAnswer(final String UserId, final String PollId, final String AnswerId){
Log.d("NINJA", "Utente: " + UserId);
Log.d("NINJA", "Poll: " + PollId);
Log.d("NINJA", "Risposta: " + AnswerId);
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_ANSWER_UPG, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
String message = jObj.getString("message");
if (!error) {
Log.d("NINJA", "Messaggio: " + message);
PollActivity pollActivity = new PollActivity();
pollActivity.reloadActivity();
} else {
//myDialog.dismiss();
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
String strErrorRes = getString(idErrorRes);
Log.d("NINJA", "ErrorePhP: " + strErrorRes);
//POPUP ERRORE
/*new MaterialDialog.Builder(QueryUtils.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(strErrorRes)
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("NINJA", "ErroreVolley: " + error);
//myDialog.dismiss();
//POPUP ERRORE
/*new MaterialDialog.Builder(QueryUtils.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();*/
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to loading url
Map<String, String> params = new HashMap<String, String>();
params.put("userid", UserId);
params.put("id_poll", PollId);
params.put("id_answer", AnswerId);
return params;
}
};
// Adding request to request queue
AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
At the end of the update procedure, I call the reloadActivity method in PollActivity, to reload itself. THIS call generate the error below:
LOGCAT
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4226)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:68)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:751)
at android.app.Activity.startActivity(Activity.java:4522)
at android.app.Activity.startActivity(Activity.java:4490)
at com.uuaba.uuaba.core.PollActivity.reloadActivity(PollActivity.java:345)
at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:48)
at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:33)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I'm new in Android programming and I tried different solution found in this great forum, but none of them worked for me.
Please help me
Problem is that you are trying to create a new instance of activity without the use of intent :
PollActivity pollActivity = new PollActivity();
pollActivity.reloadActivity();
You should replace this code with the following lines:
public void onClickChangeActivity() {
Intent intent = new Intent(this, PollActivity.class);
startActivity(intent);
}
But your solution is far away from the ideal solutions available in the market. Restarting the activity whenever there is a change in data because you have to update data can never be a good way to go.
Try considering one of these ways to prevent activity restart
Create a data stream(list of data) and keep on reading that on
activity level.
Create a local broadcast receiver
Do let me know if you need help in above ways.
As a quick fix for the problem you can use this hackish way
Create a callback
interface Result {
void success(ResponseModel model);
void failure(Throwable throw);
}
In QueryUtils
List resultCallbacks = new ArrayList(); public void
addCallback(Result result) { resultCallbacks.add(result); }
create List resultCallbacks and a method addCallback to add the callbacks
In PollsActivity write this
((QueryApplication)getApplicationContext().getApplication()).addCallbacks(this);
and implement the callback.
On receiving any data update your list and do
RVUpdater.notifyDataSetChanged();
Hope this will help.
I want change the background color of of LinearLayout of Fragment A from Fragment B .These fragments are in same viewpager in sliding tabs.
The data of both fragment are dynamically changed from server.Here I have to click a textview of Fragment B then its linearlayout's color be changed manually(POST method) but due to net slow the background color of Fragment A (Because the textview of Fragment A is already selected so its color is already set.) is not removed from LinearLayout(GET method). But after sometime it will disappear .
So I want to set color manually till color is to be loaded. To make good user interface while clicking on textview for selection package.
MinPackageFragment
public class MinPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private View mView;
private TextView nepal_minimum_package_price, nepal_minimum_package_plan;
private LinearLayout nepal_minimum_package_linearlayout;
private String GET_NEPAL_MIN_PACKAGE_URL;
private String CHECK_CURRENT_PACKAGE_URL;
private WebView webview;
private String minPackagePrice;
private String minPackageItem;
private int THIS_ID;
private String CHOOSE_PACKAGE;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_min_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1001;
GET_NEPAL_MIN_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1001?token=" + token;
webview = (WebView) mView.findViewById(R.id.minimumNepaliListWebView);
webview.getSettings().setJavaScriptEnabled(true);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_minimum_package_price = mView.findViewById(R.id.nepal_minimum_package_price);
nepal_minimum_package_plan = mView.findViewById(R.id.nepal_minimum_package_plan);
nepal_minimum_package_linearlayout = mView.findViewById(R.id.nepal_minimum_package_linearlayout);
nepal_minimum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I want change here the background color of linearlayout of another fragment but getting error
showDialog();
choosePackage();
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setContentFromServer();
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
String avgprice = pref123.getString("mineprice", minPackagePrice);
String avgitems = pref123.getString("minitems", minPackageItem);
nepal_minimum_package_price.setText(avgprice);
webview.loadData(avgitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return mView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
Log.v("mydata1", data + "");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
hideDialog();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setContentFromServer() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_MIN_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = silver.getString("name");
minPackagePrice = silver.getString("price");
minPackageItem = silver.getString("includes");
if (getActivity() != null) {
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref123.edit();
editor.putString("mineprice", minPackagePrice);
editor.putString("minitems", minPackageItem);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
MaxPackageFragment
public class MaxPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private WebView maximumNepaliListWebView;
private View maxView;
private TextView nepal_maximum_package_plan, nepal_maximum_package_price;
private String GET_NEPAL_PACKAGE_URL;
private String maxPackageprice;
private String maxPackageitems;
private String CHECK_CURRENT_PACKAGE_URL;
private LinearLayout nepal_maximum_package_linearlayout;
private String CHOOSE_PACKAGE;
private int THIS_ID;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
maxView = inflater.inflate(R.layout.fragment_max_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1003;
GET_NEPAL_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1003?token=" + token;
nepal_maximum_package_linearlayout = maxView.findViewById(R.id.nepal_maximum_package_linearlayout);
maximumNepaliListWebView = maxView.findViewById(R.id.maximumNepaliListWebView);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_maximum_package_plan = maxView.findViewById(R.id.nepal_maximum_package_plan);
nepal_maximum_package_price = maxView.findViewById(R.id.nepal_maximum_package_price);
nepal_maximum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
// I want change here the background color of linearlayout of another fragment but getting error
choosePackage();
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setItemToLayout();
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
String maxprice = pref1.getString("maxprice", maxPackageprice);
String maxitems = pref1.getString("maxitems", maxPackageitems);
nepal_maximum_package_price.setText(maxprice);
maximumNepaliListWebView.loadData(maxitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return maxView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1003) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
hideDialog();
}
}
}
else {
JSONArray errordata = responceData.getJSONArray("errors");
String errormessage = errordata.getJSONObject(0).getString("message");
Toast.makeText(getActivity(), "" + errormessage, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setItemToLayout() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
Log.v("responceData", "onResponse: " + responceData);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = platinum.getString("name");
maxPackageprice = platinum.getString("price");
maxPackageitems = platinum.getString("includes");
if (getActivity() != null) {
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("maxprice", maxPackageprice);
editor.putString("maxitems", maxPackageitems);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID ==1003){
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
There are three fragments in same viewpager of fragment,within three tabs.
If your fragment is in same Activity, You can use the FragmentManager. findFragmentById(int id) which return by invoke Fragment.getFragmentManager() method to retrieve the reference of another fragment
then invoke the method to change the background color
I have to upload a file and has three more parameters which is string.The file can be image or zip.How is it possible with volley to upload a file and submit string parameters along with it when button is clicked?
I have also tried this link-https://www.simplifiedcoding.net/upload-pdf-file-server-android/
Please help me.Thanks!!
My code is:
public class Tab1Fragment extends Fragment implements
AdapterView.OnItemSelectedListener {
EditText subj,desx;
private ImageView mAvatarImage;
Button choosefile,select,submt;
String uid, type;
String MY_PREFS_NAME = "value";
private int PICK_PDF_REQUEST = 1;
TextView filetext;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
String uploadId;
//Uri to store the image uri
private Uri filePath;
Spinner spinner,spinner2;
public Tab1Fragment() {
// Required empty public constructor
}
public static Tab1Fragment newInstance() {
Tab1Fragment fragment = new Tab1Fragment();
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview= inflater.inflate(R.layout.fragment_tab1, container,
false);
subj=(EditText)rootview.findViewById(R.id.subj);
choosefile=(Button)rootview.findViewById(R.id.choosefile);
select=(Button)rootview.findViewById(R.id.select);
submt=(Button)rootview.findViewById(R.id.submt);
filetext=(TextView)rootview.findViewById(R.id.filetext);
mAvatarImage=(ImageView)rootview.findViewById(R.id.image);
desx=(EditText)rootview.findViewById(R.id.desx);
submt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveProfileAccount();
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
choosefile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uploadMultipart();
}
});
requestStoragePermission();
SharedPreferences prefs =
this.getActivity().getSharedPreferences(MY_PREFS_NAME,
Context.MODE_PRIVATE);
uid = prefs.getString("uid", null);
spinner = (Spinner)rootview.findViewById(R.id.spinner);
spinner2 = (Spinner)rootview.findViewById(R.id.spinner2);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> deparment= new ArrayList<String>();
deparment.add("Support");
deparment.add("Project");
deparment.add("Payment");
deparment.add("Service");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, deparment);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
List<String> priority= new ArrayList<String>();
priority.add("low");
priority.add("Medium");
priority.add("High");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, priority);
// Drop down layout style - list view with radio button
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner2.setAdapter(dataAdapter2);
return rootview;
}
private void saveProfileAccount() {
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, Constants.UPLOAD_SUPPORT, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
String resultResponse = new String(response.data);
try {
JSONObject b = new JSONObject(resultResponse);
int status = b.getInt("status");
String data = b.getString("message");
Log.d("Response", data);
if (status ==100) {
/* Intent intent = new Intent(getActivity(),Skills.class);
startActivity(intent);*/
Toast.makeText(getActivity(), data, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message+" Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message+ " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message+" Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userid", uid);
params.put("department", spinner.getSelectedItem().toString());
params.put("priority",
spinner2.getSelectedItem().toString().trim());
params.put("subject", subj.getText().toString().trim());
params.put("description",desx.getText().toString().trim());
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// file name could found file base or direct access from real path
// for now just get bitmap data from ImageView
params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getContext(), mAvatarImage.getDrawable()), "*/*"));
return params;
}
};
VolleySingleton.getInstance(getContext()).addToRequestQueue(multipartRequest);
}
try this
public void fileUploadFunction() {
// Getting file path using Filepath class.
Pdfuri = FilePath.getPath(this, uri);
Log.d("Pdfuri", Pdfuri);
// If file path object is null then showing toast message to move file into internal storage.
if (Pdfuri == null) {
Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();
}
// If file path is not null then PDF uploading file process will starts.
else {
try {
PdfID = UUID.randomUUID().toString();
new MultipartUploadRequest(this, PdfID, AppConstants.URL)
.addFileToUpload(Pdfuri, "pdf")
.addParameter("course", course.trim())
.addParameter("course_id", c_id.trim())
.addParameter("stream", stream.trim())
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(5)
.startUpload();
Toast.makeText(MainActivity.this,"Successfully Uploaded",Toast.LENGTH_SHORT).show();
} catch (Exception exception) {
Toast.makeText(this,
exception.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
//Read response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Add post values here
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
// Add you file here
return params;
}
};
VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
You can use multipart for this. Here is a sample code
Hello fellow developer,
I created a map using google map activity in android studio and my class extending AppCompactActivity because i want to use Toolbar. When running onMapReady called twice (i try it using Log.d) but when i am change AppCompactActivity to FragmentActivity it only called once.
Updated Code :
public class Maps extends AppCompatActivity implements OnMapReadyCallback, DatePickerDialog.OnDateSetListener, View.OnCreateContextMenuListener {
Context context;
private GoogleMap mMap;
private LocationManager locationManager;
Location location;
TextView eta, distance, tvfrom, tvto;
EditText txtTruck;
AutoCompleteTextView search;
Bitmap keraniMarker, truck, arrowup, puninar;
BitmapDescriptor bdfKerani = null, bdfTruck = null, bdfArrow = null, bdfPuninar = null;
CardView cardFind;
Button btnfind;
SwitchCompat swTraffic;
/////////////////////
static SwitchCompat swProgress;
TextView tvFilter;
ListView lvOrderTruck;
EditText txtSearch;
ArrayList<Order_Truck_SetGet> complete = new ArrayList<>();
ArrayList<Order_Truck_SetGet> onGoing = new ArrayList<>();
String custCode = "nocust";
static String nopol_to_map = "all";
private Order_Truck_Adapter adapter_order_truck;
////////////////////
ArrayList<String> nop = new ArrayList<>();
ArrayList<LastLocationSetterGetter> lastloc = new ArrayList<>();
ArrayList<LatLng> livelatlng = new ArrayList<>();
ArrayList<startmark> arstart = new ArrayList<>();
ArrayList<String> project = new ArrayList<>();
String lokasi, nama, time, speed, statustitle;
TextView namadet, lokasidet, timedet, txtspeed, txtSPK, txtOMpils, txtOMccms, txtCust, txtDriver, txtRute, tvSiMbl, txtSiMbl;
ImageView call, sms, wa;
String telp = "+6281280688872";
LinearLayout llSpk, llOMpils, llOMccms, llCust, llDriver, llRute, llSiMbl;
private ProgressDialog pDialog;
private Dialog dashDialog, listOrderDialog;
int FLAG_START_DATE = 0;
int FLAG_END_DATE = 1;
int flag = -1;
int flag_menu = 0;
private long mLastClickTime = 0;
static final int LOCATION = 1;
static final int WRITE_EXTERNAL = 2;
static final int CALL_PHONE = 3;
static final int SEND_SMS = 4;
int PERMISSION_ALL = 1;
Marker lastmark = null;
Marker startmark = null;
Marker track_arrow = null;
String pilih = Order_Truck.nopol_to_map;
String projectselect = "all";
LinearLayout llnopol, lldate, lllokasi;
ImageView nopol_arrow, date_arrow, lokasi_arrow;
ListView lvTruck;
ArrayList<Dashboard_Truck_SetGet> dastruck = new ArrayList<>();
private Dashboard_Truck_adapter adapter;
private DisplayMetrics metrics;
private boolean mAscendingOrder[] = {true, true, true};
String classname = this.getClass().getSimpleName();
Thread live = new Thread();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//set for check permission
String[] PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE, Manifest.permission.SEND_SMS};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
distance = (TextView) findViewById(R.id.DISTANCE);
eta = (TextView) findViewById(R.id.ETA);
search = (AutoCompleteTextView) findViewById(R.id.search);
cardFind = (CardView) findViewById(R.id.cardFind);
tvfrom = (TextView) findViewById(R.id.txtFrom);
tvto = (TextView) findViewById(R.id.txtTo);
btnfind = (Button) findViewById(R.id.btnFind);
swTraffic = (SwitchCompat) findViewById(R.id.swTraffic);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Authenticating...");
pDialog.setCancelable(false);
cekOverlay();
project.add("All Project");
project.add("EXIM");
//set logo for marker
//option 1
BitmapDrawable bitmap_kerani = (BitmapDrawable) getResources().getDrawable(R.drawable.truck);
Bitmap kerani_ico = bitmap_kerani.getBitmap();
keraniMarker = Bitmap.createScaledBitmap(kerani_ico, 100, 100, false);
bdfKerani = BitmapDescriptorFactory.fromBitmap(keraniMarker);
BitmapDrawable bitmap_puninar = (BitmapDrawable) getResources().getDrawable(R.drawable.marker_puninar);
Bitmap puninar_ico = bitmap_puninar.getBitmap();
puninar = Bitmap.createScaledBitmap(puninar_ico, 150, 150, false);
bdfPuninar = BitmapDescriptorFactory.fromBitmap(puninar);
BitmapDrawable bitmap_truck = (BitmapDrawable) getResources().getDrawable(R.drawable.flat_truck);
Bitmap truck_icon = bitmap_truck.getBitmap();
truck = Bitmap.createScaledBitmap(truck_icon, 70, 100, false);
bdfTruck = BitmapDescriptorFactory.fromBitmap(truck);
BitmapDrawable bitmap_arrow = (BitmapDrawable) getResources().getDrawable(R.drawable.green_arrow);
Bitmap arrow_up = bitmap_arrow.getBitmap();
arrowup = Bitmap.createScaledBitmap(arrow_up, 70, 50, false);
bdfArrow = BitmapDescriptorFactory.fromBitmap(arrowup);
tvfrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDate();
flag = FLAG_START_DATE;
}
});
tvto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setDate();
flag = FLAG_END_DATE;
}
});
btnfind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (tvfrom.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "From date must be filled", Toast.LENGTH_SHORT).show();
} else if (tvto.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "To date must be filled", Toast.LENGTH_SHORT).show();
} else if (pilih.isEmpty()) {
Toast.makeText(getApplicationContext(), "Police number must be choosen", Toast.LENGTH_SHORT).show();
} else {
getcarloc(pilih, projectselect);
}
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-3.503399, 112.423781), 4.0f));
swTraffic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
swTraffic.setText("Traffic ON ");
mMap.setTrafficEnabled(true);
} else {
mMap.setTrafficEnabled(false);
swTraffic.setText("Traffic OFF ");
}
}
});
//GPS LAST POSITION
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
search.setText("");
}
});
Log.d("pilihan", pilih + " ^.^");
getNopol(projectselect);
getcarloc(pilih, projectselect);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 15.0f));
return false;
}
});
}
public void getcarloc(final String nopol, final String project) {
if (flag_menu != 2) {
mMap.clear();
livelatlng.clear();
lastloc.clear();
}
Log.d("PILIH2", nopol);
Log.d("LIVESTATUS", String.valueOf(live.getState()));
String url;
showpDialog();
if (flag_menu == 1) {
url = Config.GET_LOCATION_HISTORICAL;
} else {
url = Config.GET_LAST_LOCATION;
}
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.172172, 106.941581)).title("Puninar Jaya Cakung").snippet("Puninar Jaya Cakung").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.128611, 106.941747)).title("Puninar Jaya Nagrak").snippet("Puninar Jaya Nagrak").icon(bdfPuninar));
mMap.addMarker(new MarkerOptions().position(new LatLng(-6.029199, 106.085906)).title("Puninar Jaya Cilegon").snippet("Puninar Jaya Cilegon").icon(bdfPuninar));
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
hidepDialog();
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("data");
if (String.valueOf(jsonArray).equals("[]")) {
hidepDialog();
if (flag_menu == 1) {
Toast.makeText(getApplicationContext(), "There is No Trip History From " + tvfrom.getText() + " Until " + tvto.getText() + " for " + pilih, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "There is No Data / Location For " + pilih, Toast.LENGTH_SHORT).show();
}
} else {
Log.e("JSONARRAY", String.valueOf(jsonArray));
String vehicle_id = null,
vehicle_number = null;
for (int i = 0; i < jsonArray.length(); i++) {
//Get data last location or live tracking
JSONObject obj = jsonArray.getJSONObject(i);
String position_id = obj.getString("position_id");
if (flag_menu != 1) {
vehicle_id = obj.getString("vehicle_id");
vehicle_number = obj.getString("vehicle_number");
}
String date_time = obj.getString("date_time");
Double longitude = Double.parseDouble(obj.getString("longitude")) / 10000000;
Double latitude = Double.parseDouble(obj.getString("latitude")) / 10000000;
String speed = obj.getString("speed");
String course = obj.getString("course");
String street_name = obj.getString("street_name");
String kecamatan = obj.getString("kecamatan");
String kabupaten = obj.getString("kabupaten");
if (flag_menu != 1) {
lastloc.add(new LastLocationSetterGetter(position_id, vehicle_id, vehicle_number,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
} else {
lastloc.add(new LastLocationSetterGetter(position_id, pilih,
date_time, longitude, latitude, speed, course, street_name, kecamatan, kabupaten));
}
LatLng latLng = new LatLng(latitude, longitude);
if (lastmark != null) {
lastmark.remove();
}
//Log.i("InfoSize", String.valueOf(lastloc.size()));
//create marker for live tracking
if (flag_menu != 0) {
livelatlng.add(latLng);
if (startmark == null) {
//create start marker
startmark = mMap.addMarker(new MarkerOptions().position(latLng).title("Start").snippet(vehicle_number).icon(bdfKerani));
arstart.add(new startmark(street_name, kecamatan, kabupaten, vehicle_number, date_time, speed));
} else {
// create live tracking marker
lastmark = mMap.addMarker(new MarkerOptions().position(latLng).title(pilih).snippet(vehicle_number).icon(bdfTruck));
lastmark.setFlat(true);
lastmark.setRotation(Float.parseFloat(course));
if (lastloc.size() > 2) {
track_arrow = mMap.addMarker(new MarkerOptions()
.position(new LatLng(lastloc.get(lastloc.size() - 2).getLatitude(), lastloc.get(lastloc.size() - 2).getLongitude()))
.title(lastloc.get(lastloc.size() - 2).getPosition_id())
.snippet(lastloc.get(lastloc.size() - 2).getVehicle_number())
.icon(bdfArrow));
track_arrow.setFlat(true);
track_arrow.setRotation(Float.parseFloat(lastloc.get(lastloc.size() - 2).getCourse()));
}
}
if (livelatlng.size() > 1) {
//int ap22 = getResources().getColor(R.color.fbutton_color_wet_asphalt);
int ap23 = ContextCompat.getColor(getApplicationContext(), R.color.fbutton_color_belize_hole);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(livelatlng.get(livelatlng.size() - 2), livelatlng.get(livelatlng.size() - 1))
.width(10)
.color(ap23));
}
} else {
//create marker for last location
MarkerOptions marker = new MarkerOptions().position(latLng).title(vehicle_number).snippet(vehicle_number).icon(bdfKerani);
mMap.addMarker(marker);
}
}
Log.d("TOTALRECORD", String.valueOf(livelatlng.size()));
if (nopol != "all") {
Log.e("lastloc", String.valueOf(lastloc.size()));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastloc.get(lastloc.size() - 1).getLatitude(), lastloc.get(lastloc.size() - 1).getLongitude()), 16.0f));
//cardFind.setVisibility(View.VISIBLE);
} else {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-4.979218, 107.950524), 5.0f));
}
clickmap();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("ERRORCATCH", String.valueOf(e));
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidepDialog();
Log.e("ERROR", String.valueOf(error));
String message = null;
if (error instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (error instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (error instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (error instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
Log.e("VOLLEYERROR", message);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("prm_1", nopol);
params.put("project", project);
if (flag_menu == 1) {
params.put("from", tvfrom.getText().toString());
params.put("to", tvto.getText().toString());
}
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
public void getNopol(final String project) {
Log.d("PILIHNOPOL", "NOPOL");
//Get all police Number
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.GET_NOPOL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
nop.clear();
if (flag_menu == 0) {
nop.add("all");
}
try {
JSONObject json = new JSONObject(response);
JSONArray jsonArray = json.getJSONArray("nopol");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String plat = obj.getString("vehicle_number").replace(" ", "");
nop.add(plat);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Maps.this, android.R.layout.simple_list_item_1, nop);
search.setAdapter(arrayAdapter);
search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pilih = parent.getItemAtPosition(position).toString();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
mMap.clear();
startmark = null;
livelatlng.clear();
arstart.clear();
lastloc.clear();
if (flag_menu != 1) {
getcarloc(pilih, projectselect);
}
//Live Tracking selected
if (flag_menu == 2) {
if (live.getState().equals("TIMED_WAITING")) {
live.interrupt();
try {
live.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
live = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000 * 76);
runOnUiThread(new Runnable() {
#Override
public void run() {
getcarloc(pilih, projectselect);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
live.start();
}
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("NORESPONSE", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("project", project);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "admin_it" + ":" + "admin123";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
This is my library
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:design:25.3.0'
compile 'com.android.support:cardview-v7:25.3.0'
compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.akexorcist:googledirectionlibrary:1.0.4'
compile 'cn.pedant.sweetalert:library:1.3'
compile 'com.android.volley:volley:1.0.0'
compile 'com.wdullaer:materialdatetimepicker:2.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.1'
testCompile 'junit:junit:4.12'
}
Your handling of the Google Map inside your onCreate() method seems slightly different than what I have used and seen. Try using this code instead:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this); // don't pass Maps.this
// rest of your code here
}
My hunch is that somehow you were binding the listener twice, though I can't prove this without trying to duplicate your actual code locally.
public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;
ArrayList<Employee> arr, arr1;
Toolbar toolbar;
TextView t1, t2;
long l = 0;
private ProgressDialog progress;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setHasFixedSize(true);
arr = new ArrayList<Employee>();
arr = InitializeData();
final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
cu = new CustomAdapter(Recyclerview.this, arr);
final bank ban = new bank(Recyclerview.this);
rv.setAdapter(cu);
registerForContextMenu(rv);
ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress = ProgressDialog.show(Recyclerview.this, "dialog title",
"dialog message", true);
Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = ConstantValues.BASE_URL;
RequestBody formBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", "value3")
.build();
try {
post(url, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String JSON = response.body().string();
Log.e("res", " " + JSON);
try {
JSONObject jsonObj = new JSONObject(JSON);
JSONArray resultarr = jsonObj.getJSONArray("result");
final JSONArray resultarr1 = jsonObj.getJSONArray("result1");
if (resultarr1.length() == 0 ) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
} else {
ban.OpenDB();
/*Delete old Data from Table*/
ban.Delete("");
for (int i = 0; i < resultarr1.length(); i++) {
Employee emp = new Employee();
JSONObject result1obj = resultarr1.getJSONObject(i);
String result1Id = result1obj.getString(ConstantValues.Bank_ID);
String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
Log.e("result", " " + result1Id);
Log.e("result", " " + result1NAME);
emp.setId(result1obj.getString(ConstantValues.Bank_ID));
emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
arr.add(emp);
l = ban.InsertQryForTabEmpData(result1Id, result1NAME);
}
ban.CloseDB();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// you can access all the UI componenet
if (progress.isShowing())
progress.dismiss();
cu.notifyDataSetChanged();
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
} else {
Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
}
}
});
}
private ArrayList<Employee> InitializeData() {
ArrayList<Employee> arr_emp = new ArrayList<Employee>();
bank ban = new bank(Recyclerview.this);
long l = 0;
ban.OpenDB();
arr_emp = ban.AllSelectQryForTabEmpData();
ban.CloseDB();
return arr_emp;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
By calling wrong Api it should give dialog box saying unavailable data and is it possible to write dialog box in catch but its not showing dialog box do help me to get rid out of it I dont know where to use if and else...error is coming on String JSON = response.body().string(); thank you in advance
Create a method called like showAlertDialog
public void showAlertDialog(String title, String message) {
final AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
builder1.show();
}
});
}
Call this method from catch block.
One things which i can notice in your code is that
1) You are not creating dialog
2) You are not showing your dialog
With respect to code this is what you need to do extra in your code:
AlertDialog alertDialog = builder1.create();
alertDialog.show();
You can create separate method which you can call in your try and catch block:
public void showErrorAlert()
{
builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder1.create();
alertDialog.show();
}
Hope this helps you somehow.