How to get internal shared storage and sd card file paths of document files? - filepath

I am trying to get file paths of videos from internal shared storage and sd card.
I have randomly saved videos in random folders in internal shared storage and external storage.
public ArrayList<String> getVideosPath(Activity activity,Context context)
{
listOfAllImages = new ArrayList<String>();
Cursor cursor;
final String[] columns = {MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID};
final String orderBy = MediaStore.Video.Media._ID;
//Stores all the images from the gallery in Cursor
cursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
//Total number of images
int count = cursor.getCount();
//Create an array to store path to all the images
String[] arrPath = new String[count];
for (int i = 0; i < count; i++) {
cursor.moveToPosition(i);
int dataColumnIndex = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
//Store the path of the image
arrPath[i] = cursor.getString(dataColumnIndex);
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(arrPath[i],
MediaStore.Images.Thumbnails.MINI_KIND);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inSampleSize = 4;
// Bitmap b = BitmapFactory.decodeFile(arrPath[i], options);
bitmap.add(thumb);
// drawimages_onvideo.add(thumb);
Log.i("PATH", arrPath[i]);
listOfAllImages.add(arrPath[i]);
}
Although it gets the files from sd card and phone storage, the paths are different.
for e.g there are 2 video files one in android storage and one in sd-card and there path are
android storage : /storage/emulated/0/Movies/videoplay.mp4
and
sd-card : /storage/BBF7-A8D2/videos/videoplay.mp4
and i am getting these 2 files but the paths which are displayed to me are these:
/storage/emulated/0/Movies/videoplay.mp4
/storage/emulated/0/Movies/videoplay.mp4
What is wrong ?

this gives me the document files that i required, got help from one of stack over flow links.
public void getDocumentspath(){
listOfAllDocuments = new ArrayList<String>();
Cursor cursor;
String root_sd = Environment.getExternalStorageDirectory().toString();
String pdf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
String doc = MimeTypeMap.getSingleton().getMimeTypeFromExtension("doc");
String docx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("docx");
String xls = MimeTypeMap.getSingleton().getMimeTypeFromExtension("xls");
String xlsx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("xlsx");
String ppt = MimeTypeMap.getSingleton().getMimeTypeFromExtension("ppt");
String pptx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pptx");
String txt = MimeTypeMap.getSingleton().getMimeTypeFromExtension("txt");
String rtx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("rtx");
String rtf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("rtf");
String html = MimeTypeMap.getSingleton().getMimeTypeFromExtension("html");
String css = MimeTypeMap.getSingleton().getMimeTypeFromExtension("css");
// String js = MimeTypeMap.getSingleton().getMimeTypeFromExtension("js");
//Table
Uri table = MediaStore.Files.getContentUri("external");
//Column
String[] column = {MediaStore.Files.FileColumns.DATA};
//Where
String where = MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?";
//args
String[] args = new String[]{pdf,doc,docx,xls,xlsx,ppt,pptx,txt,rtx,rtf,html,css};
Cursor fileCursor = getContentResolver().query(table, column, where, args, null);
int count = fileCursor.getCount();
//Create an array to store path to all the documents
String[] arrPath = new String[count];
for (int i = 0; i < count; i++) {
fileCursor.moveToPosition(i);
int dataColumnIndex = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
//Store the path of the document
arrPath[i] = fileCursor.getString(dataColumnIndex);
Bitmap b = ((BitmapDrawable) ResourcesCompat.getDrawable(this.getResources(), R.drawable.documentfile, null)).getBitmap();
bitmap.add(b);
Log.i("PATH", arrPath[i]);
listOfAllDocuments.add(arrPath[i]);
}
}

Related

Retrieving Int Value from SQLite database

I am trying to retrieve an integer from my SQLite database and my current query crashes my program. This is what I have so far:
*/
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
db.execSQL(query);
int win = Integer.parseInt(query);
return win;
}
I am not sure why this will not work. Thanks in advance.
You are trying to convert the value SELECT ......... into a number as per int win = Integer.parseInt(query);.
For a SELECT statment you need you need to retrieve a Cursor (result set), via either the query or rawQuery SQLiteDatabase method and then extract the value(s) from the method and to then access the respective column from the respective row(s).
I believe that you would use something like :-
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1; //<<<<<<<<<< ADDED default value to return if no row found
String query = "SELECT " + COL3 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + id + "'";
Log.d(TAG, "updateName: query: " + query);
Cursor csr = db.rawQuery(query,null); //<<<<<<<<<< CHANGED to get the Cursor returned
// ADDED the following IF construct
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
//int win = Integer.parseInt(query); //<<<<<<<<<< DELETED (commented out)
csr.close(); //<<<<<<<<<< ADDED should always close a Cursor when done with it
return rv; //<<<<<<<<<< return the value (-1 if no row found)
}
This assumes that you just want the value from a single row as identified by the WHERE clause.
If possible it is recommended to a) not build the query with direct values (makes it vulnerable to SQL Injection) and to b) utilise the convenience query method.
Apply both a and b and your code could be :-
public int getWin(String id){
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1;
String whereclause = COL2 + "=?"; //<<<<<<<<<< where clause without where and ? for value that will be passed
String[] whereargs = new String[]{String.valueOf(id)}; //<<<<<<<<<< arguments used by the whereclause ? replaced on a 1 for 1 basis
String[] columns = new String[]{COL3}; //<<<<<<<<<< the columns to extract as a String array
Cursor csr = db.query(TABLE_NAME,columns,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(COL3));
}
csr.close();
return rv;
}

how to write where clause with rawquery

Hi, I have some problem to fetch data from sqlite database. Here i am fetching
data from select query but it is not responding. Please help me.
public ArrayList<String> getStudentsByClass(String stud_info) {
// Log.i("SKR", "GETTING STUDENTS by " +stud_class);
ArrayList<String> arrayList = new ArrayList<>();
Cursor cursor = liteDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE2 +
" WHERE ssg ='" + stud_info + "'", null);
if (cursor != null) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
arrayList.add(cursor.getString(cursor.getColumnIndex(KEY_STUDENT_NAME)));
cursor.moveToNext();
}
}
}
return arrayList;
}
Here is a raw query from a DBHelper Class that when called populates an ArrayList
/* Retrive ALL data from database table named "TABLE_INFO" */
public List<DatabaseModel> getDataFromDB(){
List<DatabaseModel> modelList = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_INFO;
//String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_ID + " > 0 " + " ORDER BY " + Col_ID + " DESC ";
/* Notice the SPACES before AND after the words WHERE ORDER BY ASC or DESC most of all the condition " > 0 "*/
/* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=*/
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
DatabaseModel model = new DatabaseModel();
model.setID(cursor.getString(0));
model.setWebsite(cursor.getString(1));
model.setUsernane(cursor.getString(2));
model.setPassword(cursor.getString(3));
model.setQuestion(cursor.getString(4));
model.setAnswer(cursor.getString(5));
model.setNotes(cursor.getString(6));
modelList.add(model);
}while (cursor.moveToNext());
}
db.close();
return modelList;
}
using rawQuery You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs. The values will be bound as Strings.
String selectQuery = "select * FROM settings where _id = ?";
String args[] = {"1"};
Cursor c = db.rawQuery(selectQuery, args);
if (c.moveToFirst()) {

Telegram SendPhoto() Methode in ASP.NET by Telegram Bot

I set the code for sending the photo to telegram, first is working on my localhost, after Update the telegram.bot package to ver 9.0.0 and publish to sever dosen't work at localhost and server.
i use the try/catch for sending Text instead of photo and now they not working, it is mean the Try block is working but it can't effect.
if (offerListDetail != null)
{
StringBuilder botTextA2 = new StringBuilder();
StringBuilder botTextB2 = new StringBuilder();
string remoteImgPath = offerListDetail.OFL_OfferImageUrl;
Uri remoteImgPathUri = new Uri(remoteImgPath);
string remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);
string fileName = Path.GetFileName(remoteImgPathWithoutQuery);
string localPath = Server.MapPath("~/Images/telegram/"); //AppDomain.CurrentDomain.BaseDirectory + "Images/telegram/" + fileName;
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPath + fileName);
var botphoto = new FileToSend()
{
Content = OpenFile(localPath + fileName),
Filename = fileName
};
//var botClient = new Telegram.Bot.Api("157612108:AAFr4y7WWT32xX41EMOVkmEW19pIgcHImv4"); // استانبولیار
var botClient = new Telegram.Bot.Api("186221188:AAHrihjOH7__4vlF0DCNWLEzYQ3p3ORO0_k"); // ربات ری را
try
{
botTextA2.AppendLine("🔍 http://order.reera.ir/offers.aspx?offer=" + offerListDetail.OFL_ID);
botTextA2.AppendLine("📢 " + offerListDetail.OFL_OfferName);
botTextA2.AppendLine("📌 " + offerListDetail.brn_Name);
botTextA2.AppendLine("🕔 مهلت " + offerListDetail.remainday + " روز");
botTextA2.AppendLine("📦 سفارش در http://order.reera.ir");
botTextA2.AppendLine("📝 یا تلگرام #reerabrand");
string botTextA = botTextA2.ToString().Replace(Environment.NewLine, "\n");
botClient.SendPhoto("#istanbulyar", botphoto, "ddd");//botTextA);
botClient.SendPhoto("#reera", botphoto, "ddd");//botTextA);
}
catch
{
botTextB2.AppendLine(offerListDetail.OFL_OfferImageUrl);
botTextB2.AppendLine("*********************************");
botTextB2.AppendLine("📢<b> حراجی " + offerListDetail.OFL_OfferName + "</b> ");
botTextB2.AppendLine("📌<i> توسط وبسایت " + offerListDetail.brn_Name + "</i> ");
botTextB2.AppendLine("🕔 <b>مهلت خرید تا " + offerListDetail.remainday + " روز دیگر</b> ");
botTextB2.AppendLine("🔍 <a href='http://order.reera.ir/offers.aspx?offer=" + offerListDetail.OFL_ID + "'> مشاهده بوتیک </a> ");
botTextB2.AppendLine("");
botTextB2.AppendLine("📦 سفارش در http://order.reera.ir");
botTextB2.AppendLine("📝 یا تلگرام #reerabrand");
string botTextB = botTextB2.ToString().Replace(Environment.NewLine, "\n");
botClient.SendTextMessage("#istanbulyar", botTextB, parseMode: ParseMode.Html);
botClient.SendTextMessage("#reera", botTextB, disableNotification: true, parseMode: ParseMode.Html);
}
}
read picture with stream
example
string pic = "نام عکس مورد نظر";
string yourpath = Environment.CurrentDirectory + #"\Pic\"+pic;
FileStream stream = new FileStream(yourpath, FileMode.Open, FileAccess.Read);
FileToSend fs = new FileToSend("photo3.jpg",stream);
bot.MakeRequestAsync(new SendPhoto(update.Message.Chat.Id, fs)).Wait();

How to send unicode character sms into mobile using asp.net c#

SenditemsTableAdapter sen = new SenditemsTableAdapter();
RegistrationTableAdapter reg = new RegistrationTableAdapter();
SendSMS sendsms = new SendSMS();
Here using tableAdapter
DS.RegistrationDataTable rtable = reg.GetDataByUsername(Session["username"].ToString());
if (rtable.Rows.Count > 0)
{
DS.RegistrationRow rrow = (DS.RegistrationRow)rtable.Rows[0];
int smscount = Convert.ToInt32(sen.Sumcredit(Session["username"].ToString()));
string username = rrow.Username;
// int smscount=0;
string MainString2 = txtmobileno.Text;
string[] Split2 = MainString2.Split(new Char[] { ',' });
string sendid = rrow.Senderid;
int CreditLmt = rrow.Creditlimit;
if (smscount <= CreditLmt)
{
if (rrow.Validitydate >= Convert.ToDateTime(DateTime.Now.ToString()))
{
for (int i = 0; i < Split2.Length; i++)
{
int credit = txtmessage.Text.Length / 160;
credit++;
DateTime date = DateTime.Now;
SqlConnection connection2 = new SqlConnection(con);
connection2.Open();
SqlCommand cmd1 = null;
string str = " insert into [Senditems] values('" + username + "','" + sendid + "', '" + Split2[i] + "',N'" + txtmessage.Text + "','Request.Url.AbsolutePath',' Request.UserHostAddress','Request.Browser.Platform + Request.Browser.Browser', '" + credit + "','" + date + "')";
cmd1 = new SqlCommand(str, connection2);
cmd1.ExecuteNonQuery();
string message = Convert.ToString(SqlHelper.ExecuteScalar(con, CommandType.Text, "SELECT message FROM senditems WHERE id = (SELECT MAX(id) FROM senditems)"));
sendsms.send(message, Split2[i], sendid);
connection2.Close();
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "<script>alert('Your message send successfully');</script>", false);
reset();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "<script>alert('Cant send sms because your validity is expired');</script>", false);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "<script>alert('Cant send sms because you dont have credit');</script>", false);
}
}
In the button click events i have using " sendsms.send(txtmobileno.Text, Split2[i], sendid);" this method for send sms to mobile.
strUrl = "http://onlinesms.in/api/sendValidSMSdataUrl.php?login=" + user + "&pword=" + pass +
"&msg=" + HttpUtility.UrlEncode(Message) +
"&senderid=" + sendId +
"&mobnum=" + mobNum;
WebRequest request = HttpWebRequest.Create(strUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = (Stream)response.GetResponseStream();
StreamReader readStream = new StreamReader(s);
string dataString = readStream.ReadToEnd();
response.Close();
s.Close();
readStream.Close();
And using this url to send sms.I have insert message into table is properly and i can get message to mobile ok but getting message ???????????? like this .
I want get sms properly pls any bady help.
I think it all depends of how the website API is converting back your URL string. In my opinion, I think it is safer to use the Uri.EscapeDataString() function instead of the HttpUtility.UrlEncode() because in a space you get the %20 instead of the + sign which may screw up your message.

Accessing records in Android using rawQuery and then displaying

I am working on several rawQueries to use to parse data from a table in Android. The below code works fine and returns the lowest rowid in the table.
public void firstRecord(View v){
Cursor c = db.rawQuery("SELECT * FROM surveyDB WHERE rowid = (SELECT MIN(rowid) FROM surveyDB)",null);
c.moveToFirst();
szList.add(c.getString(0));
Toast.makeText(getApplicationContext(), "Sucessful Event. szRowid is: " +szList +".", Toast.LENGTH_LONG).show();
}
I have two questions, and they are both extremely basic: 1) what is the best way to expand the above code to create language to capture the contents of other columns in this table at that specific rowid, (rowid, sampler, species, place), and display this in my application? Something like this perhaps:
((EditText)findViewById(R.id.edSpecies)).setText("");
with the proper reference replacing "" in .setText()?
String TABLE_SURVEY = "surveyDB";
String COL_ROW_ID = "rowid";
String COL_SAMPLER = "sampler";
String COL_SPECIES = "species";
String COL_PLACE = "place";
public ArrayList<SurveyRecord> getSurveyRecords()
{
ArrayList<SurveyRecord> records = new ArrayList<SurveyRecord>();
String query = "SELECT * FROM " + TABLE_SURVEY;
query += " WHERE " + COL_ROW_ID = " SELECT MIN ("
query += COL_ROW_ID + ") FROM " + TABLE_SURVEY;
Cursor c = db.rawQuery(query,null);
if(Cursor.moveToFirst())
{
do{
String sampler = c.getString(cursor.getColumnIndex(COL_SAMPLER));
String species= c.getString(cursor.getColumnIndex(COL_SPECIES));
String place = c.getString(cursor.getColumnIndex(COL_PLACE));
String rowId = c.getString(cursor.getColumnIndex(COL_ROW_ID));
records.add(new (rowId,species,place,sampler));
}while(c.moveToNext())
}
c.close();
}
public class SurveyRecord{
String mRowId;
String mSpecies;
String mPlace;
String mSampler;
public SurveyRecord(String rowId,String species,String place,String sampler)
{
this.mRowId = rowId;
this.mSpecies = species;
this.mPlace = place;
this.mSampler = sampler;
}
}
//Goes to the first record in the dataset
public void firstRecord(View v){
Cursor c = db.rawQuery("SELECT * FROM surveyDB WHERE rowid = (SELECT MIN(rowid) FROM surveyDB)",null);
c.moveToFirst();
((EditText)findViewById(R.id.edRowid))
.setText(c.getString(0));
((EditText)findViewById(R.id.edSpecies))
.setText(c.getString(1));
((EditText)findViewById(R.id.edArea))
.setText(c.getString(2));
((EditText)findViewById(R.id.edSampler))
.setText(c.getString(3));
}

Resources