-2

I am trying to connect to the server but the app is not connecting, I add the privilges

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

and this the url address(you can connect to it )

http://justedhak.comlu.com/insert.php

and this is the error:

06-30 08:21:15.332: I/System.out(4270): main calls detatch()
06-30 08:21:15.332: E/Fail 1(4270): android.os.NetworkOnMainThreadException
06-30 08:21:15.337: E/Fail 2(4270): java.lang.NullPointerException: lock == null
06-30 08:21:15.337: E/Fail 3(4270): java.lang.NullPointerException
06-30 08:21:16.802: I/System.out(4270): main calls detatch()
06-30 08:21:16.802: E/Fail 1(4270): android.os.NetworkOnMainThreadException
06-30 08:21:16.807: E/Fail 2(4270): java.lang.NullPointerException: lock == null
06-30 08:21:16.807: E/Fail 3(4270): java.lang.NullPointerException

this is my code:

public void insert()
{
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("name",name));

    try
    {
    HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://justedhak.comlu.com/insert.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.e("pass 1", "connection success ");
}
    catch(Exception e)
{
        Log.e("Fail 1", e.toString());
        Toast.makeText(getApplicationContext(), "Invalid IP Address",
        Toast.LENGTH_LONG).show();
}     

    try
    {
        BufferedReader reader = new BufferedReader
        (new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null)
    {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    Log.e("pass 2", "connection success ");
}
    catch(Exception e)
{
        Log.e("Fail 2", e.toString());
}     

try
{
        JSONObject json_data = new JSONObject(result);
        code=(json_data.getInt("code"));

        if(code==1)
        {
    Toast.makeText(getBaseContext(), "Inserted Successfully",
        Toast.LENGTH_SHORT).show();
        }
        else
        {
     Toast.makeText(getBaseContext(), "Sorry, Try Again",
        Toast.LENGTH_LONG).show();
        }
}
catch(Exception e)
{
        Log.e("Fail 3", e.toString());
}
}

what could be missing ?

Moudiz
  • 7,211
  • 22
  • 78
  • 156

3 Answers3

3

Android UI is designed as a single Thread (The Main UI Thread). Therefore, to prevent any interruptions to the UI, you cannot make Network calls in the UI thread.

Since Androidv2.3 (I think) they introduced this exception so that incorrect coding practices does not affect the Overall Android Experience.

You will have to make the calls in a separate Thread. Android provides a simple wrapper over the conventional Java Runnable (or Thread) called (quite creatively) AsyncTask. This is a link to the documentation. (You may want to ask Google Uncle as well, he knows everything)

A short example usage (shamelessly copied from Android Dev website):

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

and then from your Activity call

 new DownloadFilesTask().execute(url1, url2, url3);
Binaek Sarkar
  • 617
  • 8
  • 21
  • your question is full of details , I am quite new to connecting to the server. anyway ill read more about async task. but one more question, is there different type of asny task ? I mean every time I need to connect to the server I should use async task ? or there are different method ? – Moudiz Jun 30 '15 at 06:04
  • 1
    The idea is that you need to create a new AsyncTask instance everytime you make a network operation (ideally any IO operation). You can call execute on an instance of AsyncTask (or its children) only once, therefore, you will need to create an instance everytime you need to use it. As illustrated in the original answer, you extend the platform AsyncTask<> and create your own classes, each of which perform different operations. e.g. LoginAsyncTask, RegisterAsyncTask, ForgotPasswordAsyncTask, so on and so forth. Hope this helps. – Binaek Sarkar Jun 30 '15 at 06:12
1

For that you need to use Asynchtask or thread. Or check below link How to fix android.os.NetworkOnMainThreadException?

Community
  • 1
  • 1
Pavya
  • 6,015
  • 4
  • 29
  • 42
1

Here you are calling network in Main thread which is not allowed. You can solve this using two ways

  1. Make network call in doInBackground of AsyncTask.
  2. Use Strict Mode if you don't want to use AsyncTask.
Balvinder Singh
  • 580
  • 6
  • 19