android - Теxtview not change instantly - java

I accept the array from the server, and then fill the data textview.
private class ReadMessages extends AsyncTask<Void, Void, Integer>
{
HttpURLConnection conn;
String ansver, bfr_st;
JSONArray JsonArray;
protected Integer doInBackground(Void... params) {
try {
String post_url = server_name +"/chat.php?action=select";
conn = (HttpURLConnection) new URL(post_url).openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream(); //канал
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); //буфер
StringBuilder sb = new StringBuilder(); //сборщик строки
while ((bfr_st = br.readLine()) != null) {
sb.append(bfr_st); //получили массив в виде string
}
String json_bum = sb.toString();
JsonArray = new JSONArray(json_bum); //преобразовали string обратно в массив
for (int i=0; i<JsonArray.length(); i++) {
jsonObject = JsonArray.getJSONObject(i); //вынули все обьекты
}
tv_number.setText("Номер - " + jsonObject.getInt("_id") +
"\n"
+ "Автор - " + jsonObject.getString("author") +
"\n"
+ "Адресат - " + jsonObject.getString("client") +
"\n"
+ "Время - " + jsonObject.getLong("data") +
"\n"
+ "Текст - " + jsonObject.getString("text") +
"\n");
is.close();
br.close();
} catch (Exception e) {
} finally {
conn.disconnect();
}
return null;
}
}
when I fold the application and then come back to it the text changes . but immediately when you press a button that does not happen

You can only update your GUI elements/widgets from app main thread. AsyncTask is creating seperate thread and you can't do this from method doInBackground, try use publishProgress and onProgressUpdate or do all this staff in onPostExecute

You're not allowed to update GUI on a separate thread. You should update it in the OnPostExecute within your AsyncTask. Also, you must #Override the doInBackground.
private class ReadMessages extends AsyncTask<Void, Void, Integer> {
HttpURLConnection conn;
String ansver, bfr_st;
JSONArray JsonArray;
#Override
protected Integer doInBackground(Void... params) {
try {
String post_url = server_name +"/chat.php?action=select";
conn = (HttpURLConnection) new URL(post_url).openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream(); //канал
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); //буфер
StringBuilder sb = new StringBuilder(); //сборщик строки
while ((bfr_st = br.readLine()) != null) {
sb.append(bfr_st); //получили массив в виде string
}
String json_bum = sb.toString();
JsonArray = new JSONArray(json_bum); //преобразовали string обратно в массив
for (int i=0; i<JsonArray.length(); i++) {
jsonObject = JsonArray.getJSONObject(i); //вынули все обьекты
}
is.close();
br.close();
} catch (Exception e) {
} finally {
conn.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
tv_number.setText("Номер - " + jsonObject.getInt("_id") +
"\n"
+ "Автор - " + jsonObject.getString("author") +
"\n"
+ "Адресат - " + jsonObject.getString("client") +
"\n"
+ "Время - " + jsonObject.getLong("data") +
"\n"
+ "Текст - " + jsonObject.getString("text") +
"\n");
}

Why you decided it must be immediately ? It depends on your internet speed, ping and etc. Good practice is using progressBar to show user that something is happening, not just empty screen and then textView appears after several seconds.

The line in doInbackground:
tv_number.setText("Номер - " + jsonObject.getInt("_id") +
"\n"
+ "Автор - " + jsonObject.getString("author") +
"\n"
+ "Адресат - " + jsonObject.getString("client") +
"\n"
+ "Время - " + jsonObject.getLong("data") +
"\n"
+ "Текст - " + jsonObject.getString("text") +
"\n");
actually throws an exception, but the empty catch statement prevents the app from crashing.
you can't update views from a background thread, updating UI must be on the UI thread. In case of AsyncTask you can do this in onPostExecute or onProgressUpdate methods.
change your doInBackground implementation, make it return a String:
protected String doInBackground(Void... params){
}
then in onPostExecute, update the textview
protected onPostExecute(String result){
tv_number.setText(result);
}

Related

how to fix this error JSON in java A JSONObject text must begin with '{' at 1 [character 2 line 1]

I have managed to save the data in the BD, but when I get to JSONobject it goes to the exception and presents this error in METHOD POST:
public int insertarCliente(Cliente c){
//globalURL += "?rut=" + c.getRut() + "&nom="+ c.getNombre() +"&app=" + c.getApellidoP() + "&apm=" + c.getApellidoM();
String globalURL = "http://localhost:60367/api/Cliente?rut=" + c.getRut() + "&nom="+ c.getNombre() +"&app=" + c.getApellidoP() + "&apm=" + c.getApellidoM();
try {
HttpURLConnection conn = Conectar(globalURL);
conn.setRequestMethod("POST");
conn.setRequestProperty("ACCEPT", "application/json");
//conn.setRequestProperty("Content-Length", "0");
conn.setDoOutput(true);
conn.getOutputStream().close();
if (conn.getResponseCode() == 200) {
InputStreamReader isr = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(isr);
String resp = br.readLine();
JSONObject obj = new JSONObject(resp.trim());
//JSONArray obj = new JSONArray(resp.trim());
br.close();
return obj.getInt("resp");
}
} catch (Exception e) {
Logger.getLogger(ClienteDAO.class.getName()).log(Level.SEVERE, null, e);
}
return 0;
}
and presents the following error.
Grave: org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
at org.json.JSONObject.<init>(JSONObject.java:184)
at org.json.JSONObject.<init>(JSONObject.java:310)

Consume Zimbra Get Calendar REST Api in Java

I get this error when I consume the REST Api of Zimbra on Android: must Athenticate java.lang.RuntimeException: Failed : HTTP error code : 401
at ZimbraREST.main(ZimbraREST.java:33). However I am absolutely sure that my login and my password are the good ones and my code was working perfectly fine yesterday, and I did not modify any important stuff linked to this code. This code should get me an xml file that I use to get sync calendar on my app. Thanks for your help. Here is my code:
#Override
protected Void doInBackground(Integer... integers) {
System.out.println("15email_adress=" + email_adress);
System.out.println("15password=" + password);
String dayStart = String.valueOf(integers[0]);
String monthStart = String.valueOf(integers[1]);
String yearStart = String.valueOf(integers[2]);
String dayEnd = String.valueOf(integers[3]);
String monthEnd = String.valueOf(integers[4]);
String yearEnd = String.valueOf(integers[5]);
String[] strings = {dayStart, monthStart, yearStart, dayEnd, monthEnd, yearEnd};
int k = 0;
for(String s: strings){
if(s.length() < 2){
strings[k] = "0" + s;
}
k++;
}
dayStart = strings[0];
monthStart = strings[1];
yearStart = strings[2];
dayEnd = strings[3];
monthEnd = strings[4];
yearEnd = strings[5];
try {
URL url = new URL("https://zmail.insa-lyon.fr/home/" + email_adress + "/Calendrier%20Cocktail?fmt=xml&start=" +
monthStart +
"/" +
dayStart +
"/" +
yearStart +
"&end=" +
monthEnd +
"/" +
dayEnd +
"/" +
yearEnd);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email_adress, password.toCharArray());
}
});
conn.setRequestMethod("GET");
conn.setRequestProperty("--user", email_adress + ":" + password);
if (conn.getResponseCode() != 200) {
System.out.println("15erreur=" + url.toString());
System.out.println("15erreur=" + conn.getResponseMessage());
System.out.println("15erreur=" + conn.getRequestMethod());
return null;
}
System.out.println(conn.getResponseMessage());
InputStreamReader inputStreamReader = new InputStreamReader((conn.getInputStream()));
BufferedReader br = new BufferedReader(inputStreamReader);
String output;
StringBuilder xml = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
xml.append(output);
}
inputStreamReader.close();
br.close();
conn.disconnect();
System.out.println(xml);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml.toString())));
rootElement = document.getDocumentElement();
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
}
return null;
}
Ok so I had to authenticate the user with the code below:
// Authentication part -------------------
String userpass = email_adress + ":" + password;
conn.setRequestProperty("X-Requested-With", "Curl");
String basicAuth = "Basic " + new String(android.util.Base64.encode(userpass.getBytes(), android.util.Base64.DEFAULT));
conn.setRequestProperty("Authorization", basicAuth);
// ----------------------------------------

Read any Language String from Google Translator in Android

I am creating a translator app where I am getting the input text from android supported voice Recognizer. Example : Hindi, Chinese, etc. Now I want to build the query like this -
public JSONObject getTranslatedText() {
StringBuilder sb = new StringBuilder();
String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
JSONObject response = null;
String json = "";
HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
String line1 = "{\n" + " 'q': '" + inputString + "',\n" + " 'target': '" + targetcodeString + "'\n" + "}";
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(line1);
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
json = sb.toString();
response = new JSONObject(json);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (JSONException e) {
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return response;
}
The problem is it is not encoding properly and I am getting output like this -
Example: For a word "How are you" in Hindi i.e "क्या हाल" as 9 & HG 08 * E
Can I get some help please. Thanks in advance.
Try using Html.fromHtml(yourTranslatedStr).toString().
I tried that with Hindi and it worked.

number of search result from Bing API

how can i access to number of search result in bing search?
i found this thread:
How to get number of search result from Bing API
in this thread i understand that i should use d->results[0]->WebTotal
but how can i use this line in java?
public static void main(String[] args) throws Exception {
//term1
String searchText = "is";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="WOCKN8uXArczOkQq5phtoEc7usB0kDoPTnbqn0sKWeg";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
//conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
char[] buffer = new char[4096];
while ((output = br.readLine()) != null) {
sb.append(output);
//text.append(link + "\n\n\n");//Will print the google search links
//}
}
conn.disconnect();
int find = sb.indexOf("<d:Description");
int total = find + 1000;
System.out.println("Find index: " + find);
System.out.println("Total index: " + total);
sb.getChars(find+35, total, buffer, 0);
String str = new String(buffer);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://learn-it-stuff.blogspot.com/2012/09/using-bing-custom-search-inside-your.html
I found the answer:
public static void main(String[] args) {
String searchText = "searchtext";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="key_ID";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
//write json to string sb
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
//find webtotal among output
int find= sb.indexOf("\"WebTotal\":\"");
int startindex = find + 12;
int lastindex = sb.indexOf("\",\"WebOffset\"");
System.out.println(sb.substring(startindex,lastindex));
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Sending POST from Android Application

I'm triyng to send POST request to the server. The following java code working for PC application, but doesn't work on my Android application. The Iternet permission is added, so, what I have to do to send this post, and what other methods and libraries I have to use to replace this code for Android?
String hostname = "xxxxxxx.box";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket sock = new Socket(addr, port);
String SID = new classSID("xxxxxx").obtainSID();
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream(),"UTF-8"));
String str = "enabled=on&username="+givenName+"&email="+givenEmail+"&password="+givenPassword+"&frominternet=on&box_admin_rights=on&phone_rights=on&homeauto_rights=on&uid=&sid="+SID+"&apply=";
////////////////////////////////////////////////////////////////////////////////////////////
wr.write("POST /system/boxuser_edit.lua HTTP/1.1");
wr.write("Host: xxxxxx:80" + "\r\n");
wr.write("Accept: text/html" + "\r\n");
wr.write("Keep-Alive: 300" + "\r\n");
wr.write("Connection: Keep-Alive" + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded"+"\r\n");
wr.write("Content-Length: "+str.length()+"\r\n");
wr.write("\r\n");
wr.write(str+"\r\n");
wr.flush();
////////////////////////////////////////////////////////////////////////////////////////////
BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream(),"UTF-8"));
String line;
while((line = rd.readLine()) != null)
Log.v("Response", line);
wr.close();
rd.close();
sock.close();
}
The issue is with creating socket on port 80. You need root permission to access port < 1024 in android. See issue
Try this: and consider using an IP instead of hostname because your android device might nto be able to resolve a local hostname
private static final String UTF_8 = "UTF-8";
/**
* #param hostNameOrIP
* : the host name or IP<br/>
* #param webService
* : the web service name<br/>
* #param classOrEndPoint
* : the file or end point<br/>
* #param method
* : the method being called<br/>
* #param parameters
* : the parameters to be sent in the message body
* #return
*/
public static String connectPOST(final String url, final HashMap<String, String> parameters) {
final StringBuilder postDataBuilder = new StringBuilder();
if (null != parameters) {
for (final HashMap.Entry<String, String> entry : parameters.entrySet()) {
if (postDataBuilder.length() != 0) {
postDataBuilder.append("&");
}
postDataBuilder.append(entry.getKey()).append("=").append(entry.getValue());
}
}
final StringBuffer text = new StringBuffer();
HttpURLConnection conn = null;
OutputStream out = null;
InputStreamReader in = null;
BufferedReader buff = null;
try {
final URL page = new URL(url);
conn = (HttpURLConnection) page.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
out = conn.getOutputStream();
final byte[] postData = postDataBuilder.toString().getBytes(UTF_8);
out.write(postData);
out.flush();
out.close();
final int responseCode = conn.getResponseCode();
if ((responseCode == 401) || (responseCode == 403)) {
// Authorization Error
Log.e(TAG, "Authorization error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Authorization Error in " + method + "("
// + postDataBuilder.toString() + ")");
return null;
}
if (responseCode == 404) {
// Authorization Error
Log.e(TAG, "Not found error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Authorization Error in " + method + "("
// + postDataBuilder.toString() + ")");
return null;
}
if ((responseCode >= 500) && (responseCode <= 504)) {
// Server Error
Log.e(TAG, "Internal server error in " + url + "(" + postDataBuilder.toString() + ")");
// throw new Exception("Internal Server Error in " + method +
// "("
// + postDataBuilder.toString() + ")");
return null;
}
in = new InputStreamReader((InputStream) conn.getContent());
buff = new BufferedReader(in);
String line;
while ((null != (line = buff.readLine())) && !"null".equals(line)) {
text.append(line + "\n");
}
buff.close();
buff = null;
in.close();
in = null;
conn.disconnect();
conn = null;
} catch (final Exception e) {
Log.e(TAG, "Exception while connecting to " + url + " with parameters: " + postDataBuilder + ", exception: " + e.toString() + ", cause: "
+ e.getCause() + ", message: " + e.getMessage());
e.printStackTrace();
return null;
} finally {
if (null != out) {
try {
out.close();
} catch (final IOException e1) {
}
out = null;
}
if (null != buff) {
try {
buff.close();
} catch (final IOException e1) {
}
buff = null;
}
if (null != in) {
try {
in.close();
} catch (final IOException e1) {
}
in = null;
}
if (null != conn) {
conn.disconnect();
conn = null;
}
}
final String temp = text.toString();
if (text.length() > 0) {
Log.i(TAG, "Success in " + url + "(" + postDataBuilder.toString() + ") = " + temp);
return temp;
}
Log.w(TAG, "Warning: " + url + "(" + postDataBuilder.toString() + "), text = " + temp);
return null;
}

Categories

Resources