Hi guys ... ,
Here PHP ..... In our daily life
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
What does php mean?
php is a self-referentially acronym for PHP: Hypertext Preprocessor. Original it supposedly meant personal home page. It is an open source, server-side, HTML embedded scripting language used to create dynamic Web pages. In an HTML document, PHP script (similar syntax to that of Perl or C ) is enclosed within special PHP tags. Because PHP is embedded within tags, the author can jump between HTML and PHP (similar to ASP and Cold Fusion) instead of having to rely on heavy amounts of code to output HTML. And, because PHP is executed on the server, the client cannot view the PHP code. PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases. Also, PHP can talk across networks using IMAP, SNMP, NNTP, POP3, or HTTP. PHP was created sometime in 1994 by Rasmus Lerdorf. During mid 1997, PHP development entered the hands of other contributors. Two of them, Zeev Suraski and Andi Gutmans, rewrote the parser from scratch to create PHP version 3 (PHP3).
In simple words >>>
PHP is a scripting language which is highly powerful open source that's widely used for web development activities to create efficient and dynamic web pages. PHP programming is specialty of Arth InfoSoft, we have developed various industry based websites like realtors, financial, engineering, social networking, hotel and hospitality, B2B, Shopping and many more.
No let's learn [ PHP Login script ] : :cyclops:
Learn to create a simple login system with php + mysql script, this tutorial is easy to follow, teach you step by step.
Overview
In this tutorial, we create 3 php files for testing our code.
1. main_login.php
2. checklogin.php
3. login_success.php
Steps
1. Create table "members" in database "test".
2. Create file main_login.php.
3. Create file checklogin.php.
4. Create file login_success.php.
5. Create file logout.php
Click to expand...
Click to collapse
STEP1: Create table "members"
For testing this code, we need to create database "test" and create table "members".
CREATE TABLE `members` (
`id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
--
-- Dumping data for table `members`
--
INSERT INTO `members` VALUES (1, 'john', '1234');
Click to expand...
Click to collapse
STEP2: Create file main_login.php
The first file we need to create is "main_login.php" which is a login form
############### Code
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="text" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
Click to expand...
Click to collapse
STEP3: Create file checklogin.php
We have a login form in step 2, when a user submit their username and password, PHP code in checklogin.php will check that this user exist in our database or not.
If user has the right username and password, then the code will register username and password in the session and redirect to "login_success.php". If username or password is wrong the system will show "Wrong Username or Password".
############### Code
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>
Click to expand...
Click to collapse
STEP4: Create file login_success.php
User can't view this page if the session is not registered.
############### Code
// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
Click to expand...
Click to collapse
STEP5: Create file Logout.php
If you want to logout, create this file. The code in this file will destroy the
// Put this code in first line of web page.
<?php
session_start();
session_destroy();
?>
Click to expand...
Click to collapse
For PHP5 User - checklogin.php
############### Code
<?php
ob_start();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
Click to expand...
Click to collapse
Encrypting Password - Make your Login More Secure :
Click to expand...
Click to collapse
This is the most secure form of viewing email address < or > logging in to some website .... :cyclops: >>>>>> :fingers-crossed:
SO ... This is what i kept my name >>>> Be secure
Hit thanks button >>> If i helped you in someway :highfive:
Good tuto.
I just have one question : Why not use PDO ? Since the goal is security, won't it be more efficient ?
near the end it mentions encrypting the password but doesn't say how you are doing it.
(guessing its javascript - maybe using a library to do AES encryption or possibly just sending a hash of the password instead?)
.
maybe the encryption stuff was truncated by a length limit on posts?
Related
Hi all, i have a big problem to write file in xml.
For reading the file i hadn't problem but to write...
Well, i have created this simple xml:
<?xml version="1.0" encoding="utf-8"?>
<budget>
<entrate>
<titolo>titolo</titolo>
<descrizione>descr</descrizione>
<prezzo>1000</prezzo>
<data>24/02/2011</data>
<id>0</id>
<mese>2</mese>
<anno>2011</anno>
</entrate>
</budget>
and i have added thi into my project by "adding new existing item"
now i have this code to write the xml:
using (var applicationStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var speedListFile = applicationStorage.OpenFile("budget.xml", FileMode.OpenOrCreate, FileAccess.Write))
{
var document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
new XElement("budget",
new XElement("entrate",
new XAttribute("id", "t.Id"),
new XAttribute("subject", "t.Subject"),
new XAttribute("body", "t.Body"))));
document.Save(speedListFile);
}
and with this code in every case create a new file and don't use my file included into my project. why?
How can i open my file budget.xml of my project?
Thanks
Because files you save as content in your XAP aren't stored in isolated storage.
To use read from a file that's saved as content you need to use
var resource = System.Windows.Application.GetResourceStream(new Uri("{path to file}", UriKind.Relative);
of course, you cannot then save any changes to that file back to the content file. You'd need to save it in isolated storage.
hey guys I am getting an error when I am trying to put a twitter feed in my blog app. The error says
“The attachable property ‘ItemTemplate’ was not found in type ‘ListBox’.”
what does this mean. Here is the code that I put in my listbox on the Xaml.
Code:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding UserName}" Foreground="#FF2276BB" FontSize="28" />
<TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
<HyperlinkButton Content="{Binding TweetSource}" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="18" Foreground="#FF999999" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
any help would be appreciated.
Posted XAML code is OK so I can only guess. Probably you've referenced a wrong assembly in your project. Post whole project.
http://blog.objectgraph.com/index.php/2010/03/26/how-to-create-a-twitter-client-on-windows-phone-7/
I am using that site as a guide and putting it in the Wordpress Starter Kit I added a panarama item called Twitter, added a list box and a button and a TextBlock (the text block says OmegaRa) and the buttons says refresh. I am at work currently, so I can't post the rest of my code...
edit: if it matters I named the listbox Twitterfeed, I know I had to alter a couple spots with that to get rid of errors. Plus the original code is for 7.0, in VS2010, I right clicked on the Solution and clicked Upgrade to 7.1...
Seems like this toolkit has a different assemblies for 7.0 and 7.1 (located at sl3-wp & sl4-windowsphone71 folders), check your project references for correct library (7.1).
okay, I am a complete newb when it comes to coding (hence the starter kit and tutorial) how would I go about doing that?
Solution Explorer (on your right) -> References -> click on assembly and check properties. Press Del to remove assembly. Right click and press "Add assembly" from the context menu.
P.S. But before start coding I'm strongly recommend you to RTFM (Read The Following Manual, not the "fu%?ng" one ). Download/buy and read a good manual for Visual Studio and .NET first...
That would probably be a good idea LOL. I just like figuring it out sometimes though, but it would probably go faster if I read something about it first lol.
edit: I will try looking at that when I get home from work and after my daughters birthday dinner lol
Okay, I am home and looking at the references, which assembly would it be?
progress, fixed that part forgot the
Code:
<listbox></listbox>
surrounding it, but when I hit refresh...is doen't get my feed, lol it says something about wordpress starter kit + tweet or something lol.
here is the code for the button
Code:
private void button3_Click(object sender, RoutedEventArgs e)
{
WebClient twitter = new WebClient();
twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + tbUsername.Text));
}
void twitter_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
XElement element = XElement.Parse(e.Result);
TwitterFeed.ItemsSource = from tweet in element.Descendants("status")
select new Tweet
{
UserName = tweet.Element("user").Element("screen_name").Value,
Message = tweet.Element("text").Value,
ImageSource = tweet.Element("user").Element("profile_image_url").Value,
TweetSource = FormatTimestamp(tweet.Element("source").Value, tweet.Element("created_at").Value)
};
}
catch (Exception)
{
}
}
public class Tweet
{
public string UserName { get; set; }
public string Message { get; set; }
public string ImageSource { get; set; }
public string TweetSource { get; set; }
}
private string StripHtml(string val)
{
return System.Text.RegularExpressions.Regex.Replace(HttpUtility.HtmlDecode(val), @"<[^>]*>", "");
}
private string DateFormat(string val)
{
string format = "ddd MMM dd HH:mm:ss zzzz yyyy";
DateTime dt = DateTime.ParseExact(val, format, System.Globalization.CultureInfo.InvariantCulture);
return dt.ToString("h:mm tt MMM d");
}
private string FormatTimestamp(string imageSource, string date)
{
return DateFormat(date) + " via " + StripHtml(imageSource);
}
}
}
what the screen says when I hit refresh is WordpressStarterKit.Mainpage+Tweet, and I notice that the button and the Text Block stay on the screen no matter if I pan or not....
PM me your project in archive, I'll correct your errors and send back.
If I change
Code:
twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + tbUsername.Text));
to
Code:
twitter.DownloadStringAsync(new Uri"http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=OmegaRa" );
would that fix it? I am just curious to see if I am right..
All issues solved, mod can close thread if they want.
Hello friends.
I am a lazy person with a lack of time. So, when I wanted to Phone Commander to add support for exporting registry keys to a file, I found an older, freely usable code (first I tried RegSaveKey coredll function, but I coud not elevate calling Process privilegies). PCMD will be the first "ondevice" WP7 application that allows you to export this (thanks Ultrashot we can also do it from a PC by Remote Tools). Unfortunately, the obtained code was using an MFC classes (CFile etc). Probably would not be a problem to rewrite it for another entry in the file, but I do not want change 3rd code. And MFC can be useful in the future too.
There were basically two options:
1. Use dynamic linking, because statically linking MFC to ATL is not allowed (conflicts of application instances). But then I had to get the correct library and try if they will run on WP7. In the future, I'll try.
2. Take all the MFC source code (included in WM DTK) and rewrite them to work statically in WP7, with prepared out CWinApp etc. It was a nasty job, but for some classes (especially CFile) is complete and functional to use. Next week there will publish libraries, source code and tutorial to use MFC classes in ATL native WP7 projects. EDIT: See 2nd post, this is probably better way then first one.
Meanwhile small code sample to export registers (ExportRegKey is 3rd function using CFile parameter):
Code:
BOOL ExportRegKey(HKEY hroot, const CString &root, const CString &key, CFile &out);
STDMETHODIMP CRegistryX::RegExportKeySimple(DWORD dwKey, LPCWSTR szSubKey, LPCWSTR szFileName)
{
TRACE(L"RegExportKeySimple(DWORD dwKey = %X, LPCWSTR szSubKey = %s, LPCWSTR szFileName = %s)", dwKey, szSubKey, szFileName);
try
{
HKEY hKey = (HKEY) dwKey;
LONG lRes = ERROR_SUCCESS;
CString root = L"";
switch (dwKey)
{
case HKEY_LOCAL_MACHINE:
{
root = _T("HKEY_LOCAL_MACHINE");
} break;
case HKEY_CURRENT_USER:
{
root = _T("HKEY_CURRENT_USER");
} break;
case HKEY_CLASSES_ROOT:
{
root = _T("HKEY_CLASSES_ROOT");
} break;
case HKEY_USERS:
{
root = _T("HKEY_USERS");
} break;
/*
case HKEY_CURRENT_CONFIG:
{
root = _T("HKEY_CURRENT_CONFIG");
} break;
*/
default:
{
root = _T("HKEY_UNKNOWN");
} break;
root = _T("");
}
CString key = szSubKey;
CFile out;
out.Open(szFileName, CFile::modeWrite | CFile::modeCreate );
lRes = ExportRegKey(hKey, root, key, out);
out.Close();
TRACE(L"RegExportKeySimple ExportRegKey lRes = %d)", lRes);
if (lRes == ERROR_SUCCESS)
{
return S_OK;
}
else
{
return ReturnError(L"RegSetDwordSimple RegSetValueEx", 0x80070000 | lRes);
}
}
catch (...)
{
return ReturnError(L"RegGetDwordSimple", GetLastError());
}
}
This is also Native TRACE example to see native messages in VP2010 managed Output window.
Full MFC using
I tried FULL MFC from VS2008 CE SDK using and this is possible.
1. Exe files - success with statical or dynamical MFC linking. Drawable components may have problems only.
2. Static linking to dll: If we can want use native dll with statically linked MFC to managed VS2010 dll or application, there are two ways:
- To change our usual COM interface to MFC standard. It may be possible, but I did not try it.
- To make ATL interstitial ATL dll with COM interface, which can call exported functions from MFC dll.
3. Dynamical MFC linking to ATL (COM) dll. I mean thi is the best way now.
For dynamical linking MFC dlls must be copied to device - to appplication directory or ideally to \Windows directory. Mostly:
\\Program Files (x86)\Microsoft Visual Studio 9.0\VC\ce\dll\ARMV4I\msvcr90.dll
\\Program Files (x86)\Microsoft Visual Studio 9.0\VC\ce\dll\ARMV4I\atl90.dll
\\Program Files (x86)\Microsoft Visual Studio 9.0\VC\ce\dll\ARMV4I\msvcr90d.dll
\\Program Files (x86)\Microsoft Visual Studio 9.0\VC\ce\dll\ARMV4I\MFC90UD.dll
Hello.
I'm working on a project where I need to store some information from the Windows Phone store in my Parse database, but since I'm new to both Parse and JavaScript (only supported language for Cloud Code) I need some help.
There seem to be something wrong with a property, but more than that I can't get, not which row or anything.
My code at the moment is this:
Code:
Parse.Cloud.job("getWP8Apps", function(request, response) {
Parse.Cloud.useMasterKey();
var query = new Parse.Query("developer");
query.each(function(results) {
Parse.Cloud.httpRequest({
url: 'http://zunderstorehost.azurewebsites.net/api/WP8StoreAppList/Publisher/' + results.get("publisherName"),
success: function(httpResponse) {
var apps = httpResponse.data;
for(var app in apps) {
var application = Parse.Object.extend("application");
var newApp = new application();
newApp.save({
categories: app.categories,
guid: app.guid,
haslivetile: app.haslivetile,
icon: app.icon,
mame: app.name,
offers: app.offers,
publisher: app.publisher,
publisherid: app.publisherid,
rating: app.rating,
ratingCount: app.ratingcount,
releaseDate: app.releasedate,
version: app.version
}, {
success: function(newApp){ console.log(app.name + " saved!"); },
error: function(newApp, error) {console.error("Something failed: " + error.description); }});
}
},
error: function(error) {
console.error("Something failed: " + error.description);
}
});
});
});
The developer object that I'm fetching from the storage is a small collection of items containing some general information about the different developers included in this, amongst that information, their Windows Phone Store Publisher Name which is to be used to fetch a list of their published applications.
The application object is a json converted class through the Parse Class Import function (that function converts the Json to a valid table structure for data storage of the result).
So, anyone with some ideas on what could be the issue here?
Any help is highly appreciated!
NOTE: This code is to run in the cloud, not in the app. Thats why I posted this in the web section. If it fits better somewhere else, feel free to move it.
View attachment 5209541
What is Share Engine
As a cross-device file transfer solution, Huawei Share uses Bluetooth to discover nearby devices and authenticate connections, then sets up peer-to-peer Wi-Fi channels, so as to allow file transfers between phones, PCs, and other devices. It delivers stable file transfer speeds that can exceed 80 Mbps if the third-party device and environment allow. Developers can use Huawei Share features using Share Engine.
The Huawei Share capabilities are sealed deep in the package, then presented in the form of a simplified engine for developers to integrate with apps and smart devices. By integrating these capabilities, PCs, printers, cameras, and other devices can easily share files with each other.
Three SDK development packages are offered to allow quick integration for Android, Linux, and Windows based apps and devices.
Working Principles
Huawei Share uses Bluetooth to discover nearby devices and authenticate connections, then sets up peer-to-peer Wi-Fi channels, so as to allow file transfers between phones, PCs, and other devices.
View attachment 5209543
To ensure user experience, Huawei Share uses reliable core technologies in each phase of file transfer.
Devices are detected using in-house bidirectional device discovery technology, without sacrificing the battery or security
Connection authentication using in-house developed password authenticated key exchange (PAKE) technology
File transfer using high-speed point-to-point transmission technologies, including Huawei-developed channel capability negotiation and actual channel adjustment
For more information you can follow this link.
Let’s get into codding.
Requirements
For development, we need Android Studio V3.0.1 or later.
EMUI 10.0 or later and API level 26 or later needed for Huawei phone.
Development
1 - First we need to add this permission to AndroidManifest.xml. So that we can ask user for our app to access files.
XML:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2 - After let’s shape activity_main.xml as bellow. Thus we have one EditText for getting input and three Button in UI for using Share Engine’s features.
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:hint="@string/hint"
tools:ignore="Autofill,TextFields" />
<Button
android:id="@+id/sendTextButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="sendText"
android:text="@string/btn1"
android:textAllCaps="false" />
<Button
android:id="@+id/sendFileButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="sendFile"
android:text="@string/btn2"
android:textAllCaps="false" />
<Button
android:id="@+id/sendFilesButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="sendMultipleFiles"
android:text="@string/btn3"
android:textAllCaps="false" />
</LinearLayout>
3 - By adding the following to strings.xml, we create button and alert texts.
XML:
<string name="btn1">Send text</string>
<string name="btn2">Send single file</string>
<string name="btn3">Send multiple files</string>
<string name="hint">Write something to send</string>
<string name="errorToast">Please write something before sending!</string>
4 - Later, let’s shape the MainActivity.java class. First of all, to provide access to files on the phone, we need to request permission from the user using the onResume method.
Java:
@Override
protected void onResume() {
super.onResume();
checkPermission();
}
private void checkPermission() {
if (checkSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] permissions = {READ_EXTERNAL_STORAGE};
requestPermissions(permissions, 0);
}
}
5 - Let’s initialize these parameters for later uses and call this function in onCreate method.
Java:
EditText input;
PackageManager manager;
private void initApp(){
input = findViewById(R.id.inputEditText);
manager = getApplicationContext().getPackageManager();
}
6 - We’re going to create Intent with the same structure over and over again, so let’s simply create a function and get rid of the repeated codes.
Java:
private Intent createNewIntent(String action){
Intent intent = new Intent(action);
intent.setType("*");
intent.setPackage("com.huawei.android.instantshare");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
We don’t need an SDK to transfer files between Huawei phones using the Share Engine, instead we can easily transfer files by naming the package “com.huawei.android.instantshare” to Intent as you see above.
7 - Let’s create the onClick method of sendTextButton to send text with Share Engine.
Java:
public void sendText(View v) {
String myInput = input.getText().toString();
if (myInput.equals("")){
Toast.makeText(getApplicationContext(), R.string.errorToast, Toast.LENGTH_SHORT).show();
return;
}
Intent intent = CreateNewIntent(Intent.ACTION_SEND);
List<ResolveInfo> info = manager.queryIntentActivities(intent, 0);
if (info.size() == 0) {
Log.d("Share", "share via intent not supported");
} else {
intent.putExtra(Intent.EXTRA_TEXT, myInput);
getApplicationContext().startActivity(intent);
}
}
8 - Let’s edit the onActivityResult method to get the file/s we choose from the file manager to send it with the Share Engine.
Java:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
ArrayList<Uri> uris = new ArrayList<>();
Uri uri;
if (data.getClipData() != null) {
// Multiple files picked
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
uri = data.getClipData().getItemAt(i).getUri();
uris.add(uri);
}
} else {
// Single file picked
uri = data.getData();
uris.add(uri);
}
handleSendFile(uris);
}
}
With handleSendFile method we can perform single or multiple file sending.
Java:
private void handleSendFile(ArrayList<Uri> uris) {
if (uris.isEmpty()) {
return;
}
Intent intent;
if (uris.size() == 1) {
// Sharing a file
intent = CreateNewIntent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
} else {
// Sharing multiple files
intent = CreateNewIntent(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
List<ResolveInfo> info = manager.queryIntentActivities(intent, 0);
if (info.size() == 0) {
Log.d("Share", "share via intent not supported");
} else {
getApplicationContext().startActivity(intent);
}
}
9 - Finally, let’s edit the onClick methods of file sending buttons.
Java:
public void sendFile(View v) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, 10);
}
public void sendMultipleFiles(View v) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.setType("*/*");
startActivityForResult(i, 10);
}
We’ve prepared all the structures we need to create, so let’s see the output.
Text Sharing:
View attachment 5209563
Single File Sharing:
View attachment 5209565
Multiple File Sharing:
View attachment 5209567
With this guide, you can easily understand and integrate Share Engine to transfer file/s and text with your app.
For more information: https://developer.huawei.com/consumer/en/share-kit/
I'm not a coder and to old to learn. It is and will remain all Greek to me.
namitutonka said:
I'm not a coder and to old to learn. It is and will remain all Greek to me.
Click to expand...
Click to collapse
If you read it and follow as per instruction, its pretty simple
Dope
Wow! So nice i never think i wanna know about this thing...
Very nice and useful.