1

MYCODE

package com.example.myweb;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.login1);
        EditText emailBox   = (EditText)findViewById(R.id.email);
        EditText passwordBox   = (EditText)findViewById(R.id.password);
        final String emailId = emailBox.getText().toString();
        final String passwordId = passwordBox.getText().toString();
        button.setOnClickListener(new Button.OnClickListener()   {             
           public void onClick(View v)  {               
            try {
                getUserLoggedIn(emailId,passwordId);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();                    
            }               
           }  
         });        
    }
    public void getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException, JSONException{

        HttpClient client = new DefaultHttpClient();
        HttpPost  post = new HttpPost("http://localhost/testand.php");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("email", email));
        pairs.add(new BasicNameValuePair("password", password));
        post.setEntity(new UrlEncodedFormEntity(pairs));
        HttpResponse response = client.execute(post);

        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            String responseStr = EntityUtils.toString(resEntity).trim();

            TextView textV1 = (TextView)findViewById(R.id.textV1);
            String myName = responseStr;

            textV1.setText(myName + ", Welcome to Socionet. :) ");

        }




        //JSONObject json = stringToJsonobj(response.toString());  // a is your string response



    }

    public JSONObject stringToJsonobj(String result)
    {
        JSONObject jObj = null;
            try {

            jObj = new JSONObject(result);          

        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());

        }

         return jObj; 
}   
}

When i try to run this it shows this error!!

I am trying to send a data to php via httpost but its not working. i think i need to use AsyncTask somewhere in my code but i dont know whether its right to use and where and how to use AsyncTask

LOGCAT

12-28 06:50:59.677: W/System.err(783): android.os.NetworkOnMainThreadException
12-28 06:50:59.698: W/System.err(783):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
12-28 06:50:59.698: W/System.err(783):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
12-28 06:50:59.705: W/System.err(783):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
12-28 06:50:59.705: W/System.err(783):  at java.net.InetAddress.getAllByName(InetAddress.java:214)
12-28 06:50:59.705: W/System.err(783):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
12-28 06:50:59.718: W/System.err(783):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-28 06:50:59.725: W/System.err(783):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-28 06:50:59.725: W/System.err(783):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-28 06:50:59.725: W/System.err(783):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-28 06:50:59.739: W/System.err(783):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-28 06:50:59.739: W/System.err(783):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-28 06:50:59.745: W/System.err(783):  at com.example.myweb.MainActivity.getUserLoggedIn(MainActivity.java:64)
12-28 06:50:59.760: W/System.err(783):  at com.example.myweb.MainActivity$1.onClick(MainActivity.java:47)
12-28 06:50:59.760: W/System.err(783):  at android.view.View.performClick(View.java:4204)
12-28 06:50:59.765: W/System.err(783):  at android.view.View$PerformClick.run(View.java:17355)
12-28 06:50:59.765: W/System.err(783):  at android.os.Handler.handleCallback(Handler.java:725)
12-28 06:50:59.775: W/System.err(783):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-28 06:50:59.805: W/System.err(783):  at android.os.Looper.loop(Looper.java:137)
12-28 06:50:59.805: W/System.err(783):  at android.app.ActivityThread.main(ActivityThread.java:5041)
12-28 06:50:59.805: W/System.err(783):  at java.lang.reflect.Method.invokeNative(Native Method)
12-28 06:50:59.815: W/System.err(783):  at java.lang.reflect.Method.invoke(Method.java:511)
12-28 06:50:59.815: W/System.err(783):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-28 06:50:59.835: W/System.err(783):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-28 06:50:59.845: W/System.err(783):  at dalvik.system.NativeStart.main(Native Method)

2 Answers2

0

android.os.NetworkOnMainThreadException is the exception. Do not run network operation on main UI thread. Use AsyncTask or Handler for the same.

you can find more on the topic at here

Dexter
  • 4,036
  • 3
  • 47
  • 55
  • i knew it but how to use it ? can u give an example rather than reference – PewDrunk Pie Dec 28 '14 at 07:11
  • http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html There are many such example you can search on and rewriting them is waste of time and resource. – Dexter Dec 28 '14 at 07:14
  • Even though you are given with a ready to use code example that won't help you in long run. You must have to learn the concept to use them efficiently. developer.android.com is better place to learn concept with other sources as you can find updated info here. pls, keep in mind that in android landscape apis are changing rapidly making some code examples at other sources outdated. – Dexter Dec 28 '14 at 07:32
0

This is networkonmainthread exception...when we try to run asynctask and android-Db connectivity through webservice like php or c# this error occur....Lots of thread like this and this give its solution.

previously i have done this work around... add following code to ur activity in Oncreate() block

if (android.os.Build.VERSION.SDK_INT > 8) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }

You'll not face error then...and Dont forget permission

<uses-permission android:name="android.permission.INTERNET" />

And sometimes next error is no connectivity due to antivirus like avg or avast blocking external connections through firewall. Disable firewall of antivirus.

Community
  • 1
  • 1
SK16
  • 623
  • 8
  • 17