Android HttpPost cause the app to crash - java

I'm trying to send post request to my PHP page through java in android studio
and I tried the same code in eclipse but the same problem show, the app stop working.
I put the permission for the internet in the manifest.
My Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt=(TextView) findViewById(R.id.textView1);
String mail="aa#gmail.com",pass="pass";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2:8888/LoginTest/login.php");
try {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("mail", mail));
nameValuePair.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response= httpClient.execute(httpPost);
InputStream is= response.getEntity().getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
StringBuilder sb=new StringBuilder();
String line=null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
txt.setText(sb.toString());
br.close();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My LogCat : https://www.dropbox.com/s/smhyoxdob66czr7/testLogCat.txt?dl=0

Most probably, your application is crashing due to an exception, that is android.os.NetworkOnMainThreadException
This exception is thrown when you try to do lengthy time consuming tasks like network request and downloading the response on main thread, like you're doing in your onCreate(). Android doesn't like it. It keeps it frozen / un-responsive, which makes it angry and it kills your app.
The solution to use AsyncTask. The idea is to do lengthy tasks in background threads instead of main thread. Like as follow:
//this should be inside your Activity class
private class NetworkRequestTask extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
// your network code here
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// set the result to your label
}
}
and from your onCreate() call this task as follow:
new NetworkRequestTask(). execute();
It'll make android happy and responsive. It'll let your app running and won't kill it.

Related

ProgressDialog in AsyncTask in android

I am working on a login in application. I am trying to display progressDialog in my BackgroundWorker class which extends Async task. But as soon as I click on Login button, the progress dialog is shown just for a few seconds. Is there any possibility that signing process will last longer?
Snippets of the code
`public class BackgrroundWorker extends AsyncTask<String,Void,String>{
Context context;
AlertDialog alertDialog;
boolean correct;
public BackgrroundWorker(Context context){
this.context = context;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "random";
String register_url = "random";
if(type.equals("login")){
try {
String username = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8") + "=" +URLEncoder.encode(username,"UTF-8")+ "&"
+URLEncoder.encode("password","UTF-8") + "=" +URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = "";
String line = "";
correct = false;
while((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
System.out.println(result);
if (result.equalsIgnoreCase("login success"))
correct=true;
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "Login",
"Please wait for a while.", true);
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login status");
}
#Override
protected void onPostExecute(String result) {
if(!result.equals("login success")) {
alertDialog.setMessage(result);
alertDialog.show();
}
progressDialog.dismiss();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
`
progressDialog.dismiss();
This statement causing dialog to disappear and you have set it without any condition inside
onPostExecute
If you want to show dialog for a long time place it inside Handler or CountDownTimer. You can also make it user interaction based like button click.
For example, if you want to dismiss dialog for 5 sec:
#Override
protected void onPostExecute(String result) {
if(!result.equals("login success")) {
alertDialog.setMessage(result);
alertDialog.show();
}
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
progressDialog.dismiss();
}
}.start();
}
Is there any possibility that signing process will last longer?
(signing = signin)
There sure is. Imagine the device is being heavily throttled, the server is taking along time to respond, or stuck on a really really slow network (ex: 1g data network, or my local starbucks wifi that 100s for people use at the same time)
You can test this by loading your application on the android emulator and using the emulator console commands for netspeed and netdelay
The basics steps are something like :
telnet localhost 5554
network speed 2 1
The first number ("2"). is the upload speed (traffic from the device) in kilobytes per second
The second number ("1"), is the download speed (traffic to the device) in kilobytes per second
network netdelay 10000
Above, we set a 10 second delay/latency of the network
then on the device, perform the login
Full documentation to accomplish this is here and I recommend checking them out. Lots of great info : https://developer.android.com/studio/run/emulator-console.html
I also found this answer to be helpful:
https://stackoverflow.com/a/6236379/794088

Error in doInBackground() -> NoClassDefFoundError: org.apache.http.entity.ContentType

I am uploading an image to server. There is some error in Asynctask while I do .addpart with the fileupload. I am new to this so please help me.
The variable filepath has some issues in Asynctask according to me.
My manifest.xml file has the required permissions.
public class UploadActivity extends Activity{
private String filePath = null;
private Button btnUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
btnUpload = (Button) findViewById(R.id.btnUpload);
// Receiving the data from previous activity
Intent i = getIntent();
// image or video path that is captured in previous activity
filePath = i.getStringExtra("filePath");
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new Upload().execute();
}
});
}
/**
* Uploading the file to server
* */
private class Upload extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.102/fileUpload.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
Error log:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType
at org.apache.http.entity.mime.content.FileBody.<init>(FileBody.java:89)
at com.example.apurwa.camera.UploadActivity$Upload.uploadFile(UploadActivity.java:104)
at com.example.apurwa.camera.UploadActivity$Upload.doInBackground(UploadActivity.java:91)
at com.example.apurwa.camera.UploadActivity$Upload.doInBackground(UploadActivity.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
Your problem most probably is that you are not importing org.apache.http library correctly. That's why your crash giving you java.lang.NoClassDefFoundError
What you have to do is to make sure that you are importing the library correctly. So if you are using Eclipse, then download the JAR file form this link
If you are using Android Studio, then make sure of your dependencies in the Gradle file from this link
Also have a look on this question, it discusses similar issue to yours
Add library containing org.apache.http.entity.ContentType to build path.

My Android app needs to verify connection to internet onClick of a button but app is crashing on using my code

I need to verify the internet connection while pressing log-out button in my app and it must show a toast message "connection error" if connection is not present and must not go to the login page.
Following is the error code that i had received in the console window while running the emulator.
Android Runtime Errors:
Fatal Exception: thread -85
java.lang.RuntimeException: Can't create handler inside thread.
I had created a class called "appstatus.java" and used it and working fine with the login page but while i try to use same if else condition with the "mainactivity.java" where logout button is present. its not working and app crashes. below is my code:-
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (AppStatus.getInstance(getBaseContext()).isOnline(getBaseContext())) {
//
Log.v("driver-id from logout:",""+drv_id);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ServerConnection.ip+"LogoutFlag.jsp");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
Log.v("drv id from logout:",""+drv_id);
nameValuePairs.add(new BasicNameValuePair("driver_id", ""+drv_id));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
String reverseString = response.trim();
Log.v("Response device id from logout",reverseString);
}
catch (Exception e) {
Log.e("logout error:",e.toString());
}
}
else {
Toast.makeText(getBaseContext(), "Connection Lost", Toast.LENGTH_SHORT).show();
}
}
}).start();
I had used same if, else condition to check internet connectivity on the login page and is working fine. here the only difference i notice is a try catch method is used.
My question is:-
Why the app is crashing with above code?
How to rewrite the code avoiding errors for the above mentioned cause?
Any piece of code is highly appreciated and thanks in advance.
Try this way,hope this will help you to solve your problem
Follow few steps to check internet connection and make code without crashes
Step 1. make this method, for checking connection is available or not
void isConnectedToInternet() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null)
greenFlag();
else
new AlertDialog.Builder(activity)
.setTitle("Network connection error !")
.setMessage("Please check internet settings to continue.")
.setNegativeButton("Continue",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
isConnectedToInternet();
}
}).show();
}
Step 2. Run this method on oncreate,
isConnectedToInternet();
Step 3. In this mehtod you need to put all data related to webservices and others task,
void greenFlag() {
// Anything you want to do here
}
thanks

audio recording and POST to server

For starters i'm an Android newbie. I have an android application that records audio for 12 seconds to a raw file and then I use lame to convert it to the final file "mezzo.mp3". The application should then upload the file to a server. However, it seems the code never executes to the upload part. Here is my code.
MainActivity.java
class UploadFileTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String responseString = "";
try {
String url = "http://178.62.209.46:8000/api/tag/";
File track = new File(Environment.getExternalStorageDirectory(), "mezzo.mp3");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//InputStream inputStream = new ;
reqEntity.addBinaryBody("track", track);
final HttpEntity myEntity = reqEntity.build();
httppost.setEntity(myEntity);
HttpResponse response = httpclient.execute(httppost);
//process response
responseString = new BasicResponseHandler().handleResponse(response);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
protected void onPostExecute(String responseString){
Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_LONG).show();
}
}
and here is the timer and the UploadFileTask invocation:
Button startButton = (Button) findViewById(R.id.StartButton);
startButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mRecMicToMp3.start();
CountDownTimer countDowntimer = new CountDownTimer(12000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
mRecMicToMp3.stop();
Toast.makeText(getApplicationContext(), "Stopped recording Automatically ", Toast.LENGTH_LONG).show();
}};countDowntimer.start();
}
});
new UploadFileTask().execute();
The timer runs okay and the "Stopped recording Automatically " toast shows. However, it seems new UploadFileTask().execute();never runs.
What mistake i'm I making??
You posted way to much code. You are supposed to post only relevant code. That in onClick would have been sufficient.
You have a NetworkOnMainThreadException. This will also be clearly visible in the LogCat. You have to put the 'internet code' in an AsyncTask or Thread.
Update: Hmmmm... mayby i talked to soon. Honestly i do not know if code in 'onFinish' is executed on the main thread. But if the Toast comes through it is. Please look in the LogCat for real errors.
You are starting your asynctask at the moment you install an onclicklistener. So even before the user has clicked. You should start it when the recording is done. Place that line directly after the toast that tells that the recording is stopped.

Android startup dialog remote data

I'm trying to show a dialog box with some remote data when the app starts (welcome message). for some reason this is not working. my code is this.
p.s. I have another progress type dialog which loads at start up. I'm trying to add this just after it.
Could anyone tell if this snippet is correct?
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/welcome.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", url));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//String url=response;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title");
builder.setMessage(response);
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
} catch (ClientProtocolException e) {
//Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
//Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
best test you can do what happend this code dos not work is :
try write e.printStackTrace(); between catch like :
try {
...
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
to know waht happend.
also i think you get error that you cannot access io operation in ui thread, and you must call this method in other thread LIKE :
private void MyMethod() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/welcome.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", url));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
//String url=response;
runOnUiThread(
new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("My Title");
builder.setMessage(response);
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
}
}
);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and when want to call this method :
new Thread(new Runnable() {
#Override
public void run() {
MyMethod();
}
}).start();
What is meaning of sentence "for some reason this is not working."? Am I correct when I say dialog doesn't appear?
There's problem with httpclient.execute(). If there is some problem with internet connection, dialog isn't created, because inception has been thrown. Can you see some warning/error in Logcat?
You can't do connection operations in UI Thread, otherwise NetworkOnMainThreadException is thrown.
I'm going to say no - the snippet is not correct. Since API 11 all IO functions need to happen on a background thread. Background threads cannot touch the UI. As it currently stands you are executing an HttpPost within the same method as you are creating an AlertDialog. What you need to do is use an AsyncTask to (1) execute the post in the doInBackground method (2) return the result (3) use the returned result within the onPostExecute method to load your dialog (returning values from doInBackground will automatically send it to onPostExecute). onPostExecute runs on the UI thread so you can create an AlertDialog from that method.

Categories

Resources