-2

I am trying to make an app that connects to a MySQL database and queries for data. I don't want to insert any data, just search for a keyword in the given entries. I found a couple of tutorials on Google, and this one worked for me.

The layout looks fine, and the app launched well (I tested the app on my actual Nexus 5). But every time I click the button, whether or not there is data in the text box, it just shows "Invalid IP address" in a toast, which I assume is the error caught. My PHP looks like this :

$host='*****';
$uname='*****';
$pwd='*****';
$db="*****";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$id=$_REQUEST['id'];
$r=mysql_query("select * from ***** where id='$id'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);

Why am I getting this error? And how do I get this to work? Any additional data needed can be provided.

EDIT

Android code

public class MainActivity extends Activity {  
    String id;  
    String name;  
    InputStream is=null;  
    String result=null;  
    String line=null;  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        final EditText e_id=(EditText) findViewById(R.id.editText1);  
        Button select=(Button)findViewById(R.id.button1);  
        select.setOnClickListener(new View.OnClickListener() {  
    @Override  
        public void onClick(View v) {  
            // TODO Auto-generated method stub  
            id=e_id.getText().toString();  
            select();  
        }  
    });  
    }  
    public void select()  
    {  
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
    nameValuePairs.add(new BasicNameValuePair("id",id));  
        try  
        {  
        HttpClient httpclient = new DefaultHttpClient();  
            HttpPost httppost = new   HttpPost("http://kanurajb.co.nf/php/search.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);  
            name=(json_data.getString("name"));  
        Toast.makeText(getBaseContext(), "Name : "+name,  
            Toast.LENGTH_SHORT).show();  
        }    
        catch(Exception e)   
        {  
            Log.e("Fail 3", e.toString());    
        }   
    }  
    @Override  
    public boolean onCreateOptionsMenu(Menu menu) {  
        getMenuInflater().inflate(R.menu.main, menu);  
        return true;  
    }  
}
Lal
  • 14,726
  • 4
  • 45
  • 70
Yash Sharma
  • 31
  • 10

1 Answers1

0

See the answer here..It correctly tells you how to deal with the exception. It says..

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:

Chenge your code as follows..I have changed your select() as follows..This is just for you to get a better understanding about AsyncTask.

class RetrieveFeedTask extends AsyncTask<Void, Void, Boolean> {

  private Exception exception;

  protected Boolean doInBackground(String... urls) {
      try {
        Boolean failedflag=false;
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
        nameValuePairs.add(new BasicNameValuePair("id",id));  
        try  
        {  
            HttpClient httpclient = new DefaultHttpClient();  
            HttpPost httppost = new   HttpPost("http://kanurajb.co.nf/php/search.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) 
        {  
            failedflag=true;
            Log.e("Fail 1", e.toString());           
        }  
        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)  
        {  
            failedflag=true;
            Log.e("Fail 2", e.toString());   
        }  
        try  
        {  
            JSONObject json_data = new JSONObject(result);  
            name=(json_data.getString("name"));   
        }    
        catch(Exception e)   
        {  
            failedflag=true;
            Log.e("Fail 3", e.toString());    
        }   
        return failedflag;
  }

  protected void onPostExecute(Boolean flag) { 
      // TODO: do something with the flag
      if(!flag){
          Toast.makeText(getApplicationContext(), "Failed",  
        Toast.LENGTH_LONG).show();
      }
  }
}

How to execute the task: In MainActivity.java file you can add this line within your oncreate() method

new RetrieveFeedTask().execute();

Don't forget to add this to AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
Community
  • 1
  • 1
Lal
  • 14,726
  • 4
  • 45
  • 70
  • I'm kinda new to this. Could you please help a little more by adapting this concept to my code? Thanks a lot in advance. – Yash Sharma Mar 26 '15 at 17:52
  • the basic working of AsyncTask is that anything that has to be done, should be done in `doInBackground()` and the results obtained after performing the operations will be passed on to `onPostExecute()`.and in the `onPostExecute()` you will be able to alter the UI based on the results returned by the `doInBackground()`. Note that you'll get an error if you try to change the UI in `doInBackground()` including showing a Toast.So all the Toasts should be shown in` onPostExecute()` only. – Lal Mar 26 '15 at 17:58
  • I'm sorry, but that's kinda hard to understand to a beginner. Could you please just give me some code with comments that I can copy-paste and understand? – Yash Sharma Mar 26 '15 at 18:02
  • Network operations have to be performed inside AsyncTask, but just for you to suppress the error add `StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.setThreadPolicy(policy);` after` setContentView()` and the error will be suppressed..But this is not at all recommended. – Lal Mar 26 '15 at 18:03
  • No no, can't you just give me complete code? It's hard for me to piece together methods and functions to make full code at this stage. – Yash Sharma Mar 26 '15 at 18:05
  • you just have to add `StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.setThreadPolicy‌​(policy); after `setContentView()` in your code..try it.. – Lal Mar 26 '15 at 18:06
  • Bro, I'm really not getting you. Could you please edit your answer and add the whole edited code into it? – Yash Sharma Mar 26 '15 at 18:16
  • Did you add the above said code to your actual code? – Lal Mar 26 '15 at 18:18
  • Full code please? I have no clue where to add the method, or how to create it. – Yash Sharma Mar 26 '15 at 18:26
  • Add that code which i told you after `setContentView(R.layout.activity_main); ` in your `onCreate()` and see if the error goes.. – Lal Mar 26 '15 at 18:49
  • Dude, seriously, could you _please_ just write full code for me to copy paste? – Yash Sharma Mar 26 '15 at 18:52
  • Why dont you do what i say? Take some effort in writing the code instead of just copy pasting,..you just have to copy and paste those 2 lines that i mentioned in one of the previous comments, after the line `setContentView(R.layout.activity_main); ` in your `onCreate()` and see if the error goes.. – Lal Mar 26 '15 at 18:55
  • The type MainActivity.RetrieveFeedTask must implement the inherited abstract method AsyncTask.doInBackground(Void...)??? Help please Lal. – Yash Sharma Mar 26 '15 at 19:02
  • You just wait to do the code in my answer...hey @15KanurajBeri please undo the changes made and add the 2 lines that i said in my comments.. – Lal Mar 26 '15 at 19:05
  • Hey could a give me full code with the two lines added? I am having a little trouble with it. – Yash Sharma Mar 26 '15 at 19:09
  • Replace the start of your onCreate() as follows `public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.setThreadPolicy‌​(policy); ` – Lal Mar 26 '15 at 19:15
  • Hey thanks. I'm trying that but got an error on the last line of code which is : "Multiple markers at this line - The method setThreadPolicy‌(StrictMode.ThreadPolicy) is undefined for the type StrictMode - Syntax error on tokens, delete these tokens." – Yash Sharma Mar 26 '15 at 19:20
  • OK got rid of some of it, but still have "Syntax error on tokens, delete these tokens" even tho there aren't any tokens to delete. – Yash Sharma Mar 26 '15 at 19:21
  • It should be `StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.setThreadPolicy‌​(policy); ` – Lal Mar 26 '15 at 19:23
  • I know that, but the "StrictMode.setThreadPolicy(policy)" line keeps giving the error "Syntaxt error on tokens, delete these tokens" – Yash Sharma Mar 26 '15 at 19:26
  • I DON'T KNOW!!! No word is underlined! And yet the whole has an error shown! A solid red error circle, you know what I'm saying? – Yash Sharma Mar 26 '15 at 19:34
  • No! There is no ; missing anywhere! – Yash Sharma Mar 28 '15 at 12:29
  • Did you import strictmode? – Lal Mar 28 '15 at 15:50