How to send a notification to a distinct user of Android App - android

I am working on an android app in which client request for a job. When his job is completed I want to send a notification to submit feedback on Android App. Server Api needs to build in laravel and notifications will be send through Firebase. If you have any idea of helping material please share.
I have tried many youtube tutorials but no success. Most of them use custom php apis but i need in laravel and send notification to a specific user.
Thanks!

First of all you need to grab the InstanceToken from the app in the frontend and submit it to your backend somehow.
After you have that you can send notifications from the backend using Firebase. Have a look at this great package for some guidance on how that can be done:
https://firebase-php.readthedocs.io/en/latest/cloud-messaging.html

first of all you get devicetoken from firebase and then send notification from application using this below code.
public class UtilsFcm {
static OkHttpClient mClient;
static Context context;
static JSONArray jsonArray;
public static void sendNotification(final Context context1, final JSONArray jsonArray1) {
mClient = new OkHttpClient();
context = context1;
jsonArray = jsonArray1;
new MyTask().execute();
}
static class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject root = new JSONObject();
JSONObject notification = new JSONObject();
notification.put("text", "Your notification message");
notification.put("title", "App Title");
notification.put("line1", R.mipmap.ic_launcher);
notification.put("line2", "high");
root.put("to", jsonArray.get(i));
root.put("data", notification);
String result = postToFCM(root.toString());
Log.d("Main Activity", "Result: " + result);
return result;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject resultJson = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
static String postToFCM(String bodyString) throws IOException {
final String FCM_MESSAGE_URL = "https://fcm.googleapis.com/fcm/send";
final MediaType JSON
= MediaType.parse("application/json");
RequestBody body = RequestBody.create(JSON, bodyString);
Request request = new Request.Builder()
.url(FCM_MESSAGE_URL)
.post(body)
.addHeader("Authorization", "key=" + "firebase_web_api_key")
.build();
Response response = mClient.newCall(request).execute();
return response.body().string();
}
}
and then you call this method like this.
UtilsFcm.sendNotification(this,jsonArray);
here jsonarray have all device token.
hope this will help you.

Related

Getting data from Server too slow ? (Android)

I am trying to populate RecyclerView by the list of transactions i get from the server . but unless i put a Thread.sleep(7000) , it won't populate .
Does it take this much time to get data from server side ? If yes , Is there any faster alternative ?
or is getting the string from json response and adding object to list is time consuming ? because this sleep is just working for adding 5 rows in list. when i try to run loop for whole number of rows i don't get any data .
My host is PythonAnywhere .
API response is in json and has around 400 records :
http://sairav.pythonanywhere.com/getTransaction
Using :
Android Asynchronous Http Client:::
compile 'com.loopj.android:android-async-http:1.4.9'
public List<Transaction> getTransactions(final boolean getAll) {
Thread bgThread =null;
final List<Transaction> trList=new ArrayList<>();
RequestParams requestParams = new RequestParams();
requestParams.put("uid", Profile.getCurrentProfile().getId());
PAAPI.post("/getTransaction", requestParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray jsonArray) {
Transaction trr = null;
if (getAll) {
for (int i = 0; i < 5; i++) {
try {
//String a = jsonArray.getString(i);
JSONObject jsonObject = jsonArray.getJSONObject(i);
//JSONArray arrayWithElements = jsonObject.toJSONArray(new JSONArray(new String[]{"name","desc","amount","ttype","uid","ttime"}));
trr = new Transaction(context);
trr.uname = jsonObject.getString("uname");
trr.desc = jsonObject.getString("description");
trr.amount = jsonObject.getString("amount");
trr.type = jsonObject.getString("type");
trr.uid = jsonObject.getString("uid");
trr.date = jsonObject.getString("ttime");
trList.add(trr);
// Toast.makeText(context,"size is bro :"+trList.size(),Toast.LENGTH_SHORT).show();
if (i == 1) {
// Toast.makeText(context, trr.uname + "-" + desc + "-" + trr.amount + "-" + trr.type + "-" + trr.uid + "-" + trr.date, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Do something with the response
}
});
try {
Toast.makeText(context,"sleeping bo",Toast.LENGTH_SHORT).show();
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Toast.makeText(context, "listsize final is" + trList.size(), Toast.LENGTH_SHORT).show();
return trList;
}
class PAAPI {
protected static final String BASE_URL = "http://sairav.pythonanywhere.com";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
If you are certain that getString() operation is taking too much time to perform then you can use progress dialog instead of using Thread.sleep()
private class PAAPI extends AsyncTask<Boolean, Void, List<Transaction> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
//set message of the dialog
dialog.setMessage("Loading...");
//show dialog
dialog.show();
super.onPreExecute();
}
protected Void doInBackground(Boolean... args) {
// do background work here
return null;
}
protected void onPostExecute(List<Transaction> result) {
// do UI work here
if(dialog != null && dialog.isShowing()){
dialog.dismiss()
}
}
}
and later use it as new PAAPI().execute(getAll);
Use the retrofit library available to retrieve or post the data from a JSON URL ...it is very easy to use and is efficient

Get JSON response in listview and how to show it in listview?

I am a beginner in Android. I want to get a JSON response in a list and show it in a ListView . How to do this?
Here is my code for JSON post.
public class NewTest extends AppCompatActivity { TextView
txtJson;
Button btnOkay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_test);
txtJson= (TextView) findViewById(R.id.txtJson);
assert (findViewById(R.id.btnOkay)) != null;
(findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { new TaskPostWebService("written url here").execute(((TextView)
findViewById(R.id.txtJson)).getText().toString());
}
}); }
private class TaskPostWebService extends AsyncTask<String,Void,String> {
private String url;
private ProgressDialog progressDialog;
private JSONParser jsonParser;
public TaskPostWebService(String url ){
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(NewTest.this,"","");
}
#Override
protected String doInBackground(String... params) {
String fact = "";
try {
final MediaType JSON = MediaType.parse("application/json");
android.util.Log.e("charset", "charset - " + JSON.charset());
OkHttpClient client = new OkHttpClient();
//Create a JSONObject with the data to be sent to the server
final JSONObject dataToSend = new JSONObject()
.put("nonce", "G9Ivek")
.put("iUserId", "477");
android.util.Log.e("data - ", "data - " + dataToSend.toString());
//Create request object
Request request = new Request.Builder()
.url("written url here")
.post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
.addHeader("Content-Type", "application/json")
.build();
android.util.Log.e("request - ", "request - " + request.toString());
android.util.Log.e("headers - ", "headers - " + request.headers().toString());
android.util.Log.e("body - ", "body - " + request.body().toString());
//Make the request
Response response = client.newCall(request).execute();
android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
String responseData = response.body().string();
//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);
//See the response from the server
Log.i("response data", dataReceived.toString());
}
catch (Exception e){
e.printStackTrace();
}
return fact;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView text = (TextView) findViewById(R.id.txtJson);
text.setText(s);
progressDialog.dismiss();
}
}
So, how can I get a response in a list and show it in a ListView?
Welcome to stackOverflow,
as you are beginner so before going to complete solutions, you can think and follow following steps.
1.Network request:
For network request, we have lib volley(by Google) and retrofit(by Square). You can use this for network request and response.
2.JSON Parsing: You can used eigther GSON lib or using JSONObject/ jsonArray to parse json data. I'll recommend you to write your own parsing code for better understanding of JSON parsing.
3.ListView data binding: At this step, you should have parsed data in list(other data structure can be used to store data also). Create Adapter and bind listview with adapters.
I have not provided solutions for this, you should implement yourself and let me know for any doubts. Hope this should work.
ArrayList<JSONObject> arrayListJson;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
ListView listView = (ListView) fragmentView.findViewById(R.id.listView);
adapter = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
now in a separate thread:
JSONObject jResponse = new JSONObject(responseStr);
JSONArray jArray= jResponse.getJSONArray("OUTER_KEY");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
arrayList.add(jsonObject.optString("INNER_KEY"));
arrayListJson.add(jsonObject);
}
adapter.notifyDataSetChanged();

woocommerce rest api OAuth authentication in android

what is the sample code for OAuth 1.0a(one leg) authentication in android?
is there a library for it? .
I use eclipse and i'm new in android. can anyone clarify the path for me?
to answer my own question:
download Scrib.jar library and add it to your lib folder(you can download it from (here)
create a class with name "OneLeggedApi10" and copy below code in it:
import org.scribe.builder.api.DefaultApi10a;
import org.scribe.model.Verb;
import org.scribe.model.Token;
public class OneLeggedApi10 extends DefaultApi10a {
#Override
public String getAccessTokenEndpoint() {
return null;
}
#Override
public String getRequestTokenEndpoint() {
return null;
}
#Override
public String getAuthorizationUrl(Token requestToken) {
return null;
}
#Override
public Verb getAccessTokenVerb() {
return Verb.GET;
}
#Override
public Verb getRequestTokenVerb() {
return Verb.GET;
}
}
now you can do OAuth authentication:
String RESOURCE_URL = "http://yourDomain.com/wc-api/v3/orders";
String SCOPE = "*"; //all permissions
Response response;
OAuthRequest request;
String responsebody = "";
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("your_key")
.apiSecret("your_apiSecret")
.signatureType(SignatureType.QueryString)
.debug()
/*.scope(SCOPE).*/
.build();
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
// Now let's go and ask for a protected resource!
Log.d("scribe","Now we're going to access a protected resource...");
try{
response = request.send();
if (response.isSuccessful()) {
responsebody = response.getBody();
}
} catch (Exception e) {
e.printStackTrace();
}
note that if you are not using above code in an AsyncTask,then put the request.send() part in a thread (actually whole try_catch section) for avoiding run in main thread exception
finally if you want to send data,for example in a case that you want to update an order,replace
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
with these lines:
String payload = yourJsonOBJ.toString();
request = new OAuthRequest(Verb.PUT, RESOURCE_URL);
request.addHeader("Content-Type", "application/json");
request.addPayload(payload);
more information in WooCommerce Documentation site
Hope it help ;)
good luck..
new Thread() {
#Override
public void run() {
String RESOURCE_URL = "http://www.woocommerce.com/wp-json/wc/v1/api/";
String SCOPE = "*"; //all permissions
Response response;
OAuthRequest request;
String responsebody = "";
OAuthService service = new ServiceBuilder().provider(OneLeggedApi10.class)
.apiKey("yourConsumerKey")
.apiSecret("yourConsumerSecret")
.signatureType(SignatureType.QueryString)
.debug()
/*.scope(SCOPE).*/
.build();
request = new OAuthRequest(Verb.GET, RESOURCE_URL);
service.signRequest(new Token("", ""), request);
// Now let's go and ask for a protected resource!
Log.d("scribe","Now we're going to access a protected resource...");
try {
response = request.send();
if (response.isSuccessful()) {
responsebody = response.getBody();
Log.v("response", responsebody);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
This code is updated from above, the above code is working getting JSON from wordpress Woocommerce API.
But if you wondering how to use Thread this is the answer.
And I add Log.v for see the json response.

Android/OkHttp - client.newCall(request).execute() always return exception

I have to make an android application project. At first, I tried to use HttpURLConnection but it didn't work. So after a discussion with a friend, I tried to use OkHttp. I all time got an exception for "responses = client.newCall(request).execute();". After long hours of searching, I just try this code, which is the tutorial of "https://github.com/square/okhttp/wiki/Recipes"
And..... It doesn't work too !
My question is, what is really happening? I'm currently developping a 4.0.3 application under Android Studio 1.5.1. I also add the two following dependencies:
// DEPENDENCIES
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
// Class Http
public static String run(String url) throws IOException {
try {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodingBuilder()
.add("login", "Mr. X")
.add("password", "********")
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response responses = null;
try {
Log.d("DEBUGG ", "----------------------------------");
responses = client.newCall(request).execute();
Log.d("DEBUGG ", "----------------------------------");
return (responses.body().string());
} catch (IOException e) {
e.printStackTrace();
}
String jsonData = responses.body().string();
JSONObject Jobject = new JSONObject(jsonData);
JSONArray Jarray = Jobject.getJSONArray("employees");
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
}
} catch (JSONException e) {
}
return null;
}
// MainActivity
private TextView textView;
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textViewJSon);
button = (Button)findViewById(R.id.Hit);
textView.setText("Hello !");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
textView.setText(Http.run("https://epitech-api.herokuapp.com/login"));
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
{ ANSWER }
I finally tried to use multi-threading programming like said Selvin and it works well So the solution is to open another thread
public static int responseCode = 0;
public static String responseString = "";
public static Thread login = new Thread(new Runnable() {
private OkHttpClient client = new OkHttpClient();
private String url = "https://epitech-api.herokuapp.com/login";
private User user = User.getUser();
public void run() {
try {
// Build the request
RequestBody formBody = new FormEncodingBuilder()
.add("login", user._login)
.add("password", user._password)
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response responses = null;
// Reset the response code
responseCode = 0;
// Make the request
responses = client.newCall(request).execute();
if ((responseCode = responses.code()) == 200) {
// Get response
String jsonData = responses.body().string();
// Transform reponse to JSon Object
JSONObject json = new JSONObject(jsonData);
// Use the JSon Object
user._token = json.getString("token");
}
} catch (IOException e) {
responseString = e.toString();
} catch (JSONException e) {
responseString = e.toString();
}
}
});
Most probably, since Honeycomb, network operation in main thread is restricted. So, calling the execute() method is useful when you are already in background thread. But if you are in the main thread then enqueue() will be helpful as it will process the network request in background thread and return the response in main thread. In that case, you just need to pass a callback to get the response.
As you mentioned, using Okhttp is a suggestion from your friend. I also want to recommend you to use Retrofit. It will make your code nicer and maintainable and also handle the threading on behalf of you. Under the hood, it uses Okhttp. More importantly, since version 2.6.0 you can feel the synchronous experience with the help of Coroutines.

IOException on HTTP post request

I am creating a login form using Account Manageraccount manager and HTTP task for webservices. when i enter the username and password it gives me IOException, I have added the INTERNET PERMISSION and all the account related permission. If anyone knows any github example which uses account manager and webservices please share the url.please help.this is the code
`
public void userSignUp(String name, String email, String pass, String authType, final SignUPHandler handler) {
HttpPost localHttpPost = new HttpPost(ApiURL.USERSIGNIN);
JSONObject json_user = new JSONObject();
try {
json_user.put("email", email);
json_user.put("password", pass);
StringEntity se = new StringEntity(json_user.toString());
localHttpPost.setEntity(se);
if ((this.currentTask != null) && (this.currentTask.getStatus() != AsyncTask.Status.FINISHED))
this.currentTask.cancel(true);
this.currentTask = new HttpTask(ApiURL.HTTP_LOGIN_HOST, new HttpResponseHandler() {
public void handleException(Exception paramException) {
Log.e("Exceptionssssssss:", "" + paramException);
handler.handleException(paramException);
}
public void handleResponse(JSONObject json)
throws IOException {
Log.d("response", "" + json);
handler.handleResponse(json);
}
});
this.currentTask.execute(new HttpUriRequest[]{localHttpPost});
} catch (Exception localException) {
Log.d("Exception ID", "" + localException.getMessage());
}
}`

Categories

Resources