how to post text image into twitter same time in android - android

Hi i did one application here i need to share my score on twiter,i did using below code my score is posing fine,but now i need to share score along with app icon.but i dont know how to share that image along with text can any one help me,thankyou
TestPost.class:
public class TestPost extends Activity {
String review;
private TwitterApp mTwitter;
private String username = "";
private boolean postToTwitter = false;
private static final String twitter_consumer_key = "";
private static final String twitter_secret_key = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
Button postBtn = (Button) findViewById(R.id.button1);
final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
postBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
review = reviewEdit.getText().toString();
postToTwitter = true;
onTwitterClick();
}
});
mTwitter = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);
mTwitter.setListener(mTwLoginDialogListener);
if (mTwitter.hasAccessToken()) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
}
}
private void postToTwitter(final String review) {
new Thread() {
#Override
public void run() {
int what = 0;
try {
mTwitter.updateStatus(review);
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (msg.what == 0) ? "Posted to Twitter" : "Post to Twitter failed";
Toast.makeText(TestPost.this, text, Toast.LENGTH_SHORT).show();
}
};
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
#Override
public void onComplete(String value) {
username = mTwitter.getUsername();
username = (username.equals("")) ? "No Name" : username;
postToTwitter = true;
postToTwitter(review);
Toast.makeText(TestPost.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
}
#Override
public void onError(String value) {
Toast.makeText(TestPost.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
}
};
private void onTwitterClick() {
if (mTwitter.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Delete current Twitter connection?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mTwitter.resetAccessToken();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mTwitter.authorize();
}
}
}

This is how I upload an Image along with text to the logged in Twitter User's account. I make use of the TwitPic API for that. You will have to login and register a developer account there.
The solution can be thought of as a two step solution.
First, when the user clicks the post button, I first grab the Image and upload to TwitPic. From there, I grab the URL that is returned by TwitPic (String url = upload.upload(finalFile);).
In step two of this code, in a String instance (String finalStatusWithURL), I grab the content of an EditText and then append the URL from step 1 to it. With this done, the post is finally posted to Twitter.
Configuration conf = new ConfigurationBuilder()
.setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET)
.setOAuthAccessToken(twit_access_token)
.setOAuthAccessTokenSecret(twit_access_token_secret)
.setMediaProviderAPIKey(TWIT_PIC_API)
.build();
// SET THE FILE PATH
File finalFile = new File(getRealPathFromURI(initialURI));
// THIS IS IMPORTANT. TWITPIC NEEDS THE ACTUAL PATH ON THE DEVICE. JUST THE URI DOES NOT WORK!!!!
ImageUpload upload = new ImageUploadFactory(conf).getInstance(MediaProvider.TWITPIC);
String url = upload.upload(finalFile);
Log.e("TWITTER URL RESPONSE", url);
// NOW, UPLOAD TO TWITTER
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(YOUR_TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(YOUR_TWITTER_CONSUMER_SECRET);
AccessToken accessToken = new AccessToken(your_twit_access_token, your_twit_access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
String finalStatusWithURL = null;
if (finalStatusMessage.trim().length() > 0) {
finalStatusMessage = editStatusUpdate.getText().toString();
finalStatusWithURL = finalStatusMessage + ":\n " + url;
} else {
finalStatusWithURL = url;
}
twitter4j.Status response = twitter.updateStatus(finalStatusWithURL);
Log.e("TWITTER RESPONSE", response.getText());
This is a method to get the real path of the image you want to upload:
// HELPER METHOD TO GET REAL PATH FOR THE SELECTED IMAGE
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Hope this helps. This is production code from an app of mine.
UPDATED:
Change this in the code:
File finalFile = new File(getRealPathFromURI(initialURI));
To this:
Uri tempUri = getImageUri(getApplicationContext(), icon);
File finalFile = new File(getRealPathFromURI(tempUri));
And the helper method for Uri tempUri = getImageUri(getApplicationContext(), bmpFinal);:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
You will still need to pass a Bitmap object. To convert your app icon to a Bitmap, use this:
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
UPDATED 2:
A little while after you asking and me answering your question, Twitter wrapped up a developer meet in SF. They have introduced a few new Cards which I think may be of use to your specific use-case. It is fresh off the block and I haven't gotten around to testing/using it. But if it fits your purpose, take a look at these links:
http://www.engadget.com/2013/04/02/twitter-cards-apps-products-photo-galleries/ (Where I found out about the new feature)
https://dev.twitter.com/blog/mobile-app-deep-linking-and-new-cards (The official Twitter blog)
https://dev.twitter.com/cards (Developer page for details of the features and how to use them)

Related

App cannot send and retrieve files from server via php mysql

I have a page in my app with similar codes with different values and they send info to my PHP MySQL just fine. On the other hand, this page in my app cannot send the files and giving me an error message:
E/Volley: [258] BasicNetwork.performRequest: Unexpected response code 406
for http://applybpojobs.com/widevalueappfiles/server/api/addvehicle.php
I have already tried numerous solutions on web and this site to no avail. Can anyone help me figure this out?
Here is my java:
public class Addvehicle extends AppCompatActivity {
private static final String TAG = Addvehicle.class.getSimpleName();
private EditText plate_number, vin, car_make, car_model, car_year, displacement,
fuel_type, transmission, mileage, owner_name, address, phone_number,
email_adress, facebook;
private TextView btnCreate;
private TextView btnClose;
private ImageView upload_car, preview;
private int GALLERY = 1, CAMERA = 2;
private static String URL_ADD_VEHICLE = "http://abcde/server/api/addvehicle.php";
//private static String URL_VEHICLE_IMAGE = "http://abcde/server/api/addvehicle.php";
private Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addvehicle);
requestMultiplePermissions();
/*EditText Area*/
plate_number = findViewById(R.id.plate_number);
vin = findViewById(R.id.vin);
car_make = findViewById(R.id.car_make);
car_model = findViewById(R.id.car_model);
car_year = findViewById(R.id.car_year);
displacement = findViewById(R.id.displacement);
fuel_type = findViewById(R.id.fuel_type);
transmission = findViewById(R.id.transmission);
mileage = findViewById(R.id.mileage);
owner_name = findViewById(R.id.owner_name);
address = findViewById(R.id.address);
phone_number = findViewById(R.id.phone_number);
email_adress = findViewById(R.id.email_adress);
facebook = findViewById(R.id.facebook);
/*TextView Area*/
btnClose = findViewById(R.id.btnClose);
btnCreate = findViewById(R.id.btnCreate);
/*Button Area*/
upload_car = findViewById(R.id.iv);
preview = findViewById(R.id.iv);
upload_car.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showPictureDialog();
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Addvehicle.this, Home.class));
}
});
btnCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showLoader();
addVehicle(getStringImage(bitmap));
}
});
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
String path = getStringImage(bitmap);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
preview.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(Addvehicle.this, "Failed!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
preview.setImageBitmap(thumbnail);
getStringImage(thumbnail);
Toast.makeText(Addvehicle.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
addVehicle(getStringImage(bitmap));
}
private void addVehicle(final String stringImage) {
final String plate_number = this.plate_number.getText().toString().trim();
final String vin = this.vin.getText().toString().trim();
final String car_make = this.car_make.getText().toString().trim();
final String car_model = this.car_model.getText().toString().trim();
final String car_year = this.car_year.getText().toString().trim();
final String displacement = this.displacement.getText().toString().trim();
final String fuel_type = this.fuel_type.getText().toString().trim();
final String transmission = this.transmission.getText().toString().trim();
final String mileage = this.mileage.getText().toString().trim();
final String owner_name = this.owner_name.getText().toString().trim();
final String address = this.address.getText().toString().trim();
final String phone_number = this.phone_number.getText().toString().trim();
final String email_adress = this.email_adress.getText().toString().trim();
final String facebook = this.facebook.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_ADD_VEHICLE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
String Success = jsonObject.getString("success");
if (Success.equals("1")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Successfully",Toast.LENGTH_SHORT).show();
}else if (Success.equals("0")){
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Already Exist",Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
e.printStackTrace();
hideLoader();
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(Addvehicle.this,"Vehicle Added Error"+error.toString(),Toast.LENGTH_SHORT).show();
hideLoader();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError{
Map<String, String> params = new HashMap<>();
params.put("plate_number", plate_number);
params.put("vin", vin);
params.put("car_make", car_make);
params.put("car_model", car_model);
params.put("car_year", car_year);
params.put("displacement", displacement);
params.put("fuel_type", fuel_type);
params.put("transmission", transmission);
params.put("mileage", mileage);
params.put("owner_name", owner_name);
params.put("address", address);
params.put("phone_number", phone_number);
params.put("email_adress", email_adress);
params.put("facebook", facebook);
params.put("photo", stringImage);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Adding Vehicle...");
progressDialog.show();
}
public void hideLoader(){
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.hide();
}
public String getStringImage(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageByteArray, Base64.DEFAULT);
return encodedImage;
}
private void requestMultiplePermissions(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
This is my server api file (mysqli) which is giving me the error response from logcat with this url : "http://abcde/server/api/addvehicle.php"
error_reporting(E_ALL); ini_set('display_errors', 1);
require '../core/connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$plate_number=$_POST['plate_number'];
$vin=$_POST['vin'];
$car_make=$_POST['car_make'];
$car_model=$_POST['car_model'];
$car_year=$_POST['car_year'];
$displacement=$_POST['displacement'];
$fuel_type=$_POST['fuel_type'];
$transmission=$_POST['transmission'];
$mileage=$_POST['mileage'];
$owner_name=$_POST['owner_name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email_adress=$_POST['email_adress'];
$facebook=$_POST['facebook'];
$adddate = date("d/m/Y");
$photo = $_POST['photo'];
$id=uniqid();
$path = "vehicle_upload/$id.jpeg";
$finalpath =
"http://abcde/server/api/addvehicle.php".$path;
$sql1=mysqli_query($connect,"SELECT * FROM _addvehicle WHERE
PlateNumber='$plate_number'");
if (mysqli_num_rows($sql1) > 0) {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
}else{
$sql = mysqli_query($connect, "INSERT IGNORE INTO
_addvehicle(PlateNumber, Vin, Make, Model, Year, Displacement, FuelType,
Transmission, Mileage, OwnerorCompany, HomeorCompanyAddress, ContactNumber,
EmailAddress, FacebookID, AddDate, vehicleImage)VALUES('$plate_number','$vin','$car_make','$car_model','$car_year','$displacement','$fuel_type','$transmission','$mileage','$owner_name','$address','$phone_number','$email_adress','$facebook','$adddate','$finalpath')");
if ($sql) {
if (file_put_contents($path, base64_decode($photo))) {
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
//mysqli_close($connect);
}
}
}
I am having a hard time identifying what went wrong. Although I am seeing that logcat points me to the php file, it doesn't specifically tell me what to change. This page was working a couple of days ago.

How to save chatbot input from user using Dialogflow into firebase ( Android Studio )

I want to send money between different PaypalCustomerAccount, every user's transaction would be recorded in UserTransaction table. Example in the photo, PaypalCustomerAccount user_id rmMe7a68kOXIvblu4aah1ZHc7Qx2. When she makes a transaction it will be saved into UserTransaction table with its user_id with a new transaction_id -LOvXSpmHnjmN2sWkhap.
enter image description here
I want to use a chatbot from DialogFlow integrated in Android Studio to send money between the PaypalCustomerAccount.
In the screenshot is how to android app chatbot looks like, when user wants to send a "whoosh"(digital cheque), the conversation goes:
send a whoosh Sure
who would u like to send it to
enter image description here
send it to susie
May i know the post date for the cheque
enter image description here
send it tmr
Alright, ive sent a whoosh to susie it will be processed by
2018-10-17
enter image description here
Now after the user makes the request, i want to save the request of the new transaction to my firebase. From PaypalCustomerAccount rmMe7a68kOXIvblu4aah1ZHc7Qx2 to a2u4aqw3Hc7Qx2 .
Meaning a new Transaction record will appear under UserTransaction:
for a2u4aqw3Hc7Qx2 and the status will be receive.
for rmMe7a68kOXIvblu4aah1ZHc7Qx2 status will be sent.
The follow below is index.js code in fulfilment page for Dialog Flow. I do not know how to write the codes in order for the above described to happen (Meaning a new Transaction record will appear under UserTransaction)
Do i write the codes in dialog flow or in my android studio (the backend for chatbot code) for that to happen?
'use strict';
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
// initialise DB connection
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'ws://whooshapplication.firebaseio.com/',
});
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function SendWhoosh(agent)
{
const nameParam = agent.parameters.name;
const context = agent.getContext('send_a_whoosh');
const name = nameParam || context.parameters.name;
// push input into db
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
// // Uncomment and edit to make your own intent handler
// // uncomment `intentMap.set('your intent name here', yourFunctionHandler);`
// // below to get this function to be run when a Dialogflow intent is matched
// function yourFunctionHandler(agent) {
// agent.add(`This message is from Dialogflow's Cloud Functions for Firebase editor!`);
// agent.add(new Card({
// title: `Title: this is a card title`,
// imageUrl: 'https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png',
// text: `This is the body text of a card. You can even use line\n breaks and emoji! 💁`,
// buttonText: 'This is a button',
// buttonUrl: 'https://assistant.google.com/'
// })
// );
// agent.add(new Suggestion(`Quick Reply`));
// agent.add(new Suggestion(`Suggestion`));
// agent.setContext({ name: 'weather', lifespan: 2, parameters: { city: 'Rome' }});
// }
// // Uncomment and edit to make your own Google Assistant intent handler
// // uncomment `intentMap.set('your intent name here', googleAssistantHandler);`
// // below to get this function to be run when a Dialogflow intent is matched
// function googleAssistantHandler(agent) {
// let conv = agent.conv(); // Get Actions on Google library conv instance
// conv.ask('Hello from the Actions on Google client library!') // Use Actions on Google library
// agent.add(conv); // Add Actions on Google library responses to your agent's response
// }
// // See https://github.com/dialogflow/dialogflow-fulfillment-nodejs/tree/master/samples/actions-on-google
// // for a complete Dialogflow fulfillment library Actions on Google client library v2 integration sample
// Run the proper function handler based on the matched Dialogflow intent name
[enter image description here][1] let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
// intentMap.set('your intent name here', yourFunctionHandler);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
enter image description here
This is my android studio ChatBot.java codes for the chatbot to work
public class ChatBot extends AppCompatActivity implements AIListener
{
public Bot bot;
public static Chat chat;
private ListView mListView;
private Button mButtonSend;
private EditText mEditTextMessage;
private Button mImageView;
private ChatMessageAdapter mAdapter;
AIService aiService;
private static final String TAG = "ChatBot";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_bot);
mListView = (ListView) findViewById(R.id.listView);
mImageView = (Button)findViewById(R.id.voice_record);
mButtonSend = (Button) findViewById(R.id.btn_send);
mEditTextMessage = (EditText) findViewById(R.id.et_message);
mAdapter = new ChatMessageAdapter(this, new ArrayList<ChatMessage>());
mListView.setAdapter(mAdapter);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO);
if (permission != PackageManager.PERMISSION_GRANTED)
{
Log.i(TAG, "Permission to record denied");
makeRequest();
}
final AIConfiguration config = new AIConfiguration("c43d5450b1a54959a44158fb897f1dcb",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, config);
aiService.setListener(this);
mButtonSend.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String message = mEditTextMessage.getText().toString();
//bot
String response = chat.multisentenceRespond(mEditTextMessage.getText().toString());
if (TextUtils.isEmpty(message))
{
return;
}
sendMessage(message);
mimicOtherMessage(response);
mEditTextMessage.setText("");
mListView.setSelection(mAdapter.getCount() - 1);
}
});
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aiService.startListening();
}
});
// *************************************
//checking SD card availablility
boolean a = isSDCARDAvailable();
//receiving the assets from the app directory
AssetManager assets = getResources().getAssets();
File jayDir = new File(Environment.getExternalStorageDirectory().toString() + "/cheque/bots/whoosh");
boolean b = jayDir.mkdirs();
if (jayDir.exists())
{
//Reading the file
try {
for (String dir : assets.list("whoosh")) {
File subdir = new File(jayDir.getPath() + "/" + dir);
boolean subdir_check = subdir.mkdirs();
for (String file : assets.list("whoosh/" + dir)) {
File f = new File(jayDir.getPath() + "/" + dir + "/" + file);
if (f.exists())
{
continue;
}
InputStream in = null;
OutputStream out = null;
in = assets.open("whoosh/" + dir + "/" + file);
out = new FileOutputStream(jayDir.getPath() + "/" + dir + "/" + file);
//copy file from assets to the mobile's SD card or any secondary memory
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
}
} catch (IOException e)
{
e.printStackTrace();
}
}
//get the working directory
MagicStrings.root_path = Environment.getExternalStorageDirectory().toString() + "/cheque";
System.out.println("Working Directory = " + MagicStrings.root_path);
AIMLProcessor.extension = new PCAIMLProcessorExtension();
//Assign the AIML files to bot for processing
bot = new Bot("whoosh", MagicStrings.root_path, "chat");
chat = new Chat(bot);
String[] args = null;
mainFunction(args);
// *************************************
} // onCreate
protected void makeRequest()
{
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
101);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode)
{
case 101:
{
if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED)
{
Log.i(TAG, "Permission has been denied by user");
}
else
{
Log.i(TAG, "Permission has been granted by user");
}
return;
}
}
}
public void voiceclick(View view)
{
aiService.startListening();
}
//check SD card availability
public static boolean isSDCARDAvailable()
{
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)? true :false;
}
//copying the file
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
} //copyFile
//Request and response of user and the bot
public static void mainFunction (String[] args)
{
MagicBooleans.trace_mode = false;
System.out.println("trace mode = " + MagicBooleans.trace_mode);
Graphmaster.enableShortCuts = true;
Timer timer = new Timer();
String request = "Hello.";
String response = chat.multisentenceRespond(request);
System.out.println("Human: "+request);
System.out.println("Robot: " + response);
} //mainFunction
private void sendMessage(String message)
{
ChatMessage chatMessage = new ChatMessage(message, true, false);
mAdapter.add(chatMessage);
//respond as Helloworld
mimicOtherMessage("HelloWorld");
} //sendMessage
private void mimicOtherMessage(String message)
{
ChatMessage chatMessage = new ChatMessage(message, false, false);
mAdapter.add(chatMessage);
}
private void sendMessage()
{
ChatMessage chatMessage = new ChatMessage(null, true, true);
mAdapter.add(chatMessage);
mimicOtherMessage();
}
private void mimicOtherMessage()
{
ChatMessage chatMessage = new ChatMessage(null, false, true);
mAdapter.add(chatMessage);
}
#Override
public void onResult(AIResponse result)
{
Log.d("anu",result.toString());
Result result1 = result.getResult();
mEditTextMessage.setText("Query" + result1.getResolvedQuery() + " action: " + result1.getAction());
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
}
#Override
public void onListeningCanceled() {
}
#Override
public void onListeningFinished() {
}
}
enter image description here
Here is also a screenshot of my intent in dialogflow
enter image description here
enter image description here
Please help me! and thank you in advance
First of all, Awesome Project on which you are working on, implementing the real-time chatbot transaction management.
I have reviewed each file you have attached and your asked question properly. I want to highlight some important steps that you can follow to implement the asked thing that are:
Checkout and implement Paypal SDK in your Android Application: https://github.com/paypal/PayPal-Android-SDK
Then, using the methods and objects you can simply put the returned values of any transaction from Paypal to your android application and thus, you can pass that on Realtime Database at Firebase.
The Chatbot Code is fine here, just you have to trigger action on particular intent calling of when the user says to send money to someone, to the android application backend where the Paypal code will run in Android Class File.
I hope you have got me! Better to know more, please feel free to ask doubts in reply section.
All the best for your future implementation!

Sending data to a server

So I'm going to post the simple code to a program I'm writing. Here is my question. I think I'm connecting to my server just fine (Because I'm posting this online I will replace the server address with a fake one) and I want to know if I'm actually sending the variables to the server. I am sending the data to a PHP server using this string ("?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36"). This is hard-coded for testing purposes. My question is, am I actually sending the data? There doesn't seem to be a send() method. Please excuse my ignorance. I'm new to Android.
My thought was that when I write to the OutputStream, I am also sending the data. Please take a look
public class PrintTicketActivity extends AppCompatActivity {
private static final String TAG2 = "PrintTicketActivity";
Context mContext;
Button mButtonA, mButtonB, mButtonC, mButtonD, mButtonE, mButtonF;
List<Button> mButtons;
List<PrintJob> mPrintJobs;
WebView mWebView;
int printJobNum = 1;
// here i'm initializing the variables with an arbitrary value so the compiler won't complain
// that they may have not been initialized in the button's onclick listeners
// these values are overwritten from sharedPreferences anyway.....the file will always exist unless there is a major problem
int numA, numB, numC, numD, numE, numF;
String buttonA, buttonB, buttonC, buttonD, buttonE, buttonF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print_ticket);
mContext = this;
mButtons = new ArrayList<>();
mPrintJobs = new ArrayList<>();
mButtonA = (Button) findViewById(R.id.button_a);
mButtonB = (Button) findViewById(R.id.button_b);
mButtonC = (Button) findViewById(R.id.button_c);
mButtonD = (Button) findViewById(R.id.button_d);
mButtonE = (Button) findViewById(R.id.button_e);
mButtonF = (Button) findViewById(R.id.button_f);
// add the buttons to the list so we can check later to see if any of the buttons has empty text
// and then hide the button if it is empty
mButtons.add(mButtonA);
mButtons.add(mButtonB);
mButtons.add(mButtonC);
mButtons.add(mButtonD);
mButtons.add(mButtonE);
mButtons.add(mButtonF);
// check for the start up file
File file = new File("data/data/com.myDomain.myProgram/shared_prefs/start.xml");
if (file.exists()) {
// place text from preferences on the buttons
updateUI();
} else {
Toast.makeText(mContext, "Something went wrong", Toast.LENGTH_SHORT).show();
}
mButtonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_A, numA, "A", mButtonA);
new SendQueueToServer().execute();
}
});
mButtonB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_B, numB, "B", mButtonB);
}
});
mButtonC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_C, numC, "C", mButtonC);
}
});
mButtonD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_D, numD, "D", mButtonD);
}
});
mButtonE.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_E, numE, "E", mButtonE);
}
});
mButtonF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_F, numF, "F", mButtonF);
}
});
}
private void executeQueue(String prefKey, int num, String category, Button button) {
printTicket(button.getText().toString(), category + num);
// increment the number after printing the ticket
++num;
// update the number in the shared preferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS, MODE_PRIVATE).edit();
editor.putInt(prefKey, num);
editor.apply();
// update the UI to get an updated version of the queue number
updateUI();
}
private void updateUI() {
SharedPreferences preferences = getSharedPreferences(MY_PREFS, MODE_PRIVATE);
buttonA = preferences.getString(A, "");
buttonB = preferences.getString(B, "");
buttonC = preferences.getString(C, "");
buttonD = preferences.getString(D, "");
buttonE = preferences.getString(E, "");
buttonF = preferences.getString(F, "");
numA = preferences.getInt(NUMBER_A, 1);
numB = preferences.getInt(NUMBER_B, 1);
numC = preferences.getInt(NUMBER_C, 1);
numD = preferences.getInt(NUMBER_D, 1);
numE = preferences.getInt(NUMBER_E, 1);
numF = preferences.getInt(NUMBER_F, 1);
mButtonA.setText(buttonA);
mButtonB.setText(buttonB);
mButtonC.setText(buttonC);
mButtonD.setText(buttonD);
mButtonE.setText(buttonE);
mButtonF.setText(buttonF);
// if a button doesn't have anything assigned to it, hide the button
for (Button button : mButtons) {
if (button.getText().equals("")) {
button.setVisibility(View.GONE);
}
}
}
private void printTicket(String queueTitle, String queueCategory) {
// create a WebView object for printing
WebView webView = new WebView(mContext);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
Log.i(TAG2, "page finished loading " + url);
createWebPrintJob(view);
mWebView = null;
}
});
String html = "<html><body><h2 style=\"text-align:center;font-size:60px\">" + queueTitle + "</h2><h1 style=\"text-align:center" +
";font-size:200px\">" +
queueCategory + "</h1>";
webView.loadDataWithBaseURL(null, html, "text/HTML", "UTF-8", null);
// Keep a reference to WebView object until you pass the PrintDocumentAdapter
// to the PrintManager
mWebView = webView;
}
#SuppressWarnings("deprecation")
private void createWebPrintJob(WebView webView) {
PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
printAdapter = webView.createPrintDocumentAdapter("print_job_num" + printJobNum);
printJobNum++;
} else {
printAdapter = webView.createPrintDocumentAdapter();
printJobNum++;
}
// Create a print job with name and adapter instance
String jobName = getString(R.string.app_name) + " Document";
PrintJob printJob = printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
// save for status checking later
mPrintJobs.add(printJob);
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
// #Override
// public void onBackPressed() {
// // don't add superclass constructor
// // I am disabling the back button here
// }
private class SendQueueToServer extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
OutputStream out = null;
String urlParameters = "?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36";
HttpsURLConnection connection = null;
try {
URL url = new URL("https://www.example.com/php");
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(out, "UTF-8"));
writer.write(urlParameters);
writer.flush();
writer.close();
Log.d(TAG2, " and the response is: " + connection.getResponseMessage());
Log.d(TAG2, "you are connected and good to go");
} catch (IOException e) {
e.printStackTrace();
} finally {
assert connection != null;
connection.disconnect();
}
return null;
}
}
}
The url parameters indicates that you are trying to make a GET request and this is not proper procedure to make an HTTP GET request. You don't need to write anything to the OutputStreamWriter if you are making a GET request. Here's a template for the same:
URL url;
HttpURLConnection urlConnection = null;
String urlParameters = "?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36";
try {
url = new URL("https://www.example.com/php"+urlParameters);
urlConnection = (HttpURLConnection) url
.openConnection();
//use this block of code in case you are looking for some response from your server
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can use Retrofit Library to send data to Server. It's very easy to communicate with Server using this library.
Visit http://square.github.io/retrofit/ for tutorial on how to use this library in Android/Java.

How to read text from an image using OCR in android

I want to implement OCR in Android. I.e. getting texts from a business card image. I used code from here.
But when I run this code I got the following error:
java.lang.NoClassDefFoundError:
org.apache.http.entity.mime.content.FileBody
I think it points to the following line:
final FileBody image = new FileBody(new File(filePath));
of the OCRServiceAPI class. How can I fix this?
Can't guess about your above error but I have done this task in Blackberry by using third party application ABBYY product of OCR on PHP server.
During my long R & D I have also worked on the below link of Github_Abbyy.
For using this code you should create a free account here: ocrsdk.com
Not all the Apache packages are available by default in Android, so you will have to download them from the Apache repositories and include those yourself. See the question Android libraries not found and the links provided in the answer there.
Edit: Specifically the sub-packages of org.apache.http.entity are not included, only the entity package itself.
In the example project given by the OCR API they have placed the mime package in a jar in the lib folder.
Checkout that whether you are getting correct path of the image which are selecting from the gallery.
I have also tried this demo and its working fine for me.
Here I'm posting my code:
OCRServiceAPI.java
public class OCRServiceAPI {
public final String m_serviceUrl = "http://api.ocrapiservice.com/1.0/rest/ocr";
private final String m_paramImage = "image";
private final String m_paramLanguage = "language";
private final String m_paramApiKey = "apikey";
private String m_apiKey, m_responseText;
private int m_responseCode;
public OCRServiceAPI(final String p_apiKey) {
this.m_apiKey = p_apiKey;
}
/*
* Convert image to text.
*
* #param language The image text language.
*
* #param filePath The image absolute file path.
*
* #return true if everything went okay and false if there is an error with
* sending and receiving data.
*/
public boolean convertToText(final String p_language,
final String p_filePath) {
try {
sendImage(p_language, p_filePath);
return true;
} catch (ClientProtocolException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/*
* Send image to OCR service and read response.
*
* #param language The image text language.
*
* #param filePath The image absolute file path.
*/
private void sendImage(final String p_language, final String p_filePath)
throws ClientProtocolException, IOException {
final HttpClient m_httpclient = new DefaultHttpClient();
final HttpPost m_httppost = new HttpPost(m_serviceUrl);
final FileBody m_image = new FileBody(new File(p_filePath));
final MultipartEntity m_reqEntity = new MultipartEntity();
m_reqEntity.addPart(m_paramImage, m_image);
m_reqEntity.addPart(m_paramLanguage, new StringBody(p_language));
m_reqEntity.addPart(m_paramApiKey, new StringBody(getApiKey()));
m_httppost.setEntity(m_reqEntity);
final HttpResponse m_response = m_httpclient.execute(m_httppost);
final HttpEntity m_resEntity = m_response.getEntity();
final StringBuilder m_sb = new StringBuilder();
if (m_resEntity != null) {
final InputStream m_stream = m_resEntity.getContent();
byte m_bytes[] = new byte[4096];
int m_numBytes;
while ((m_numBytes = m_stream.read(m_bytes)) != -1) {
if (m_numBytes != 0) {
m_sb.append(new String(m_bytes, 0, m_numBytes));
}
}
}
setResponseCode(m_response.getStatusLine().getStatusCode());
setResponseText(m_sb.toString());
}
public int getResponseCode() {
return m_responseCode;
}
public void setResponseCode(int p_responseCode) {
this.m_responseCode = p_responseCode;
}
public String getResponseText() {
return m_responseText;
}
public void setResponseText(String p_responseText) {
this.m_responseText = p_responseText;
}
public String getApiKey() {
return m_apiKey;
}
public void setApiKey(String p_apiKey) {
this.m_apiKey = p_apiKey;
} }
SampleActivity.java
public class SampleActivity extends Activity implements OnClickListener {
private final int RESPONSE_OK = 200;
private final int IMAGE_PICKER_REQUEST = 1;
private TextView m_tvPicNameText;
private EditText m_etLangCodeField, m_etApiKeyFiled;
private String m_apiKey; // T7GNRh7VmH
private String m_langCode; // en
private String m_fileName;
#Override
public void onCreate(Bundle p_savedInstanceState) {
super.onCreate(p_savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
m_tvPicNameText = (TextView) findViewById(R.id.imageName);
m_etLangCodeField = (EditText) findViewById(R.id.lanuageCode);
m_etApiKeyFiled = (EditText) findViewById(R.id.apiKey);
m_etApiKeyFiled.setText("T7GNRh7VmH");
final Button m_btnPickImage = (Button) findViewById(R.id.picImagebutton);
m_btnPickImage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Starting image picker activity
startActivityForResult(
new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI),
IMAGE_PICKER_REQUEST);
}
});
final Button m_btnConvertText = (Button) findViewById(R.id.convert);
m_btnConvertText.setOnClickListener(this);
}
public void onClick(View p_v) {
m_apiKey = m_etApiKeyFiled.getText().toString();
m_langCode = m_etLangCodeField.getText().toString();
// Checking are all fields set
if (m_fileName != null && !m_apiKey.equals("")
&& !m_langCode.equals("")) {
final ProgressDialog m_prgDialog = ProgressDialog.show(
SampleActivity.this, "Loading ...", "Converting to text.",
true, false);
final Thread m_thread = new Thread(new Runnable() {
public void run() {
final OCRServiceAPI m_apiClient = new OCRServiceAPI(
m_apiKey);
m_apiClient.convertToText(m_langCode, m_fileName);
// Doing UI related code in UI thread
runOnUiThread(new Runnable() {
public void run() {
m_prgDialog.dismiss();
// Showing response dialog
final AlertDialog.Builder m_alert = new AlertDialog.Builder(
SampleActivity.this);
m_alert.setMessage(m_apiClient.getResponseText());
m_alert.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface p_dialog,
int p_id) {
}
});
// Setting dialog title related from response code
if (m_apiClient.getResponseCode() == RESPONSE_OK) {
m_alert.setTitle("Success");
} else {
m_alert.setTitle("Faild");
}
m_alert.show();
}
});
}
});
m_thread.start();
} else {
Toast.makeText(SampleActivity.this, "All data are required.",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int p_requestCode, int p_resultCode,
Intent p_data) {
super.onActivityResult(p_requestCode, p_resultCode, p_data);
if (p_requestCode == IMAGE_PICKER_REQUEST && p_resultCode == RESULT_OK) {
m_fileName = getRealPathFromURI(p_data.getData());
m_tvPicNameText.setText("Selected: en"
+ getStringNameFromRealPath(m_fileName));
}
}
/*
* Returns image real path.
*/
private String getRealPathFromURI(final Uri p_contentUri) {
final String[] m_proj = { MediaStore.Images.Media.DATA };
final Cursor m_cursor = managedQuery(p_contentUri, m_proj, null, null,
null);
int m_columnIndex = m_cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
m_cursor.moveToFirst();
return m_cursor.getString(m_columnIndex);
}
/*
* Cuts selected file name from real path to show in screen.
*/
private String getStringNameFromRealPath(final String bucketName) {
return bucketName.lastIndexOf('/') > 0 ? bucketName
.substring(bucketName.lastIndexOf('/') + 1) : bucketName;
} }

Android Post Image to Facebook

I have this code running in my app and it is trying to post text and an image to a users wall. At the moment it is only posting the text. I think I have missed something simple, but would appreciate another pair of eyes check everything or another sample.
Any help is greatly appreciated.
Bundle bundle = new Bundle();
bundle.putString("message", "test update"); //'message' tells facebook that you're updating your status
bundle.putString(Facebook.TOKEN,accessToken);
bundle.putString("attachment", "{\"name\":\"My Test Image\","
+"\"href\":\""+"http://www.google.com"+"\","
+"\"media\":[{\"type\":\"image\",\"src\":\""+"http://www.google.com/logos/mucha10-hp.jpg"+"\",\"href\":\""+"http://www.google.com"+"\"}]"
+"}");
+"}");
//tells facebook that you're performing this action on the authenticated users wall, thus
// it becomes an update. POST tells that the method being used is POST
String response = facebook.request("me/feed",bundle,"POST");
Hope this will be work for you
Create class for facebook varible utility
import android.app.Application;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
public class Utility extends Application{
public static Facebook mFacebook;
public static AsyncFacebookRunner mAsyncRunner;
public static String userUID;
public static final String ICON_URL = "http://i.imgur.com/6G1b7.png";
}
Now mathod used to post image to facebook wall
public void postOnFacebookPicture(final Bitmap bitmap) {
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
Utility.mFacebook.setAccessToken(access_token);
}
if (expires != 0) {
Utility.mFacebook.setAccessExpires(expires);
}
if (!Utility.mFacebook.isSessionValid()) {
showErrorDialog(
"Facebook Account is not configure,Setting Facebook Account?",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
// Move to setting the facebook account
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
} else {
new Thread() {
#Override
public void run() {
int what = 0;
try {
String accessToken = mPrefs.getString("access_token",
null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, bos);
byte[] pictureData = bos.toByteArray();
Bundle bundle = new Bundle();
bundle.putByteArray("facebookPictureData", pictureData);
bundle.putString(Facebook.TOKEN, accessToken);
Utility.mFacebook.request("me/photos", bundle, "POST");
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
}
For Posting Text and Image in Facebook wall, check this link:
You can insert Image using Media attachment.

Categories

Resources