0

I am trying to connect my android to php. I found some code over the internet but it keeps giving me this exception. Here is my main activity

public class MainActivity extends ActionBarActivity {
    TextView tv;
    String text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv  = (TextView)findViewById(R.id.textview);
        text    = "";

        try {
            postData();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public void postData() throws JSONException{
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.99.7.91/post.php");
        JSONObject json = new JSONObject();

        try {
            // JSON data:
            json.put("name", "puffles");
            json.put("position", "lame");

            JSONArray postjson=new JSONArray();
            postjson.put(json);

            // Post the data:
            httppost.setHeader("json",json.toString());
            httppost.getParams().setParameter("jsonpost",postjson);

            // Execute HTTP Post Request
            System.out.print(json);
            HttpResponse response = httpclient.execute(httppost);

            // for JSON:
            if(response != null)
            {
                InputStream is = response.getEntity().getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                text = sb.toString();
            }

            tv.setText(text);

        }catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

And here is my manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fatima.scmyproject" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

</manifest>

Here is activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ScrollView android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:id="@+id/scrollView1">
        <LinearLayout android:layout_width="match_parent"
            android:id="@+id/linearLayout1"
            android:layout_height="match_parent">
            <TextView android:id="@+id/textview"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="hellow" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>

I can't find any problem with my code so far. I have added the textview in xml file, made sure setcontentview() is called before findViewById() is called. And I haven't deleted all the auto generated methods. Kindly tell me what the problem is.

puffles
  • 352
  • 2
  • 5
  • 23
  • 1
    Already asked 100s of times http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – Rohit5k2 Feb 24 '16 at 14:28
  • Do not perform a networking operation on main thread. Run your code in `AsyncTask`. Read this article and find what is `AsyncTask` and how to implement it: http://developer.android.com/intl/zh-tw/reference/android/os/AsyncTask.html – Stanojkovic Feb 24 '16 at 14:52

1 Answers1

0

Android don't recommend to call network call on main thread that's why you getting error instead calling network call on main use Async Task or you want to call on main thread just add following line in onCreate() of activity just after setContentView()

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
Rohit Patil
  • 1,068
  • 8
  • 9
  • Downvoting. Please do not never suggest anyone (specially beginners (it's a beginner mistake)) to change the ThreadPolicy. This will not solve the problem, this will only postpone it. – Budius Feb 24 '16 at 14:46