android display arabic doc,docx file from sdcard in textView - android

I need to read an arabic docx placed into my sdcard from my android app, and display the text into a textView, i use the code below but the text appears like weird characters. What is the encoding to use other than UTF-8:
File logFile = new File(path + name);
if (logFile.exists())
{
try
{ FileInputStream fIn = new FileInputStream(logFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn,"UTF-8"));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";}
tv.setText(aBuffer); //tv is the textView
myReader.close();
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

you can convert it to HTML file and put it to assets and show it with WebView.
in your XML:
<WebView
android:layout_width="match_parrent"
android:layout_height="match_parrent"
android:id="#+id/WV1"
/>
in your activity class:
public class MainActivity extends AppCompatActivity {
public WebView wv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wv = (WebView) findViewById(R.id.WV1);
wv.loadUrl("file:///android_asset/myWV.html");
}
}

Related

Amazon s3 file download from android

I am trying to make a demo app.
That download a image from my s3 server to my phones memory card.
I tried the demo codes and wrote the following. But the app force closes as soon as i run it on my phone.
Any help would be appreciated.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File f=null;
try{
File dir= Environment.getExternalStorageDirectory();
f= new File(dir,"test.jpg");
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Exception", Toast.LENGTH_SHORT).show();
}
AWSCredentials creden=new BasicAWSCredentials(accessKey,secretKey);
AmazonS3Client s3Client=new AmazonS3Client(creden);
ObjectMetadata obj= s3Client.getObject(new GetObjectRequest("adj-temp","funflick_1.jpg"),f);
}
Try this it will work Happy coding
{
String str_FilePathInDevice = "/sdcard/" + "/"
+ "RestoreFolderName" + "/" + "filname.extention";
File file = new File(str_FilePathInDevice);
String str_Path = file.getPath().replace(file.getName(), "");
File filedir = new File(str_Path);
try {
filedir.mkdirs();
} catch (Exception ex1) {
}
S3Object object = s3Client.getObject(new GetObjectRequest(
"BucketName", "keyName"));
BufferedReader reader = new BufferedReader(new InputStreamReader(
object.getObjectContent()));
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
while (true) {
String line = reader.readLine();
if (line == null)
break;
writer.write(line + "\n");
}
writer.flush();
writer.close();
reader.close();
}

IO Exception in FileInputStream.read. Android

I'm writting an Android's app. Two activities, one has TextEdit to type 'hello message', and button to save message in Internal Storage. Second is main activity. Hello mesage should appear after app's start.
Second activity:
String s = ((EditText) findViewById(R.id.message_act_editText_hello)).getText().toString();
FileOutputStream fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_PRIVATE);
fos.write(s.getBytes());
fos.close();
first (main) activity:
static String FILENAME = "message_file.zip";
FileOutputStream fos;
try {
//piece of code to guarantee that file exists
fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_APPEND);
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis = openFileInput(FILENAME);
messageString = new StringBuffer("");
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast t = Toast.makeText(this, messageString, 3000);
t.show();
I'm getting IO Exception in logcat at line:
while ((length = fis.read(buffer)) != -1)
but app seems to work correctly (defined message appears after app's start). I tried to find explanation, I found several topics, but all was according to large files, or files in assets, or compressed files.
I tried to name my file like
static String FILENAME = "message_file.zip",
static String FILENAME = "message_file.txt",
to try different extensions, but always i'm getting the same IO Exception.
Thanks for suggestions.
of course you will get an IO Exception your file doesn't exit and you request to open it
You forget this peice of code
File myFile = new File("/sdcard/mysdfile.txt");
In your first activity you can use this code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
EditText txtData;
Button btnWriteSDFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),SecondActivity.class);
startActivity(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
});
}
}
in the second one you can use this:
public class SecondActivity extends Activity {
private TextView txtData2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
txtData2 = (TextView) findViewById(R.id.textView2);
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData2.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The first latout uses a linearlayout that contain an edittext and a button
The second a linearLayout with only a textview
Try it works fine if you find problem let me know!!
Ah i forget you have to add in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I found reason. Problem was in fragment:
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
What's the catch?
fis.close();
should be after while. I didn't notice that yesterday...

web page not displaying special characters

I have an ".HTML" file which is stored in the "res\raw" folder.
I used the following code to display the contents of my file:
static String TAG="WebPageShowActivity";
WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webpagedisplay);
String summary = readRawTextFile(this,R.raw.spotlighterhelp);
//getResources().openRawResource(R.raw.spotlighterhelp).toString();
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadDataWithBaseURL (null,summary, "text/html","ASCII" ,null);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
}
} catch (IOException e) {
return null;
}
Log.e(TAG, "file content: "+text.toString());
return text.toString();
}
now, my problem is: Whatever be the type of encoding, it is not displaying special characters like " or ' What do I do so that these characters are shown too?
Following is the output I am getting
I think it may works, Try to use UTF-8 instead of ASCII for your webView.
mWebView.loadDataWithBaseURL (null,summary, "text/html","UTF-8" ,null);

How can I get a listview with links to assets?

I have the HTML files in assets named n0.html, n1.html, etc. I want to create a listview with links to these files, but I don't know how to do it.
I have such a decision with a raw folder. How should I change it to assets files?
public class ViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Bundle bundle = getIntent().getExtras();
String itemname = "n" + bundle.getString("defStrID"); //getting string and forming resource name
Context context = getBaseContext(); //getting context
// Reading text file from resources by name
String text = readRawTextFile(context, getResources().getIdentifier(itemname, "raw", "ru.falcon5f.carguide;"));
WebView wWebView = (WebView) findViewById(R.id.webView);
String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
wWebView.loadData(summary, "text/html", "utf-8"); //uploading text to webview
}
public static String readRawTextFile(Context ctx, int resId) // Reading text raw txt file
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
return null;
}
return text.toString();
}
}
Added
I'm sorry if I ask too stupid questions and I ask too much, but I want to work my first application. This is very important for me. So it consists of two activities:
ViewActivity which I've changed according to your advices
public class ViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Bundle bundle = getIntent().getExtras();
String htmlFileName = "n" + bundle.getString("defStrID"); // Getting file name
Context context = getBaseContext(); // Getting context. You still need that
// Reading text file from resources by name
try {
String text = readAssetTextFile(context, htmlFileName);
WebView wWebView = (WebView) findViewById(R.id.webView);
String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
wWebView.loadData(summary, "text/html", "utf-8"); // Uploading text to webview
}
catch (IOException e) {
Log.e("TAG", e); // Note that you will need to import android.util.Log
}
}
public static String readAssetTextFile(Context ctx, String fileName) throws IOException // Reading the HTML file from assets
{
InputStream inputStream = ctx.getAssets().open(fileName);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
return null;
}
return text.toString();
}
}
In Log.e("TAG", e);, Eclipse wants to change type of "e" to "String".
How can I fix this?
It will not be that much different. You know that you can access a file in the assets like this:
InputStream inputStream = ctx.getAssets().open(fileName);
You can place this instead of your line InputStream inputStream = ctx.getResources().openRawResource(resId);. Then you need to pass in the correct file name. When working with assets you need not use IDs.
Editing your snippet:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Bundle bundle = getIntent().getExtras();
String htmlFileName = "n" + bundle.getString("defStrID") + ".html"; // Getting file name
Context context = getBaseContext(); // Getting context. You still need that
// Reading text file from resources by name
try {
String text = readAssetTextFile(context, htmlFileName);
WebView wWebView = (WebView) findViewById(R.id.webView);
String summary = "<!Doctype html><html><head><meta charset=utf-8></head><body>" + text + "</body></html>";
wWebView.loadData(summary, "text/html", "utf-8"); // Uploading text to webview
} catch (IOException e) {
Log.e("TAG", "Exception thrown", e); // Note that you will need to import android.util.Log
}
}
public static String readAssetTextFile(Context ctx, String fileName) // Reading HTML file from assets
{
InputStream inputStream = ctx.getAssets().open(fileName);
.....

problem with display web content

I had add in this remember me function inside my project, and I need to display the search result in the webview, but now everytime I click on the search button, the search content can be remembered, but the web content can not be displayed.
public class InternalStorageDemo extends Activity {
EditText txt;
Button writeBtn;
Button readBtn;
TextView tv;
WebView wv;
String FILE_NAME = "mFile";
String FILE_CONTENT;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt = (EditText)findViewById(R.id.txt);
writeBtn = (Button)findViewById(R.id.writeBtn);
readBtn = (Button)findViewById(R.id.readBtn);
writeBtn.setOnClickListener(listener);
readBtn.setOnClickListener(listener);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.writeBtn:
FILE_CONTENT = txt.getText().toString().equals("")?"null":txt.getText().toString();
try {
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
fos.write(FILE_CONTENT.getBytes());
fos.close();
//Toast.makeText(InternalStorageDemo.this, "stored done", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.readBtn:
FileInputStream fis;
try {
fis = openFileInput(FILE_NAME);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){}
txt.setText(new String(input));
try{
String str = txt.getText().toString();
URL url = new URL("http://epoly.tp.edu.sg/tpapp/isistt/TTServlet?txtModule=StudentSearch&txtAction=GetTT&txtSelStudentID=" + str);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
// Read the contents line by line (assume it is text),
// storing it all into one string
String content ="";
String line = reader.readLine();
while (line != null) {
//adding on to the string (+=)
//"\n" goes to a new line so that it has a break
content += line + "\n";
line = reader.readLine();
}
//close reader after reading contents
reader.close();
//using substring to get html contents from a specific tag
String myString = content.substring(content.indexOf("</script>"));
int start = myString.indexOf("</script>");
//if start less than 0, no contents from start tag found,
//nothing will be displayed in webview, error message will be logged
if (start < 0) {
Log.d(this.toString(), "Academic calendar start tag not found");
}
else {
int end = myString.indexOf("</body>", start);
if (end < 0) {
Log.d(this.toString(), "Academic calendar end tag not found");
} else {
//load only <newcollection> tag
myString = "<html><body>" + myString.substring(start, end) + "</body></html>";
}
}
//display contents that have been extracted to webview
WebView wv = (WebView)findViewById(R.id.wv);
wv.getSettings().setBuiltInZoomControls(true);
//set the webview contents' size
wv.setInitialScale(80);
//wv.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
//wv.loadData(myString, "text/html", "utf-8");
wv.loadDataWithBaseURL("http://epoly.tp.edu.sg/tpapp/isistt/TTServlet?txtModule=StudentSearch&txtAction=GetTT&txtSelStudentID="+str, myString, "text/html", "UTF-8", "about:blank");
}catch (IOException e) {
e.printStackTrace();
Log.d(this.toString(), "Error!");
}} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Log.d(this.toString(), "Error!");
}break;
}
}
};
}

Categories

Resources