This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
Hi I've the RegisterActivity.java like this:
public class RegisterActivity extends Activity{
private static final String TAG = "PostFetcher";
private static String URL = "http://api.example.com/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText inputFname = (EditText) findViewById(R.id.registerFname);
final EditText inputLname = (EditText) findViewById(R.id.registerLname);
final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
Button btnRegister = (Button) findViewById(R.id.btnRegister);
Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
Login login2;
RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
public void onClick(View view) {
String fname = inputFname.getText().toString();
String lname = inputLname.getText().toString();
String email = inputEmail.getText().toString();
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
String gender = radioSexButton.getText().toString();
//System.out.println(fname);
//Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();
String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
System.out.println(registerURL);
if( email.length() == 0) {
loginErrorMsg.setText(R.string.empty);
//Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
return;
}else{
try {
//Create an HTTP client
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(registerURL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
Gson gson = new Gson();
this.login2 = gson.fromJson(reader, Login.class);
//System.out.println(this.login2);
//handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoading();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoading();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoading();
}
//To set register message
if(login2.getResult().equals("OK")){
loginErrorMsg.setText(login2.getMessage().toString());
}else if(login2.getResult().equals("KO")){
loginErrorMsg.setText(login2.getMessage().toString());
}
}
}
});
// Link to Login
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
finish();
}
});
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.male:
if (checked)
// Pirates are the best
break;
case R.id.female:
if (checked)
// Ninjas rule
break;
}
}
private void failedLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
}
But I'm getting error as follows: Failed to send HTTP POST request due to: android.os.NetworkOnMainThreadException
Android developers forum suggest me to implement it using AsyncTask to solve this problem. But I don't know how to change this. Can someone help me to solve this issue? I spent several hours, but couldn't find any solution.
You want to put all of your network/parsing code in doInBackground() of your AsyncTask. Make the AsyncTask an inner class of your Activity. After getting your result you will want to return this to onPostExecute() to do any UI stuff such as updating Views.
By making the AsyncTask an inner class you will have access to member variables of the Activity and its functions.
This answer will give you a good starting point for creating your AsyncTask and calling it.
Read through the AsyncTask Docs to understand the rules it requires
Check out those links and give it a try. Then post a question with a more specific problem when you run into trouble (be sure to include relevant code and logcat errors if you get stuck).
The simplest approach to get you started is to create an anonymous inner class and execute it in your onCreate:
// if email length != 0
new AsyncTask<Void, Void, Void> {
protected void doInBackground() {
//Create an HTTP client
//Update login2
}
}.execute();
There are, however, a lot of subtle nuances and I highly recommend reading all of these 2 pages: http://developer.android.com/reference/android/os/AsyncTask.html and http://developer.android.com/guide/components/processes-and-threads.html
I honestly think you would figure it out with some effort, but here you go:
public class RegisterActivity extends Activity{
private static final String TAG = "PostFetcher";
private static String URL = "http://api.example.com/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText inputFname = (EditText) findViewById(R.id.registerFname);
final EditText inputLname = (EditText) findViewById(R.id.registerLname);
final EditText inputEmail = (EditText) findViewById(R.id.registerEmail);
Button btnRegister = (Button) findViewById(R.id.btnRegister);
Button btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLogin);
final TextView loginErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
Login login2;
RadioGroup radioSexGroup = (RadioGroup) findViewById(R.id.sex);
public void onClick(View view) {
String fname = inputFname.getText().toString();
String lname = inputLname.getText().toString();
String email = inputEmail.getText().toString();
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
RadioButton radioSexButton = (RadioButton) findViewById(selectedId);
String gender = radioSexButton.getText().toString();
//System.out.println(fname);
//Toast.makeText(RegisterActivity.this, radioSexButton.getText(), Toast.LENGTH_SHORT).show();
String registerURL = URL +"&user_email="+ email /**+"&first_name="+ fname +"&last_name="+ lname*/ +"&gender="+ gender;
System.out.println(registerURL);
if( email.length() == 0) {
loginErrorMsg.setText(R.string.empty);
//Toast.makeText(view.getContext(), R.string.empty, Toast.LENGTH_SHORT).show();
return;
}else{
new LoginTask.execute();
}
}
});
// Link to Login
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
finish();
}
});
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.male:
if (checked)
// Pirates are the best
break;
case R.id.female:
if (checked)
// Ninjas rule
break;
}
}
private void failedLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this, "Failed to Register. look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
private class LoginTask extends
AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
// Before running code in separate thread
#Override
protected void onPreExecute() {
// Create a new progress dialog.
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal bar .
// progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// Set the dialog title to 'Loading...'.
// progressDialog.setTitle("Loading...");
// Set the dialog message to 'Loading application View, please
// wait...'.
progressDialog.setMessage("Loading...");
// This dialog can't be canceled by pressing the back key.
progressDialog.setCancelable(false);
// This dialog isn't indeterminate.
progressDialog.setIndeterminate(true);
// The maximum number of progress items is 100.
// progressDialog.setMax(100);
// Set the current progress to zero.
// progressDialog.setProgress(0);
// Display the progress dialog.
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected VoiddoInBackground(Void... arg) {
try {
//Create an HTTP client
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(registerURL);
//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
Gson gson = new Gson();
this.login2 = gson.fromJson(reader, Login.class);
//System.out.println(this.login2);
//handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoading();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoading();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoading();
}
}
// after executing the code in the thread
#Override
protected void onPostExecute() {
// close the progress dialog
progressDialog.dismiss();
//To set register message
if(login2.getResult().equals("OK")){
loginErrorMsg.setText(login2.getMessage().toString());
}else if(login2.getResult().equals("KO")){
loginErrorMsg.setText(login2.getMessage().toString());
}
}
}
}
Related
When the http server (on AndroidApp) receives a request, I show an alert dialog to the user about this request. After the user responds to this alert dialog, I want it to return to the client (Browser).
I also want to add a 10 second timeout in case the user doesn't press any button.
Create HttpServer
`
private HttpServerManager() {
try {
InetSocketAddress address = new InetSocketAddress(8080);
httpServer = HttpServer.create(address, 0);
httpServer.createContext("/getDeviceRegister", new EchoGetHandlerForDeviceRegister());
httpServer.setExecutor(null);
httpServer.start();
Log.i(TAG, "HttpServer Start");
} catch (Exception e) {
e.printStackTrace();
}
}
`
HttpHandler for -> EchoGetHandlerForDeviceRegister
`
class EchoGetHandlerForDeviceRegister implements HttpHandler {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void handle(HttpExchange he) throws IOException {
// parse request
Map<String, Object> parameters = new HashMap<String, Object>();
URI requestedUri = he.getRequestURI();
String query = requestedUri.getRawQuery();
HttpServerManager.parseQuery(query, parameters);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
//SHOW DIALOG HERE
TestApplication.instance().showAdminRegisterDialog(he.getRemoteAddress());
}
});
// send response
String response = "<h1>Device Register</h1>";
for (String key : parameters.keySet())
response += key + " = " + parameters.get(key) + "\n";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}
`
ShowDialog Method
`
public void showAdminRegisterDialog(InetSocketAddress clientAdress){
Log.i(TAG, "showAdminRegisterDialog()");
if (adminRegisterDialog != null)
adminRegisterDialog.cancel();
Context context = MainActivity.instance();
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.NewDialog2);
builder = new AlertDialog.Builder(context);
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
adminRegisterView = li.inflate(R.layout.register_dialog, null);
builder.setView(adminRegisterView);
builder.setCancelable(false);
TextView deviceNameText = adminRegisterView.findViewById(R.id.deviceNameText);
TextView infoText = adminRegisterView.findViewById(R.id.infoText);
deviceNameText.setText(clientAdress.toString());
infoText.setText(R.string.register_admin_allow_text);
AppCompatButton allowButton = adminRegisterView.findViewById(R.id.allowButton);
AppCompatButton notAllowButton = adminRegisterView.findViewById(R.id.notAllowButton);
allowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(TAG,"allowButton");
adminRegisterDialog.dismiss();
}
});
notAllowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(TAG,"not allowButton");
adminRegisterDialog.dismiss();
}
});
adminRegisterDialog = builder.create();
adminRegisterDialog.show();
adminRegisterDialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
`
-I tried using AsyncTask but I couldn't because it was too complicated.
-Thread.sleep didn't work as it stopped all processes.
I solved the problem as follows: I am using Alertdialog in class where I defined HttpServer. I keep it in a while loop until the user responds when the alertdialog is shown. After the user click alertdialog button, I finish the while loop and send a response to the client.
boolean isClick = false;
//SHOW ALERT DIALOG HERE
//ALERT DILOG CLICK LISTENER
result.getAllowButton().setOnClickListener(new View.OnClickListener() {
isClick = true;
});
while (!isClick) {
Log.i(TAG, "in while loop");
}
Log.i(TAG, "out while loop");
isClick = false;
// send response
String response = "<h1>Alert Dialog Clicked</h1>";
for (String key : parameters.keySet())
response += key + " = " + parameters.get(key) + "\n";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.toString().getBytes());
os.close();
So I have been trying to fetch JSON objects in my Django REST Framework API. The algorithm for this called within the onPostExecute of my AsyncTask but it seems that it is not being called as when I debug it doesn't go there. Nothing fatal seems to be appearing in my logcat except that there is nothing in my array that should contain data from the DRF API.
I have two activities that calls my AsyncTask from my WSAdapter class. One is for logging in and the other is for listing all posts once logged in.
The logging in works just fine but listing the posts doesn't.
My code is below:
Posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
I was expecting my onPostExecute to be called and store data for my posts arrays.
Okay this is a nice example of async tasks. The problem here is when you call an async task then the code below will continue to execute even when the async task hasn't finished. So what happens in your case:
You fetch the posts and then ask to display them on the exact moment that the async function is still getting the posts. So of course the List is empty.
You can fix this by using the await keyword. This keyword stops the rest of your code from executing until that line has been executed. So change:
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
to:
await postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
Now the reason that the login does work is because you call that function within the if statement. If you would store the return value of that function in a boolean first then it wouldn't work either.
I want to make a SIP call with Android. I know that the connection is ok. I tested it in X-Lite. But the createSipSession() does not execute. This is the error:
Failed to create SipSession; network unavailable?
This is my code:
public SipManager mSipManager = null;
public SipProfile mSipProfile = null;
public SipAudioCall mCall = null;
public void onbtnLoginClicked(View v) {
// Create SIP Manager
if (mSipManager == null) {
mSipManager = SipManager.newInstance(this);
}
// Find EditText controls
EditText txtId = (EditText) findViewById(R.id.txtId);
EditText txtUsername = (EditText) findViewById(R.id.txtUsername);
EditText txtPassword = (EditText) findViewById(R.id.txtPassword);
TextView lblError = (TextView) findViewById(R.id.lblError);
lblError.setText("No Errors Yet");
String id = txtId.getText().toString();
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
try {
SipProfile.Builder builder = new SipProfile.Builder(username,id);
SipProfile.Builder builder = new SipProfile.Builder("sip:rostamiani#sip2sip.info");
builder.setPassword(password);
mSipProfile = builder.build();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
}
public void onbtnCallClicked(View v) {
TextView lblError = (TextView) findViewById(R.id.lblError);
lblError.setText("No Errors Yet");
try {
mCall = mSipManager.makeAudioCall(mSipProfile.getUriString(),"sip:3333#sip2sip.info",null,20);
SipAudioCall.Listener mCallListener = new SipAudioCall.Listener(); // <---Error
}
catch (SipException e) {
Log.e("SipService", e.getMessage());
lblError.setText(e.getMessage());
}
}
In my case the solution was changing the sip account, because it didn't support my country, and secondly I added a "sleep time" right after the login (10 seconds, but it could be 5).
Thread.sleep(10000);
I'm trying put the all alert box in my code.. but still can't run... when the editText in empty or null. It will show a dialog box which is needed to be filled by user. I've already tried all the steps and all dialog alert box. But it still functional. but in my case... this is more than 3 edittext involve. Just need an opinion where should I put the code for error empty edittext and need user fill it before they push the button.
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
// url to create new product
private static String url_create_product = "http://192.168.0.102/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
//private static final CharSequence TITLE_DIALOG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressDialog pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
List<EditText> editTextList = new ArrayList<EditText>();
//editTextList.add(myEditText);
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
for(EditText inputName : editTextList)
{
if (name == null || inputName.getText().toString().length() == 0)
{
Context context = getApplicationContext();
CharSequence error = "Please enter a track name" + name;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}
else {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
I actually would do this quite a bit differently... The error checking code should be a part of the Dialog onClick button. Check to see if all of the values are entered, and if they are not, put an indicator that the user needs to fill in that box, all while not finishing the dialog. Here's an example of this from one of my programs, in this case, getting a name to add to a high scores routine.
EditText input;
input=new EditText(this.getApplicationContext());
final int index=i;
new AlertDialog.Builder(this)
.setTitle("Update Status")
.setMessage(R.string.getName)
.setView(input)
.setPositiveButton(sayings_array[rnum], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
String name=value.toString();
if (name!=null)
{
addToHighScore(name,level,score,index);
dialog.dismiss();
}
}
}).show();
Check Edittext for null before starting AsyncTask execution. just first check EditText for empty on button click first then start CreateNewProduct AsyncTask . change your code as:
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
if (name != null || inputName.getText().toString().length() != 0)
{
if (price != null || price.getText().toString().length() != 0)
{
if (description != null || description.getText().toString().length() != 0)
{
// creating new product in background thread
new CreateNewProduct().execute();
}
else{
//show alert here
}
}else{
//show alert here
}
}else{
//show alert here
}
}
});
I am sending details to be stored in a database using a web service using KSOAP. I have used visual studio to create the web service. The web service works fine. A string will be returned when the details have been inserted into the database. The problem is that this string is empty, maybe something is wrong in the way that i am getting the response. I have been trying to find out whats wrong for a long time. please help
public class Registration extends Activity{
private static final String SOAP_ACTION = "http://tempuri.org/register";
private static final String OPERATION_NAME = "register";
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:58076/WebSite1/Service.asmx";
Button sqlRegister, sqlView;
EditText sqlFirstName,sqlLastName,sqlEmail,sqlMobileNumber,sqlCurrentLocation,sqlUsername,sqlPassword;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
sqlFirstName = (EditText) findViewById(R.id.etFname);
sqlLastName = (EditText) findViewById(R.id.etLname);
sqlEmail = (EditText) findViewById(R.id.etEmail);
sqlMobileNumber = (EditText) findViewById(R.id.etPhone);
sqlCurrentLocation = (EditText) findViewById(R.id.etCurrentLoc);
sqlUsername = (EditText) findViewById(R.id.etUsername);
sqlPassword = (EditText) findViewById(R.id.etPwd);
sqlRegister = (Button) findViewById(R.id.bRegister);
sqlRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()){
case R.id.bRegister:
new LongOperation().execute("");
break;
}
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String firstname = sqlFirstName.getText().toString();
String lastname = sqlLastName.getText().toString();
String emailadd = sqlEmail.getText().toString();
String number = sqlMobileNumber.getText().toString();
String loc = sqlCurrentLocation.getText().toString();
String uname = sqlUsername.getText().toString();
String pwd = sqlPassword.getText().toString();
SoapObject Request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Request.addProperty("fname", String.valueOf(firstname));
Request.addProperty("lname", String.valueOf(lastname));
Request.addProperty("email", String.valueOf(emailadd));
Request.addProperty("num", String.valueOf(number));
Request.addProperty("loc", String.valueOf(loc));
Request.addProperty("username", String.valueOf(uname));
Request.addProperty("password", String.valueOf(pwd));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Log.d("work","work");
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
String result = response.getProperty(0).toString();
Log.d("res",result);
if(result.equals("reg"))
{
Log.d("reg","reg");
return "Registered";
}
else
{
Log.d("no","no");
return "Not Registered";
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("tag","onpost");
if(result!=null)
{
if(result.equals("Registered"))
{
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
}
else if(result.equals("Not Registered"))
{
Toast.makeText(Registration.this, "Try Again", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(Registration.this, "Somethings wrong", Toast.LENGTH_LONG).show(); ///This is what gets printed on screen
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
Your webservice is returning a String.
Try using this to solve your problem
Object result = envelope.getResponse();
when your webservice return values of type byte[] ,you can do this:
SoapObject response=(SoapObject)envelope.bodyIn;
Hope it helps