I am hitesh my problem is ,i work on httpclient in andriod i gave internet permission to my application and i run my application and click on button the tehy gave unfortunately stopped. please help me there my code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText user=(EditText) findViewById(R.id.username);
final EditText pass=(EditText) findViewById(R.id.password);
Button login=(Button) findViewhere`ById(R.id.login);
login.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String u=user.getText().toString();
String p=pass.getText().toString();
HttpClient httpClient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://202.164.53.122");
BasicNameValuePair usernameBaseNameValuePair=new BasicNameValuePair("id",u);
BasicNameValuePair passBaseNameValuePair=new BasicNameValuePair("pass",p);
List<NameValuePair> nameValuePairList=new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBaseNameValuePair);
nameValuePairList.add(passBaseNameValuePair);
try {
UrlEncodedFormEntity urlEncodedFormEntity=new
UrlEncodedFormEntity(nameValuePairList,HTTP.UTF_8);
httppost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse=httpClient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
user.setText(e.getMessage());
}
}catch(UnsupportedEncodingException uee){
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
dont work with network on main thread(or get android.os.NetworkOnMainThreadException). use thread class or AsyncTask class.
AsyncTask
Thread
If you are using this code in android 4.0+ you get exception android.os.NetworkOnMainThreadException. Use AsyncTask to provide any http communication.
Firstly, create a separate class for getting the Request and use Asynctask to perform all your actions. Use a String to pass the URI and then pass the URI in the Asynctask. This method won't block your Main UI Thread.
Refer to this link for how to use Asynctask.
http://developer.android.com/reference/android/os/AsyncTask.html
For network operation you should use different thread rather than using main thread because using network on main thread will cause to application UI unresponsive to avoid this you should AyncTask
For Example of AsyncTask use this Link
First of all, you should use a different thread for sending a request. Or, the best way is to use volley requests with post method. It is faster and more efficient.
Related
After user press the button it fires up weather function. But it doesn't log any JSON data or any error. Should it be done in background? I've used gson libary to download JSON.
Edit: I edited my code but user must enter a city which is pasted to the link. So is it possible to run in background process when the button is tapped?
public class MainActivity extends AppCompatActivity {
public class Download extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL("api.openweathermap.org/data/2.5/weather?q="+strings[0]+"&APPID=****");
URLConnection request = url.openConnection();
request.connect();
JsonParser jp=new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
String weather = rootobj.getAsString();
Log.i("weather:",weather);
}
catch (Exception e){
e.printStackTrace();;
}
return null;
}
}
public void weather(View view){
TextView textView=(TextView) findViewById(R.id.editText);
String city=textView.getText().toString();
Download download=new Download();
download.execute(city);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
All io operation should be executed in background , because all this operations are time consuming . which means you will block your main thread if you donot execute these codes in background and may cause Android Not Respond exception. IO operation in ui thread generally lead to bad user experience . so i strongly advice you do this in background.
You should definitely load your data in the background. The Main Thread i.e. the UI Thread is the thread that renders the UI components so no heavy operation should be done there. If heavy operation is done in the UI Thread, it will freeze the UI.
You should look at the AsyncTask class to perform your loading in the background.
Here is some good tutorials:
https://alvinalexander.com/android/asynctask-examples-parameters-callbacks-executing-canceling
https://www.journaldev.com/9708/android-asynctask-example-tutorial
https://www.tutorialspoint.com/android-asynctask-example-and-explanation
Actully i working in a app, but i have problems to connect my Web services, i have this code:
try{
HttpServices post = new HttpServices ("http://sotem.com.mx/WebServices/controller.php");
post.add("funcion", "test");
System.out.println("Si lo mande///////////////////Jhgfdsa");
String respuesta = post.getRespueta();
System.out.println(respuesta);
Toast.makeText(getApplicationContext(),"Cool: "+respuesta, Toast.LENGTH_SHORT).show();
}catch (Exception ex) {
Toast.makeText(getApplicationContext(),"error: "+ex.toString(), Toast.LENGTH_SHORT).show();
}
but i can make connection, i try to make other thinks, but i can make the thread, i'am new in this part, the app launcher this error:
android os network on main thread exception
It is not okay to do the Network Operation on main thread.. You can use AsyncTask to perform such operations and handle the result in onPostExecute method.
class YourNetworkingTasks extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
try{
HttpServices post = new HttpServices ("http://sotem.com.mx/WebServices/controller.php");
post.add("funcion", "test");
String respuesta = post.getRespueta();
Log.d("Output", respuesta);
// DON'T DO ANY UI CHANGES LIKE TOAST FROM BACKGROUND THREAD.. Toast.makeText(getApplicationContext(),"Cool: "+respuesta, Toast.LENGTH_SHORT).show();
}catch (Exception ex) {
// DON'T DO ANY UI CHANGES LIKE TOAST FROM BACKGROUND THREAD.. Toast.makeText(getApplicationContext(),"error: "+ex.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
protected void onPostExecute(RSSFeed feed) {
// TODO: YOU CAN MAKE U.I. Changes Like Display text in TextView, TOAST HERE.
// TODO: do something with the result
}
}
And write new YourNetworkingTasks().execute(); to run that code in background thread.
Please also not that since you are using http and not https you may get Network Security Exception and may not get any output due to recent security change in android.
I have created a program that will connect to a database through PHP and echo back a response. My android program then makes a request to the PHP file and reads the echo in.
public class Read_Author extends AsyncTask<String, Void, String> {
String authorName = "";
#Override
public String doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/scripts/read_information.php");
HttpResponse response = httpclient.execute(httppost);
authorName = String.valueOf(EntityUtils.toString(response.getEntity()));
String myStr = "ANSWER";
Log.v(myStr, authorName);
}
catch(Exception e){
}
return authorName;
}
public String returnAuthor(){
return authorName;
}
}
I successfully retrieve the echo string and put it in the author name string variable. But when I then try to call return author from my main activity I get no error but the code does not get run.
I call a function called "readValue" within my main activity and within that function, the execute function gets read and then what is supposed to happen is the returnauthor function is supposed to run. But instead, nothing happens
Main Activity Code:
public void returnAuthor(){
loadAuthor.execute();
String a = loadAuthor.returnAuthor();
Log.v("HIT ME", a);
}
If anyone has any suggestion on why this could be happening and how to fix it that will be very much appreciated!
You seem to have misconception about AsyncTask. The result of AsyncTask may not be available instantly, because the background task might not have been completed.
You need to override the method onPostExecute in your AsyncTask to perform some task after the background task has been completed.
First show a progressDialog before executing the AsyncTask
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading..");
progressDialog.setCancelable(false);
progressDialog.show();
Then in the onPostExecute:
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
Log.d("author", result);
}
I have scoured the internet, and developed code that I thought would work to get the html of a website in readable form. However, I am still unable to make this work. Here is my code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("http://www.cnn.com");
}
private class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
HttpResponse response = null;
HttpGet httpGet = null;
HttpClient mHttpClient = null;
String s = "";
try {
if(mHttpClient == null){
mHttpClient = new DefaultHttpClient();
}
httpGet = new HttpGet(urls[0]);
response = mHttpClient.execute(httpGet);
s = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result){
final TextView textview1 = (TextView) findViewById(R.id.headline);
textview1.setText(result);
}
}
}
When I try this, the app crashes on startup, with the LogCat shown below:
07-26 16:13:42.561: W/dalvikvm(23584): threadid=12: thread exiting with uncaught exception (group=0x416dfda0)
07-26 16:13:42.561: E/AndroidRuntime(23584): FATAL EXCEPTION: AsyncTask #1
07-26 16:13:42.561: E/AndroidRuntime(23584): Process: com.app.firstapp, PID: 23584
07-26 16:13:42.561: E/AndroidRuntime(23584): java.lang.RuntimeException: An error occured while executing doInBackground()
I have no idea why this is happening, does anyone know how I can modify my code to make this work? Thanks in advance.
A library that might be helpful to you is jsoup.
Link: http://jsoup.org
To get a pages HTML in jsoup you just do:
Jsoup.connect("http://google.com").get();
And then from this HTML you can use Jsoup to parse whatever data from the HTML you need.
Link: http://jsoup.org/cookbook/extracting-data/dom-navigation
Edit: I miss read the question. I thought you were having trouble with getting the HTML instead of the fact that there was a problem in the backgrounding.
Make sure that you have included
<uses-permission android:name="android.permission.INTERNET"/>
in your Manifest file.
I'm writing an android app I use a background thread to pull a JSONArray from a web service. I then need to interact with that JSONArray inside the main activity. Here's what I'm doing now:
public class MainActivity extends Activity {
JSONArray stories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new getAll().execute();
// try {
System.out.println("stories.length());
// } catch (JSONException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
//}
}
And the background thread:
private class getAll extends AsyncTask <Void, Void, JSONArray> {
private static final String url = "http://10.0.2.2:8080/CalibServer/webresources/storypkg.story/";
#Override
protected JSONArray doInBackground(Void... params) {
//set up client and prepare request object to accept a json object
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
httpget.addHeader("accept", "application/json");
HttpResponse response;
String resprint = new String();
try {
response = httpclient.execute(httpget);
// Get the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// get entity contents and convert it to string
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
resprint = result;
// construct a JSON object with result
stories =new JSONArray(result);
// Closing the input stream will trigger connection release
instream.close();
}
}
catch (ClientProtocolException e) {System.out.println("CPE"); e.printStackTrace();}
catch (IOException e) {System.out.println("IOE"); e.printStackTrace();}
catch (JSONException e) { System.out.println("JSONe"); e.printStackTrace();}
System.out.println("FUCKYEAHBG: " + resprint);
// stories = object;
return stories;
}
My problem is that I'm getting a NullPointerException at the call to
System.out.println("stories.length());
It's acting like a didn't initialize the stories array, but should't that have been taken care of by the background thread (at the line: stories =new JSONArray(result); ) before that call is ever made?
I have a feeling this is because of the threading - perhaps there is another step I have to take to update the main activity after the AsyncTask runs?
You're initializing the variable in a background thread. That means that the line
System.out.println(stories.length());
is executed in parallel with the code initializing the variable. That thus means that there is a huge chance that the background thread has not had the time to initialize the variable yet when this line is executed.
Your code is similar to the following situation: you have an empty cup in front of you, and ask someone to go make some coffee and to fill your cup. And immediately after asking, you start drinking. There will be no coffee inside the cup, obviously.
Re-read the android documentation on how to execute asynchronous tasks.
You can't rely on stories to be initialized when a separate Thread that runs parallel to the UI Thread initializes and updates stories.
perhaps there is another step I have to take to update the main
activity after the AsyncTask runs?
onPostExecute() of the AsyncTask. Do whatever UI updates you need there. Since getAll is already a private inner class, you have full access to the Activity. You already return stories off to that (unoverriden) method, so this should be a minor change.
#Override
protected void onPostExecute (JSONArray stories)
{
//use the now initialized stories
}