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;
}
}
};
}
Related
I am trying to get my webview to show a page that is only accesible after i am logged in. but whatever i try i cant get past the login url.
How can i open/show the SEND_VISUM_URL after i login.
this is what i have so far:
String LOGIN_URL = "http://10.35.50.125/BCS/index.php?module=";
String SEND_VISUM_URL = "http://10.35.50.1/BCS/index.php?module=ScanVisa&Action=save";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webviewer);
webView.loadUrl(LOGIN_URL);
cookieManager = new CookieManager();
Button login = (Button) findViewById(R.id.PostData);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new loginTask().execute(getLoginData());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public class loginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String loginData = params[0];
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL login_url = new URL(LOGIN_URL);
// getting cookies:
URLConnection conn = login_url.openConnection();
conn.connect();
// setting cookies
cookieManager.storeCookies(conn);
cookieManager.setCookies(login_url.openConnection());
cookiestring = cookieManager.toString();
Log.d("Cookie in logintask:", cookiestring);
conn.getContent();
conn.setDoOutput(true);
conn.setConnectTimeout(3000);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
try {
wr.write(loginData); //post
wr.flush();
} catch (Exception e) {
e.printStackTrace();
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
sb.append(line + "\n");
if (line == null) {
continue;
}
}
}
text = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return text;
}
protected void onPostExecute(String line) {
if (!line.contains("I107")) { //I107 is an error code that is returend when a login failed
Toast.makeText(getBaseContext(), "Login succesfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}
}
public void setCookies(URLConnection conn) throws IOException {
// let's determine the domain and path to retrieve the appropriate cookies
URL url = conn.getURL();
String domain = getDomainFromHost(url.getHost());
String path = url.getPath();
Map domainStore = (Map)store.get(domain);
if (domainStore == null) return;
StringBuffer cookieStringBuffer = new StringBuffer();
Iterator cookieNames = domainStore.keySet().iterator();
while(cookieNames.hasNext()) {
String cookieName = (String)cookieNames.next();
Map cookie = (Map)domainStore.get(cookieName);
// check cookie to ensure path matches and cookie is not expired
// if all is cool, add cookie to header string
if (comparePaths((String)cookie.get(PATH), path) && isNotExpired((String)cookie.get(EXPIRES))) {
cookieStringBuffer.append(cookieName);
cookieStringBuffer.append("=");
cookieStringBuffer.append((String)cookie.get(cookieName));
if (cookieNames.hasNext()) cookieStringBuffer.append(SET_COOKIE_SEPARATOR);
}
}
try {
conn.setRequestProperty(COOKIE, cookieStringBuffer.toString());
} catch (java.lang.IllegalStateException ise) {
IOException ioe = new IOException("Illegal State! Cookies cannot be set on a URLConnection that is already connected. "
+ "Only call setCookies(java.net.URLConnection) AFTER calling java.net.URLConnection.connect().");
throw ioe;
}
}
any help would be greatly appreciated!
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");
}
}
I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));
In this code, only the last word entered in the .txt file is being read. I am calling the same activity when a condition is met. What changes should I make to the code so that it reads a word, calls the same activity again and then reads a new word?
public class Page extends Activity {
Button b;
TextView t;
EditText e;
int i = 0;
String str2;
String w, x=null;
static BufferedReader c = null;
static BufferedReader ic = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page);
b = (Button) findViewById(R.id.benter);
t = (TextView) findViewById(R.id.tv);
e = (EditText) findViewById(R.id.et);
InputStream f = getResources().openRawResource(R.raw.incorrect);
ic = new BufferedReader(new InputStreamReader(f));
try {
while ((w = ic.readLine()) != null) {
t.setText(w);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str2 = e.getText().toString();
if (str2.equals(x)) {
Toast.makeText(getApplication(), "RIGHT", Toast.LENGTH_LONG).show();
Intent open = new Intent(Page.this, Page.class);
startActivity(open);
} else {
Toast.makeText(getApplication(), "WRONG", Toast.LENGTH_LONG).show();
e.setText("");
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can read file line by line using this code
try {
FileReader fileReader = new FileReader("FilePath");
BufferedReader reader = new BufferedReader(fileReader);
String data = null;
StringBuilder builder = new StringBuilder();
while ((data = reader.readLine()) != null) {
builder.append(data);
}
System.out.println(builder.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In your code there is problem in your onclick listener .. please put onclick listener on out of while loop..
There is minot mistake in your onClickListener() :
public class Page extends Activity {
Button b;
TextView t;
EditText e;
int i = 0;
String str2;
String w, x=null;
static BufferedReader c = null;
static BufferedReader ic = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page);
b = (Button) findViewById(R.id.benter);
t = (TextView) findViewById(R.id.tv);
e = (EditText) findViewById(R.id.et);
InputStream f = getResources().openRawResource(R.raw.incorrect);
ic = new BufferedReader(new InputStreamReader(f));
try {
while ((w = ic.readLine()) != null) {
t.setText(w);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str2 = e.getText().toString();
// it was str2.equals(x) nut x is null, replace w with x
if (str2.equals(w)) {
Toast.makeText(getApplication(), "RIGHT", Toast.LENGTH_LONG).show();
Intent open = new Intent(Page.this, Page.class);
startActivity(open);
} else {
Toast.makeText(getApplication(), "WRONG", Toast.LENGTH_LONG).show();
e.setText("");
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code will work for you
You can use Apache Commons I/O library for this.It's so simple. And keep your code beauty. And why do get .txt files from assets ?
AssetManager am = context.getAssets();
InputStream fs = am.open("a.txt");
List<String> lines = IOUtils.readLines(file,"UTF-8");
You can save your text file in "Assets" folder of project and use following code to retrieve that file in java class
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("YOUR_TEXT_FILE.txt")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
message=total.toString();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
After that you have that file in String message
Your program is reading the last line because you are overwriting your 'w' variable every time that you are calling the readLine() method. What you should do is set your 'w' variable empty, and append it with readLine() to keep all the lines in your text file that have been read, then call setText() once to place everything in your View. Without appending, you are essentially overwriting the 'w' variable every time your while loop runs through, which is why you are receiving the last line from your text file.
i am working on an app in which i have to populate gridview of images dynamically. I am getting an array of image ids from server, i am decoding json array and getting the image ids. now i have stored all the images in my drawable folder, i want to show the images of the ids i am getting from the json, but i am stuck at this point i don't know how this. help
this is my main activity
public class MainActivity extends Activity {
GridView grid ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid = (GridView)findViewById(R.id.grid_view);
grid.setAdapter(new Adapter(this));
Button play = (Button)findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
playgame();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
protected void playgame() throws JSONException {
if(cardcount >=1 ){
BufferedReader reader=null;
data_to_send = "userId=" + userId ;
try
{
Log.e("inside try block", "get text");
// Defined URL where to send data
URL url = new URL("http://172.16.10.5/Ankur/andapp/request_Play.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside", "while loop");
}
play_response = sb.toString();
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
Log.e("play response from the server", ""+play_response);
}else
{
Toast.makeText(getApplicationContext(), "Sorry you don't have cards.buy a new card now", Toast.LENGTH_LONG).show();
}
JSONObject jo = new JSONObject(play_response);
pos1 = jo.getString("0");
pos2 = jo.getString("1");
pos3 = jo.getString("2");
pos4= jo.getString("3");
pos5 = jo.getString("4");
pos6= jo.getString("5");
pos7= jo.getString("6");
pos8= jo.getString("7");
pos9= jo.getString("8");
Log.e("value of 1st place of array", "array value "+pics[7]);
}
i recommend to use Loader. see this [documentation] (http://developer.android.com/guide/components/loaders.html)
thus you can transfer images loading in not ui thread in Loade