I'm having trouble getting data from OpenSubtitles api. I have looked at many examples for java and python. Below is the class I'm trying to use to authenticate with OpenSubtitles api. After that I want to make request that will return a list of items I can pass to my recyclerview.
package com.shivito.subreader;
import android.app.DownloadManager;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class OpensubsRequest {
static String username;
static String password;
static String language;
static String useragent;
#RequiresApi(api = Build.VERSION_CODES.O)
public static void makerequest(){
Thread thread = new Thread() {
#Override
public void run() {
try {
Log.d("here","nope");
URL Opensubs = new URL("https://api.opensubtitles.org/xml-rpc");
URL url = new URL("https", "api.opensubtitles.org", 443, "/xml-rpc");
URLConnection uc = Opensubs.openConnection();
Log.d("working",uc.toString());
uc.addRequestProperty("username",username);
uc.addRequestProperty("password",password);
uc.addRequestProperty("language",language);
uc.addRequestProperty("useragent",useragent);
uc.connect();
Log.d("anythingnow", String.valueOf(uc.getAllowUserInteraction()));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
Okay so in the above class I am trying to send my login information to the api then I try to check if it was successful by reading the response from(uc.getAllowUserInteraction()). Up to this point it always says false. Of course I'm likely not doing this right and I hope someone can point me in the right direction. Thank you!!
Related
I am trying to extract text from a pdf and want to also include images.
Those images I am getting from pdfbox page object.
Now what I have in mind is using base64converter.
After searching the net I found that I could use The below code to do it
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
The problem With the below code is that in react-native.android dose not include BufferedImage , ImageIO or Base64 in its SDK
How am I going to do this? Are there any alternative way in doing this?
Here is the complete code below incase
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;
import com.facebook.react.bridge.Promise;
import com.viliussutkus89.android.pdf2htmlex.pdf2htmlEX;
import java.io.File;
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import com.tom_roush.pdfbox.pdmodel.PDDocument;
import com.tom_roush.pdfbox.pdmodel.PDDocumentInformation;
import com.tom_roush.pdfbox.pdmodel.PDDocumentCatalog;
import com.tom_roush.pdfbox.pdmodel.PDPage;
import com.tom_roush.pdfbox.PDXObject;
import com.tom_roush.pdfbox.COSName;
import com.tom_roush.pdfbox.pdmodel.PDResources;
import com.tom_roush.pdfbox.pdmodel.PDPageContentStream;
import com.tom_roush.pdfbox.pdmodel.encryption.AccessPermission;
import com.tom_roush.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import com.tom_roush.pdfbox.pdmodel.font.PDFont;
import com.tom_roush.pdfbox.pdmodel.font.PDType1Font;
import com.tom_roush.pdfbox.pdmodel.graphics.image.JPEGFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory;
import com.tom_roush.pdfbox.pdmodel.graphics.image.PDImageXObject;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDAcroForm;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDComboBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDListBox;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton;
import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField;
import com.tom_roush.pdfbox.rendering.ImageType;
import com.tom_roush.pdfbox.rendering.PDFRenderer;
import com.tom_roush.pdfbox.text.PDFTextStripper;
import com.tom_roush.pdfbox.android.PDFBoxResourceLoader;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.Arguments;
// below Import are not found in the SDK
import java.io.ByteArrayOutputStream;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.util.Base64;
import java.util.UUID;
public class PdfToHtmlModule extends ReactContextBaseJavaModule {
// add to CalendarModule.java
#Override
public String getName() {
return "PdfToHtmlModule";
}
private ReactApplicationContext appContext;
PdfToHtmlModule(ReactApplicationContext context) {
super(context);
appContext = context;
PDFBoxResourceLoader.init(appContext.getApplicationContext());
}
public static String imgToBase64String(final BufferedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, os);
return Base64.getEncoder().encodeToString(os.toByteArray());
} catch (final IOException ioe) {
return "";
}
}
#ReactMethod
public void getCompleteTextFromPdf(String pdfFilePath, Promise promise) {
try {
String pdfText = "";
File file = new File(pdfFilePath);
WritableMap params = this.getPDFInfo(file);
WritableArray array = new WritableNativeArray();
PDDocument pddoc = PDDocument.load(file);
if (pddoc.isEncrypted()) {
pddoc.setAllSecurityToBeRemoved(true);
}
for (int i = 0; i < pddoc.getNumberOfPages(); i++) {
PDFTextStripper pdfstripper = new PDFTextStripper();
pdfstripper.setStartPage(i);
pdfstripper.setEndPage(i);
pdfText = pdfstripper.getText(pddoc);
PDPage page = pddoc.getPage(i);
PDResources rs = page.getResources();
for (COSName cosObj : rs.getXObjectNames()) {
PDXObject obj = rs.getXObject(cosObj);
if (obj instanceof PDImageXObject) {
// this doe not work yet
String base64String = PdfToHtmlModule.imgToBase64String(((PDImageXObject) obj).getImage(), "png");
if (base64String != "")
array.pushString("data:image/png;" + base64String);
}
}
array.pushString(pdfText);
}
pddoc.close();
params.putArray("chapters", array);
promise.resolve(params);
} catch (Exception e) {
promise.reject(e.getMessage());
}
}
}
I'm making OTP based registrations how do I validate my OTP number please help.
here are 2 scripts
1 is a validation activity
2 is an async task running ok http req
3 there is one more activity which takes a user phone number and sends OTP SMS
which is working fine
I just wanna check if OTP on my edit text matches with message user received
package com.example.test2;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
class Verifyotp extends AsyncTask<String, Void, Void> {
public static String string;
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("mobile_no", MainActivity.phoneNo)
.addFormDataPart("otp", OTP_activity.OTP)
.build();
Request request = new Request.Builder()
.url("http://127.0.0.1:8000/api/verifyotp")
.method("POST", body)
.addHeader("Accept", "application/json")
.build();
try {
Response response = client.newCall(request).execute();
string = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.example.test2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Objects;
public class OTP_activity extends AppCompatActivity {
public static String OTP;
TextView mssg;
EditText ED;
Button ver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_activity);
mssg = (TextView) findViewById(R.id.txtmssg);
ver = (Button) findViewById(R.id.verify);
ED = (EditText)findViewById(R.id.otp);
mssg.setText("We have sent you an SMS on " + MainActivity.phoneNo + " with 4 digit verification code.");
ver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OTP = ED.getText().toString();
Verifyotp chk= new Verifyotp();
chk.execute();
int i = Verifyotp.string.length();
if (i < 20){
Toast.makeText(getApplicationContext(),
"please try again.", Toast.LENGTH_LONG).show();
}
else {
Intent in = new Intent(OTP_activity.this, Home_Acivity.class);
startActivity(in);
}
}
});
}
}
Any help is appreciated
You Could Use Firebase OTP Authentication For This Work.
I'm trying to pull all the data from a table using SELECT * from book, but I'm getting:
Attempt to invoke interface method 'java.sql.ResultSet java.sql.Statement.executeQuery(java.lang.String)' on a null object reference
I got it working when triggering the SQL statement in Eclipse. I'm trying to recreate it in Android Studio, but seems to throw this issue. Any help is appreciated.
SQL.java
package com.example.andy.loginapp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* Created by Andy on 1/4/2017.
*/
public class SQL {
private Statement st;
private Connection con;
private ResultSet rs;
public SQL(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sqltest", "root", "");
st = con.createStatement();
}
catch(Exception e){
System.out.println(e);
}
}
public void getData(){
try{
String query = "SELECT * from book";
String queryInsert = "INSERT into Book " + "VALUE(authorField.getText(), titleField.getText(), yearField.getText())";
rs = st.executeQuery(query);
while(rs.next()){
String author = rs.getString("author");
String title = rs.getString("title");
System.out.println("Author: " + author + " " + "Title" + " " + title);
}
}
catch(Exception e){
System.out.println(e);
}
System.out.println("success");
}
}
MainActivity.java
package com.example.andy.loginapp;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class MainActivity extends AppCompatActivity {
private Statement st;
private Connection con;
private ResultSet rs;
TextView hi;
RelativeLayout background;
Button sqlButton;
SQL data = new SQL();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqlButton = (Button) findViewById(R.id.sqlButton);
sqlButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
data.getData();
}
});
}
}
You would have to write a webservice to connect to any external databases such as MYSQL to connect android application to a database. It also involves writing a very basic PHP script.
See the following link for some examples.
https://www.b4x.com/android/forum/threads/connect-android-to-mysql-database-tutorial.8339/
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
So you're better off using SQLLite unless its absolutely necessary.
I tried to implement a simple publisher and subscriber in android using zeromq. When i try to debug it loops in subscriber recv. I dont know where i am going wrong. I think it is not able to get any data from the publisher.
Below is the code :subscriber
package com.example.jeromqps;
import java.util.*;
import org.jeromq.ZMQ;
import android.os.AsyncTask;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
public class client implements Runnable {
Messenger messenger;
public client()
{
System.out.println("client started");
}
#Override
public void run()
{
ZMQ.Context context=ZMQ.context(1);
System.out.println("collecting data from server");
ZMQ.Socket subscriber=context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:4444");
String code="10001";
subscriber.subscribe(code.getBytes());
int totalvalue=0;
//store the data in a data structure
for(int i=0;i<10;i++)
{
byte[] msg = subscriber.recv(0);
String string=new String(subscriber.recv(0));
StringTokenizer sscanf=new StringTokenizer(string," ");
int value=Integer.valueOf(sscanf.nextToken());
String string= new String(msg);
System.out.println();
totalvalue+=value;
}
int avg=totalvalue;
Message msg1=Message.obtain();
msg1.obj=string;
try {
messenger.send(msg1);
System.out.println("sent to main");
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
subscriber.close();
context.term();
}
}
The publisher code is below
package com.example.jeromqps;
import java.util.*;
import org.jeromq.*;
public class server implements Runnable{
public server()
{
System.out.println("server started");
}
#Override
public void run()
{
ZMQ.Context context=ZMQ.context(1);
ZMQ.Socket publisher=context.socket(ZMQ.PUB);
publisher.bind("tcp://*:4444");
Random srandom=new Random(System.currentTimeMillis());
System.out.println("in server");
while(!Thread.currentThread().isInterrupted())
{ //System.out.println("in while")
int zipcode =1000 +srandom.nextInt(10000);
int temperature = srandom.nextInt(215) - 80 + 1;
String update = String.format("%05d %d", zipcode, temperature);
String update="publisher";
publisher.send(update.getBytes(),0);
}
publisher.close();
context.term();
}
}
Main is below:
package com.example.jeromqps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Handler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends Activity implements Handler.Callback {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new server()).start();
new Thread(new client()).start();
}
#Override
public boolean handleMessage(Message arg0)
{
String str = new String((byte[]) arg0.obj);
System.out.println("****");
System.out.println(str);
//new AlertDialog.Builder(this).setMessage(str).show();
System.out.println("****");
textView.append(str+ "\n");
return false;
}
}
In program loops at byte[] msg = subscriber.recv(0); in the subscribers class. Where am i going wrong?Am i missing something?
First of all, you've got some errors in the code:
In the publisher, update is defined twice
String update = String.format("%05d %d", zipcode, temperature);
String update= "publisher";
You have a similar problem in the subscriber code, string is defined twice...
String string = new String(subscriber.recv(0));
String string = new String(msg);
In the subscriber, you're receiving messages twice in the same iteration..
byte[] msg = subscriber.recv(0);
String string = new String(subscriber.recv(0));
...you only need this in the loop to receive...
String string = new String(subscriber.recv(0));
Try fixing those problems and see how far you get...
This isn't a solution to the question posted here, but reading this question I noticed that 0 was specified as the second parameter in the send(...) method, which subsequently matches the parameter set in the recv(...) method.
I have a simple pub/sub system set up and couldn't figure out why messages weren't being sent. I was using recv(0) but was specifying some random flag in the send(...) method. Changing the value to 0 fixed my issues.
Figured I'd post this here as it was from reading through the code in the question that I happened to have that thought. So maybe this will help someone else in the future.
I am creating an widget to access the events stored in a google calendar.
Target : Android 2.1
I have included following external jar :
google-collect-1.0-rc1.jar jsr305.jar
gdata-calendar-2.0.jar,
gdata-calendar-meta-2.0.jar,
gdata-client-1.0.jar,
gdata-client-meta-1.0.jar,
gdata-core-1.0.jar
I get the following exception :
com.google.gdata.util.ParseException : org.xml.sax
here is my code: HelloWidget.java
package de.thesmile.android.widget2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.util.Log;
import android.widget.RemoteViews;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import de.thesmile.android.widget2.R;
public class HelloWidget extends AppWidgetProvider {
int number =0;
public String gooleres()
{
String result=new String("Unable to login into your account");
// Create a CalenderService and authenticate
try
{
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(DateTime.parseDateTime("2011-03-01T00:00:00"));
myQuery.setMaximumStartTime(DateTime.parseDateTime("2011-03-06T23:59:59"));
CalendarService myService = new CalendarService("wqewq");
myService.setUserCredentials("sunnycool333#gmail.com", "XXXXXX");
//Send the request and receive the response:
Feed resultFeed = myService.query(myQuery, Feed.class);
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
Entry entry = resultFeed.getEntries().get(i);
result= entry.getTitle().getPlainText().toString();
}
}
catch(Exception e)
{
result="Exception raised "+e.toString();
}
return result;
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main);
views.setTextViewText(R.id.widget_textview, gooleres());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
The code seems to be proper because when I try to put the same code as simple java file then I do get the output..
the simple java file I created looks something like this and it gives proper output..
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create a CalenderService and authenticate
try
{
URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
CalendarQuery myQuery = new CalendarQuery(feedUrl);
myQuery.setMinimumStartTime(DateTime.parseDateTime("2011-03-01T00:00:00"));
myQuery.setMaximumStartTime(DateTime.parseDateTime("2011-03-08T23:59:59"));
CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
myService.setUserCredentials("sunnycool333#gmail.com", "ytrfvgb$");
// Send the request and receive the response:
Feed resultFeed = myService.query(myQuery, Feed.class);
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
Entry entry = resultFeed.getEntries().get(i);
System.out.println(Integer.toString(i)+entry.getTitle().getPlainText().toString());
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
}
gdata api is not supported fully by android..
so have to move to google java client library :(