0

I am trying a sample to insert data from my data base to the server. But iam getting an Exception Invalid IP address. My IP is a global IP and can be accessed from any where

public class MainActivity extends Activity {

    String name;
    String id;
    InputStream is=null;
    String result=null;
    String line=null;
    int code;

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

        final EditText e_id=(EditText) findViewById(R.id.editText1);
        final EditText e_name=(EditText) findViewById(R.id.editText2);
        Button insert=(Button) findViewById(R.id.button1);

        insert.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            id = e_id.getText().toString();
            name = e_name.getText().toString();

            insert();
        }
    });
    }

    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://****/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());
        }
    }
}

I am new to this. For security reasons I cant put my IP. Please help me.

Simulant
  • 19,190
  • 8
  • 63
  • 98
androidGenX
  • 1,108
  • 3
  • 18
  • 44
  • replace Log.e("Fail 1", e.toString()); at to e.printStackrtrace(), and get what you see on logcat, post it here, so we can all check, better than usless msg "Invalid Ip ..." – Yazan May 19 '14 at 08:20
  • 05-19 13:03:52.850: E/Fail 1(1242): android.os.NetworkOnMainThreadException 05-19 13:03:52.870: E/Fail 2(1242): java.lang.NullPointerException 05-19 13:03:52.870: E/Fail 3(1242): java.lang.NullPointerException 05-19 13:03:53.201: D/dalvikvm(1242): GC_CONCURRENT freed 178K, 2% free 10995K/11207K, paused 9ms+60ms, total 243ms – androidGenX May 19 '14 at 08:31
  • 1
    see, now its a whole new story :) i will post you an answer – Yazan May 19 '14 at 08:39

2 Answers2

3

Run this in

public class MainActivity extends Activity {

String name;
String id;
InputStream is=null;
String result=null;
String line=null;
int code;

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

    final EditText e_id=(EditText) findViewById(R.id.editText1);
    final EditText e_name=(EditText) findViewById(R.id.editText2);
    Button insert=(Button) findViewById(R.id.button1);

    insert.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub


          id = e_id.getText().toString();
          name = e_name.getText().toString();
        new loadData().execute();
    }
});
}


class loadData extends AsyncTask<String, Integer, String> {
private StringBuilder sb;
private ProgressDialog pr;
private HttpResponse req;
private InputStream is;

@Override
protected void onPreExecute() {
    super.onPreExecute();
Toast.makeText(getApplicationContext(), "Start", Toast.LENGTH_LONG).show();
}

@Override
protected String doInBackground(String... arg0) {

      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://xxxxx/insert.php");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost); 
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                InputStreamReader ireader = new InputStreamReader(is);
                BufferedReader bf = new BufferedReader(ireader);
                sb = new StringBuilder();
                String line = null;
                while ((line = bf.readLine()) != null) {
                    sb.append(line);
                }
                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();
        }
            return id;     





}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    pr.dismiss();
    Toast.makeText(getApplicationContext(), "End", Toast.LENGTH_LONG).show();

}

} }

its performing networking operation on its main thread. Run your code in AsyncTask

user3559657
  • 141
  • 7
2

android.os.NetworkOnMainThreadException

this means you can't communicate with network from the UI thread, so, you have to use async task

create asyncTask class:

class insertTask extends AsyncTask<String, String, String> {
     protected String doInBackground(String... params) {
         String result = insert();
         return result ;
     }



     protected void onPostExecute(String result) {
         if(result.equals("OK"))....
         //after background is done, use this to show or hide dialogs
     }
 }

you need to execute task at onClick()

@Override
public void onClick(View v) {

    id = e_id.getText().toString();
    name = e_name.getText().toString();

    new insertTask().execute("");
}

and modify public void insert() to return some string telling what status is, OK, ERR, ...

Yazan
  • 6,074
  • 1
  • 19
  • 33