Reputation: 158
I'm having trouble with sending data to my database. I'm using the same sort of code in another class and thats working fine, but somehow this isn't working.
This is the class with the HttpResponse. There are no errors, but when the code reaches
HttpResponse response = httpclient.execute(httppost);
it goes into the catch and returns "Klant not added")
public void StoreKlantInDatabase()
{
EditText ETklantnaam = (EditText) dialog.findViewById(R.id.addKlantNaam);
EditText ETlocatie = (EditText) dialog.findViewById(R.id.addKlantLocatie);
EditText ETfabriek = (EditText) dialog.findViewById(R.id.addFabrieken);
EditText ETmachine = (EditText) dialog.findViewById(R.id.addMachines);
String klantnaam = ETklantnaam.getText().toString();
String locatie = ETlocatie.getText().toString();
String fabriek = ETfabriek.getText().toString();
String machine= ETmachine.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlInsertKlant);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("klantnaam", klantnaam));
nameValuePairs.add(new BasicNameValuePair("locatie", locatie));
nameValuePairs.add(new BasicNameValuePair("fabriek", fabriek));
nameValuePairs.add(new BasicNameValuePair("machine", machine));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
@SuppressWarnings("unused")
HttpResponse response = httpclient.execute(httppost);
Toast.makeText(getApplicationContext(), "Klant succesvol toegevoegd", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Klant NIET toegevoegd", Toast.LENGTH_LONG).show();
}
}
this method is called from an dialog, like this (down in the last OnClick method):
btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// custom dialog
dialog = new Dialog(context);
dialog.setContentView(R.layout.addklant_layout);
dialog.setTitle("Klant toevoegen");
Button BTNannuleren = (Button) dialog.findViewById(R.id.dialogAnnuleren);
// if button is clicked, close the custom dialog
BTNannuleren.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button BTNtoevoegen = (Button) dialog.findViewById(R.id.dialogToevoegen);
// if button is clicked, close the custom dialog
BTNtoevoegen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
StoreKlantInDatabase();
dialog.dismiss();
}
});
dialog.show();
}
});
I've tryed to just do it all in the onClick method of the dialog, but that made no difference.
Ofcouse the dialog is initiated at the top of the code like:
Dialog dialog;
Does anyone see where i'm going wrong? I'm a bit lost.
Edit: This happens in the catch:
09-30 09:36:52.452: W/System.err(14665): android.os.NetworkOnMainThreadException
09-30 09:36:52.482: W/System.err(14665): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1186)
09-30 09:36:52.482: W/System.err(14665): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-30 09:36:52.482: W/System.err(14665): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-30 09:36:52.482: W/System.err(14665): at libcore.io.IoBridge.connect(IoBridge.java:112)
09-30 09:36:52.482: W/System.err(14665): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-30 09:36:52.482: W/System.err(14665): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-30 09:36:52.482: W/System.err(14665): at java.net.Socket.connect(Socket.java:872)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:591)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:510)
09-30 09:36:52.482: W/System.err(14665): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:488)
09-30 09:36:52.482: W/System.err(14665): at com.example.emmtec.FirstScreen.StoreKlantInDatabase(FirstScreen.java:272)
09-30 09:36:52.482: W/System.err(14665): at com.example.emmtec.FirstScreen$10$2.onClick(FirstScreen.java:236)
09-30 09:36:52.482: W/System.err(14665): at android.view.View.performClick(View.java:3538)
09-30 09:36:52.492: W/System.err(14665): at android.view.View$PerformClick.run(View.java:14330)
09-30 09:36:52.492: W/System.err(14665): at android.os.Handler.handleCallback(Handler.java:608)
09-30 09:36:52.492: W/System.err(14665): at android.os.Handler.dispatchMessage(Handler.java:92)
09-30 09:36:52.492: W/System.err(14665): at android.os.Looper.loop(Looper.java:156)
09-30 09:36:52.492: W/System.err(14665): at android.app.ActivityThread.main(ActivityThread.java:4977)
09-30 09:36:52.492: W/System.err(14665): at java.lang.reflect.Method.invokeNative(Native Method)
09-30 09:36:52.492: W/System.err(14665): at java.lang.reflect.Method.invoke(Method.java:511)
09-30 09:36:52.492: W/System.err(14665): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-30 09:36:52.492: W/System.err(14665): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-30 09:36:52.492: W/System.err(14665): at dalvik.system.NativeStart.main(Native Method)
Thanks in advance!
Upvotes: 0
Views: 202
Reputation: 8023
09-30 09:36:52.452: W/System.err(14665): android.os.NetworkOnMainThreadException
You're doing a network request on the main thread which is not supported by the Android Version you're using.
You can use an AsyncTask to make any network requests using the UI thread. The Android Developer Page gives a very good example of how to use it.
Now why to use an AsyncTask ? Assuming we are doing network operation on a button click in our application. On button click a request would be made to the server and response will be awaited. Due to single thread model of android, till the time response is awaited our screen is non-responsive. So we should avoid performing long running operations on the UI thread. This includes file and network access.
You'll need to create a private class inside your Activity. Then create a Object of the AsyncTask Class inside your button click listener and execute.
BTNtoevoegen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
asyncTask task = new asyncTask();
task.execute(url1);
}
});
You might also want to show ProgressDialogs while making the network request. You can handle that in the onPreExecute() and onPostExecuteMethod().
You can check out an implementation here :
https://github.com/vshivam/privly-android/blob/master/src/ly/priv/mobile/Login.java#L184
Upvotes: 1
Reputation: 1495
Use AsyncTask to do network operations...
Another Solution is add below lines in your code above your network operation code
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Upvotes: 2
Reputation: 1948
Android does not support network operation on main/worker thread to HoneyComb and later versions. So perform network operation on other thread then main thread.
AsyncTask
is a good option for performing that.
Upvotes: 2