-2

I am currently trying to post data via android emulator to a php file on wamp server but it's not connecting. It keeps showing "Unfortunately, Creditswitch Test has stopped."

Below is the code. Please I need to resolve this now.

public class Confirm_instant_top_up extends Activity {

TextView network;
TextView names;
TextView amount;
TextView phone_number;
TextView email_address;

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.confirm_instant_top_up);

   network = (TextView) findViewById(R.id.network);
   names = (TextView) findViewById(R.id.names);
   amount = (TextView) findViewById(R.id.amount);
   phone_number = (TextView) findViewById(R.id.phone_number);
   email_address = (TextView) findViewById(R.id.email_address);

    Intent intent = getIntent();

    final String ntwk = intent.getStringExtra("network");
    final String nms = intent.getStringExtra("names");
    final String amt = intent.getStringExtra("amount");
    final String phone = intent.getStringExtra("phone");
    final String email = intent.getStringExtra("email");

    network.setText(ntwk);
    names.setText(nms);
    amount.setText(amt);
    phone_number.setText(phone);
    email_address.setText(email);       

   Button btnOk = (Button) findViewById(R.id.btn_ok);
    btnOk.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View v) {
              //Intent intent = new Intent(Confirm_instant_top_up.this, Confirm_instant_top_up.class);      

                // check whether the network field is empty or not            
                if(ntwk.length()>0) {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://10.0.2.2/test/confirmPayment.php");

                    try {
                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);                            
                        nameValuePairs.add(new BasicNameValuePair("network", ntwk));
                            nameValuePairs.add(new BasicNameValuePair("names", nms));
                            nameValuePairs.add(new BasicNameValuePair("amount", amt));
                            nameValuePairs.add(new BasicNameValuePair("phone_number", phone));
                            nameValuePairs.add(new BasicNameValuePair("email_address", email));
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            httpclient.execute(httppost);
                            Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    //display message if text field is empty
                    Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
                }

          }

        });;
     }
     }

Below is the logcat

 03-10 11:12:46.868: W/dalvikvm(2198): threadid=1: thread exiting with uncaught exception (group=0xb3cf3b20)
 03-10 11:12:46.958: E/AndroidRuntime(2198): FATAL EXCEPTION: main
 03-10 11:12:46.958: E/AndroidRuntime(2198): Process: com.creditswitchtest, PID: 2198
 03-10 11:12:46.958: E/AndroidRuntime(2198): android.os.NetworkOnMainThreadException
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at    android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at libcore.io.IoBridge.connect(IoBridge.java:112)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at java.net.Socket.connect(Socket.java:843)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at com.creditswitchtest.Confirm_instant_top_up$1.onClick(Confirm_instant_top_up.java:74)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at android.view.View.performClick(View.java:4438)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at android.view.View$PerformClick.run(View.java:18422)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at android.os.Handler.handleCallback(Handler.java:733)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at android.os.Handler.dispatchMessage(Handler.java:95)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at android.os.Looper.loop(Looper.java:136)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at android.app.ActivityThread.main(ActivityThread.java:5017)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at java.lang.reflect.Method.invokeNative(Native Method)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at java.lang.reflect.Method.invoke(Method.java:515)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
 03-10 11:12:46.958: E/AndroidRuntime(2198):    at dalvik.system.NativeStart.main(Native Method)
Talha Q
  • 4,350
  • 4
  • 28
  • 40
fidazik
  • 423
  • 1
  • 5
  • 11
  • Please post the logcat – Talha Q Mar 10 '14 at 15:16
  • You might got the networkOnMainthread exception.I think you are testing above api 10.upto api 10 you can perform network operation on main thread.For newer api levels you have to perform network operations in asyctask. – Talha Q Mar 10 '14 at 15:18
  • Yeah i was right there you see a NetworknMainthreadException on line 4..Just cut the code inside of your button OnclickListener and paste in AsyncTask. – Talha Q Mar 10 '14 at 15:39
  • Hello TalhaQ please I still a beginner in android development; what is AsyncTask? I don't seem to get how to get to AsyncTask. – fidazik Mar 10 '14 at 15:45
  • Check out the below answer.@Hbibna posted your solution. – Talha Q Mar 10 '14 at 15:47
  • also see here http://stackoverflow.com/questions/12473711/how-to-make-an-udp-connection-in-android/12473942#12473942 – MemLeak Mar 10 '14 at 15:52
  • @fidazik now check out..I have posted a complete answer :) – Talha Q Mar 10 '14 at 16:16

2 Answers2

0

You're trying to execute an Http request on the UI Thread. You should use an AsyncTask for that.

Example:

public void onClick(View v) {
MyAsyncTask myAsyncTask = new myAsyncTask();
myAsyncTask.link(this);
myAsyncTask.execute(new String[]{ntwk, nms, amt, phone, email});
}

And declare this class as an internal or external class :

public class MyAsyncTask extends AsyncTask<String, Void, Void> {

WeakReference<Context> ctx;

public void link(Context ctx){
    this.ctx= new WeakReference<Context>(ctx);
}

@Override
protected Void doInBackground(String... params) {

        if(params[0].length()>0) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2/test/confirmPayment.php");

                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);                            
                    nameValuePairs.add(new BasicNameValuePair("network", params[0]));
                        nameValuePairs.add(new BasicNameValuePair("names", params[1]));
                        nameValuePairs.add(new BasicNameValuePair("amount", params[2]));
                        nameValuePairs.add(new BasicNameValuePair("phone_number", params[3]));
                        nameValuePairs.add(new BasicNameValuePair("email_address", params[4]));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        httpclient.execute(httppost);
                        Toast.makeText(ctx.get(),"Sent",Toast.LENGTH_SHORT).show();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //display message if text field is empty
                Toast.makeText(ctx.get(),"All fields are required",Toast.LENGTH_SHORT).show();
            }

    return null;
}
}

And of course as @TalhaQ has mentioned, don't forget to add the permissions to the manifest.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Hbibna
  • 568
  • 7
  • 11
  • I've just done it but I'm getting this error message, "Cannot make a static reference to a non-static method execute(String...) from the type AsyncTask" – fidazik Mar 10 '14 at 16:12
  • Actually i've edited my code, i didn't properly instantiate the class. It should work perfectly now. – Hbibna Mar 10 '14 at 16:22
  • @Hbibna...error message, "the method getBaseContext() is undefined for the type MyAsyncTask" – fidazik Mar 10 '14 at 16:55
  • I suppose you should have your problem fixed by now but in case you haven't i've modified the code yet again to provide you with a solution that works – Hbibna Mar 11 '14 at 11:53
0

Well i have done your task just copy and paste it.Its complete task.If you still got any errors comment here.

public class Confirm_instant_top_up extends Activity {
TextView network;
TextView names;
TextView amount;
TextView phone_number;
TextView email_address;
String ntwk; 
String nms;
String amt;
String phone;
String email;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.confirm_instant_top_up);
network = (TextView) findViewById(R.id.network);
names = (TextView) findViewById(R.id.names);
amount = (TextView) findViewById(R.id.amount);
phone_number = (TextView) findViewById(R.id.phone_number);
email_address = (TextView) findViewById(R.id.email_address);

Intent intent = getIntent();

 ntwk = intent.getStringExtra("network");
 nms = intent.getStringExtra("names");
 amt = intent.getStringExtra("amount");
 phone = intent.getStringExtra("phone");
 email = intent.getStringExtra("email");

network.setText(ntwk);
names.setText(nms);
amount.setText(amt);
phone_number.setText(phone);
email_address.setText(email);       
Button btnOk = (Button) findViewById(R.id.btn_ok);
btnOk.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View v) {
          BackGroundTask task = new BackGroundTask();
            task.execute();     

      }

    });

    class BackGroundTask extends AsyncTask<String,Void,Void> {

        public BackGroundTask()
        {
            super();
        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(String...params) {

            if(ntwk.length()>0) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2/test/confirmPayment.php");

                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);                            
                    nameValuePairs.add(new BasicNameValuePair("network", ntwk));
                        nameValuePairs.add(new BasicNameValuePair("names", nms));
                        nameValuePairs.add(new BasicNameValuePair("amount", amt));
                        nameValuePairs.add(new BasicNameValuePair("phone_number", phone));
                        nameValuePairs.add(new BasicNameValuePair("email_address", email));
                        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        httpclient.execute(httppost);
                        Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                //display message if text field is empty
                Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show();
            }
            return null;

        }
        @Override
        protected Void onPostExecute() {

            return null;
        }

    }
         }
     }

Also dont forget to add permissions in the AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Talha Q
  • 4,350
  • 4
  • 28
  • 40