2

i am trying to do my first android app with connection on MySQL, i google a lot and find some tutorials and things like that. Base on them i have this code:

package com.example.helloworld;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.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.Toast;

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();

            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://localhost/xampp/android_connect/index.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());
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }    
}

I cant see any error or anything in it but when i try to load it it says : "Invalid IP Address" (it's error message from catch{}) . I try to research where can be problem and in LogCat i found this error:

11-16 10:39:10.036: I/ActivityManager(150): Start proc com.example.helloworld for activity com.example.helloworld/.MainActivity: pid=612 uid=10045 gids={3003, 1028}
11-16 10:39:10.386: E/Trace(612): error opening trace file: No such file or directory (2)
11-16 10:39:10.966: D/gralloc_goldfish(612): Emulator without GPU emulation detected.
11-16 10:39:11.016: I/ActivityManager(150): Displayed com.example.helloworld/.MainActivity: +1s32ms
11-16 10:39:11.066: I/Choreographer(150): Skipped 34 frames!  The application may be doing too much work on its main thread.
11-16 10:39:18.945: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:18.975: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:18.975: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:19.195: D/dalvikvm(612): GC_CONCURRENT freed 191K, 4% free 6229K/6471K, paused 17ms+65ms, total 206ms
11-16 10:39:20.065: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:20.075: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:20.075: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:20.645: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:20.645: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:20.645: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.055: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.065: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.065: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.535: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.545: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.545: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.728: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.735: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.735: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:21.925: E/Fail 1(612): android.os.NetworkOnMainThreadException
11-16 10:39:21.925: E/Fail 2(612): java.lang.NullPointerException
11-16 10:39:21.925: E/Fail 3(612): java.lang.NullPointerException
11-16 10:39:22.535: I/Choreographer(612): Skipped 37 frames!  The application may be doing too much work on its main thread.
: E/(): Device disconnected: 1
: E/(): Device disconnected

Especialy i look at can't find directory, i try to open same adress in my borowser and i open it with no problem. Can somebody give me advise what i am doing wrong?

Thanks

Andurit
  • 5,612
  • 14
  • 69
  • 121

3 Answers3

2

localhost points to the device itself; so you could try the following :

  • If you're running this for test purposes on your own network, try typing your local ip instead of localhost, e.g. http://192.168.0.123

  • Try http://10.0.2.2 instead of localhost, type it in a browser on the device and see if it connects properly.

Check out this question as well.

Reference for 10.0.2.2


About the NetworkOnMainThreadException

You're trying to do network operations on the main thread of your application, which could cause severe delays and unpredictable results.

You should always use an AsyncTask for network operations. Please see this article from the android docs.

Here's an example usage;

Your AsyncTask should look like the following :

 private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
          
        // params comes from the execute() call: params[0] is the url.
        try {

            // Initialize your parameters
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id",urls[1]));
            nameValuePairs.add(new BasicNameValuePair("name",urls[2]));         
            
            // Make your HTTP Request
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(urls[0]);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            
            // Read the response
            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();
            
            // Return the response.
            return result;
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    
    // onPostExecute gets the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        
        // Read your response into a JSONObject and do stuff...
        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();
        }
   }
}

And you can use it like :

// Params : url, id, name
new DownloadWebpageTask().execute("http://10.0.2.2/xampp/android_connect/index.php", "12345", "Foo Bar");

Here is a full example that your code should look like :

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.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.Toast;

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();
                
                insert();
            }
        });
    }
    
    public void insert()
    {
        new DownloadWebpageTask().execute("http://10.0.2.2/xampp/android_connect/index.php", id, name);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            // Initialize your parameters
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("id",urls[1]));
            nameValuePairs.add(new BasicNameValuePair("name",urls[2]));         
            
            // Make your HTTP Request
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(urls[0]);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost); 
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            // Read the response
            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();

            // Return the response.
            return result;
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }

    // onPostExecute gets the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {

        // Read your response into a JSONObject and do stuff...
        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();
        }
   }
}
}
Community
  • 1
  • 1
mehmetseckin
  • 3,061
  • 1
  • 31
  • 43
  • Hi, thansk for your answer, i try it in my android emulator borowser and opened http://10.0.2.2/xampp/android_connect/index.php succesfully. Problem is i am still getting same error in app anyway :( – Andurit Nov 16 '14 at 11:20
  • Just realised the error you're getting is related with the main thread. You should be using an AsyncTask for your network tasks, i'll update my answer with an example shortly. – mehmetseckin Nov 16 '14 at 11:23
  • Thanks i look forward. If it's possible add some comments there to let lame people like me understand – Andurit Nov 16 '14 at 11:32
  • I've updated my answer. Please check and feel free to ask if you don't understand. – mehmetseckin Nov 16 '14 at 11:42
  • I really thank you for that, unfortunately it looks i need working example with everything to let me edit things and start play and understand the code. As i said i am totaly new in this and it make me lost even in really nice code :( – Andurit Nov 16 '14 at 12:30
  • I've added a full version of the code to get you started with, please check. – mehmetseckin Nov 16 '14 at 12:41
1

I think you have two problems :

  1. Change localhost to your machine's IP address.
  2. You are doing network calls on UI thread and it's bad for performance. you can use AsyncTask instead or use libraries like Retrofit that rocks! ;)
mehmetseckin
  • 3,061
  • 1
  • 31
  • 43
Mohammad Rahchamani
  • 5,002
  • 1
  • 26
  • 36
  • How can i get the name of my device? And how its gong to work? Becuase this .php file is in my PC, what if it's in some external hosting how else then i should display it? – Andurit Nov 16 '14 at 11:08
  • get your PC's IP address using and place it instead of localhost in your URL. for external hosting, place your host's IP then! – Mohammad Rahchamani Nov 16 '14 at 11:09
  • It's not the problem then because i try it here: http://audatex-systems.cz/melnikovic/android/index.php And still get same error in my app – Andurit Nov 16 '14 at 11:13
  • maybe it's because you are executing network call on UI thread. use asyncTask instead. – Mohammad Rahchamani Nov 16 '14 at 11:17
0

You are doing it wrong. Try 10.0.2.2/android_connect/index.php. 10.0.2.2 redirects to your xampp/htdoc/ folder.

Sajib Acharya
  • 1,666
  • 5
  • 29
  • 54