I am trying to do a HTTP Post and as I came to know that time consuming tasks should be used within a Async Task or a Handler, I tried to code it using a Handler but I am getting an Handler uncaught exception, Unable to determine where I am going wrong. Below is my code and the log trace.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Bt = (Button)findViewById(R.id.button1);
Button Btx = (Button)findViewById(R.id.button2);
et = (EditText)findViewById(R.id.editText1);
etp = (EditText)findViewById(R.id.editText2);
Bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this,"Loading", "Please Wait...");
h = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dialog.dismiss();
}
};
new Thread(){
#Override
public void run() {
super.run();
Connection();
try {
Thread.sleep(3000);
h.sendEmptyMessage(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
});
// Btx.setOnClickListener(Sig);
}
private View.OnClickListener Sig =new View.OnClickListener() {
public void onClick(View v){
Intent Sign = new Intent(MainActivity.this,Signup.class);
startActivity(Sign);
}
};
public void Connection(){
String is = null;
String X = et.getText().toString();
String Y = etp.getText().toString();
if(X.length()>0 && Y.length()>0){
A = X;
B = Y;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://animsinc.com/query.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", X));
nameValuePairs.add(new BasicNameValuePair("password",Y));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
// et.setText(""); // clear text box
// etp.setText(""); // clear text box
HttpResponse responce = httpclient.execute(httppost);
HttpEntity entity = responce.getEntity();
is = EntityUtils.toString(entity);
// in = entity.getContent();
// Log.e("post responce----->", "" + is);
Toast.makeText(this,""+is, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
}
} else{
// display message if text fields are empty
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show();
}
if(is != null){
Toast.makeText(this,""+is, Toast.LENGTH_LONG).show();
}
}
}
This is my Log Cat:
Problem is that you are calling:
Toast.makeText(this,""+is, Toast.LENGTH_LONG).show();
from worker Thread inside run() method. You shouldn't do it. You can manipulate with UI only from Main(UI) Thread.
Solution is to use runOnUiThread() or AsyncTask or show Toast in Handler.
Related
Unfortunately android application has been stopped. At Http Post while attempting to call server at post activity please help
HttpClient cli = new DefaultHttpClient();
//HttpPost post = new HttpPost("http://" + sp.getString("ip", "localhost") + "/attendance/cliLogin.php");
HttpPost post = new HttpPost("localhost/attendance/");
// seting post data
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
String result = EntityUtils.toString(resent);
// reading response
if(result.equals("NoParams"))
Commons.showToast("Something went wrong", true);
else if(result.equals("Login"))
{
navi = new Intent(this, HomeActivity.class);
startActivity(navi);
}
else
Commons.showToast(result, true);
}
catch (HttpHostConnectException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Commons.showToast("Can't reach server, check the Hostname", true);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
Commons.showToast("Username/Password can't be empty", true);
}
}
Could you please share your logcat to see the error? I think that your are calling the php script in your main thread (that is your activity thread) and you may have NetworkOnMainThreadException
If that is the case:
Create a class that extends the AsyncTask.
Override its methods.
In the creator of this class pass the variables and assign them to the fields (variables) of your class.
Make your post in an AsyncTask inside the doInBackground method
And call the AsyncTask execute. Like this:
public class MyTask extends AsyncTask<String,String,String>{
private short errorType = -1;
private String result;
private String uname;
private String pass;
public MyTask(String uname, String pass){
this.uname = uname;
this.pass = pass;
}
#Override
protected String onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (errorType == 1){
Commons.showToast("Can't reach server, check the Hostname", true);
}
if(result.equals("NoParams")) {
Commons.showToast("Something went wrong", true); }
else if(result.equals("Login")) {
Intent navi = new Intent(this, HomeActivity.class); startActivity(navi);
}
else {
Commons.showToast(result, true);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try
{
HttpClient cli = new DefaultHttpClient();
HttpPost post = new HttpPost("localhost/attendance/");
List<NameValuePair> loginData = new ArrayList<NameValuePair>(2);
loginData.add(new BasicNameValuePair("uname", uname));
loginData.add(new BasicNameValuePair("pass", pass));
post.setEntity(new UrlEncodedFormEntity(loginData));
// executing login
HttpResponse res = cli.execute(post);
HttpEntity resent = res.getEntity();
return result = EntityUtils.toString(resent);
}
catch (HttpHostConnectException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
errorType = 1;
return null;
}
catch (ParseException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 2;
return null;
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
errorType = 3;
return null;
}
catch(Exception e){
errorType = 4;
return null;
}
}
}
And inside the activity make your call like this:
MyTask new MyTask(uname, pass).execute();
Again. All this is applicable only if you have
NetworkOnMainThreadException
Please share your logcat for further help.
I am new to android and stuck with the following problem. This is my async task and I want to show result in next activity. I am getting the whole result in the console but in textview, it only shows the last name.
private class MyTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
String link = "http://www.amtechnologies.org/emergency/get_medicine.php";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(link));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("disease_name", result2));
System.out.println("Result2:"+result2);
UrlEncodedFormEntity form = new UrlEncodedFormEntity(postParameters);
request.setEntity(form);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String result=EntityUtils.toString(entity);
result1 = result;
System.out.println("Result: "+result);
System.out.println("Result1: "+result1);
Intent i= new Intent(Medicines.this,View_medicines.class);
i.putExtra("result", result.toString());
startActivity(i);
}catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Next activty :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_medicines);
mnm=(EditText) findViewById(R.id.m3);
mi=(TextView) findViewById(R.id.m2);
nextbtn=(Button) findViewById(R.id.okmedi);
nextbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(View_medicines.this,Homepage.class);
startActivity(myIntent);
finish();
}
});
try {
Intent intent = getIntent();
String jsonArray=intent.getStringExtra("result");
jArray = new JSONArray(jsonArray);
System.out.println("Universe Acitivy Json Array: "+jArray);
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.setText(names);
mi.setText(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Change this part
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.setText(names);
mi.setText(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
to following
for(int i=0;i<jArray.length();i++){
String names=new JSONObject(jArray.getString(i)).get("medicine_name").toString();
System.out.println(names+"");
mnm.append(names);
mi.append(""+new JSONObject(jArray.getString(i)).get("medicine_intake"));
Toast.makeText(getApplicationContext(),""+new JSONObject(jArray.getString(i)).get("medicine_name").toString(), Toast.LENGTH_SHORT).show();
}
The code isn't working. Please help. The item gets added to the database except for the quantity. It's always zero. Why is that?
String value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creamy);
EditText et = (EditText) findViewById(R.id.CreamyEdit);
value = et.getText().toString();
Button b = (Button) findViewById(R.id.buttonCreamy);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Creamy.this, "Item Submitted", Toast.LENGTH_LONG).show();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"http://10.0.2.2:8080/http/test.php");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("item", "Creamy Delight")); //reflected in db
pairs.add(new BasicNameValuePair("quantity", value)); //not reflected in db
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
});
Help please!
Move the line value = et.getText().toString(); into the onClick method. If you call et.getText in onCreate it always returns an empty string, because that's all that's inside the EditText at the time of onCreate.
I Have this JSP which just check the username and password and "out.write" 1 or 0 based on true or false.
<%# page import="java.io.*" %>
<%
if(request.getParameter("username").equals("anas") && request.getParameter("password").equals("azeem"))
{
out.write("1");
}
else
out.write("0");
%> </br>
Now my android code is somerhing like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agent_login);
edit_username = (EditText) findViewById(R.id.edit_username);
edit_password = (EditText) findViewById(R.id.edit_password);
btn_login = (Button) findViewById(R.id.btnLogin);
if (android.os.Build.VERSION.SDK_INT > 9) { // must add this code in
// order not to get the
// Exception while executing
// program
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = edit_username.getText().toString();
password = edit_password.getText().toString();
Log.d(TAG, "Username:" + username);
Log.d(TAG, "Password:" + password);
try {
new Thread() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://10.0.2.2:8080/MyApp/login.jsp");
List<NameValuePair> pairs = new ArrayList<NameValuePair>(2);
pairs.add(new BasicNameValuePair("username",edit_username.getText().toString()));
pairs.add(new BasicNameValuePair("password",edit_password.getText().toString()));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
xml = EntityUtils.toString(httpEntity);
Log.d("xml", ""+xml.length()); //To confirm anything is there in the "xml"
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
} catch (Exception e) {
Log.d("xml", xml.toString());
Log.d("Server", e.toString());
}
try {
if (Integer.parseInt(String.valueOf(xml.charAt(10))) == 1) { //****HERE*******
Toast.makeText(getApplicationContext(), "LoginSuccessful",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Agent_Login.this,AgentHome.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),"Invalid Username or Password", Toast.LENGTH_SHORT).show();
edit_password.setText("");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Now on HERE (in comment) there gives a NullPointerException, which is I think because the xml is empty.
So, my question is how can I get the reply from the JSP in Android. I tested it on PC with an HTML form and its working absolutely fine.
Any help would be greatly appreciated.
A varaible is named xml but it will probably not contain any XML, as far is I can see; you're returning HTML.
Why would the 1 be located at position 10 in the returned string?
You're logging the content of xml; what is its value?
I have Service and AsyncTask in it, which due to check updatings on the server. It have to be reexecuted if it get some data and also if it doesn't. So my AsyncTask implementation is :
private class DklabExecute extends AsyncTask<Void, String, Void> {
int count;
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
String url = "http://192.168.0.250:81/?identifier=nspid_"+md5(LoginActivity.passUserId)+
",nspc&ncrnd="+Long.toString(currentTimestamp.getTime());
HttpGet rplPost = new HttpGet(url);
protected Void doInBackground(Void... args)
{
Log.i("service count", Integer.toString(count));
count ++;
Log.i("md5 func", md5(LoginActivity.passUserId));
String testData = "http://192.168.0.250/app_dev.php/api/comet/testOrder/";
JSONParser parser = new JSONParser();
DefaultHttpClient testClient = new DefaultHttpClient();
DefaultHttpClient rplClient = new DefaultHttpClient();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("", ""));
HttpGet httpTest = new HttpGet(testData);
httpTest.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
rplPost.setHeader("Cookie", CookieStorage.getInstance().getArrayList().get(0).toString());
try {
httpResponse = rplClient.execute(rplPost);
}
catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Header[] head = httpResponse.getAllHeaders();
Log.i("http Response",httpResponse.toString());
for (Header one:head)
{
Log.i("headers",one.toString());
}
Log.i("response code", Integer.toString(httpResponse.getStatusLine().getStatusCode()));
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line);// + "n");
}
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
json = sb.toString();
Log.i("rpl response",json);
if (new JSONArray(json) != null)
jArr = new JSONArray(json);
else
this.cancel(true);
JSONObject toObj = jArr.getJSONObject(0);
JSONObject data = toObj.getJSONObject(KEY_DATA);
if (data.has(KEY_ORDER))
{
for (Order a : ServiceMessages.orderExport)
{
Log.i("service before list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("before dashboard list", a.toString());
}
JSONObject jsonOrder = data.getJSONObject(KEY_ORDER);
Gson gson = new Gson();
Order orderObj= gson.fromJson(jsonOrder.toString(), Order.class);
try
{
for (ListIterator<Order> itr = orderExport.listIterator(); itr.hasNext();)
{
Order a = itr.next();
Log.i("order count", a.toString());
if(orderObj.getOrderid()==a.getOrderid())
{
Log.i("Service","order was changed");
a = orderObj;
someMethod("Your order "+ orderObj.getTitle() + " was changed");
}
else
{
Log.i("Service","order"+ orderObj.getTitle()+" was added");
// DashboardActivityAlt.forPrint.add(0, orderObj);
ServiceMessages.orderExport.add(0,orderObj);
Log.i("status",Integer.toString(orderObj.getProcess_status().getProccessStatusId()));
someMethod("Your order "+ orderObj.getTitle() + " was added");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
for (Order a : ServiceMessages.orderExport)
{
Log.i("service after list", a.toString());
}
Log.i(" ", " ");
for (Order a : DashboardActivityAlt.forPrint)
{
Log.i("after dashboard list", a.toString());
}
// intentOrder.putParcelableArrayListExtra("ordersService", orderExport);
sendBroadcast(intentOrder);
Log.i("after parse order",orderObj.toString());
Log.i("orders after updating",DashboardActivityAlt.orders.toString() );
}
else if (data.has(KEY_MESSAGE))
{
JSONObject jsonMessage = data.getJSONObject(KEY_MESSAGE);
Gson gson = new Gson();
Log.i("messages before parse", jsonMessage.toString());
for (Order a: DashboardActivityAlt.forPrint)
{
Log.i("messages count", Integer.toString(a.getCusThread().getMessages().size()));
}
Log.i("disparse message",jsonMessage.toString());
Message message = gson.fromJson(jsonMessage.toString(),Message.class);
Log.i("incomming message",message.toString());
JSONObject jsonThread = jsonMessage.getJSONObject(KEY_THREAD);
Threads thread = gson.fromJson(jsonThread.toString(),Threads.class);
Log.i("incomming thread",thread.toString());
Order orderChanged = new Order();
String orderName = null;
for(Order as : DashboardActivityAlt.forPrint)
{
if (as.getOrderid() == thread.getTreadOrder().getOrderid())
{
orderName = as.getTitle();
orderChanged = as;
Log.i("messages count after", Integer.toString(as.getCusThread().getMessages().size()));
}
}
Log.i("orderchanged",orderChanged.toString());
someMethod("Your order "+ thread.getTreadOrder().getTitle() + " was changed. Message was added");
orderChanged.getCusThread().addMessage(message);
sendBroadcast(intentMessage);
Log.i("messages service", "before sleep");
Log.i("messages service", "after sleep");
}
else
{
this.cancel(true);
}
}
catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
rplClient.getConnectionManager().shutdown();
testClient.getConnectionManager().shutdown();
someMethod("You've lost internet connection. You should try later.");
e2.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void bitmap) {
this.cancel(true);
new DklabExecute().execute();
}
}
If I send some data to the server, it gives me back in JSON format via rpl server. Everything works good, but the problem is when I get some data from the server, AsyncTask reexecuted in onPostExecute() method and it is the same reapeted one or two times data in my list of orders. If I do not reexecute AsyncTask the listening happens only in onStartCommand() method but not permanently. Tell me please how can I implement this in the best manner...
if it's a service there's no reason to use an AsyncTask.
AyncTasks were build to deliver content back on the original thread (normally a UI thread), but services don't have those.
I suggest you use a ScheduledExecutorService instead http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
private ScheduledExecutorService executor;
// call those on startCommand
executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(run, 250,3000, TimeUnit.MILLISECONDS);
and have a Runnable doing the work
private Runnable run = new Runnable() {
#Override
public void run() {
// do your network stuff
}
};
and don't forget to cancel everything when your service stops
executor.shutdown();
edit:
or to use a thread in loop you can:
boolean isRunning;
.
// this on your start
Thread t = new Thread(run);
isRunning = true;
t.start();
the runnable
private Runnable run = new Runnable() {
#Override
public void run() {
while(isRunning){
// do your network stuff
}
}
};
and again, don't forget to finish it whenever the service finishes with:
isRunning = false;