Toast in Fragment ( No syntax but no show when running the code) - android

I am a newbie for android development. Recently, i faced a problem when i want to use toast and alert dialog.
Toast.makeText(getActivity(), " error", Toast.LENGTH_LONG).show();
I have tried getActivity().getApplicationContext() instead of only getActivity
both code have no syntax error but show nothing when i run
More code:
public class RegisterFragment extends Fragment {
...
.... onCreate...
.... GetData();...
..
In GetData()
inputStream = response.getEntity().getContent();
String error = convertInputStreamToString(inputStream);
JSONObject data = new JSONObject(error);
String test123 = data.getJSONObject("error").getString("code");
RegisterFragment register = new RegisterFragment();
register.makeToast(test123);
...
..
}
In makeToast function:
public void makeToast(String error){
Log.v("error",error);
Toast.makeText(getActivity(), "missing input",Toast.LENGTH_LONG).show();
}
}

The toast can only be shown on a UI Thread. Since you are making a network call the response must be running on a background thread. change your method to
public void makeToast(String error) {
Log.v("error", error);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "missing input", Toast.LENGTH_LONG).show();
}
});
}

Can you please try below ? Actually I have faced same issue 1 month ago, I have solved by below code:
new CountDownTimer(2000,2000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
makeToast("Your Error Message");
}
}.start();
Hope it will help you.

RegisterFragment register = new RegisterFragment();
register.makeToast(test123);
This is your problem. You have just created an instance of RegisterFragment, but it is not attached to an Activity at this point. Therefore, the getActivity() call within makeToast() will return null.

Related

how to update delivery status in PHP with this android code

I don't even know I am right are wrong. My situation of thinking is currently null. can some please tell me how to update deliverystatus
This is code in AdapterClass
delivered.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String serverURL= PathUrls.pathUrl+"evs_updatedeliverystatus.php?db="+companyName.getString("companyName","")+"&invoiceid="+dlb.getInvoiceNo()+"&deliverystatus=1";
JsonObjectRequest jsonArrayRequest=new JsonObjectRequest(serverURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("update delivery list",response.toString());
deliveryListBeans.clear();
notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error DeliveryList:%n %s ", error);
Toast.makeText(ct,"NetworkError Not Responding", Toast.LENGTH_SHORT).show();
}
});
//Toast.makeText(ct, "companyName"+companyName.getString("companyName","").toString(), Toast.LENGTH_LONG).show();
VolleySingleton.getsInstance().getRequestQueue().add(jsonArrayRequest);
}
});
I already tested PHP with its URL it is working fine
I think you should check data follow
1 . Make sure serverURL is correct.
2 . While connecting to server you already call UpdateDeliveryList Activity. It will destroy current Activity
3 . When server return response successful:
deliveryListBeans.clear();// Clear list
notifyDataSetChanged(); // and update list
I dont see you get deliverystatus from onResponse()

Null context in onResponse callback method retrofit android

I have a DialogFragment. When i click the OK button, i execute a retrofit call to my api like this
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
int code = response.code();
if (code == 200) {
LoginResponse lr = response.body();
if (lr.getError()) {
Utils.showToast(getActivity(), "Error! Los datos son incorrectos.");
} else {
startActivity(new Intent(getActivity(), ConfigGeneralActivity.class));
}
} else {
Toast.makeText(getActivity(), "Error: " + String.valueOf(code), Toast.LENGTH_LONG).show();
}
}
at this part of the code, getActivity() is null.
Another option is to pass the context from the oncreatedialog to this callback, but when i do this, i got the error that says activity is not attached to fragment.
I know i can implement Otto but it's too complex for what i want to do. I just want to start a new activity from a retrofit callback inside a DialogFragment.
Any ideas? Thanks!
You need to runOnUiThread to get the Context inside OnResponse Callback
Like:
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//your code
}
});
}
}

Retrofit response body sometimes error, but sometimes success

I'm getting some error when post some data.
My app could register a new user, send data register to server and then return a result.
result if register is success
{
"res": "success"
}
result if register is failed
{
"res": "customer id not found"
}
Here my piece of code for post data
Register register = new Register(nameStr, emailStr, phoneStr, passStr, rePassStr,customerIDStr );
Call<ResultRegister> call = apiInterface.registration(register);
call.enqueue(new Callback<ResultRegister>() {
#Override
public void onResponse(Call<ResultRegister> call, Response<ResultRegister> response) {
String responseString;
responseString = response.body().getRes();
if(responseString.equalsIgnoreCase("success")){
Toast.makeText(getActivity(), "Register Success", Toast.LENGTH_SHORT).show();
Fragment fragment = new LoginFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.wrap_login_container, fragment)
.addToBackStack(null).commit();
}else{
Toast.makeText(getActivity(), "Register Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResultRegister> call, Throwable t) {
t.printStackTrace();
call.cancel();
Toast.makeText(getActivity(), "Please check your network connection and internet permission", Toast.LENGTH_LONG).show();
}
});
Everything is fine if the register return success, but if register return error a null pointer exception appears, pointing to this line:
responseString = response.body().getRes();
EDIT
this is my ResultRegister class
public class ResultRegister {
#SerializedName("res")
String res;
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
}
Any solution??
I have solved my problem. The main problem is when the register is failed, the error code is 500 (internal error server). So the response.body() is null.

Toast doesn't disapear

I have made an application that sends messages from my smartphone to my smartwatch.
This is the class where I create a Message that I can send to smartwatch.
public class Message implements GoogleApiClient.ConnectionCallbacks{
private String message;
private Application app;
public Message(String message, Application app){
this.message=message;
this.app = app;
}
public void sendMessage() {
new Thread( new Runnable() {
#Override
public void run() {
GoogleApiClient clientApi = new GoogleApiClient.Builder(aplicacao.getApplicationContext())
.addApiIfAvailable( Wearable.API )
.build();
clientApi.connect();
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( clientApi ).await();
if(nodes.getNodes().isEmpty())
Log.w("No signal!","No signal!");
else {
for (Node node : nodes.getNodes()) {
Wearable.MessageApi.sendMessage(clientApi, node.getId(), message, message.getBytes()).await();
}
}
clientApi.disconnect();
}
}).start();
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
}
When I want to send a Message to smartwatch I use this two lines of code:
Message message = new Message("Message", getApplication());
message.sendMessage();
I made this service on my smartwatch application to receive messages from smartphone.
When I receive a message I show a Toast with the text of that message:
public class ReceiveMessages extends WearableListenerService {
#Override
public void onMessageReceived(MessageEvent event) {
String message = event.getPath();
showMessages(message);
}
private void showMessages(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
The smartwatch is receiving the message and shows the text of the message correctly, it does not disappear after Toast.LENGTH_SHORT.
I want to know whether there is any problem in my code (I don't have any infinite loop).
Thanks.
TOAST IN SERVICE? HAHA THIS IS YOUR SOLUTION:
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Lumos Maxima", Toast.LENGTH_LONG).show();
}
});
Be sure your Thread is terminated cus it seems you are sending many toasts that appear like one.
You use this also:
Toast.makeText(Activityname.this, "message", Toast.LENGTH_SHORT).show();
Or if it is outside the class, you'll need to get your activity context (pass it in the constructor etc.)
How to use Toast when I cant use "this" as context
Try next code:
Toast.makeText(getApplicationContext(), "Your Message", Toast.LENGTH_LONG).show();
You use this also:
Toast.makeText(Activityname.this, "message", Toast.LENGTH_SHORT).show();

Async-http often hangs.

I start a ProgressDialog when I start my async request and on seemingly random occasions the dialogue does not dismiss (code does not fire onSuccess or onFailure). I handle both possible success responses from the server (one of which is an error) and I have a failure block so in theory the ProgressDialog should always dismiss. Can someone tell what event I am missing? Or is there a better structure?
My code structure:
I have a Gateway class that handles all the networking
The calling calls handles the .show() and .dismiss() events for the dialog
Gateway:
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void loadItems(final ItemAdapter itemAdapter, int itemID) {
final String url = String.format(Constants.URL_ITEMS, itemID);
post(url, null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
try {
if (!response.isNull("items")) {
itemAdapter.updateData(items);
} else if (!response.isNull("error")) {
itemAdapter.signalError(response.getString("error"));
}
} catch (JSONException e) {
itemAdapter.signalError("An unknown error has occurred");
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error)
{
if (error instanceof SocketTimeoutException || error instanceof ConnectTimeoutException) {
itemAdapter.signalError("Connection timeout! Please check that you are connected to the internet");
} else {
itemAdapter.signalError("An unknown error has occurred");
}
}
});
}
The adapter:
public ItemAdapter(Context context, int itemID) {
progressDialog = ProgressDialog.show(context, "Items",
"Loading items", true);
Gateway.loadItems(this, itemID);
}
public void updateData(ArrayList<Items> items) {
progressDialog.dismiss();
this.items = items;
notifyDataSetChanged();
}
public void signalError(String errorMessage) {
progressDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null).show();
}
I have no idea what your code is doing, but your if statements look suspicious.
if (!response.isNull("items")) {
itemAdapter.updateData(items);
} else if (!response.isNull("error")) {
itemAdapter.signalError(response.getString("error"));
}
could it be that none of the two conditions are met? If so, the dialog will not be dismissed. You only dismiss it on exception or if one of the above conditions are met.
I read somewhere that there is a design flaw in the library and people had some problems with the same issue.
But the most reliable solution was to override all the onSuccess and onFailure methods in the JsonHttpResponseHandler. In that way you can be sure that a communication is going on.
Hope this helps
Handle else case also onSuccess method like
#Override
public void onSuccess(JSONObject response) {
try {
if (!response.isNull("items")) {
itemAdapter.updateData(items);
} else if (!response.isNull("error")) {
itemAdapter.signalError(response.getString("error"));
} else {
// Code to dismiss the dialog
}
} catch (JSONException e) {
itemAdapter.signalError("An unknown error has occurred");
e.printStackTrace();
}
}
If your main concern is just closing ProgressDialog .. then try like this .
try{
runOnUiThread(new Runnable() {
public void run() {
progressDialog.dismiss();
}
});
}catch(Exception beauty)
{
// Log error if any ..
}
Hope it helps!

Categories

Resources