Stuck at gdata calendar parse exception in Android - android

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 :(

Related

Converting image to bas64string in react.native.android SDK using pdfbox

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());
}
}
}

OpenSubtitles api android class

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!!

While loop or for loop for json object for android not working

I am trying to add a for loop or while loop for method getuserDetailWhileLoop(); but i am having a hard time figuring out on how to do it. This code suppose to show json object to text view and text view has scroll view in it. However when i ran the code the while loop is not working and only show 1 object. I need the while loop to show multiple object. How will i be doing that? Thanks.
package com.demo.myblog.profile;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.demo.myblog.R;
import com.demo.myblog.volley.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class UserProfile extends AppCompatActivity {
private String ID,NAME,EMAIL,CREATED_DATE, ID2;
private String appURl, appURl2;
Activity mContext = this;
TextView mId,mName,mEmail,mDate, mid2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile2);
mId = findViewById(R.id.txt_Id);
mid2 = findViewById(R.id.textView5);
mName = findViewById(R.id.txt_Name);
mEmail = findViewById(R.id.txt_Email);
mDate = findViewById(R.id.txt_Data);
Intent data = getIntent();
EMAIL = data.getStringExtra("email");
appURl = "url here";
appURl2 = "url2 here";
getUserDetail();
getuserDetailWhileLoop();
}
private void getuserDetailWhileLoop()
{
if (EMAIL.isEmpty()){
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setMessage("Email cannot be empty");
alert.setCancelable(false);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
else{
StringRequest stringRequest = new StringRequest(Request.Method.GET,appURl2, new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try
{
JSONObject jo = new JSONObject( response );
for(int i =0 ;i < jo.length(); i++)
{
ID2 = jo.getString( "id" );
//NAME = jsonObject.getString("username");
//EMAIL = jsonObject.getString("user_email");
//CREATED_DATE = jsonObject.getString("created_date");
//sonObject = jsonObject.getJSONObject( "id" );
mid2.setText( ID2 );
//mName.setText(NAME);
//mEmail.setText(EMAIL);
//mDate.setText(CREATED_DATE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I like to use for loops over while loops, because with a for loop you're able to check the progress of the loop.
In this case it is best to use a for loop, just like you already did.
Can you post a example response of the StringRequest?
[EDIT]
You forgot to add the counter 'i', your for loop is fine.
JSONObject obj = jo.getJSONObject(i);
obj.getString("id");
I think this is the solution to your problem.

Bluemix: How to insert JSON in Cloudant in Android with Replicator?

I am finding it difficult to make this simple upload. I've used all encontrandos tutorials on the internet such as Bluelist and android-sync. I already have a database created within the service. My code is as follows:
MainActivity.java
package com.example.engenharia.replicator;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.cloudant.sync.datastore.BasicDocumentRevision;
import com.cloudant.sync.datastore.Datastore;
import com.cloudant.sync.datastore.DatastoreException;
import com.cloudant.sync.datastore.DatastoreManager;
import com.cloudant.sync.datastore.DocumentBodyFactory;
import com.cloudant.sync.datastore.DocumentException;
import com.cloudant.sync.datastore.DocumentRevision;
import com.cloudant.sync.datastore.MutableDocumentRevision;
import com.cloudant.sync.query.IndexManager;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.io.File;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
public class MainActivity extends AppCompatActivity {
private static final String DATASTORE_MANGER_DIR = "data";
private Datastore DataStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URI uri = new URI(my_uri);
File path = getApplicationContext().getDir(DATASTORE_MANGER_DIR, Context.MODE_PRIVATE);
DatastoreManager manager = new DatastoreManager(path.getAbsolutePath());
DataStore = manager.openDatastore("banco0"); //banco0 is the DB created in Cloudant NoSQL service.
// Create a replicator that replicates changes from the local
// datastore to the remote database.
Replicator replicator = ReplicatorBuilder.push().to(uri).from(DataStore).build();
// Use a CountDownLatch to provide a lightweight way to wait for completion
CountDownLatch latch = new CountDownLatch(1);
Listener listener = new Listener(latch);
replicator.getEventBus().register(listener);
replicator.start();
latch.await();
replicator.getEventBus().unregister(listener);
if(replicator.getState() != Replicator.State.COMPLETE){
System.out.println("Error replicating TO remote");
System.out.println(listener.error);
} else {
System.out.println(String.format("Replicated %d documents in %d batches",
listener.documentsReplicated, listener.batchesReplicated));
}
}catch (Exception e){
e.printStackTrace();
}
}
public DocumentRevision createDocument() {
MutableDocumentRevision rev = new MutableDocumentRevision();
rev.body = DocumentBodyFactory.create(HashMap());
try {
return DataStore.createDocumentFromRevision(rev);
} catch (DocumentException e) {
//throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
public Map<String, Object> HashMap() {
HashMap<String, Object> map = new HashMap<String, Object>();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Street", "121");
map1.put("Street1", "12112");
map1.put("Street123", "1211111");
String[] array1 = new String[]{"Cloudant", "NoSQL", "JSON"};
map.put("address", map1);
map.put("description", "This is sample description");
map.put("skills", array1);
return map;
}
}
listener.java
package com.example.engenharia.replicator;
import com.cloudant.sync.notifications.ReplicationCompleted;
import com.cloudant.sync.notifications.ReplicationErrored;
import com.cloudant.sync.replication.ErrorInfo;
import com.google.common.eventbus.Subscribe;
import com.cloudant.sync.replication.ReplicatorBuilder;
import com.cloudant.sync.replication.Replicator;
import java.util.concurrent.CountDownLatch;
/**
* Created by engenharia on 19/08/16.
*/
public class Listener {
private final CountDownLatch latch;
public ErrorInfo error = null;
public int documentsReplicated;
public int batchesReplicated;
Listener(CountDownLatch latch) {
this.latch = latch;
}
#Subscribe
public void complete(ReplicationCompleted event) {
this.documentsReplicated = event.documentsReplicated;
this.batchesReplicated = event.batchesReplicated;
latch.countDown();
}
#Subscribe
public void error(ReplicationErrored event) {
this.error = event.errorInfo;
latch.countDown();
}
}
Executing this code I have the follow error:
CouchException: error: forbidden, reason: server_admin access is
required for this request, statusCode: 403, msg: null, cause: null
But I am the admin!
How do I fix the problem or what is the solution?

no communication between pub/sub code in android using zeromq

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.

Categories

Resources