HttpPost and Thread Exception - java

Here is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://shopstable.turkcell.com.tr/timmenu/getPerosConfig.do");
try {
HttpResponse response = httpclient
.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
});
}
});
}
i'am getting NetworkOnMainThreadException. I think the problem is in the httppost, but i couldn't figure it out.

This exception is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. Run your code in AsyncTask:

// use async task like this .this will solve ur problem
Class A{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
new RequestLogInFromServer().execute();
}
});
}
});
}
public class RequestLogInFromServer extends AsyncTask<Object, Object, Object>
{
#Override
protected Object doInBackground(Object... params)
{
String responsearray[] = new String[2];
//JSONObject jsonResponse = null;
// Create a new HttpClient and Post Header
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://shopstable.turkcell.com.tr/timme/getPerosConfig.do");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
try {
// Add your data
in case if u want to pass any data to server else leave it
List<NameValuePair> signinDetails = new ArrayList<NameValuePair>();
signinDetails.add(new BasicNameValuePair("name",uname));
signinDetails.add(new BasicNameValuePair("pass",pwd));
httpPost.setEntity(new UrlEncodedFormEntity(signinDetails));
// Execute HTTP Post Request
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.v("Post Status", "Code: "
+ httpResponse.getStatusLine().getStatusCode());
responseCode = httpResponse.getStatusLine().getStatusCode();
Log.e("responseBody", String.valueOf(responseCode));
responsearray[0]=String.valueOf(responseCode);
switch(responseCode){
case 200:
Log.e("responseCode", String.valueOf(responseCode));
HttpEntity entity = httpResponse.getEntity();
Log.e("entity", String.valueOf(entity));
if (entity != null) {
responsearray[1] = EntityUtils.toString(entity);
Log.e("responsearray", String.valueOf(responsearray));
/* Log.e("responseBody", String.valueOf(responseBody));
JSONTokener jsonTokener = new JSONTokener(responseBody);
jsonResponse = new JSONObject(jsonTokener);
Log.e("finalResult", String.valueOf(jsonResponse));
JSONObject response = jsonResponse.getJSONObject("response");
// Getting String inside response object
String status = response.getString("status");
String message = response.getString("message");
Log.e("status", String.valueOf(status));
Log.e("message", String.valueOf(message));
*/
} // if (entity != null) end
break;
case 503:
responsearray[1]="";
break;
default:
responsearray[1]="";
break;
}//switch end
} catch (ClientProtocolException cpeExp) {
// TODO Auto-generated catch block
} catch (Exception allExp) {
// TODO Auto-generated catch block
}
return responsearray;
}
#Override
protected void onPostExecute(Object result)
{
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(SignInActivity.this, "", "Please wait");
super.onPreExecute();
}
}
} //close class A

you have simply use this so get solution:
Here SDK version is your app's minimum sdk version ..so you have to set your minimum sdk version here. And put this code after onCreate() method:
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
And also add this permission to your manifest file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Related

Crash my Android app in HttpResponse response Code

I am trying to get the response code for the HttpReponse.
I have changed the method for getting the response but it is not working.
Before I used this try & catch:
(url is parameter for function)
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
if (params != null) {
method.setEntity(new UrlEncodedFormEntity(params));
}
HttpResponse response = httpclient .execute(method);
InputStream inputStream = response.getEntity().getContent();
String result = convertInputStreamToString(inputStream);
return result;
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
But this code gave me a runtime error in HttpResponse response = httpclient .execute(method);
So I changed my code:
public class RegisterActivity extends Activity {
String username;
String password;
InputStream is = null;
String result = null;
String line = null;
int code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText usernamefield = (EditText) findViewById(R.id.username_reg);
final EditText passwordfield = (EditText) findViewById(R.id.password_reg);
Button reg_btn = (Button) findViewById(R.id.reg_btn);
reg_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = usernamefield.getText().toString();
password = passwordfield.getText().toString();
insert();
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", usernamefield.getText().toString()));
params.add(new BasicNameValuePair("password", passwordfield.getText().toString()));
params.add(new BasicNameValuePair("action", "insert"));
}
});
}
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("action", "insert"));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.10/ferdos/service.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch (Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch (Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code == 1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.e("Fail 3", e.toString());
}
}}
Please help me with this code to solve my problem.
Thats what Google says.
To avoid creating an unresponsive UI, don't perform network operations on the UI thread. By default, Android 3.0 (API level 11) and higher requires you to perform network operations on a thread other than the main UI thread; if you don't, a NetworkOnMainThreadException is thrown.
You need to execute your HTTP requests in separate thread. This can be done in a AsyncTask.
In your case you need to update UI after the downloading is finished. Use a listener to notify the UI thread
public interface ResultsListener {
public void onResultsSucceeded(String result);
}
This is an example from Google developers guide. I edited it and it calls the listener when the result is finished.
private class HttpRequestTask extends AsyncTask<URL, Integer, String> {
public void setOnResultsListener(ResultsListener listener) {
this.listener = listener;
}
protected String doInBackground(URL... urls) {
int count = urls.length;
for (int i = 0; i < count; i++) {
String httpResult = // Do your HTTP requests here
// Escape early if cancel() is called
if (isCancelled()) break;
}
return httpResult;
}
// use this method if you need to show the progress (eg. in a progress bar in your UI)
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// this method is called after the download finished.
protected void onPostExecute(String result) {
showDialog("Downloaded " + result);
listener.onResultsSucceded(result);
}
}
Now you can execute the task by calling new HttpRequestTask().execute(url) in your Activity. Your activity needs to implement the ResultsListener. Inside the onResultsSucceeded method you can update your UI elements.
You see, you can use the AsyncTask in your example pretty well. You just need some reformatting of your code.
I use AsyncTask but dont working again
please check my code
public class RegisterActivity extends Activity {
EditText editusername;
EditText editpassword;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
editusername = (EditText) findViewById(R.id.username_reg);
editpassword = (EditText) findViewById(R.id.password_reg);
Button reg_btn = (Button) findViewById(R.id.reg_btn);
reg_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = editusername.getText().toString();
password = editpassword.getText().toString();
new RegisterAsyncTask().execute();
}
});
}
class RegisterAsyncTask extends AsyncTask<Void, Void, Boolean> {
private void postData(String username, String password) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myurl");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("action", "insert"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
}
catch (Exception e)
{
Log.e("log_tag", "Error: " + e.toString());
}
}
#Override
protected Boolean doInBackground(Void... params) {
postData(username, password);
return null;
}
}}

How to retrieve a website via HTTP?

i have this application force close with this code, what i do wrong?
public void buscaAno(View v){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://sapires.netne.net/teste.php?formato=json&idade=55");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.idade);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It seems like this is onClick listener and it does a blocking operation on main thread which in turn causes ANR or NetworkOnMainThreadException. You should probably use AsyncTask or Service for your purpose.
For example, you could extend AsyncTask the following way:
private class PostRequestTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strings[0]);
try {
HttpResponse response = httpclient.execute(httppost);
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
//Handle exception here
}
}
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.idade);
textView.setText(result);
}
}
And then use it like this:
public void buscaAno(View v) {
new PostRequestTask().execute("http://sapires.netne.net/teste.php?formato=json&idade=55");
}

how read a Json file From a URL?

I wrote a program
I want download a json file from a URL and show it in a text view ..
When you click the button the program will stop after a few seconds .
I do not know what the problem is .
Please help me..
java code:
public class MainActivity extends Activity {
TextView tx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button2);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetJsonTask().execute("http://shahid.ifilmtv.ir/query/englishcurrentshows");
}
});
}
public class GetJsonTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
return getJson(urls[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONArray jsonArray;
try {
jsonArray = new JSONArray(result);
JSONObject object = jsonArray.getJSONObject(1);
tx.setText(object.getString("id"));
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getJson(String url) {
try {
InputStream inputStream = null;
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String result = sb.toString();
return result;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}
}
I think the issue is in getJSON method. I have rewritten a following code. Please try this.
public String getJson(String url) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
Object resp = defaultHttpClient.execute(httpPost, responseHandler);
String json = resp.toString();
// create a object here if you want
JSONObject obj = new JSONObject(json);
return json;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}

Unable to fetch JSON data from Server

Unable to fetch data from server even i have value in textview as per my condition in onCreate() and when i remove this condition this works just fine for me (my mean, in that case i am able to fetch JSON data from Server).
and i tried many things but still no success for me, always getting "Unable to fetch data from server" because i used this as Toast in onPostExecute() method of AsyncTask
I am getting value for TextView and that's for sure its calling execute method of AsyncTask as well, but always getting Unable to fetch data from server
Do you have Questions in your mind :
1) Why I am using such condition in onCreate(), then check my this question
2) Why I am setting adapter in onPostExecute(), then check my this question
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_category);
etTextToSave = (TextView) findViewById(R.id.textView2);
sharedprefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
etTextToSave.setText(sharedprefs.getString("SharedPrefsData",""));
actorsList = new ArrayList<VideoCategory>();
if(etTextToSave.getText().toString().length()>0)
{
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}
centerLockHorizontalScrollview = (HSVActivity) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new VideoCategoryAdapter(getApplicationContext(), R.layout.adapter_video_category, actorsList);
centerLockHorizontalScrollview.setAdapter(HomeActivity.this, adapter);
}
}
}
I am not getting any exception or toast message.
Check the Json response.
As per your posted question , you get data form the server still you get Toast that "Unable to fetch data from server" . I done the small change in your code please try it and let me known .
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_category);
etTextToSave = (TextView) findViewById(R.id.textView2);
sharedprefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
etTextToSave.setText(sharedprefs.getString("SharedPrefsData",""));
actorsList = new ArrayList<VideoCategory>();
if(etTextToSave.getText().toString().length()>0)
{
new JSONAsyncTask().execute("http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors");
}
centerLockHorizontalScrollview = (HSVActivity) findViewById(R.id.scrollView);
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
JSONObject jObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
jObj = new JSONObject(data);
if(!(jObj.equals(null)))
{
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Actors actor = new Actors();
actor.setName(object.getString("name"));
Log.d("Name:", object.getString("name"));
actor.setImage(object.getString("image"));
Log.d("Image:", object.getString("image"));
actorsList.add(actor);
}
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if(jObj== null)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
if(actorsList != null) {
adapter = new VideoCategoryAdapter(getApplicationContext(), R.layout.adapter_video_category, actorsList);
centerLockHorizontalScrollview.setAdapter(HomeActivity.this, adapter);
}
}
}

How to use HttpGet Request in Android?

I am using this code, but it catches an error in a try-catch. Where is a mistake?
When I print a error, content.setText(ex.getMessage()); is empty.
Here is the relevant code:
public class MainActivity extends Activity {
TextView content;
EditText fname, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content = (TextView) findViewById(R.id.content);
Button saveme = (Button) findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Please wait, connecting to server.", Toast.LENGTH_LONG).show();
try {
String loginValue = URLEncoder.encode("ffa", "UTF-8");
String fnameValue = URLEncoder.encode("fdsfdb", "UTF-8");
HttpClient Client = new DefaultHttpClient();
String URL = "http://mysite/app.php?a=" + loginValue + "&b=" + fnameValue;
try {
String SetServerString;
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
content.setText(SetServerString);
} catch (Exception ex) {
content.setText(ex.getMessage());
}
} catch (UnsupportedEncodingException ex) {
content.setText(ex.getMessage());
}
}
});
}
}
I think you get NetworkOnMainThreadException. You should perform network communication on background thread. Consider using IntentService or AsyncTask.
I have same opinion with Nickolai.
Work around:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Use code above, only when you are writing code for yourself.
If your application are produced to others,you need a better way.
Better way:
You should use a handle to access http-request, more info in developer.android.com
I use this myself:
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();

Categories

Resources