unexpected behavior of android program - android

i want to run the script behind the button of Google search that means...posting a form to google server and getting the response in the form of html string and finally i put that string on webview to display result....
then i run the code ...
some times it shows correct result (like someone click on google search button) but some times it shows me message to "force to close" without any changes i do in to code....that means prediction about output is unexpected...
My code is like this......
public class url extends Activity
{
HttpResponse end = null;
String endResult = null;
WebView mWebView;
Intent myWebViewIntent;
public static final int TIMEOUT_MS=10000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT_MS);
HttpPost post = new HttpPost("http://www.google.com/m");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("hl", "en"));
pairs.add(new BasicNameValuePair("gl", "us"));
pairs.add(new BasicNameValuePair("source", "android-launcher-widget"));
pairs.add(new BasicNameValuePair("q", "persistent"));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
/* Uri uri = Uri.parse(post.toString());
TextView t1=new TextView(this);
t1.setText(post.getRequestLine().getUri());
this.setContentView(t1);*/
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Toast msg = Toast.makeText(url.this, "Message", Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
HttpResponse response = client.execute(post);
end = response;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
//Toast.makeText(url.this, "problem in execute....", 20).show();
// TODO Auto-generated catch block
//put the balance is empty dialog box here.
e.printStackTrace();
}
BasicResponseHandler myHandler = new BasicResponseHandler();
try {
// Log.i("file tag","we are out of url");
endResult = myHandler.handleResponse(end);
} catch (HttpResponseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
WebView engine = (WebView)findViewById(R.id.webview);
engine.loadDataWithBaseURL(post.getRequestLine().getUri(), endResult, "text/html", "UTF-8", null);
//engine.loadData(endResult, "text/html", "UTF-8");
engine.requestFocus(View.FOCUS_DOWN);
//engine.loadUrl(endResult);
}
}
so is there any problem in emulator or installation of SDk or program itself....? becoz it seems to be the connection with the internet is done but i use the proper permission..
thank you..

The ANR you get is because you're making a blocking call on the UI thread. To perform a blocking action without blocking the UI thread you have to use a thread and a handler, or (recommended) an AsyncTask.
See Painless Threading.

Related

unfortunately android application has been stopped. At Http Post while attempting to call server

Unfortunately android application has been stopped. At Http Post while attempting to call server at post activity please help
HttpClient cli = new DefaultHttpClient();
//HttpPost post = new HttpPost("http://" + sp.getString("ip", "localhost") + "/attendance/cliLogin.php");
HttpPost post = new HttpPost("localhost/attendance/");
// seting post data
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
String result = EntityUtils.toString(resent);
// reading response
if(result.equals("NoParams"))
Commons.showToast("Something went wrong", true);
else if(result.equals("Login"))
{
navi = new Intent(this, HomeActivity.class);
startActivity(navi);
}
else
Commons.showToast(result, true);
}
catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Commons.showToast("Can't reach server, check the Hostname", true);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
Commons.showToast("Username/Password can't be empty", true);
}
}
Could you please share your logcat to see the error? I think that your are calling the php script in your main thread (that is your activity thread) and you may have NetworkOnMainThreadException
If that is the case:
Create a class that extends the AsyncTask.
Override its methods.
In the creator of this class pass the variables and assign them to the fields (variables) of your class.
Make your post in an AsyncTask inside the doInBackground method
And call the AsyncTask execute. Like this:
public class MyTask extends AsyncTask<String,String,String>{
private short errorType = -1;
private String result;
private String uname;
private String pass;
public MyTask(String uname, String pass){
this.uname = uname;
this.pass = pass;
}
#Override
protected String onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (errorType == 1){
Commons.showToast("Can't reach server, check the Hostname", true);
}
if(result.equals("NoParams")) {
Commons.showToast("Something went wrong", true); }
else if(result.equals("Login")) {
Intent navi = new Intent(this, HomeActivity.class); startActivity(navi);
}
else {
Commons.showToast(result, true);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try
{
HttpClient cli = new DefaultHttpClient();
HttpPost post = new HttpPost("localhost/attendance/");
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
return result = EntityUtils.toString(resent);
}
catch (HttpHostConnectException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
errorType = 1;
return null;
}
catch (ParseException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 2;
return null;
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 3;
return null;
}
catch(Exception e){
errorType = 4;
return null;
}
}
}
And inside the activity make your call like this:
MyTask new MyTask(uname, pass).execute();
Again. All this is applicable only if you have
NetworkOnMainThreadException
Please share your logcat for further help.

Send JSON data from a service to UI in Android

The requirement is : I have a background service and in that service I am doing a REST call to get a JSON data. I want to send the JSON data to UI and update contents.
One method I can use i.e. store the entire JSON string in SharedPreferences and retrieve in UI but I don't think that's efficient.
Any idea guys ? I have added a Handler in UI to update elements but I am not that familiar in using it.
Sample REST call code :
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(DATA_URL);
httpPost.setHeader("Content-Type", "application/json");
//passes the results to a string builder/entity
StringEntity se = null;
try {
se = new StringEntity(RequestJSON.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//sets the post request as the resulting string
httpPost.setEntity(se);
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
try {
HttpResponse response = (HttpResponse) httpClient.execute(httpPost, responseHandler);
// response will have JSON data that I need to update in UI
//Show notification
showNotification("Update Complete");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// httpClient = null;
}
On UI activity
Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle Recevied = msg.getData();
String resp = Recevied.getString("Mkey");
}
};
messenger = new Messenger(myHandler);
}
pass the messanger to service and once result ready:
Message msg = Message.obtain();
Bundle data = new Bundle();
data.putString("Mkey",
Smsg);
msg.setData(data);
try {
// Send the Message back to the client Activity.
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
Something like that may be suitable for you. TL;DR: Create a listener in the service that updates the activity.
In the service, make a static function and a static field:
private static BlaBlaService _instance;
public static BlaBlaService getInstance() {
return _instance;
}
Populate the _instance field on the onCreate function:
public void onCreate() {
super.onCreate();
_instance = this;
...
}
public void addRESTCompleteListener(RESTCompleteListener l) {...}
Once a REST call is complete call:
listener.RESTCompleted(JSON.whatever)
Now in your activity, simply add the listener to the service once it starts:
BlaBlaService.getInstance().addRESTCompleteListener(listener)
Don't forget to dispose all the pointers when needed.
Hope this helps :)

HTTP Post to Php isn't working

The code isn't working. Please help. The item gets added to the database except for the quantity. It's always zero. Why is that?
String value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creamy);
EditText et = (EditText) findViewById(R.id.CreamyEdit);
value = et.getText().toString();
Button b = (Button) findViewById(R.id.buttonCreamy);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Creamy.this, "Item Submitted", Toast.LENGTH_LONG).show();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"http://10.0.2.2:8080/http/test.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("item", "Creamy Delight")); //reflected in db
pairs.add(new BasicNameValuePair("quantity", value)); //not reflected in db
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
Help please!
Move the line value = et.getText().toString(); into the onClick method. If you call et.getText in onCreate it always returns an empty string, because that's all that's inside the EditText at the time of onCreate.

Android - HttpClient execute has a mind of its own - 1 second or 200 seconds

I'm trying to use HttpClient to connect to a php page that logs in and passes back a sessionid and then goes to a new page, using that sessionid and obtains a mySQL datafield associated with that sessionid.
On the first request, HttpClient can take 1.5 seconds, 6 seconds, or 2 minutes. If the first request was slow, subsequence requests seem to be faster, and visaversa.
The HttpClient request occurs when a Button view is clicked
Here's my code:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
name = (TextView)findViewById(R.id.name);
user = (EditText) findViewById(R.id.user);
pass = (EditText) findViewById(R.id.pass);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(this);
HttpParams params1 = new BasicHttpParams();
params1.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client = new DefaultHttpClient(params1);
httpclient = new DefaultHttpClient();
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Create local HTTP context
}
public void onClick(View v) {
if (v.getId() == R.id.button1) {
//submit.setClickable(false);
String username = user.getText().toString();
String password = pass.getText().toString();
String targetURL = "<<<<LOGIN PHP URL>>>>";
post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("params","params added");
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d("entity added","entityadded");
Log.d("preex","PRE EXECUTION");
localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//submit.setText("Logging In...");
new Thread(new Runnable(){
public void run(){
try {
Log.d("pre","pre execute");
response = client.execute(post,localContext);
Log.d("post","post execute");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("response: ",convertStreamToString(input));
getFullName(localContext);
}
}
}).start();}
}
private void getFullName(final HttpContext context){
Log.d("called","called");
String targetURL = "<<<<SESSION CHECKER PHP URL>>>>";
//client1 = new DefaultHttpClient();
post1 = new HttpPost(targetURL);
Log.d("","about to call runable....");
// submit.setText("Obtaining Full Name...");
try {
Log.d("pre","CALLING!");
response = client.execute(post1,context);
Log.d("post","called..");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
Log.d("post","FIANLLY");
try {
//submit.setText("Full Name Obtained!...");
input = response.getEntity().getContent();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("response: ",convertStreamToString(input));
outputResponse(input);
}
}
private void outputResponse(final InputStream in) {
name.post(new Runnable(){
public void run(){
String fullname=convertStreamToString(in);
name.setText("Full Name is: "+fullname);
}
});
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Before I set Http version 1.1 it took double the time, but for my application, the speed cannot be unreliable. This is all on a pretty fast WiFi connections -- can you image Edge or 3G speeds??
So what can I optimize?
Thanks everyone:)
EDIT: I did a new test with: http://www.posttestserver.com/ and it happened pretty fast. The urls I'm using currently aren't my final server urls, they are for a different site on a different server -- shared hosting, so could it be that contacting my shared hosting site is just slow and will be compared to my .net server?
Thanks again !

Parameters not being passed into URL in Android

Ok, I have looked at multiple examples and my code seems to be correct, but for what ever reason the parameters are not being added to the URL. I'm trying to connect to the Last.Fm API and my code is as follows:
searchIT.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//Create new HTTPClient and Post header
HttpPost API_ROOT = new HttpPost("http://ws.audioscrobbler.com/2.0/");
HttpClient httpclient = new DefaultHttpClient();
try
{
//Add Data
List<NameValuePair> nameValPairs = new ArrayList<NameValuePair>(4);
nameValPairs.add(new BasicNameValuePair("method", "artist.getevents")); //Get events for artist
nameValPairs.add(new BasicNameValuePair("artist", namesBox.getText().toString())); //Get artist name
nameValPairs.add(new BasicNameValuePair("autocorrect", "1")); //Turn on AutoCorrect
nameValPairs.add(new BasicNameValuePair("api_key", "xxxxxxxxxxxxxxxxxxxx")); //API Key - redacted for privacy
API_ROOT.setEntity(new UrlEncodedFormEntity(nameValPairs));
Log.i(TAG, "URL: " + API_ROOT.getURI().toString());
//Execute HTTP Post Request
HttpResponse response = httpclient.execute(API_ROOT);
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Am I just missing something here? In the log the url is shown as: http://ws.audioscrobbler.com/2.0/ so it seems to missing all the parameters I was trying to pass into it. Any ideas, tips, corrections or suggestions? Thanks!
From your onClick method start a new activity and pass all the parameters you want to as
HashMap<String, String> o = (HashMap<String, String>) searchList.getItemAtPosition(position);
Intent i = new Intent(SearchActivity.this, SearchDetails.class);
i.putExtra("method", o.get("method"));
i.putExtra("artist", o.get("artist"));
i.putExtra("autocorrect", o.get("autocorrect"));
i.putExtra("api_key", o.get("api_key"));
Then in your new activity: In the onCreate method
Intent myIntent = getIntent();
String method= myIntent.getStringExtra("method");
String artist= myIntent.getStringExtra("artist");
String autocorrect= myIntent.getStringExtra("autocorrect");
String api_key= myIntent.getStringExtra("api_key");
Now you'll get the params as you require and add them to your URL.
Hope it works

Categories

Resources