Could not execute method of the activity httpdata - android

What do you think is wrong with this code ?
I am using this class: https://github.com/btouchard/HttpData/blob/master/README.md
Error:
java.lang.IllegalStateException: Could not execute method of the activity
Location of error: Log.i line!
Thanks for the assistance.
I guess it is a basic solution, but I can't find it.
public class Formulaire extends Activity {
EditText msgTextField;
Button sendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form);
//make message text field object
msgTextField = (EditText) findViewById(R.id.msgTextField);
//make button object
sendButton = (Button) findViewById(R.id.sendButton);
}
public void send(View v) {
//get message from message box
try {
String MonURL = "http://www.davidmarchioni.fr/glopper/test.txt";
HttpData request = new HttpData(MonURL);
request.header(MonURL);
String html = request.asString();
Thread.sleep(2600);
Log.i("OK >> ", html);
Toast.makeText(getApplicationContext(), html, Toast.LENGTH_SHORT).show();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

well try on catching Exception, what if String html comes null? what maybe the reason

Related

Wrong data saved in file during writing in Android Development

I'm learning to write a demo about get input message from the EditText, but after finishing it, i found the message is wrong. I tried to log it. The answer is as below.
Code is here:
public class MainActivity extends Activity {
private EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.editText);
}
#Override
protected void onDestroy() {
super.onDestroy();
String input = edit.toString();
Log.i("tag",input);
save(input);
}
public void save(String input){
FileOutputStream out = null;
BufferedWriter writer = null;
try{
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(input);
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(writer != null){
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My log cat shows following response
Replace this line:
String input = edit.toString();
with:
String input = edit.getText().toString();
try
edit.getText().toString(); to get text from EditText
When you try to use toString() method it will give hashcode value of the object.
In your case it is giving hashcode value of EditText object you have created.
If you want to get the string value you have entered in EditText field u have to first get Editable from EditText example below
editText.getText().toString() it will return the value you have entered in EditText

AsyncTask. Problems with receiving from Java Server

I want to use AsyncTask for receiving ArrayList's(in this case) from Java server. To be sure, that I received something from server I'm trying to display it with Toast.
The Code is following:
public class MainActivity extends Activity {
private DataReceiving dRec;
private DataTransfer dTrans;
private EditText inputData;
private Button sendParametersBtn;
private Button startComputationBtn;
private TextView displayText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputData=(EditText) findViewById(R.id.InputText);
sendParametersBtn=(Button) findViewById(R.id.button1);
startComputationBtn=(Button) findViewById(R.id.button2);
displayText=(TextView) findViewById(R.id.textView1);
sendParametersBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dRec = new DataReceiving();
dRec.execute();
}
});
private class DataReceiving extends AsyncTask<Void, Void, ArrayList>
{
#Override
protected ArrayList doInBackground(Void... params) {
ArrayList b = new ArrayList();
try {
b = receive();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
protected void onPostExecute(ArrayList result) {
super.onPostExecute(result);
Toast toast=Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT);
toast.show();
}
public ArrayList receive () throws IOException, ClassNotFoundException
{
ServerSocket s= new ServerSocket(8888);
Socket incoming =s.accept();
ObjectInputStream ios = new ObjectInputStream(incoming.getInputStream());
ArrayList b = (ArrayList) ios.readObject();
ios.close();
incoming.close();
s.close();
return b;
}
While clicking the sendParametersBtn nothing happening.
P.S. I can successfully transmit from Android to Server. So its not a connection or permission problem.
Thank you for help
Hi If your getting some thing from server you have to call web server url for fetching data. After data arrives response have some type it will JSON/XML if they are restful services if they are SOAP services they are in envelope. So after response return get that and parse them as per logic.
Look for HTTP get/post (for ping to server and get data )and parsing (JSON/XML).
Figured out! I removed receive method into doInBackground.

How to change activity after an async task is completed?

The problem has been solved, thank you for the help.
Essentially, I have my onCreate() class that sets an OnClick listener on a button. Once I click it, an async task is created and executed.
This async task gets a response from a server and then sends the info to onPostExecute().
From here, if the info is valid or not, I want to toast the result and switch activities accordingly.
As of now, I have tried to do it from the onPostExecute() and it does not work. Somehow, I must get back to my main thread and do it there. How do I do this?
Here is the code:
public class Class1 extends Activity {
JSONObject jObj = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
Button submit = (Button) findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
(new CallAPI(restfulCall)).execute();
}
});
}
public class CallAPI extends AsyncTask<Void,Void,String>
{
private String restfulCall = "";
public CallAPI(String command)
{
restfulCall = command;
}
protected String doInBackground(Void... urls)
{
return API.getData(restfulCall);
}
protected void onPostExecute(String result) {
try {
jObj = new JSONObject(result);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
if(jObj.get("status").toString().equals("success"))
{
Toast.makeText(getBaseContext(),"Registration Succesful",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Class1.this,Success.class);
Class1.this.startActivity(intent);
}
else
{
Toast.makeText(getBaseContext(),jObj.get("error").toString(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(Class1.this,Error.class);
Class1.this.startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
use equals for comparing Strings intead of == as :
if(jObj.get("status").toString().equals("success")
instead of
if(jObj.get("status").toString() == "success")

How to check empty edittext in android [duplicate]

This question already has answers here:
How do I check if my EditText fields are empty? [closed]
(30 answers)
Closed 9 years ago.
My code does not print empty edit text itry trim stirng .length==00 but is not work hat wrong in my code?? how do my code check if edittext is empty before sumbit query
I want to check before submit method if edittext is empty? If is empty then print toast message
public class AgAppTransPayExternalAccount extends Activity {
TextView lblTPEAWelcomeToPayExternalAccountPage;
TextView lblTPEAOtherAccount;
TextView lblTPEAPinno;
TextView lblTPEAAmount;
EditText txtTPEAotheraccount;
EditText txtTPEApinno;
EditText txtTPEAamount;
Button btnTPEAsubmit;
Button clearTPEAButton;
Button btnTPEAgoback;
String sms;
public static ProgressDialog PayExternalAccountProgressDialog = null;
public static boolean value=true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapptranspayexternalaccount);
sms=LoginScreen.item.toString();
/*
lblTPEAWelcomeToPayExternalAccountPage = (TextView)
findViewById(R.id.lblTPEAWelcomeToPayExternalAccountPage);
lblTPEAWelcomeToPayExternalAccountPage.setText("Welcome To Pay External
Account Page");
lblTPEAWelcomeToPayExternalAccountPage.setTextColor(getResources().getColor
(R.color.text_color_black));
*/
lblTPEAOtherAccount = (TextView) findViewById(R.id.lblTPEAOtherAccount);
lblTPEAOtherAccount.setText("Other Account :");
txtTPEAotheraccount=(EditText) findViewById(R.id.txtTPEAotheraccount);
lblTPEAPinno = (TextView) findViewById(R.id.lblTPEAPinno);
lblTPEAPinno.setText("PIN Number :");
txtTPEApinno=(EditText) findViewById(R.id.txtTPEApinno);
lblTPEAAmount = (TextView) findViewById(R.id.lblTPEAAmount);
lblTPEAAmount.setText("Amount :");
txtTPEAamount=(EditText) findViewById(R.id.txtTPEAamount);
btnTPEAsubmit=(Button) findViewById(R.id.btnTPEAsubmit);
btnTPEAsubmit.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton=(Button) findViewById(R.id.clearTPEAButton);
clearTPEAButton.setTextColor(getResources().getColor(R.color.text_color_blue));
btnTPEAgoback=(Button) findViewById(R.id.btnTPEAgoback);
btnTPEAgoback.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
txtTPEAotheraccount.setText("");
txtTPEApinno.setText("");
txtTPEAamount.setText("");
}
});
btnTPEAgoback.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
btnTPEAsubmit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String tpeapinemptycheck = txtTPEApinno.getText().toString();
String otheraccountemptycheck =
lblTPEAOtherAccount.getText().toString();
String amountemptycheck = txtTPEAamount.getText().toString();
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
showProgress();
submitPEA();
}
});
}
private void submitPEA() {
String message;
String mobilenumber= LoginScreen.smsmobileno;
if (( sms.compareTo("SMS")==0))
{
SmsManager smsmanager = SmsManager.getDefault();
message="AGPEA"+AgAppHelperMethods.varMobileNo+AgAppHelperMethods.
arMobileNo+txtTPEAotheraccount.getText().toString()+AgAppHelperMethods.
varMobileNo+txtTPEApinno.getText().toString()+txtTPEAamount.getText().toString();
smsmanager.sendTextMessage(mobilenumber, null, message, null, null);
}
else
{
Intent j = new Intent(AgAppTransPayExternalAccount.this, AgAppTransPEAResponse.class);
Bundle bundle = new Bundle();
bundle.putString("txtTPEApinno", txtTPEApinno.getText().toString());
bundle.putString("txtTPEAotheraccount",txtTPEAotheraccount.getText().toString());
bundle.putString("txtTPEAamount",txtTPEAamount.getText().toString());
j.putExtras(bundle);
startActivity(j);
value=false;
PayExternalAccountProgressDialog.dismiss();
}
}
private void showProgress()
{
PayExternalAccountProgressDialog =
ProgressDialog.show(AgAppTransPayExternalAccount.this,null, "Processing please
wait...", true);
if (PayExternalAccountProgressDialog != null) {
try
{
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
PayExternalAccountProgressDialog.dismiss();
if(value)
{
Toast.makeText(AgAppTransPayExternalAccount.this, "Request
TimeOut " , Toast.LENGTH_SHORT).show();
}
}
}, 15000); // <--- here is the time adjustment.
}
catch (Exception e)
{
}
}
}
}
Your code is right, only missing this is { } braces in the else condition, try out as following,
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
{ // add this
showProgress();
submitPEA();
} // add this
Just because you haven't added those { } braces, your control was going into submitPEA() method.
Try like this
edit_text.getText().toString().trim().equals("");
Create a String variable say x;
Now if et is your EditText field use this:
x = et.getText().toString();
if the EditText field has any text in it it would be passed to the string x.
Now to check if the string x is not null or contains nothing use
if(x.matches(""))
{
//your code here
}
else
{
//the counter action you'll take
}
this way you can check that the entry you are about to enter in the database won't be empty.
Happy coding.

One Android chat app unable to receive messages ( aSamck + Openfire )

I have implemented a chat application using aSmack. I used the openfire server as the chat server. All of these applications are running in the same machine. But when I try to send messages between two emulators only one emulator successfully receives messages. Other client won't receive any messages. But from both emulators I was able to send messages to pigin(IM clinet). Also if I use gmail.com as the chat server everything works just fine.
User names used to login
jayamal
suchith
(openfire indicates users are online )
names used to send messages
jayamal#elearn (elearn is the domain i created in my machine using openfire)
suchith#elearn
( but in openfire archives shows one name as jayamal#elearn/Smack, tried sending message to that name but it also unsuccessful )
Please help to rectify this problem. Your help is really appreciated.
public class ASmackChatTestActivity extends Activity {
public int state = 0;
private static final String TAG = "HelloFormStuffActivity";
XMPPConnection xmpp ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnLogin = (Button) findViewById(id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtUserName = (EditText) findViewById(id.txtUserName);
EditText txtPass = (EditText) findViewById(id.txtPass);
String userName = txtUserName.getText().toString();
String password = txtPass.getText().toString();
new login().execute(userName,password);
}
});
Button btnSend = (Button) findViewById(id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtMessage = (EditText) findViewById(id.txtMessage);
EditText txtTo = (EditText) findViewById(id.txtTo);
String message = txtMessage.getText().toString();
String to = txtTo.getText().toString();
new sendMessage().execute(to,message);
}
});
Button btnStop = (Button) findViewById(id.btnStopServices);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText txtTo = (EditText) findViewById(id.txtTo);
String to = txtTo.getText().toString();
new recieveMessages().execute(to);
}
});
}
class login extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String userName = params[0];
String password = params[1];
//XMPPConnection xmpp = new XMPPConnection("jabber.iitsp.com");
xmpp = new XMPPConnection("10.0.2.2");
try {
xmpp.connect();
// for other jabber accounts, truncate after the #
//xmpp.login("username", "password");
// for gtalk / gmail, include the #
xmpp.login(userName, password);
Log.v(TAG,"Logged in");
} catch (XMPPException e) {
Log.v(TAG, "Failed to connect to " + xmpp.getHost());
e.printStackTrace();
}
return null;
}
}
class sendMessage extends AsyncTask<String, Void, String>{
//String msg;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String to = params[0];
String message = params[1];
ChatManager chatmanager = xmpp.getChatManager();
Chat newChat = chatmanager.createChat(to, new MessageListener() {
// THIS CODE NEVER GETS CALLED FOR SOME REASON
public void processMessage(Chat chat, Message message) {
try {
// msg = message.getBody();
Log.v(TAG, "Got:" + message.getBody());
chat.sendMessage(message.getBody());
} catch (XMPPException e) {
Log.v(TAG, "Couldn't respond:" + e);
}
Log.v(TAG, message.toString());
}
});
// Send something to friend#gmail.com
try {
newChat.sendMessage(message);
Log.v(TAG, "sent:" + message);
} catch (XMPPException e) {
Log.v(TAG, "couldn't send:" + e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(),"Message Recieved : " + msg, Toast.LENGTH_LONG);
super.onPostExecute(result);
}
}
class recieveMessages extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String to = params[0];
// Accept only messages from friend#gmail.com
PacketFilter filter
= new AndFilter(new PacketTypeFilter(Message.class),
new FromContainsFilter(to));
// Collect these messages
PacketCollector collector = xmpp.createPacketCollector(filter);
while(true) {
Packet packet = collector.nextResult();
if (packet instanceof Message) {
Message msg = (Message) packet;
// Process message
Log.v(TAG, "Got message: " + msg.getBody());
}
}
//return null;
}
}
}
Sorry this is a bit late.
The one user you can send to the IM client (pidgin) can you send back to your emulator. I.e. can you receive in either emulator?
Message receiving is event based so you don't need to use a button click to set it off.
Check out this great example. By Davanum Srinivas
I've modified it for my use quite extensively but the base code is still very useful.
http://davanum.wordpress.com/2008/12/29/updated-xmpp-client-for-android/ also look at the original article.

Categories

Resources