I need to use this api,
"http://sconysoft.com/api/md5.php?q="
for doing something like this app :
https://play.google.com/store/apps/details?id=com.sconysoft.md5encoderdecoder&hl=en
Actually, i have one button with Two EditText in Android app, just i need send first string to this api, and if this hash encoded(in url) exist, show that in Edit Text2.
and this is above app Codec class :
public class Codec {
public String decode(String md5) throws Exception {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(new HttpGet("http://sconysoft.com/api/md5.php?q=" + md5));
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
JSONObject jo = new JSONObject(br.readLine());
if(jo.getString("md5").equals(""))
throw new Exception();
return jo.getString("word");
} catch (Exception e) {
}
throw new Exception("Can't decode given md5");
}
}
main :
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public void decode(View view) {
final EditText etWord = (EditText)findViewById(R.id.edit1);
final EditText etMd5 = (EditText)findViewById(R.id.edit2);
if(!isNetworkAvailable()) {
etWord.setText("Network unavailable");
return;
}
final ProgressDialog pd = ProgressDialog.show(view.getContext(),"Waiting for Server", "It should take a few seconds");
Thread th = new Thread() {
#Override
public void run() {
try {
Codec cd = new Codec();
String md5 = etMd5.getText().toString();
try {
final String word = cd.decode(md5);
runOnUiThread(new Runnable() {
public void run() {
etWord.setText(word);
pd.dismiss();
}
});
} catch (final Exception e) {
runOnUiThread(new Runnable() {
public void run() {
etWord.setText(e.getMessage());
pd.dismiss();
}
});
}
} catch(Exception e) {
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
}
}
};
th.start();
}
}
i also try this codes with same situation in developing, but unfortunately, this codes doesn't work and i cannot see this buttons codes or other something on this app codes.
Can someone help me, how to doing this with one button and Two EditTexts?
Need some help about doing this with above API.
I am assuming
public void decode(View view)
gets called from the button onClick?
I suggest doing the network call (and managing the progress dialog) in an AsyncTask. Examples:
Using AsyncTask for android network connection
How to use AsyncTask to show a ProgressDialog while doing background work in Android?
You update the second EditText (you could use TextView) in the AsyncTask's onPostExecute.
Related
I'm developing a simple Android application that has to scrape content of one website and then add this to the URL of another website that I have to scrape. The first scraping is okay, but the second gives me an error: "HTTP error fetching URL". The second URL is fine because when I give it to the first scraper everything is okay (but the URL is changing, so I cannot use it as a constraint). I think that I have to finish the thread of the first scraper somehow, but I don't know how.
My current code:
private void getBodyText() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
String url="http://example.com";
Document doc = Jsoup.connect(url).get();
Element body = doc.body();
builder.append(body.text());
} catch (Exception e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(builder.toString());
token1=builder.toString();
checkPairing();
}
});
}
}).start();
}
private void checkPairing() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
String url="http:example.com/"+token1;
Document doc = Jsoup.connect(url).get();
Element body = doc.body();
builder.append(body.text());
} catch (Exception e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if (builder.toString()!="Not Found") {
tokenPar = builder.toString();
}
}
});
}
}).start();
}
I've also tried to execute the second function directly from onCreate() after the first scraper is executed but nothing changed.
I just want to read (-1) value which is the only value in website but I am not able to fetch this value Can any buddy guide me how to do that. I am getting the value of API url when I am pasting it in web browser and android is not fetching it. Link of API is given below.
Link OF API
Code I am trying is:
private void getWebsite() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("https://api.thingspeak.com/channels/411172/feeds.json?results=1").get();
String title = doc.title();
Elements links = doc.select("[pre]");
builder.append(title).append("\n");
for (Element link : links) {
builder.append("\n").append("Link : ").append(link.attr("pre"))
.append("\n").append("Text : ").append(link.text());
}
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
Screen shot of web API call in browser
Error I am getting is Error: HTTP error fetching URL
As I see response from your API is JSON formatted you have to modify your code as follow
private void getWebsite() {
new Thread(new Runnable() {
#Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("https://api.thingspeak.com/channels/411172/feeds.json?results=1")
.ignoreContentType(true)
.get();
String json = doc.body().text();
builder.append(json);
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
I load my articles from my wordpress webpage. And want to display them in my app.
In order to be allowed to wait for a internet response I had to create a Thread.
Using this method:
private void loadArticles(final String url) {
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
//Get my data and run createArticles();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Then in the createArticles function I try to use my function addViewToParent(...) and I get an error that says:
Only the original thread that created a view hierarchy can touch its
views.
How can i work around this problem?
EDIT: I use these networking functions if it matters...
//Connect to the url
URL pageURL = new URL(url);
HttpURLConnection connection = (HttpURLConnection) pageURL.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream())
);
If you want to modify your Views, e.g. show your article, you have to run the code on the UI/main thread. To achieve this, you could call run runOnUiThread() in your Activity:
private void loadArticles(final String url) {
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
//Get my data ...
runOnUiThread(new Runnable() {
public void run() {
// modify Views here
createArticles();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
You need to use function runOnUiThread. This is function for user interface thread.
private void loadArticles(final String url) {
//Get my data ...
runOnUiThread(new Runnable() {
public void run() {
// modify Views here
createArticles();
}
});
});
Just use a Handler instead, so you'll have access to the UI Thread:
new Handler().post(new Runnable(){
#Override
public void run() {
try {
//Get my data and run createArticles();
} catch (Exception e) {
e.printStackTrace();
}
}
});
I am working on parse.com android application. Like in normal http request if we don't get the response from the server in a certain time then it will show time out functionality. For example my following code will works for http request time out:
HttpsURLConnection connection = null;
connection = (HttpsURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setHostnameVerifier(DO_NOT_VERIFY);
connection.setReadTimeout(3*1000);
Now i want the same functionality in parse.com, if i can't get the response from the parse server because of any reason like internet connectivity issue, then it will gives me timeout.
Thanks in advance.
Parse.com SDK does not have such functionality which you have described at your question.
But you can do some trick, for example, at ParseQuery exists method cancel(). So if you want timeout less then standard one, you can run query in background and and wait until or query callback will delivery result of it, or your implementation of timeout will cancel query running.
Update:
public class TimeoutQuery<T extends ParseObject> {
private ParseQuery<T> mQuery;
private final long mTimeout;
private FindCallback<T> mCallback;
private final Object mLock = new Object();
private final Thread mThread;
public TimeoutQuery(ParseQuery<T> query, long timeout) {
mQuery = query;
mTimeout = timeout;
mThread = new Thread() {
#Override
public void run() {
if (isInterrupted()) return;
try {
Thread.sleep(mTimeout);
} catch (InterruptedException e) {
return;
}
cancelQuery();
}
};
}
private void cancelQuery() {
synchronized (mLock) {
if (null == mQuery) return; // it's already canceled
mQuery.cancel();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mCallback.done(Collections.<T>emptyList(), new ParseException(ParseException.TIMEOUT, ""));
}
});
}
}
public void findInBackground(final FindCallback<T> callback) {
synchronized (mLock) {
mCallback = callback;
mQuery.findInBackground(new FindCallback<T>() {
#Override
public void done(List<T> ts, ParseException e) {
synchronized (mLock) {
mThread.interrupt();
mQuery = null;
mCallback.done(ts, e);
}
}
});
mThread.start();
}
}
}
Usage:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Test");
new TimeoutQuery<>(query, 1000).findInBackground(new FindCallback<ParseObject>() {
...
});
Hi and thank you for looking at my question.
I am an intermediate programmer in C but an Android newbie. I have been trying to get a chat programming working. Assuming everything else in the code below works perfectly. The one question I like to ask is when I try to setText() from a thread running, I get an exception above. I looked at many many websites and here too. Found many things, but I really do not understand. Please explain to me in the most simple way or offer me some simple fix if possible.
Thank you very much!!
public class chatter extends Activity {
private String name = "Unknown User";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText msgToServer = (EditText) findViewById(R.id.msgBox);
final EditText chatFromServer = (EditText) findViewById(R.id.chatBox);
final Button MsgToServer = (Button) findViewById(R.id.sendButton);
Socket socket = null;
String ipAddress = "192.168.1.103";
try {
InetAddress serverAddr = InetAddress.getByName(ipAddress);
Socket socketMain = new Socket(serverAddr, 4444);
socket = socketMain;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "error", e);
}
final OutMsg outMsg = new OutMsg(socket);
Thread msgSenderThread = new Thread(outMsg);
msgSenderThread.start();
//chatFromServer.post(new InMsg(socket, chatFromServer));
Thread msgReceiverThread = new Thread(new InMsg(socket, chatFromServer));
msgReceiverThread.start();
MsgToServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msgToServerString;
msgToServerString = msgToServer.getText().toString();
outMsg.message = name + ": " + msgToServerString;
outMsg.readyToSend = true;
msgToServer.setText("");
}
});
}
public void updateResultsInUi (String msg)
{
final EditText chatFromServer = (EditText) findViewById(R.id.chatBox);
chatFromServer.setText(msg);
}
public class InMsg implements Runnable {
Socket socket;
EditText chatFromServer;
public InMsg(Socket socket, EditText chatFromServer)
{
this.socket = socket;
this.chatFromServer = chatFromServer;
}
public void run(){
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = "FIRSTMESSAGEFROMSERVER";
while (true)
{
if (str.equals("FIRSTMESSAGEFROMSERVER"))
str = in.readLine();
else
str = str + "\n" + in.readLine();
Log.e("TCP", "got the message: " + str);
//Here is where went wrong******************
chatFromServer.setText(str);
//******************************************
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "error in receiving", e);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.setNameMenu:
setname();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void populateChatBox (String msgFromS)
{
Log.e("TCP", "going in to popC");
final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
Log.e("TCP", " popC");
textNameInput.setText(msgFromS);
Log.e("TCP", "going out from popC");
}
public void setname()
{
setContentView(R.layout.custom_dialog);
final EditText textNameInput = (EditText) findViewById(R.id.nameBox);
Button submitNameButton = (Button) findViewById(R.id.submitNameButton);
submitNameButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String nameinput = textNameInput.getText().toString();
if (!name.equals(""))
name = nameinput;
setContentView(R.layout.main);
}
});
}
}
In your run() method:
Message msg = new Message();
String textTochange = "text";
msg.obj = textTochange;
mHandler.sendMessage(msg);
Create the mHandler in your UI thread;
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String)msg.obj;
//call setText here
}
};
You are not on the UI thread when setting the text. You need to be on UI if you want to work on UI items. Create a message handler on the UI thread, post your messages to it and call setText from the handler on the UI thread.
you can do this whenever you are in a thread:
msgToServer.post(new Runnable() {
public void run() {
msgToServer.setText("your text here");
}
}
Your problem is that there are certain interactions that you can only do on the UI thread. This is one of them.
Looks like you might want to use AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
Basically you could make your Runnable an AsyncTask instead and do the setText in onProgressUpdate, which gets run on the UIThread.
If you would like to use an AsyncTask to run in the background this is how I would do it:
public class UpdateTextProgress_Task extends AsyncTask<Void,String,Void> {
Socket socket;
EditText chatFromServer;
UpdateTextProgress_Task(EditText chatFromServer, Socket socket){
this.socket = socket;
this.chatFromServer = chatFromServer;
}
#Override
protected Void doInBackground(Void... params) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = "FIRSTMESSAGEFROMSERVER";
while(true){
if (str.equals("FIRSTMESSAGEFROMSERVER")){
str = in.readLine();
}
else{
str = str + "\n" + in.readLine();
}
Log.e("TCP", "got the message: " + str);
publishProgress(str); // calls the onProgressUpdate method
}catch (IOException e) {
Log.e("UpdateTextProgress", e.getMessage());
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
chatFromServer.setText(progress[0]); //now we are on the UI thread so we can update our EditText
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.e("UpdateTextProgress", "Finished");
}
}
To execute the code:
UpdateTextProgress_Task task = new UpdateTextProgress_Task(chatFromServer,socket);
task.execute();