I have developed an Android application that launches a Google Translate Activity using the following code:
...
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.putExtra("key_text_input", "What time is it?");
i.putExtra("key_text_output", "");
i.putExtra("key_language_from", "en");
i.putExtra("key_language_to", "es");
i.putExtra("key_suggest_translation", "");
i.putExtra("key_from_floating_window", false);
i.setComponent(new ComponentName("com.google.android.apps.translate",
"com.google.android.apps.translate.translation.TranslateActivity"));
startActivityForResult(i, 0);
...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("yoyo", "in onActivityResult()");
// data is null
}
The parent onActivityResult() is called in my application from the Google Translate Activity, but data is null. Therefore, I assume that there is no way to return any translated text from Google Translate back into my application. Is this correct?
Also, if there was a way to do this, would it be a violation of the API's terms of service? Would it still be a violation if using the Google Translate offline language packs/translation?
If a Google developer (employee) happens to see this and could weigh in, I would appreciate it. I'm really looking for an official response.
Thanks!
I also am curious to know if this is possible.
Meanwhile, if you need to translate simple text here a class that wrap the Google Translate Http Service.
I've never used it in a production enviroment (read a released app) becouse I'm not sure if it's legal.
So if a Google (employee) will answer to your question..maybe could let me know if this approach is legal.
For convenience here the simple AsyncTask that wrap the Google Translate Http Service:
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Random;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.lus.android.net.RESTClient;
public class TranslatorTask extends AsyncTask<Bundle, Void, String> {
static final private String TAG = "TRANSLATOR";
static final private String[] UA_LIST = {
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0",
"Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:22.0) Gecko/20130328 Firefox/22.0",
"Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; InfoPath.1; SV1; .NET CLR 3.8.36217; WOW64; en-US)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; .NET CLR 2.7.58687; SLCC2; Media Center PC 5.0; Zune 3.4; Tablet PC 3.6; InfoPath.3)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322)"
};
public interface OnTranslatorTaskListener {
void onTextTranslated(String value);
};
private OnTranslatorTaskListener mCallback = null;
public void setOnTranslatorTaskListener(OnTranslatorTaskListener listener) {
mCallback = listener;
}
#Override
protected String doInBackground(Bundle... params) {
if (params == null) return null;
Collections.shuffle(Arrays.asList(UA_LIST));
String json = null;
RESTClient rest = null;
try {
rest = new RESTClient("http://translate.google.com/translate_a/t");
rest.header("User-Agent", UA_LIST[new Random().nextInt(UA_LIST.length)]);
rest.data("client", "j"); //t = TEXT
rest.data("ie", "UTF-8");
rest.data("oe", "UTF-8");
rest.data("hl", params[0].getString("hl")); //, Locale.getDefault().getLanguage()));
rest.data("sl", params[0].getString("sl"));
rest.data("tl", params[0].getString("tl"));
rest.data("q", params[0].getString("text"));
json = rest.execute();
} catch (IOException ioe) {
Log.e(TAG, ioe.getMessage(), ioe);
} finally {
if (rest != null) rest.shutdown();
}
if (json == null) return null;
StringBuffer result = new StringBuffer();
try {
JSONObject jo = new JSONObject(json);
if (jo.has("sentences")) {
JSONArray ja = jo.getJSONArray("sentences");
for (int i = 0; i < ja.length(); i++) {
JSONObject item = ja.getJSONObject(i);
if (item.has("trans"))
result.append(item.getString("trans"));
}
}
} catch (JSONException je) {
Log.e(TAG, je.getMessage(), je);
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
if (result != null && mCallback != null)
mCallback.onTextTranslated(result);
}
};
The [RESTClient class] is a wrapper to HttpClient, you can found the source code here
Regards,
luca
Related
I want to read html code of arduino web server.
I can make web server simply with from example 4. code is below.
#include <SoftwareSerial.h>
#include "WiFly.h"
#define SSID "yum2"
#define KEY "yum000000"
// check your access point's security mode, mine was WPA20-PSK
// if yours is different you'll need to change the AUTH constant, see the file WiFly.h for avalable security codes
#define AUTH WIFLY_AUTH_WPA2_PSK
int flag = 0;
// Pins' connection
// Arduino WiFly
// 2 <----> TX
// 3 <----> RX
SoftwareSerial wiflyUart(2, 3); // create a WiFi shield serial object
WiFly wifly(&wiflyUart); // pass the wifi siheld serial object to the WiFly class
void setup()
{
wiflyUart.begin(9600); // start wifi shield uart port
Serial.begin(9600); // start the arduino serial port
Serial.println("--------- WIFLY Webserver --------");
// wait for initilization of wifly
delay(1000);
wifly.reset(); // reset the shield
delay(1000);
//set WiFly params
wifly.sendCommand("set ip local 80\r"); // set the local comm port to 80
delay(100);
wifly.sendCommand("set comm remote 0\r"); // do not send a default string when a connection opens
delay(100);
wifly.sendCommand("set comm open *OPEN*\r"); // set the string that the wifi shield will output when a connection is opened
delay(100);
Serial.println("Join " SSID );
if (wifly.join(SSID, KEY, AUTH)) {
Serial.println("OK");
} else {
Serial.println("Failed");
}
delay(5000);
wifly.sendCommand("get ip\r");
char c;
while (wifly.receive((uint8_t *)&c, 1, 300) > 0) { // print the response from the get ip command
Serial.print((char)c);
}
Serial.println("Web server ready");
}
void loop()
{
if(wifly.available())
{ // the wifi shield has data available
if(wiflyUart.find("*OPEN*")) // see if the data available is from an open connection by looking for the *OPEN* string
{
Serial.println("New Browser Request!");
delay(1000); // delay enough time for the browser to complete sending its HTTP request string
// send HTTP header
wiflyUart.println("HTTP/1.1 200 OK");
wiflyUart.println("Content-Type: text/html; charset=UTF-8");
wiflyUart.println("Content-Length: 244"); // length of HTML code
wiflyUart.println("Connection: close");
wiflyUart.println();
// send webpage's HTML code
wiflyUart.print("<html>");
wiflyUart.print("<head>");
wiflyUart.print("<title>My WiFI Shield Webpage</title>");
wiflyUart.print("</head>");
wiflyUart.print("<body>");
wiflyUart.print("<h1>Hello World!</h1>");
wiflyUart.print("<h3>10 20 30 40 50</h3>");
wiflyUart.print("Yahoo! Google");
wiflyUart.print("<br/><button>My Button</button>");
wiflyUart.print("</body>");
wiflyUart.print("</html>");
}
}
}
the web server work well.
I wrote simple android code to read html is below.
package com.example.http;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private TextView tv;
String urlAddress = "192.168.0.10"; // doesn't show
// String urlAddress = "http://www.kma.go.kr/weather/main.jsp#1159068000"; // work well
Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadHtml();
}
});
}
void loadHtml() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
final StringBuffer sb = new StringBuffer();
try {
URL url = new URL(urlAddress);
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
if (conn != null) {
conn.setConnectTimeout(2000);
conn.setUseCaches(false);
if (conn.getResponseCode()
== HttpURLConnection.HTTP_OK) {
BufferedReader br
= new BufferedReader(new InputStreamReader
(conn.getInputStream()));
while (true) {
String line = br.readLine();
if (line == null) break;
sb.append(line + "\n");
}
br.close();
}
conn.disconnect();
}
Log.d("test", sb.toString());
handler.post(new Runnable() {
#Override
public void run() {
tv.setText(sb.toString());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.start();
}
}
It work very well with String urlAddress = "http://www.kma.go.kr/weather/main.jsp#1159068000";
but it doesn't show when using
String urlAddress = "192.168.0.10"; instead of before one.
the 192.168.0.10 is allocated ip of arduino from DHCP that i can check on serial monitor.
there is any way to read html from arduino web server??
Your urlAddress isn't a URL, it's just an IP address. You should fully qualify the address with the protocol and the path you want to land on, for example:
String urlAddress = "http://192.168.0.10/";
I would expect you're getting a MalformedURLException.
My current code works perfectly fine to get current version from google store,
But is theres away to get both current version and whats new in the same response ?
I want to recommend the user an update if the application is updated on play store and the user still using an older version.
Here's my code below
public class AppVersion extends AsyncTask<String, Void, String> {
private final String packageName;
private final Listener listener;
public interface Listener {
void result(String version);
}
AppVersion(String packageName, Listener listener) {
this.packageName = packageName;
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
return getPlayStoreAppVersion(String.format("https://play.google.com/store/apps/details?id=%s", packageName));
}
#Override
protected void onPostExecute(String version) {
listener.result(version);
}
#Nullable
private static String getPlayStoreAppVersion(String appUrlString) {
String
currentVersion_PatternSeq = "<div[^>]*?>Current\\sVersion</div><span[^>]*?>(.*?)><div[^>]*?>(.*?)><span[^>]*?>(.*?)</span>",
appVersion_PatternSeq = "htlgb\">([^<]*)</s";
try {
URLConnection connection = new URL(appUrlString).openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
StringBuilder sourceCode = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sourceCode.append(line);
// Get the current version pattern sequence
String versionString = getAppVersion(currentVersion_PatternSeq, sourceCode.toString());
if (versionString == null) return null;
// get version from "htlgb">X.X.X</span>
return getAppVersion(appVersion_PatternSeq, versionString);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Nullable
private static String getAppVersion(String patternString, String input) {
try {
Pattern pattern = Pattern.compile(patternString);
if (pattern == null) return null;
Matcher matcher = pattern.matcher(input);
if (matcher.find()) return matcher.group(1);
} catch (PatternSyntaxException e) {
e.printStackTrace();
}
return null;
}
}
and to call the method i use
new AppVersion(context.getPackageName(), version ->
Log.d("app version test", String.format("App version: %s", version)
)).execute();
In my opinion this is a bad design for your App. You should not rely on scraping to Play store to show a prompt to the user to upgrade. What if the Play Store decides to change design of their HTML? You could leave all your users in a buggy situation.
A much better solution would be to use something like Firebase Remote Config. Have your app read the minimum allowed version code from this. Then it is completely controllable by you, and you don't even have to write a server - firebase does it for you.
You can get App version from BuildConfig Class:
BuildConfig.VERSION_CODE.toString()
1 more thing i want to clear that you cannot get the app version of published app on playstore..
You can put your version code on your backend server and then check this code with your current app version through api call.
i think this will help you.
I have tried to connect to my localhost xampp with android studio using AsyncTask class. Here is AsyncTask but it gives error saying Failed to connect
to /10.0.2.2:800
I tried my real ip address cmd --> ipconfig IPV4 and some other tricks but
they did not succeed
belwow is my app structure
AsyncTask using class
package app.buil.land.food.doymaj.doymaj;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by ProgrammingKnowledge on 1/5/2016.
*/
public class backGroundActivities extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
backGroundActivities (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.0.2.2:800/login.php";
if(type.equals("login")) {
try {
String phone_number = params[1];
// String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("phone_number","UTF-8")+"="+URLEncoder.encode(phone_number,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
Log.e("Line_from_php_server",result);
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
here is my MainActivity
package app.buil.land.food.doymaj.doymaj;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText phone_Number;
EditText user_Name;
EditText pass_Word;
Button singButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// singButton = (Button)findViewById(R.id.sing_id);
// singButton.setOnClickListener(kyListener);
phone_Number =(EditText)findViewById(R.id.mobile_id);
user_Name =(EditText)findViewById(R.id.name_id);
pass_Word =(EditText)findViewById(R.id.p_id);
}
// Push_Identity db = new Push_Identity(this,"CustomerDatabas.db",null,1);
public boolean validate(EditText[] fields){
for(int i = 0; i < fields.length; i++){
EditText currentField = fields[i];
if(currentField.getText().toString().length() <= 0){
switch (i){
case 0:
Toast.makeText(getApplicationContext(),"شماره تلفن وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
case 1:
Toast.makeText(getApplicationContext(),"نام کاربری وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
case 2:
Toast.makeText(getApplicationContext(),"رمز وارد نشده ",Toast.LENGTH_LONG).show() ;
break;
}
return false;
}
}
return true;
}
//private View.OnClickListener kyListener = new View.OnClickListener() {
public void send_number(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
boolean fieldsOK = validate(new EditText[] { phone_Number, user_Name, pass_Word });
if (fieldsOK ==true){
String Phon = phone_Number.getText().toString();
Toast.makeText(getApplicationContext(),Phon,Toast.LENGTH_LONG);
// the Tooast dose not display anything
// it seems that the EditText is empty buy i enter the value in
// in it.
String type ="login";
backGroundActivities back = new backGroundActivities(this);
back.execute(type,Phon);
//
}
}
// };
}
XML
<EditText
android:id="#+id/mobile_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:background="#drawable/customized_edtitext"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="#drawable/ic_smartphone"
android:elevation="2dp"
android:textStyle="bold"
android:hint="#string/register_phone_commnet"
android:fontFamily="#font/iransansmedium"
android:textSize="12sp"
/>
<EditText
android:id="#+id/name_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:layout_below="#id/mobile_id"
android:background="#drawable/customized_edtitext1"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="#mipmap/ic_user"
android:elevation="2dp"
android:textStyle="bold"
android:hint="#string/register_user_commnet"
android:fontFamily="#font/iransansmedium"
android:textSize="12dp" />
<EditText
android:id="#+id/p_id"
android:layout_width="match_parent"
android:layout_height="43dp"
android:layout_below="#+id/name_id"
android:background="#drawable/customized_edtitext2"
android:drawablePadding="15dp"
android:paddingRight="10dp"
android:paddingLeft="15dp"
android:drawableRight="#mipmap/ic_unlocked"
android:elevation="2dp"
android:textStyle="bold"
android:hint="#string/register_pass_commnet"
android:fontFamily="#font/iransansmedium"
android:textSize="12sp"
android:paddingEnd="10dp" />
here is the url of my php page
enter image description here
And some more information: I have Genymotion installed and also bluestack, and VirtaulBox. Do they confilct about port? I mean could these softwares cause conflicting ports Apache xampp and their ports?
My Xampp was working with Port: 80 as shown in below image. So writing below ip address as http://10.0.2.2:80/ worked for me.
If you have wifi and your computer and real device (mobile) is connected to the same wifi you can use NGROK software tool to run and debug your app in your real device.
Run the ngrok.exe and type ngrok http 80, it will give you an address like the below image.
Just use the url in your app where you use your ip address.
It is best to use.
This answer assumes, that the browser screenshot shows a successful page load. I believe, the error page is a bit more gray.
There might be a firewall issue at hand. Since you are using a non-standard port, the firewall exceptions that are installed with XAMPP might not cover that.
Go to the Windows Firewall Advanced settings -> inbound rules. Now add a rule that allows for traffic on the TCP port 800. Make sure, that you uncheck the public profile so that if you are on a public wifi, nobody will be able to connect to this application.
Now check with a browser from the smartphone, if your PHP Application is accessible.
Hi i have searched the internet and stackoverflow all day without any solution! :(
My problem is:
I have to show some schedules in a app, and the data is stored on a webpage, normally on PC you visit the page, enter your id, and it shows the schedule...
but how do i get to the schedule without interacting with a webview or stuff like that? i have to save some specific html data after login...
i have tired with jsoup, but after login, then the url changes, and i dont know how to get it, therefore i tried with webview, but this didnt work either
please help :)
public class getHTML extends AsyncTask{
String words;
#Override
protected Void doInBackground(Void... params) {
try {
final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36";
final String FORM_URL = "http://timetable.scitech.au.dk/apps/skema/VaelgElevskema.asp?webnavn=skema";
final String SCHEDULE_URL = "http://timetable.scitech.au.dk/apps/skema/ElevSkema.asp";
final String USERID = "201506426";
// # Go to search page
Connection.Response loginFormResponse = Jsoup.connect(FORM_URL)
.method(Connection.Method.GET)
.userAgent(USER_AGENT)
.execute();
// # Fill the search form
FormElement loginForm = (FormElement)loginFormResponse.parse()
.select("form").first();
// ## ... then "type" the id ...
Element loginField = loginForm.select("input[name=aarskort]").first();
loginField.val(USERID);
// # Now send the form
Connection.Response loginActionResponse = loginForm.submit()
.cookies(loginFormResponse.cookies())
.userAgent(USER_AGENT)
.execute();
// # go to the schedule
Connection.Response someResponse = Jsoup.connect(SCHEDULE_URL)
.method(Connection.Method.GET)
.userAgent(USER_AGENT)
.execute();
// # print out the body
Element el = someResponse.parse()
.select("body").first();
words = el.text();
System.out.println(loginActionResponse.parse().html());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
tv.setText(words);
Toast.makeText(MainActivity.this, "DET VIRKER!", Toast.LENGTH_SHORT).show();
}
}
I've set up a web server on my own computer using xampp and I am trying to access the server in my App like this:
package com.example.connect2php;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
static String yahooStackInfo = "http://localhost/21/test03.php";
static String stockSymbol = "";
static String stockDaysLow = "";
static String stockDaysHigh = "";
static String stockChange = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... parms) {
// TODO Auto-generated method stub
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(yahooStackInfo);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder theStringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
theStringBuilder.append(line + "\n");
}
result = theStringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (inputStream != null)
inputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
JSONObject jsonObject;
try {
result = result.substring(7);
result = result.substring(0, result.length() - 2);
// Log.v("JSONParser RESULT " , result);
jsonObject = new JSONObject(result);
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
JSONObject resultsJSONObject = queryJSONObject
.getJSONObject("results");
JSONObject quoteJSONObject = resultsJSONObject
.getJSONObject("quote");
stockSymbol = quoteJSONObject.getString("symbol");
stockSymbol = quoteJSONObject.getString("DaysLow");
stockSymbol = quoteJSONObject.getString("DaysHigh");
stockSymbol = quoteJSONObject.getString("Change");
}
catch (JSONException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
TextView line1 = (TextView) findViewById(R.id.line1);
TextView line2 = (TextView) findViewById(R.id.line2);
TextView line3 = (TextView) findViewById(R.id.line3);
line1.setText("Stack: " + stockSymbol + " : " + stockChange);
line2.setText("Days Low " + stockDaysLow);
line3.setText("Days High " + stockDaysHigh);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
But it didn't work. The server code is just:
echo 'cbfunc({"query":{"count":1,"created":"2013-08-24T13:38:58Z","lang":"en-US","results": {"quote":{"symbol":"MSFT","AverageDailyVolume":"47950000","Change":"+2.36","DaysLow":"34.00","DaysHigh":"35.20","YearLow":"26.26","YearHigh":"36.43","MarketCapitalization":"289.5B","LastTradePriceOnly":"34.75","DaysRange":"34.00 - 35.20","Name":"Microsoft Corpora","Symbol":"MSFT","Volume":"225493744","StockExchange":"NasdaqNM"}}}})';
Here is the ip detail:
#ppeterka
Microsoft Windows [版本 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\hcleeab>ipconfig / all
錯誤: 無法辨識或不完整的命令列。
使用方式:
ipconfig [/allcompartments] [/? | /all |
/renew [adapter] | /release [adapter] |
/renew6 [adapter] | /release6 [adapter] |
/flushdns | /displaydns | /registerdns |
/showclassid adapter |
/setclassid adapter [classid] |
/showclassid6 adapter |
/setclassid6 adapter [classid] ]
其中
adapter 連線名稱
(允許使用萬用字元 * 與 ?,請見範例)
選項:
/? 顯示此說明訊息。
/all 顯示完整設定資訊。
/release 釋放指定介面卡的 IPv4 位址。
/release6 釋放指定介面卡的 IPv6 位址。
/renew 更新指定介面卡的 IPv4 位址。
/renew6 更新指定介面卡的 IPv6 位址。
/flushdns 清除 DNS 解析快取。
/registerdns 重新整理所有 DHCP 租用並重新登錄 DNS 名稱。
/displaydns 顯示 DNS 解析快取的內容。
/showclassid 顯示介面卡所有允許的 DHCP 類別識別碼。
/setclassid 修改 DHCP 類別識別碼。
/showclassid6 顯示介面卡允許的所有 IPv6 DHCP 類別識別碼。
/setclassid6 修改 IPv6 DHCP 類別識別碼。
預設是僅顯示每個繫結到 TCP/IP 之介面卡的 IP 位址、子網路遮罩及預設閘道。
對於 Release 與 Renew,如果沒有指定介面卡名稱,則會釋放或更新所有繫結到
TCP/IP 介面卡的 IP 位址租用。
對於 Setclassid 與 Setclassid6,如果沒有指定 ClassId,則將移除 ClassId。
範例:
ipconfig ... 顯示資訊
ipconfig /all ... 顯示詳細資訊
ipconfig /renew ... 更新所有介面卡
ipconfig /renew EL* ... 更新所有名稱開頭為 EL 的連線
ipconfig /release Con ... 釋放所有符合的連線,
例如 "Local Area Connection 1" 或
"Local Area Connection 2"
ipconfig /allcompartments ... 顯示所有區間的相關資訊
ipconfig /allcompartments /all ... 顯示所有區間的詳細資訊
C:\Users\hcleeab>ipconfig
Windows IP 設定
無線區域網路介面卡 無線網路連線:
媒體狀態 . . . . . . . . . . . . .: 媒體已中斷連線
連線特定 DNS 尾碼 . . . . . . . . : hgcbroadband.com
通道介面卡 isatap.hgcbroadband.com:
媒體狀態 . . . . . . . . . . . . .: 媒體已中斷連線
連線特定 DNS 尾碼 . . . . . . . . : hgcbroadband.com
通道介面卡 6TO4 Adapter:
通道介面卡 Teredo Tunneling Pseudo-Interface:
預設閘道 . . . . . . . . . . . . .:
C:\Users\hcleeab>
You should use:
http://10.0.2.2/21/test03.php
10.0.2.2 is the special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
See: Emulator Network Address Space in the official docs
Though you could have added a logcat, this is most likely why your app fails to obtain the content:
static String yahooStackInfo = "http://localhost/21/test03.php";
This tells your android device to try and access itself. Localhost is the device itself. substitute that with the hostname or IP address of your host.
You might need to check firewall settings too...
Update
Updated with the IP in the comment:
static String yahooStackInfo = "http://223.18.60.177/21/test03.php";