400 error code while using twitter search API - java

I am trying to query Twitter on my android app and retrieve all the tweets related to the keyword "AgilebizKE" using retrofit.
I am currently getting a 400 error code. After doing some research i have found that either my query parameters are wrong or my request isn't 'authorized'. However, i see no issues with my query parameters.
Main Activity relevant code:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.twitter.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
tweetAPI tweetapi = retrofit.create(tweetAPI.class);
Call<List<tweet>> call = tweetapi.getTweets();
call.enqueue(new Callback<List<tweet>>() {
#Override
public void onResponse(Call<List<tweet>> call, Response<List<tweet>> response) {
if (!response.isSuccessful()) {
tweets_results.setText("code: " + response.code());
return;
}
List<tweet> tweets = response.body();
for (tweet tweet : tweets){
String content = "";
content+="Created at: "+tweet.getCreated_at()+"\n";
content+="Text: "+tweet.getText()+"\n";
content+="Retweets: "+tweet.getRetweet_count()+"\n";
content+="Favs: "+tweet.getFavorite_count()+"\n\n";
tweets_results.append(content);
}
}
#Override
public void onFailure(Call<List<tweet>> call, Throwable t) {
tweets_results.setText(t.getMessage());
}
});
Interface
public interface tweetAPI {
#GET("1.1/search/tweets.json?q=AgilebizKE")
Call<List<tweet>> getTweets();
}
Tweet pojo
ublic class tweet {
private String created_at;
private String text;
private String retweet_count;
private String favorite_count;
public String getCreated_at() {
return created_at;
}
public String getText() {
return text;
}
public String getRetweet_count() {
return retweet_count;
}
public String getFavorite_count() {
return favorite_count;
}
}

Ok so i decided to switch to using twitter4j instead of retrofit since it is much easier and quicker. For more details on this go to this site: http://twitter4j.org/
I will now explain how i implemented twitter search functionality for my use case.
Android Manifest
Add these permissions
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
build.gradle(Module: app)
Add this
implementation files('libs/twitter4j-core-4.0.7.jar')
Next, you have to create a JobIntentService so as to run the network functions, that twitter4j requires, off the main thread. This is the video I used to better understand this concept: https://www.youtube.com/watch?v=B4gFbWnNpac&t=567s
TweetJobIntentService.java
Before proceeding any further, register your app and get its personal OAuth twitter credentials from the twitter for devs portal. Fill these credentials where I have indicated in the code sample below.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class TweetJobIntentService extends JobIntentService {
private static final String TAG = "TweetJobIntentService";
static void enqueueWork(Context context, Intent work) {
enqueueWork(context, TweetJobIntentService.class, 123, work);
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.d(TAG, "onHandleWork: ");
List tweets = new ArrayList();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("Your_OAuthConsumerKey", "Your_AuthConsumerSecret");
AccessToken accessToken = new AccessToken("Your_OAuthAccessToken", "Your_OAuthAccessTokenSecret");
twitter.setOAuthAccessToken(accessToken);
Query query = new Query(Your_search_Keyword);
try {
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
Log.d(TAG, status.getText());
}
if (isStopped()) return;
} catch (TwitterException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDeastroy");
}
#Override
public boolean onStopCurrentWork() {
Log.d(TAG, "onStopCurrentWork");
return super.onStopCurrentWork();
}
}
Your retrieved tweets should be printed in logcat.
Your Main activity/fragment
Here, you will initiate/call your JobIntentService. For me, my service is initiated in a fragment in the onViewCreated method. Yours can be initiated following a button click or whatever you wish.
Intent jobserviceIntent = new Intent(getActivity(), TweetJobIntentService.class);
TweetJobIntentService.enqueueWork(getActivity(), jobserviceIntent);

Related

Android Studio Retrofit Call Failure

I'm trying to use Retrofit in my app via Java. I'm using this worldtime API. You can call this URL in your browser to see the response : http://worldtimeapi.org/api/timezone/Europe/Istanbul (response comes too late, just refresh your browser)
I added this line to my AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
I added these to gradle
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
I only want to see few keys of response, so I created a class TimeForIstanbul.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TimeForIstanbul {
#SerializedName("day_of_week")
#Expose
public Integer dayOfWeek;
#SerializedName("utc_datetime")
#Expose
public String utcDatetime;
#SerializedName("week_number")
#Expose
public Integer weekNumber;
public Integer getDayOfWeek() {
return dayOfWeek;
}
public void setDayOfWeek(Integer dayOfWeek) {
this.dayOfWeek = dayOfWeek;
}
public String getUtcDatetime() {
return utcDatetime;
}
public void setUtcDatetime(String utcDatetime) {
this.utcDatetime = utcDatetime;
}
public Integer getWeekNumber() {
return weekNumber;
}
public void setWeekNumber(Integer weekNumber) {
this.weekNumber = weekNumber;
}
}
I created my interface ApiService.java
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiService {
#GET("Europe/Istanbul")
Call<TimeForIstanbul> getTime();
}
And simply I edited my MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
private ApiService apiService;
private String BASE_URL = "http://worldtimeapi.org/api/timezone/";
private Call<TimeForIstanbul> timeForIstanbulCall;
private TimeForIstanbul timeForIstanbul;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRetrofitSettings();
}
private void setRetrofitSettings(){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
timeForIstanbulCall = apiService.getTime();
timeForIstanbulCall.enqueue(new Callback<TimeForIstanbul>() {
#Override
public void onResponse(Call<TimeForIstanbul> call, Response<TimeForIstanbul> response) {
if(response.isSuccessful()){
timeForIstanbul = response.body();
System.out.println(timeForIstanbul.getDayOfWeek());
}
}
#Override
public void onFailure(Call<TimeForIstanbul> call, Throwable t) {
System.out.println("Error is ");
System.out.println(t.toString());
}
});
}
}
And when I run this app, I see
I/System.out: Error is
java.net.UnknownServiceException: CLEARTEXT communication to worldtimeapi.org not permitted by network security policy
on logcat so it goes to onFailure. What am I missing? What is wrong here? My resource for this example is this video
What you have to do to solve the problem is add this on my manifest.xml
android:usesCleartextTraffic="true"
But you may have to use other approaches you can take a look on android-8-cleartext-http-traffic-not-permitted.
android:usesCleartextTraffic="true"
Add This line in your manifest application
It will allow to connect with without SSL certified URL
You have to use https with that api. Change:
private String BASE_URL = "http://worldtimeapi.org/api/timezone/";
to
private String BASE_URL = "https://worldtimeapi.org/api/timezone/";
If you want to have a cleartext communication with the api you have to follow the steps from the Android documentation

Unable to integrate java code to my react native project - error: incompatible types: ReactApplicationContext cannot be converted to Activity

I am trying to bridge java code with my react native project.
My flow is this - when the user clicks on my pay button in react native, it routes to a page (which is a payment gateway) written in java and then when the user is done with the payment process it routes back to the initial page in react native.
I am getting the error below:
HelloWorldModule.java:56: error: incompatible types: ReactApplicationContext cannot be converted
to Activity
new RavePayManager((Activity)reactContext).setAmount(Double.parseDouble(String.valueOf(amount)))
Please see below my code:
//React native code to connect to java
// We are importing the native Java module here
import {NativeModules} from 'react-native';
var HelloWorld = NativeModules.HelloWorld;
// type Props = {};
export default class App extends Component {
// async function to call the Java native method
async sayHiFromJava() {
HelloWorld.sayHi( (err) => {console.log(err)}, (msg) => {console.log(msg)} );
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={ this.sayHiFromJava }>
<Text>Invoke native Java code</Text>
</TouchableOpacity>
</View>
);
}
}
// MainApplication.java
package com.packagename;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.RNFetchBlob.RNFetchBlobPackage;
import com.reactnativecommunity.geolocation.GeolocationPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.facebook.react.bridge.Callback;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new HelloWorldPackage(MainApplication.this)); ---- // added payment gateway
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
#Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this); // Remove this line if you don't want Flipper enabled
}
/**
* Loads Flipper in React Native templates.
*
* #param context
*/
private static void initializeFlipper(Context context) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
// HelloWorldModule.java - payment gateway code
package com.packagename;
import com.facebook.react.bridge.ReactApplicationContext;
import android.content.Context;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.flutterwave.raveandroid.RaveConstants;
import com.flutterwave.raveandroid.RavePayActivity;
import com.flutterwave.raveandroid.RavePayManager;
import android.app.Activity;
public class HelloWorldModule extends ReactContextBaseJavaModule {
Context context;
ReactApplicationContext reactContext;
public HelloWorldModule(ReactApplicationContext reactContext,Context context) {
super(reactContext); //required by React Native
this.reactContext= reactContext;
this.context= context;
}
#Override
//getName is required to define the name of the module represented in JavaScript
public String getName() {
return "HelloWorld";
}
#ReactMethod
public void sayHi(Callback errorCallback, Callback successCallback) {
// try {
// System.out.println("Greetings from Java");
// successCallback.invoke("Callback : Greetings from Java");
// } catch (IllegalViewOperationException e) {
// errorCallback.invoke(e.getMessage());
// }
try{
int amount = 100;//call.argument("amount");
String narration = "Payment for soup";//call.argument("nara");
String countryCode = "NG"; //call.argument("countryCode");
String currency = "NGN"; //call.argument("currency");
String amountText = "100";//call.argument("amountText");
String email = "haha#gmail.com";//call.argument("email");
String name = "King John";//call.argument("name");
String paymentId = "a98sjkhdjdu";//call.argument("paymentId");
String key ="*********-***********-X";
String secret = "*********-*********-X";
new RavePayManager((Activity)reactContext).setAmount(Double.parseDouble(String.valueOf(amount)))
.setCountry(countryCode)
.setCurrency(currency)
.setEmail(email)
.setfName(name)
.setlName("")
.setNarration(narration)
.setPublicKey(key)
.setTxRef(paymentId)
.acceptMpesaPayments(false)
.acceptAccountPayments(true)
.acceptCardPayments(true)
.acceptGHMobileMoneyPayments(false)
.onStagingEnv(false)
.initialize();
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
}
// HelloWorldPackage.java
package com.packagename;
import com.facebook.react.ReactPackage;
import android.content.Context;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.visioncapitaleye.HelloWorldModule;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HelloWorldPackage implements ReactPackage {
Context context;
HelloWorldPackage(Context context) {
this.context = context;
}
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override
public List<NativeModule> createNativeModules(
ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
//this is where you register the module
modules.add(new HelloWorldModule(reactContext,context)); // added HelloWorldModule
return modules;
}
}
I am new to java and cant seem to figure out what I am doing wrong.
Please assist.
I had a similar issue while trying to integrate a sdk into an existing react-native project. Try the following to see if it works for you. Instead of casting reactContext into Activity, just get the current activity and use that.
final Activity activity = getCurrentActivity();

Android MVVM architecture and observing changes on data from an API

I'm new to the Android MVVM architecture. I have an API running locally with data ("deals") in it. I'd like to simply make a request to the API and display that data in a text field. Currently the data does not show up when the fragment is first loaded, but if I go to another activity and then back to the fragment it loads.
There are 3 classes of importance here.
DashboardViewModel.java:
package com.example.android_client.ui.dashboard;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.example.android_client.models.Deal;
import com.example.android_client.repository.Repository;
import java.util.List;
public class DashboardViewModel extends ViewModel {
private MutableLiveData<String> mText;
private Repository repository;
private MutableLiveData<List<Deal>> deals = null;
public void init() {
if(this.deals == null) {
this.repository = Repository.getInstance();
this.deals = this.repository.getDeals();
}
}
public DashboardViewModel() {
this.mText = new MutableLiveData<>();
}
public LiveData<List<Deal>> getDeals() {
return this.deals;
}
}
DashboardFragment.java:
package com.example.android_client.ui.dashboard;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.example.android_client.R;
import com.example.android_client.models.Deal;
import java.util.List;
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
final TextView textView = root.findViewById(R.id.text_dashboard);
dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
dashboardViewModel.init();
dashboardViewModel.getDeals().observe(this, new Observer<List<Deal>>() {
#Override
public void onChanged(List<Deal> deals) {
if (deals != null && !deals.isEmpty()) {
System.out.println(deals.get(0).toString());
textView.setText(deals.get(0).toString());
}
}
});
return root;
}
}
and Repository.java:
package com.example.android_client.repository;
import androidx.lifecycle.MutableLiveData;
import com.example.android_client.models.Deal;
import com.google.gson.Gson;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class Repository {
private static Repository instance;
private ArrayList<Deal> dealsList = new ArrayList<>();
private final OkHttpClient client = new OkHttpClient();
public static Repository getInstance() {
if(instance == null) {
instance = new Repository();
}
return instance;
}
private Repository() {}
public MutableLiveData<List<Deal>> getDeals() {
setDeals();
MutableLiveData<List<Deal>> deals = new MutableLiveData<>();
deals.setValue(dealsList);
return deals;
}
private void setDeals() {
Request request = new Request.Builder()
.url("http://10.0.2.2:8000/api/deals?<params here>")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
String jsonDeals = responseBody.string(); // can only call string() once or you'll get an IllegalStateException
Deal[] deals = new Gson().fromJson(jsonDeals, Deal[].class);
dealsList = new ArrayList<>(Arrays.asList(deals));
}
}
});
}
}
When stepping through the code in the Repository class I can see that setDeals() is called when I load the fragment, and the request in the callback is queued. The first time getDeals() returns, it returns a list of 0 deals (within the MutableLiveData object).
onResponse in the callback doesn't run until the fragment is already loaded. When debugging I can see that the data is in the objects (all the Gson stuff works fine), but onChanged doesn't get called again (which sets the text view).
Am I not observing changes on the deals properly?
Your code is not working due to a new live data instance be created whenever getDeals() is called and the api response value be informed to other live data instance. You must set api response value to same instance of MutableLiveData returned by getDeals()
I'm not saying that it is the best architectural solution, but if you create a mutable live data as a class attribute and return it whenever getDeals() is called. Probably, it's going to work.
Also, a good practice is return a LiveData and not a MutableLiveData to not allowing a external component modify the internal value.
Please, take a look at the piece of code below.
OBS: Maybe, there is some syntax error, because I have not compiled it
import com.example.android_client.models.Deal;
import com.google.gson.Gson;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class Repository {
private static Repository instance;
private ArrayList<Deal> dealsList = new ArrayList<>();
private final OkHttpClient client = new OkHttpClient();
private MutableLiveData<List<Deal>> _deals = new MutableLiveData<>();
private LiveData<List<Deal>> deals = _deals
public static Repository getInstance() {
if(instance == null) {
instance = new Repository();
}
return instance;
}
private Repository() {}
public LiveData<List<Deal>> getDeals() {
setDeals();
return deals;
}
private void setDeals() {
Request request = new Request.Builder()
.url("http://10.0.2.2:8000/api/deals?<params here>")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
String jsonDeals = responseBody.string(); // can only call string() once or you'll get an IllegalStateException
Deal[] deals = new Gson().fromJson(jsonDeals, Deal[].class);
dealsList = new ArrayList<>(Arrays.asList(deals));
_deals.setValue(dealsList);
}
}
});
}
}
When
I think this would help. Try postValue on MutableLiveData in onResponse of network call. Please change your repository class like below:
package com.example.android_client.repository;
import androidx.lifecycle.MutableLiveData;
import com.example.android_client.models.Deal;
import com.google.gson.Gson;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class Repository {
private static Repository instance;
private ArrayList<Deal> dealsList = new ArrayList<>();
private final OkHttpClient client = new OkHttpClient();
MutableLiveData<List<Deal>> deals = new MutableLiveData<>();
public static Repository getInstance() {
if(instance == null) {
instance = new Repository();
}
return instance;
}
private Repository() {}
private MutableLiveData<List<Deal>> getDeals() {
Request request = new Request.Builder()
.url("http://10.0.2.2:8000/api/deals?<params here>")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
String jsonDeals = responseBody.string(); // can only call string() once or you'll get an IllegalStateException
Deal[] deals = new Gson().fromJson(jsonDeals, Deal[].class);
dealsList = new ArrayList<>(Arrays.asList(deals));
deals.postValue(dealsList);
}
}
});
return deals;
}
}
in your repository class in function get deals. you are initializing live data. requesting url in background thread and posting value on live data which is not received from server yet.
to solve this create livedata instance in constructor of repository and postvalue on livedata in onResponse callback.
//sorry for bad writting, posted from mobile.

How can i pass data from class to another class?

I am doing in this code: message receiving,filtering and getting then sending data to a sql server. I need the category_id from mysql database. Then i will use it in CallAPI as ide . I took the data from my mysql database but i couldn't transfer the data one class to another. So how can i transfer the data from one class to another?
I solved my problem and updated it i hope it can help to another peoples.
my smsCame codes:
package com.pvalid.api;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Request;
import okhttp3.Response;
public class smsCame extends BroadcastReceiver {
private static final String TAG = "MyBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG , "SMS RECEIVEDD");
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
String format = intent.getExtras().getString("format");
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[0], format);
String messagea = message.getOriginatingAddress();
String messagesb = message.getMessageBody();
Boolean messagee= messagesb.substring(0, 8).matches("(G-)\\d\\d\\d\\d\\d\\d");
String Code = messagesb.substring(2, 8);
String ide;
String usercode = "Admin";
//i need to POST this lmessage to my php server when sms received
//property is has to be Code:lmessage
// i have a receiver in my url when isset($_POST['Code'])
if (messagee){
try{
ide = new heyAPI(usercode).execute().get();
new CallAPI(usercode, Code, ide).execute();}
catch(Exception e){
ide="11";
new CallAPI(usercode, Code, ide).execute();
}
}
else{
Log.i(TAG,"Didnt match");}
}
private static class heyAPI extends AsyncTask<String, String, String> {
private final OkHttpClient client = new OkHttpClient();
String usercodes;
private heyAPI(String usercode){
usercodes= usercode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
RequestBody formBody = new FormBody.Builder()
.add("usercode", usercodes) // A sample POST field
.build();
Request request = new Request.Builder()
.url("url-here")
.post(formBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
String elem_id= response.body().string();
return elem_id;
}
catch (Exception e){
Log.i(TAG,"Error:"+e);
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
private static class CallAPI extends AsyncTask<String, String, String> {
String emailString;
String commentString;
String id;
private CallAPI(String usercode, String Code,String ide){
emailString = usercode;
commentString = Code;
id=ide;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("usercode", emailString) // A sample POST field
.add("Code", commentString) // Another sample POST field
.add("category_id", id) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("url here") // The URL to send the data to
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
}catch(IOException e){
Log.i(TAG,"IO exception");
return "";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}
You can use transfer your data in different class by using database , shared preference and intents.
If You want to transfer data from class A to B by intent then
In class A
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("key_name", value);
startActivity(intent);
and In class B for getting the transferred data
Intent intent=new getIntent();
String s=intent.getExtras().getString("key_name");
hi you can send parameters class A to class B is so way...
you can use constructor like this
public class test {
public test(String p){...}
}
and you can use intent
you can use shared preference in
learn with this site Shared preference
save data from class A and read class B
and you must be careful because when you give data from server thread is different Ui thread !
private SharedPreferences mPreference;
mPreference = getSharedPreferences("Share", Context.MODE_PRIVATE);
// save data
mPreference.edit()
.putBoolean("test", category_id)
.apply();
// read data
mPreference.getString("test", defaultSTR);

Is there any jax-rs like libraries on Android to implement restful service?

Hello guys I have very basic knowledge on rest services. I have implemented a basic program on Java to get output "hello world!" at URI http://localhost:8080/greeting/greet
package greeting;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
#Path("/greet")
public class Greet {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String justGreet(){
return "hello world!";
}
}
I would like to implement similar kind on Android, so that I can see output at some URI on any browser in that network. I'm confusing which dependencies or libraries have to use for Android to get that. Hoping for answers.
Thanks a ton in Advance!
Edit: I have used Retrofit library as suggested, it's executing well but I cannot see the output "Hello World!" at this URI http://192.168.0.104:8080/greeting/greet1, like usig Java and Jax-rs.
here is the implementation
package abc.xyz.com.retrotut;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private static final String URL = "http://192.168.0.104:8080/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService api = retrofit.create(ApiService.class);
Greeting greet = new Greeting("Hello World!");
Call<Greeting> call = api.getGreeting(greet);
call.enqueue(new Callback<Greeting>() {
#Override
public void onResponse(Call<Greeting> call, Response<Greeting> response) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Greeting> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
Pojo kind
public class Greeting {
private String greet;
public Greeting(String greet) {
this.greet = greet;
}
}
Interface
public interface ApiService {
#POST("greeting/greet1")
Call<Greeting> getGreeting(#Body Greeting greet);
}
However I'm getting "success", when executing application, I cannot get output what I've wanted. Are there any libraries which should I use or any alternatives?

Categories